repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/http_metadata.rb | lib/puppet/file_serving/http_metadata.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving/metadata'
# Simplified metadata representation, suitable for the information
# that is available from HTTP headers.
class Puppet::FileServing::HttpMetadata < Puppet::FileServing::Metadata
def initialize(http_response, path = '/dev/null')
super(path)
# ignore options that do not apply to HTTP metadata
@owner = @group = @mode = nil
# hash available checksums for eventual collection
@checksums = {}
# use a default mtime in case there is no usable HTTP header
@checksums[:mtime] = "{mtime}#{Time.now}"
# RFC-1864, deprecated in HTTP/1.1 due to partial responses
checksum = http_response['content-md5']
if checksum
# convert base64 digest to hex
checksum = checksum.unpack1("m").unpack1("H*")
@checksums[:md5] = "{md5}#{checksum}"
end
{
md5: 'X-Checksum-Md5',
sha1: 'X-Checksum-Sha1',
sha256: 'X-Checksum-Sha256'
}.each_pair do |checksum_type, header|
checksum = http_response[header]
if checksum
@checksums[checksum_type] = "{#{checksum_type}}#{checksum}"
end
end
last_modified = http_response['last-modified']
if last_modified
mtime = DateTime.httpdate(last_modified).to_time
@checksums[:mtime] = "{mtime}#{mtime.utc}"
end
@ftype = 'file'
end
# Override of the parent class method. Does not call super!
# We can only return metadata that was extracted from the
# HTTP headers during #initialize.
def collect
# Prefer the checksum_type from the indirector request options
# but fall back to the alternative otherwise
[@checksum_type, :sha256, :sha1, :md5, :mtime].each do |type|
next if type == :md5 && Puppet::Util::Platform.fips_enabled?
@checksum_type = type
@checksum = @checksums[type]
break if @checksum
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/terminus_helper.rb | lib/puppet/file_serving/terminus_helper.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/fileset'
# Define some common methods for FileServing termini.
module Puppet::FileServing::TerminusHelper
# Create model instance for a file in a file server.
def path2instance(request, path, options = {})
result = model.new(path, :relative_path => options[:relative_path])
result.links = request.options[:links] if request.options[:links]
result.checksum_type = request.options[:checksum_type] if request.options[:checksum_type]
result.source_permissions = request.options[:source_permissions] if request.options[:source_permissions]
result.collect
result
end
# Create model instances for all files in a fileset.
def path2instances(request, *paths)
filesets = paths.collect do |path|
# Filesets support indirector requests as an options collection
Puppet::FileServing::Fileset.new(path, request)
end
Puppet::FileServing::Fileset.merge(*filesets).collect do |file, base_path|
path2instance(request, base_path, :relative_path => file)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/terminus_selector.rb | lib/puppet/file_serving/terminus_selector.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
# This module is used to pick the appropriate terminus
# in file-serving indirections. This is necessary because
# the terminus varies based on the URI asked for.
module Puppet::FileServing::TerminusSelector
def select(request)
# We rely on the request's parsing of the URI.
case request.protocol
when "file"
:file
when "puppet"
if request.server
:rest
else
Puppet[:default_file_terminus]
end
when "http", "https"
:http
when nil
if Puppet::Util.absolute_path?(request.key)
:file
else
:file_server
end
else
raise ArgumentError, _("URI protocol '%{protocol}' is not currently supported for file serving") % { protocol: request.protocol }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/base.rb | lib/puppet/file_serving/base.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
require_relative '../../puppet/util'
# The base class for Content and Metadata; provides common
# functionality like the behaviour around links.
class Puppet::FileServing::Base
# This is for external consumers to store the source that was used
# to retrieve the metadata.
attr_accessor :source
# Does our file exist?
def exist?
stat
true
rescue
false
end
# Return the full path to our file. Fails if there's no path set.
def full_path
if relative_path.nil? or relative_path == "" or relative_path == "."
full_path = path
else
full_path = File.join(path, relative_path)
end
if Puppet::Util::Platform.windows?
# Replace multiple slashes as long as they aren't at the beginning of a filename
full_path.gsub(%r{(./)/+}, '\1')
else
full_path.gsub(%r{//+}, '/')
end
end
def initialize(path, links: nil, relative_path: nil, source: nil)
self.path = path
@links = :manage
self.links = links if links
self.relative_path = relative_path if relative_path
self.source = source if source
end
# Determine how we deal with links.
attr_reader :links
def links=(value)
value = value.to_sym
value = :manage if value == :ignore
# TRANSLATORS ':link', ':manage', ':follow' should not be translated
raise(ArgumentError, _(":links can only be set to :manage or :follow")) unless [:manage, :follow].include?(value)
@links = value
end
# Set our base path.
attr_reader :path
def path=(path)
raise ArgumentError, _("Paths must be fully qualified") unless Puppet::FileServing::Base.absolute?(path)
@path = path
end
# Set a relative path; this is used for recursion, and sets
# the file's path relative to the initial recursion point.
attr_reader :relative_path
def relative_path=(path)
raise ArgumentError, _("Relative paths must not be fully qualified") if Puppet::FileServing::Base.absolute?(path)
@relative_path = path
end
# Stat our file, using the appropriate link-sensitive method.
def stat
@stat_method ||= links == :manage ? :lstat : :stat
Puppet::FileSystem.send(@stat_method, full_path)
end
def to_data_hash
{
'path' => @path,
'relative_path' => @relative_path,
'links' => @links.to_s
}
end
def self.absolute?(path)
Puppet::Util.absolute_path?(path, :posix) || (Puppet::Util::Platform.windows? && Puppet::Util.absolute_path?(path, :windows))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/configuration.rb | lib/puppet/file_serving/configuration.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/mount'
require_relative '../../puppet/file_serving/mount/file'
require_relative '../../puppet/file_serving/mount/modules'
require_relative '../../puppet/file_serving/mount/plugins'
require_relative '../../puppet/file_serving/mount/locales'
require_relative '../../puppet/file_serving/mount/pluginfacts'
require_relative '../../puppet/file_serving/mount/scripts'
require_relative '../../puppet/file_serving/mount/tasks'
class Puppet::FileServing::Configuration
require_relative 'configuration/parser'
def self.configuration
@configuration ||= new
end
Mount = Puppet::FileServing::Mount
private_class_method :new
attr_reader :mounts
# private :mounts
# Find the right mount. Does some shenanigans to support old-style module
# mounts.
def find_mount(mount_name, environment)
# Reparse the configuration if necessary.
readconfig
# This can be nil.
mounts[mount_name]
end
def initialize
@mounts = {}
@config_file = nil
# We don't check to see if the file is modified the first time,
# because we always want to parse at first.
readconfig(false)
end
# Is a given mount available?
def mounted?(name)
@mounts.include?(name)
end
# Split the path into the separate mount point and path.
def split_path(request)
# Reparse the configuration if necessary.
readconfig
mount_name, path = request.key.split(File::Separator, 2)
raise(ArgumentError, _("Cannot find file: Invalid mount '%{mount_name}'") % { mount_name: mount_name }) unless mount_name =~ /^[-\w]+$/
raise(ArgumentError, _("Cannot find file: Invalid relative path '%{path}'") % { path: path }) if path and path.split('/').include?('..')
mount = find_mount(mount_name, request.environment)
return nil unless mount
if mount.name == "modules" and mount_name != "modules"
# yay backward-compatibility
path = "#{mount_name}/#{path}"
end
if path == ""
path = nil
elsif path
# Remove any double slashes that might have occurred
path = path.gsub(%r{/+}, "/")
end
[mount, path]
end
def umount(name)
@mounts.delete(name) if @mounts.include? name
end
private
def mk_default_mounts
@mounts["modules"] ||= Mount::Modules.new("modules")
@mounts["plugins"] ||= Mount::Plugins.new("plugins")
@mounts["locales"] ||= Mount::Locales.new("locales")
@mounts["pluginfacts"] ||= Mount::PluginFacts.new("pluginfacts")
@mounts["scripts"] ||= Mount::Scripts.new("scripts")
@mounts["tasks"] ||= Mount::Tasks.new("tasks")
end
# Read the configuration file.
def readconfig(check = true)
config = Puppet[:fileserverconfig]
return unless Puppet::FileSystem.exist?(config)
@parser ||= Puppet::FileServing::Configuration::Parser.new(config)
return if check and !@parser.changed?
# Don't assign the mounts hash until we're sure the parsing succeeded.
begin
newmounts = @parser.parse
@mounts = newmounts
rescue => detail
Puppet.log_exception(detail, _("Error parsing fileserver configuration: %{detail}; using old configuration") % { detail: detail })
end
ensure
# Make sure we've got our plugins and modules.
mk_default_mounts
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/fileset.rb | lib/puppet/file_serving/fileset.rb | # frozen_string_literal: true
require 'find'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/metadata'
# Operate recursively on a path, returning a set of file paths.
class Puppet::FileServing::Fileset
attr_reader :path, :ignore, :links
attr_accessor :recurse, :recurselimit, :max_files, :checksum_type
# Produce a hash of files, with merged so that earlier files
# with the same postfix win. E.g., /dir1/subfile beats /dir2/subfile.
# It's a hash because we need to know the relative path of each file,
# and the base directory.
# This will probably only ever be used for searching for plugins.
def self.merge(*filesets)
result = {}
filesets.each do |fileset|
fileset.files.each do |file|
result[file] ||= fileset.path
end
end
result
end
def initialize(path, options = {})
if Puppet::Util::Platform.windows?
# REMIND: UNC path
path = path.chomp(File::SEPARATOR) unless path =~ %r{^[A-Za-z]:/$}
else
path = path.chomp(File::SEPARATOR) unless path == File::SEPARATOR
end
raise ArgumentError, _("Fileset paths must be fully qualified: %{path}") % { path: path } unless Puppet::Util.absolute_path?(path)
@path = path
# Set our defaults.
self.ignore = []
self.links = :manage
@recurse = false
@recurselimit = :infinite
@max_files = 0
if options.is_a?(Puppet::Indirector::Request)
initialize_from_request(options)
else
initialize_from_hash(options)
end
raise ArgumentError, _("Fileset paths must exist") unless valid?(path)
# TRANSLATORS "recurse" and "recurselimit" are parameter names and should not be translated
raise ArgumentError, _("Fileset recurse parameter must not be a number anymore, please use recurselimit") if @recurse.is_a?(Integer)
end
# Return a list of all files in our fileset. This is different from the
# normal definition of find in that we support specific levels
# of recursion, which means we need to know when we're going another
# level deep, which Find doesn't do.
def files
files = perform_recursion
soft_max_files = 1000
# munged_max_files is needed since puppet http handler is keeping negative numbers as strings
# https://github.com/puppetlabs/puppet/blob/main/lib/puppet/network/http/handler.rb#L196-L197
munged_max_files = max_files == '-1' ? -1 : max_files
if munged_max_files > 0 && files.size > munged_max_files
raise Puppet::Error, _("The directory '%{path}' contains %{entries} entries, which exceeds the limit of %{munged_max_files} specified by the max_files parameter for this resource. The limit may be increased, but be aware that large number of file resources can result in excessive resource consumption and degraded performance. Consider using an alternate method to manage large directory trees") % { path: path, entries: files.size, munged_max_files: munged_max_files }
elsif munged_max_files == 0 && files.size > soft_max_files
Puppet.warning _("The directory '%{path}' contains %{entries} entries, which exceeds the default soft limit %{soft_max_files} and may cause excessive resource consumption and degraded performance. To remove this warning set a value for `max_files` parameter or consider using an alternate method to manage large directory trees") % { path: path, entries: files.size, soft_max_files: soft_max_files }
end
# Now strip off the leading path, so each file becomes relative, and remove
# any slashes that might end up at the beginning of the path.
result = files.collect { |file| file.sub(%r{^#{Regexp.escape(@path)}/*}, '') }
# And add the path itself.
result.unshift(".")
result
end
def ignore=(values)
values = [values] unless values.is_a?(Array)
@ignore = values.collect(&:to_s)
end
def links=(links)
links = links.to_sym
# TRANSLATORS ":links" is a parameter name and should not be translated
raise(ArgumentError, _("Invalid :links value '%{links}'") % { links: links }) unless [:manage, :follow].include?(links)
@links = links
@stat_method = @links == :manage ? :lstat : :stat
end
private
def initialize_from_hash(options)
options.each do |option, value|
method = option.to_s + "="
begin
send(method, value)
rescue NoMethodError => e
raise ArgumentError, _("Invalid option '%{option}'") % { option: option }, e.backtrace
end
end
end
def initialize_from_request(request)
[:links, :ignore, :recurse, :recurselimit, :max_files, :checksum_type].each do |param|
if request.options.include?(param) # use 'include?' so the values can be false
value = request.options[param]
elsif request.options.include?(param.to_s)
value = request.options[param.to_s]
end
next if value.nil?
value = true if value == "true"
value = false if value == "false"
value = Integer(value) if value.is_a?(String) and value =~ /^\d+$/
send(param.to_s + "=", value)
end
end
FileSetEntry = Struct.new(:depth, :path, :ignored, :stat_method) do
def down_level(to)
FileSetEntry.new(depth + 1, File.join(path, to), ignored, stat_method)
end
def basename
File.basename(path)
end
def children
return [] unless directory?
Dir.entries(path, encoding: Encoding::UTF_8)
.reject { |child| ignore?(child) }
.collect { |child| down_level(child) }
end
def ignore?(child)
return true if child == "." || child == ".."
return false if ignored == [nil]
ignored.any? { |pattern| File.fnmatch?(pattern, child) }
end
def directory?
Puppet::FileSystem.send(stat_method, path).directory?
rescue Errno::ENOENT, Errno::EACCES
false
end
end
# Pull the recursion logic into one place. It's moderately hairy, and this
# allows us to keep the hairiness apart from what we do with the files.
def perform_recursion
current_dirs = [FileSetEntry.new(0, @path, @ignore, @stat_method)]
result = []
while entry = current_dirs.shift # rubocop:disable Lint/AssignmentInCondition
next unless continue_recursion_at?(entry.depth + 1)
entry.children.each do |child|
result << child.path
current_dirs << child
end
end
result
end
def valid?(path)
Puppet::FileSystem.send(@stat_method, path)
true
rescue Errno::ENOENT, Errno::EACCES
false
end
def continue_recursion_at?(depth)
# recurse if told to, and infinite recursion or current depth not at the limit
recurse && (recurselimit == :infinite || depth <= recurselimit)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount.rb | lib/puppet/file_serving/mount.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/metadata'
require_relative '../../puppet/file_serving/content'
# Broker access to the filesystem, converting local URIs into metadata
# or content objects.
class Puppet::FileServing::Mount
include Puppet::Util::Logging
attr_reader :name
def find(path, options)
raise NotImplementedError
end
# Create our object. It must have a name.
def initialize(name)
unless name =~ /^[-\w]+$/
raise ArgumentError, _("Invalid mount name format '%{name}'") % { name: name }
end
@name = name
super()
end
def search(path, options)
raise NotImplementedError
end
def to_s
"mount[#{@name}]"
end
# A noop.
def validate
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/metadata.rb | lib/puppet/file_serving/metadata.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/indirector'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/base'
require_relative '../../puppet/util/checksums'
require 'uri'
# A class that handles retrieving file metadata.
class Puppet::FileServing::Metadata < Puppet::FileServing::Base
include Puppet::Util::Checksums
extend Puppet::Indirector
indirects :file_metadata, :terminus_class => :selector
attr_reader :path, :owner, :group, :mode, :checksum_type, :checksum, :ftype, :destination, :source_permissions, :content_uri
PARAM_ORDER = [:mode, :ftype, :owner, :group]
def checksum_type=(type)
raise(ArgumentError, _("Unsupported checksum type %{type}") % { type: type }) unless Puppet::Util::Checksums.respond_to?("#{type}_file")
@checksum_type = type
end
def source_permissions=(source_permissions)
raise(ArgumentError, _("Unsupported source_permission %{source_permissions}") % { source_permissions: source_permissions }) unless [:use, :use_when_creating, :ignore].include?(source_permissions.intern)
@source_permissions = source_permissions.intern
end
def content_uri=(path)
begin
uri = URI.parse(Puppet::Util.uri_encode(path))
rescue URI::InvalidURIError => detail
raise(ArgumentError, _("Could not understand URI %{path}: %{detail}") % { path: path, detail: detail })
end
raise(ArgumentError, _("Cannot use opaque URLs '%{path}'") % { path: path }) unless uri.hierarchical?
raise(ArgumentError, _("Must use URLs of type puppet as content URI")) if uri.scheme != "puppet"
@content_uri = path.encode(Encoding::UTF_8)
end
class MetaStat
extend Forwardable
def initialize(stat, source_permissions)
@stat = stat
@source_permissions_ignore = !source_permissions || source_permissions == :ignore
end
def owner
@source_permissions_ignore ? Process.euid : @stat.uid
end
def group
@source_permissions_ignore ? Process.egid : @stat.gid
end
def mode
@source_permissions_ignore ? 0o644 : @stat.mode
end
def_delegators :@stat, :ftype
end
class WindowsStat < MetaStat
if Puppet::Util::Platform.windows?
require_relative '../../puppet/util/windows/security'
end
def initialize(stat, path, source_permissions)
super(stat, source_permissions)
@path = path
raise(ArgumentError, _("Unsupported Windows source permissions option %{source_permissions}") % { source_permissions: source_permissions }) unless @source_permissions_ignore
end
{ :owner => 'S-1-5-32-544',
:group => 'S-1-0-0',
:mode => 0o644 }.each do |method, default_value|
define_method method do
default_value
end
end
end
def collect_stat(path)
stat = stat()
if Puppet::Util::Platform.windows?
WindowsStat.new(stat, path, @source_permissions)
else
MetaStat.new(stat, @source_permissions)
end
end
# Retrieve the attributes for this file, relative to a base directory.
# Note that Puppet::FileSystem.stat(path) raises Errno::ENOENT
# if the file is absent and this method does not catch that exception.
def collect(source_permissions = nil)
real_path = full_path
stat = collect_stat(real_path)
@owner = stat.owner
@group = stat.group
@ftype = stat.ftype
# We have to mask the mode, yay.
@mode = stat.mode & 0o07777
case stat.ftype
when "file"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
when "directory" # Always just timestamp the directory.
@checksum_type = "ctime"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", path).to_s
when "link"
@destination = Puppet::FileSystem.readlink(real_path)
@checksum = begin
"{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
rescue
nil
end
when "fifo", "socket"
@checksum_type = "none"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
else
raise ArgumentError, _("Cannot manage files of type %{file_type}") % { file_type: stat.ftype }
end
end
def initialize(path, data = {})
@owner = data.delete('owner')
@group = data.delete('group')
@mode = data.delete('mode')
checksum = data.delete('checksum')
if checksum
@checksum_type = checksum['type']
@checksum = checksum['value']
end
@checksum_type ||= Puppet[:digest_algorithm]
@ftype = data.delete('type')
@destination = data.delete('destination')
@source = data.delete('source')
@content_uri = data.delete('content_uri')
links = data.fetch('links', nil) || data.fetch(:links, nil)
relative_path = data.fetch('relative_path', nil) || data.fetch(:relative_path, nil)
source = @source || data.fetch(:source, nil)
super(path, links: links, relative_path: relative_path, source: source)
end
def to_data_hash
super.update(
{
'owner' => owner,
'group' => group,
'mode' => mode,
'checksum' => {
'type' => checksum_type,
'value' => checksum
},
'type' => ftype,
'destination' => destination,
}.merge(content_uri ? { 'content_uri' => content_uri } : {})
.merge(source ? { 'source' => source } : {})
)
end
def self.from_data_hash(data)
new(data.delete('path'), data)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/plugins.rb | lib/puppet/file_serving/mount/plugins.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' plugins directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::Plugins < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.plugin(relative_path) }
return nil unless mod
mod.plugin(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on plugins - return
# them all.
paths = request.environment.modules.find_all(&:plugins?).collect(&:plugin_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/file.rb | lib/puppet/file_serving/mount/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
class Puppet::FileServing::Mount::File < Puppet::FileServing::Mount
def self.localmap
@localmap ||= {
"h" => Puppet.runtime[:facter].value('networking.hostname'),
"H" => [
Puppet.runtime[:facter].value('networking.hostname'),
Puppet.runtime[:facter].value('networking.domain')
].join("."),
"d" => Puppet.runtime[:facter].value('networking.domain')
}
end
def complete_path(relative_path, node)
full_path = path(node)
raise ArgumentError, _("Mounts without paths are not usable") unless full_path
# If there's no relative path name, then we're serving the mount itself.
return full_path unless relative_path
file = ::File.join(full_path, relative_path)
unless Puppet::FileSystem.exist?(file) or Puppet::FileSystem.symlink?(file)
Puppet.info(_("File does not exist or is not accessible: %{file}") % { file: file })
return nil
end
file
end
# Return an instance of the appropriate class.
def find(short_file, request)
complete_path(short_file, request.node)
end
# Return the path as appropriate, expanding as necessary.
def path(node = nil)
if expandable?
expand(@path, node)
else
@path
end
end
# Set the path.
def path=(path)
# FIXME: For now, just don't validate paths with replacement
# patterns in them.
if path =~ /%./
# Mark that we're expandable.
@expandable = true
else
raise ArgumentError, _("%{path} does not exist or is not a directory") % { path: path } unless FileTest.directory?(path)
raise ArgumentError, _("%{path} is not readable") % { path: path } unless FileTest.readable?(path)
@expandable = false
end
@path = path
end
def search(path, request)
path = complete_path(path, request.node)
return nil unless path
[path]
end
# Verify our configuration is valid. This should really check to
# make sure at least someone will be allowed, but, eh.
def validate
raise ArgumentError, _("Mounts without paths are not usable") if @path.nil?
end
private
# Create a map for a specific node.
def clientmap(node)
{
"h" => node.sub(/\..*$/, ""),
"H" => node,
"d" => node.sub(/[^.]+\./, "") # domain name
}
end
# Replace % patterns as appropriate.
def expand(path, node = nil)
# This map should probably be moved into a method.
map = nil
if node
map = clientmap(node)
else
Puppet.notice _("No client; expanding '%{path}' with local host") % { path: path }
# Else, use the local information
map = localmap
end
path.gsub(/%(.)/) do |v|
key = ::Regexp.last_match(1)
if key == "%"
"%"
else
map[key] || v
end
end
end
# Do we have any patterns in our path, yo?
def expandable?
if defined?(@expandable)
@expandable
else
false
end
end
# Cache this manufactured map, since if it's used it's likely
# to get used a lot.
def localmap
self.class.localmap
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/scripts.rb | lib/puppet/file_serving/mount/scripts.rb | # frozen_string_literal: true
require 'puppet/file_serving/mount'
class Puppet::FileServing::Mount::Scripts < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(path, request)
raise _("No module specified") if path.to_s.empty?
module_name, relative_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.script(relative_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/pluginfacts.rb | lib/puppet/file_serving/mount/pluginfacts.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' pluginfacts directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::PluginFacts < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.pluginfact(relative_path) }
return nil unless mod
mod.pluginfact(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on plugins - return
# them all.
paths = request.environment.modules.find_all(&:pluginfacts?).collect(&:plugin_fact_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/locales.rb | lib/puppet/file_serving/mount/locales.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' locales directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::Locales < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.locale(relative_path) }
return nil unless mod
mod.locale(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on locales - return
# them all.
paths = request.environment.modules.find_all(&:locales?).collect(&:locale_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/tasks.rb | lib/puppet/file_serving/mount/tasks.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
class Puppet::FileServing::Mount::Tasks < Puppet::FileServing::Mount
def find(path, request)
raise _("No task specified") if path.to_s.empty?
module_name, task_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.task_file(task_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/mount/modules.rb | lib/puppet/file_serving/mount/modules.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# This is the modules-specific mount: it knows how to search through
# modules for files. Yay.
class Puppet::FileServing::Mount::Modules < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(path, request)
raise _("No module specified") if path.to_s.empty?
module_name, relative_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.file(relative_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_serving/configuration/parser.rb | lib/puppet/file_serving/configuration/parser.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/configuration'
require_relative '../../../puppet/util/watched_file'
class Puppet::FileServing::Configuration::Parser
Mount = Puppet::FileServing::Mount
MODULES = 'modules'
# Parse our configuration file.
def parse
raise(_("File server configuration %{config_file} does not exist") % { config_file: @file }) unless Puppet::FileSystem.exist?(@file)
raise(_("Cannot read file server configuration %{config_file}") % { config_file: @file }) unless FileTest.readable?(@file)
@mounts = {}
@count = 0
File.open(@file) do |f|
mount = nil
f.each_line do |line|
# Have the count increment at the top, in case we throw exceptions.
@count += 1
case line
when /^\s*#/; next # skip comments
when /^\s*$/; next # skip blank lines
when /\[([-\w]+)\]/
mount = newmount(::Regexp.last_match(1))
when /^\s*(\w+)\s+(.+?)(\s*#.*)?$/
var = ::Regexp.last_match(1)
value = ::Regexp.last_match(2)
value.strip!
raise(ArgumentError, _("Fileserver configuration file does not use '=' as a separator")) if value =~ /^=/
case var
when "path"
path(mount, value)
when "allow", "deny"
# ignore `allow *`, otherwise report error
if var != 'allow' || value != '*'
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
Puppet.err("Entry '#{line.chomp}' is unsupported and will be ignored at #{error_location_str}")
end
else
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
raise ArgumentError, _("Invalid argument '%{var}' at %{error_location}") %
{ var: var, error_location: error_location_str }
end
else
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
raise ArgumentError, _("Invalid entry at %{error_location}: '%{file_text}'") %
{ file_text: line.chomp, error_location: error_location_str }
end
end
end
validate
@mounts
end
def initialize(filename)
@file = Puppet::Util::WatchedFile.new(filename)
end
def changed?
@file.changed?
end
private
# Create a new mount.
def newmount(name)
if @mounts.include?(name)
error_location_str = Puppet::Util::Errors.error_location(@file, @count)
raise ArgumentError, _("%{mount} is already mounted at %{name} at %{error_location}") %
{ mount: @mounts[name], name: name, error_location: error_location_str }
end
case name
when "modules"
mount = Mount::Modules.new(name)
when "plugins"
mount = Mount::Plugins.new(name)
when "scripts"
mount = Mount::Scripts.new(name)
when "tasks"
mount = Mount::Tasks.new(name)
when "locales"
mount = Mount::Locales.new(name)
else
mount = Mount::File.new(name)
end
@mounts[name] = mount
mount
end
# Set the path for a mount.
def path(mount, value)
if mount.respond_to?(:path=)
begin
mount.path = value
rescue ArgumentError => detail
Puppet.log_exception(detail, _("Removing mount \"%{mount}\": %{detail}") % { mount: mount.name, detail: detail })
@mounts.delete(mount.name)
end
else
Puppet.warning _("The '%{mount}' module can not have a path. Ignoring attempt to set it") % { mount: mount.name }
end
end
# Make sure all of our mounts are valid. We have to do this after the fact
# because details are added over time as the file is parsed.
def validate
@mounts.each { |_name, mount| mount.validate }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module/task.rb | lib/puppet/module/task.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
class Puppet::Module
class Task
class Error < Puppet::Error
attr_accessor :kind, :details
def initialize(message, kind, details = nil)
super(message)
@details = details || {}
@kind = kind
end
def to_h
{
msg: message,
kind: kind,
details: details
}
end
end
class InvalidName < Error
def initialize(name)
msg = _("Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
super(msg, 'puppet.tasks/invalid-name')
end
end
class InvalidFile < Error
def initialize(msg)
super(msg, 'puppet.tasks/invalid-file')
end
end
class InvalidTask < Error
end
class InvalidMetadata < Error
end
class TaskNotFound < Error
def initialize(task_name, module_name)
msg = _("Task %{task_name} not found in module %{module_name}.") %
{ task_name: task_name, module_name: module_name }
super(msg, 'puppet.tasks/task-not-found', { 'name' => task_name })
end
end
FORBIDDEN_EXTENSIONS = %w[.conf .md]
MOUNTS = %w[files lib scripts tasks]
def self.is_task_name?(name)
return true if name =~ /^[a-z][a-z0-9_]*$/
false
end
def self.is_tasks_file?(path)
File.file?(path) && is_tasks_filename?(path)
end
# Determine whether a file has a legal name for either a task's executable or metadata file.
def self.is_tasks_filename?(path)
name_less_extension = File.basename(path, '.*')
return false unless is_task_name?(name_less_extension)
FORBIDDEN_EXTENSIONS.each do |ext|
return false if path.end_with?(ext)
end
true
end
def self.get_file_details(path, mod)
# This gets the path from the starting point onward
# For files this should be the file subpath from the metadata
# For directories it should be the directory subpath plus whatever we globbed
# Partition matches on the first instance it finds of the parameter
name = "#{mod.name}#{path.partition(mod.path).last}"
{ "name" => name, "path" => path }
end
private_class_method :get_file_details
# Find task's required lib files and retrieve paths for both 'files' and 'implementation:files' metadata keys
def self.find_extra_files(metadata, envname = nil)
return [] if metadata.nil?
files = metadata.fetch('files', [])
unless files.is_a?(Array)
msg = _("The 'files' task metadata expects an array, got %{files}.") % { files: files }
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
impl_files = metadata.fetch('implementations', []).flat_map do |impl|
file_array = impl.fetch('files', [])
unless file_array.is_a?(Array)
msg = _("The 'files' task metadata expects an array, got %{files}.") % { files: file_array }
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
file_array
end
combined_files = files + impl_files
combined_files.uniq.flat_map do |file|
module_name, mount, endpath = file.split("/", 3)
# If there's a mount directory with no trailing slash this will be nil
# We want it to be empty to construct a path
endpath ||= ''
pup_module = Puppet::Module.find(module_name, envname)
if pup_module.nil?
msg = _("Could not find module %{module_name} containing task file %{filename}" %
{ module_name: module_name, filename: endpath })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
unless MOUNTS.include? mount
msg = _("Files must be saved in module directories that Puppet makes available via mount points: %{mounts}" %
{ mounts: MOUNTS.join(', ') })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
path = File.join(pup_module.path, mount, endpath)
unless File.absolute_path(path) == File.path(path).chomp('/')
msg = _("File pathnames cannot include relative paths")
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
unless File.exist?(path)
msg = _("Could not find %{path} on disk" % { path: path })
raise InvalidFile, msg
end
last_char = file[-1] == '/'
if File.directory?(path)
unless last_char
msg = _("Directories specified in task metadata must include a trailing slash: %{dir}" % { dir: file })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
dir_files = Dir.glob("#{path}**/*").select { |f| File.file?(f) }
dir_files.map { |f| get_file_details(f, pup_module) }
else
if last_char
msg = _("Files specified in task metadata cannot include a trailing slash: %{file}" % { file: file })
raise InvalidMetadata.new(msg, 'puppet.task/invalid-metadata')
end
get_file_details(path, pup_module)
end
end
end
private_class_method :find_extra_files
# Executables list should contain the full path of all possible implementation files
def self.find_implementations(name, directory, metadata, executables)
basename = name.split('::')[1] || 'init'
# If 'implementations' is defined, it needs to mention at least one
# implementation, and everything it mentions must exist.
metadata ||= {}
if metadata.key?('implementations')
unless metadata['implementations'].is_a?(Array)
msg = _("Task metadata for task %{name} does not specify implementations as an array" % { name: name })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
implementations = metadata['implementations'].map do |impl|
unless impl['requirements'].is_a?(Array) || impl['requirements'].nil?
msg = _("Task metadata for task %{name} does not specify requirements as an array" % { name: name })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
path = executables.find { |real_impl| File.basename(real_impl) == impl['name'] }
unless path
msg = _("Task metadata for task %{name} specifies missing implementation %{implementation}" % { name: name, implementation: impl['name'] })
raise InvalidTask.new(msg, 'puppet.tasks/missing-implementation', { missing: [impl['name']] })
end
{ "name" => impl['name'], "path" => path }
end
return implementations
end
# If implementations isn't defined, then we use executables matching the
# task name, and only one may exist.
implementations = executables.select { |impl| File.basename(impl, '.*') == basename }
if implementations.empty?
msg = _('No source besides task metadata was found in directory %{directory} for task %{name}') %
{ name: name, directory: directory }
raise InvalidTask.new(msg, 'puppet.tasks/no-implementation')
elsif implementations.length > 1
msg = _("Multiple executables were found in directory %{directory} for task %{name}; define 'implementations' in metadata to differentiate between them") %
{ name: name, directory: implementations[0] }
raise InvalidTask.new(msg, 'puppet.tasks/multiple-implementations')
end
[{ "name" => File.basename(implementations.first), "path" => implementations.first }]
end
private_class_method :find_implementations
def self.find_files(name, directory, metadata, executables, envname = nil)
# PXP agent relies on 'impls' (which is the task file) being first if there is no metadata
find_implementations(name, directory, metadata, executables) + find_extra_files(metadata, envname)
end
def self.is_tasks_metadata_filename?(name)
is_tasks_filename?(name) && name.end_with?('.json')
end
def self.is_tasks_executable_filename?(name)
is_tasks_filename?(name) && !name.end_with?('.json')
end
def self.tasks_in_module(pup_module)
task_files = Dir.glob(File.join(pup_module.tasks_directory, '*'))
.keep_if { |f| is_tasks_file?(f) }
module_executables = task_files.reject(&method(:is_tasks_metadata_filename?)).map.to_a
tasks = task_files.group_by { |f| task_name_from_path(f) }
tasks.map do |task, executables|
new_with_files(pup_module, task, executables, module_executables)
end
end
attr_reader :name, :module, :metadata_file
# file paths must be relative to the modules task directory
def initialize(pup_module, task_name, module_executables, metadata_file = nil)
unless Puppet::Module::Task.is_task_name?(task_name)
raise InvalidName, _("Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
end
name = task_name == "init" ? pup_module.name : "#{pup_module.name}::#{task_name}"
@module = pup_module
@name = name
@metadata_file = metadata_file
@module_executables = module_executables || []
end
def self.read_metadata(file)
if file
content = Puppet::FileSystem.read(file, :encoding => 'utf-8')
content.empty? ? {} : Puppet::Util::Json.load(content)
end
rescue SystemCallError, IOError => err
msg = _("Error reading metadata: %{message}" % { message: err.message })
raise InvalidMetadata.new(msg, 'puppet.tasks/unreadable-metadata')
rescue Puppet::Util::Json::ParseError => err
raise InvalidMetadata.new(err.message, 'puppet.tasks/unparseable-metadata')
end
def metadata
@metadata ||= self.class.read_metadata(@metadata_file)
end
def files
@files ||= self.class.find_files(@name, @module.tasks_directory, metadata, @module_executables, environment_name)
end
def validate
files
true
end
def ==(other)
name == other.name &&
self.module == other.module
end
def environment_name
@module.environment.respond_to?(:name) ? @module.environment.name : 'production'
end
private :environment_name
def self.new_with_files(pup_module, name, task_files, module_executables)
metadata_file = task_files.find { |f| is_tasks_metadata_filename?(f) }
Puppet::Module::Task.new(pup_module, name, module_executables, metadata_file)
end
private_class_method :new_with_files
# Abstracted here so we can add support for subdirectories later
def self.task_name_from_path(path)
File.basename(path, '.*')
end
private_class_method :task_name_from_path
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module/plan.rb | lib/puppet/module/plan.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
class Puppet::Module
class Plan
class Error < Puppet::Error
attr_accessor :kind, :details
def initialize(message, kind, details = nil)
super(message)
@details = details || {}
@kind = kind
end
def to_h
{
msg: message,
kind: kind,
details: details
}
end
end
class InvalidName < Error
def initialize(name, msg)
super(msg, 'puppet.plans/invalid-name')
end
end
class InvalidFile < Error
def initialize(msg)
super(msg, 'puppet.plans/invalid-file')
end
end
class InvalidPlan < Error
end
class InvalidMetadata < Error
end
class PlanNotFound < Error
def initialize(plan_name, module_name)
msg = _("Plan %{plan_name} not found in module %{module_name}.") %
{ plan_name: plan_name, module_name: module_name }
super(msg, 'puppet.plans/plan-not-found', { 'name' => plan_name })
end
end
ALLOWED_EXTENSIONS = %w[.pp .yaml]
RESERVED_WORDS = %w[and application attr case class consumes default else
elsif environment false function if import in inherits node or private
produces site true type undef unless]
RESERVED_DATA_TYPES = %w[any array boolean catalogentry class collection
callable data default enum float hash integer numeric optional pattern
resource runtime scalar string struct tuple type undef variant]
def self.is_plan_name?(name)
return true if name =~ /^[a-z][a-z0-9_]*$/
false
end
# Determine whether a plan file has a legal name and extension
def self.is_plans_filename?(path)
name = File.basename(path, '.*')
ext = File.extname(path)
return [false, _("Plan names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")] unless is_plan_name?(name)
unless ALLOWED_EXTENSIONS.include? ext
return [false, _("Plan name cannot have extension %{ext}, must be .pp or .yaml") % { ext: ext }]
end
if RESERVED_WORDS.include?(name)
return [false, _("Plan name cannot be a reserved word, but was '%{name}'") % { name: name }]
end
if RESERVED_DATA_TYPES.include?(name)
return [false, _("Plan name cannot be a Puppet data type, but was '%{name}'") % { name: name }]
end
[true]
end
# Executables list should contain the full path of all possible implementation files
def self.find_implementations(name, plan_files)
basename = name.split('::')[1] || 'init'
# If implementations isn't defined, then we use executables matching the
# plan name, and only one may exist.
implementations = plan_files.select { |impl| File.basename(impl, '.*') == basename }
# Select .pp before .yaml, since .pp comes before .yaml alphabetically.
chosen = implementations.min
[{ "name" => File.basename(chosen), "path" => chosen }]
end
private_class_method :find_implementations
def self.find_files(name, plan_files)
find_implementations(name, plan_files)
end
def self.plans_in_module(pup_module)
# Search e.g. 'modules/<pup_module>/plans' for all plans
plan_files = Dir.glob(File.join(pup_module.plans_directory, '*'))
.keep_if { |f| valid, _ = is_plans_filename?(f); valid }
plans = plan_files.group_by { |f| plan_name_from_path(f) }
plans.map do |plan, plan_filenames|
new_with_files(pup_module, plan, plan_filenames)
end
end
attr_reader :name, :module, :metadata_file
# file paths must be relative to the modules plan directory
def initialize(pup_module, plan_name, plan_files)
valid, reason = Puppet::Module::Plan.is_plans_filename?(plan_files.first)
unless valid
raise InvalidName.new(plan_name, reason)
end
name = plan_name == "init" ? pup_module.name : "#{pup_module.name}::#{plan_name}"
@module = pup_module
@name = name
@metadata_file = metadata_file
@plan_files = plan_files || []
end
def metadata
# Nothing to go here unless plans eventually support metadata.
@metadata ||= {}
end
def files
@files ||= self.class.find_files(@name, @plan_files)
end
def validate
files
true
end
def ==(other)
name == other.name &&
self.module == other.module
end
def environment_name
@module.environment.respond_to?(:name) ? @module.environment.name : 'production'
end
private :environment_name
def self.new_with_files(pup_module, name, plan_files)
Puppet::Module::Plan.new(pup_module, name, plan_files)
end
private_class_method :new_with_files
# Abstracted here so we can add support for subdirectories later
def self.plan_name_from_path(path)
File.basename(path, '.*')
end
private_class_method :plan_name_from_path
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors.rb | lib/puppet/module_tool/errors.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
module Errors
require_relative 'errors/base'
require_relative 'errors/installer'
require_relative 'errors/uninstaller'
require_relative 'errors/upgrader'
require_relative 'errors/shared'
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/tar.rb | lib/puppet/module_tool/tar.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/util'
module Puppet::ModuleTool::Tar
require_relative 'tar/gnu'
require_relative 'tar/mini'
def self.instance
if Puppet.features.minitar? && Puppet.features.zlib?
Mini.new
elsif Puppet::Util.which('tar') && !Puppet::Util::Platform.windows?
Gnu.new
else
# TRANSLATORS "tar" is a program name and should not be translated
raise RuntimeError, _('No suitable tar implementation found')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications.rb | lib/puppet/module_tool/applications.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
module Applications
require_relative 'applications/application'
require_relative 'applications/checksummer'
require_relative 'applications/installer'
require_relative 'applications/unpacker'
require_relative 'applications/uninstaller'
require_relative 'applications/upgrader'
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/shared_behaviors.rb | lib/puppet/module_tool/shared_behaviors.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Shared
include Puppet::ModuleTool::Errors
def get_local_constraints
@local = Hash.new { |h, k| h[k] = {} }
@conditions = Hash.new { |h, k| h[k] = [] }
@installed = Hash.new { |h, k| h[k] = [] }
@environment.modules_by_path.values.flatten.each do |mod|
mod_name = (mod.forge_name || mod.name).tr('/', '-')
@installed[mod_name] << mod
d = @local["#{mod_name}@#{mod.version}"]
(mod.dependencies || []).each do |hash|
name = hash['name']
conditions = hash['version_requirement']
name = name.tr('/', '-')
d[name] = conditions
@conditions[name] << {
:module => mod_name,
:version => mod.version,
:dependency => conditions
}
end
end
end
def get_remote_constraints(forge)
@remote = Hash.new { |h, k| h[k] = {} }
@urls = {}
@versions = Hash.new { |h, k| h[k] = [] }
Puppet.notice _("Downloading from %{uri} ...") % { uri: forge.uri }
author, modname = Puppet::ModuleTool.username_and_modname_from(@module_name)
info = forge.remote_dependency_info(author, modname, @options[:version])
info.each do |pair|
mod_name, releases = pair
mod_name = mod_name.tr('/', '-')
releases.each do |rel|
semver = begin
SemanticPuppet::Version.parse(rel['version'])
rescue
SemanticPuppet::Version::MIN
end
@versions[mod_name] << { :vstring => rel['version'], :semver => semver }
@versions[mod_name].sort_by! { |a| a[:semver] }
@urls["#{mod_name}@#{rel['version']}"] = rel['file']
d = @remote["#{mod_name}@#{rel['version']}"]
(rel['dependencies'] || []).each do |name, conditions|
d[name.tr('/', '-')] = conditions
end
end
end
end
def implicit_version(mod)
return :latest if @conditions[mod].empty?
if @conditions[mod].all? { |c| c[:queued] || c[:module] == :you }
return :latest
end
:best
end
def annotated_version(mod, versions)
if versions.empty?
implicit_version(mod)
else
"#{implicit_version(mod)}: #{versions.last}"
end
end
def resolve_constraints(dependencies, source = [{ :name => :you }], seen = {}, action = @action)
dependencies = dependencies.filter_map do |mod, range|
source.last[:dependency] = range
@conditions[mod] << {
:module => source.last[:name],
:version => source.last[:version],
:dependency => range,
:queued => true
}
if forced?
range = begin
Puppet::Module.parse_range(@version)
rescue
Puppet::Module.parse_range('>= 0.0.0')
end
else
range = (@conditions[mod]).map do |r|
Puppet::Module.parse_range(r[:dependency])
rescue
Puppet::Module.parse_range('>= 0.0.0')
end.inject(&:&)
end
if @action == :install && seen.include?(mod)
next if range === seen[mod][:semver]
req_module = @module_name
req_versions = @versions[@module_name.to_s].map { |v| v[:semver] }
raise InvalidDependencyCycleError,
:module_name => mod,
:source => (source + [{ :name => mod, :version => source.last[:dependency] }]),
:requested_module => req_module,
:requested_version => @version || annotated_version(req_module, req_versions),
:conditions => @conditions
end
if !(forced? || @installed[mod].empty? || source.last[:name] == :you)
next if range === SemanticPuppet::Version.parse(@installed[mod].first.version)
action = :upgrade
elsif @installed[mod].empty?
action = :install
end
if action == :upgrade
@conditions.each { |_, conds| conds.delete_if { |c| c[:module] == mod } }
end
versions = @versions[mod.to_s].select { |h| range === h[:semver] }
valid_versions = versions.select { |x| x[:semver].special == '' }
valid_versions = versions if valid_versions.empty?
version = valid_versions.last
unless version
req_module = @module_name
req_versions = @versions[@module_name.to_s].map { |v| v[:semver] }
raise NoVersionsSatisfyError,
:requested_name => req_module,
:requested_version => @version || annotated_version(req_module, req_versions),
:installed_version => @installed[@module_name].empty? ? nil : @installed[@module_name].first.version,
:dependency_name => mod,
:conditions => @conditions[mod],
:action => @action
end
seen[mod] = version
{
:module => mod,
:version => version,
:action => action,
:previous_version => @installed[mod].empty? ? nil : @installed[mod].first.version,
:file => @urls["#{mod}@#{version[:vstring]}"],
:path => if action == :install
@options[:target_dir]
else
@installed[mod].empty? ? @options[:target_dir] : @installed[mod].first.modulepath
end,
:dependencies => []
}
end
dependencies.each do |mod|
deps = @remote["#{mod[:module]}@#{mod[:version][:vstring]}"].sort_by(&:first)
mod[:dependencies] = resolve_constraints(deps, source + [{ :name => mod[:module], :version => mod[:version][:vstring] }], seen, :install)
end unless @ignore_dependencies
dependencies
end
def download_tarballs(graph, default_path, forge)
graph.map do |release|
begin
if release[:tarball]
cache_path = Pathname(release[:tarball])
else
cache_path = forge.retrieve(release[:file])
end
rescue OpenURI::HTTPError => e
raise RuntimeError, _("Could not download module: %{message}") % { message: e.message }, e.backtrace
end
[
{ (release[:path] ||= default_path) => cache_path },
*download_tarballs(release[:dependencies], default_path, forge)
]
end.flatten
end
def forced?
options[:force]
end
def add_module_name_constraints_to_graph(graph)
# Puppet modules are installed by "module name", but resolved by
# "full name" (including namespace). So that we don't run into
# problems at install time, we should reject any solution that
# depends on multiple nodes with the same "module name".
graph.add_graph_constraint('PMT') do |nodes|
names = nodes.map { |x| x.dependency_names + [x.name] }.flatten
names = names.map { |x| x.tr('/', '-') }.uniq
names = names.map { |x| x[/-(.*)/, 1] }
names.length == names.uniq.length
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/installed_modules.rb | lib/puppet/module_tool/installed_modules.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../puppet/forge'
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
class InstalledModules < SemanticPuppet::Dependency::Source
attr_reader :modules, :by_name
def priority
10
end
def initialize(env)
@env = env
modules = env.modules_by_path
@fetched = []
@modules = {}
@by_name = {}
env.modulepath.each do |path|
modules[path].each do |mod|
@by_name[mod.name] = mod
next unless mod.has_metadata?
release = ModuleRelease.new(self, mod)
@modules[release.name] ||= release
end
end
@modules.freeze
end
# Fetches {ModuleRelease} entries for each release of the named module.
#
# @param name [String] the module name to look up
# @return [Array<SemanticPuppet::Dependency::ModuleRelease>] a list of releases for
# the given name
# @see SemanticPuppet::Dependency::Source#fetch
def fetch(name)
name = name.tr('/', '-')
if @modules.key? name
@fetched << name
[@modules[name]]
else
[]
end
end
def fetched
@fetched
end
class ModuleRelease < SemanticPuppet::Dependency::ModuleRelease
attr_reader :mod, :metadata
def initialize(source, mod)
@mod = mod
@metadata = mod.metadata
name = mod.forge_name.tr('/', '-')
begin
version = SemanticPuppet::Version.parse(mod.version)
rescue SemanticPuppet::Version::ValidationFailure
Puppet.warning _("%{module_name} (%{path}) has an invalid version number (%{version}). The version has been set to 0.0.0. If you are the maintainer for this module, please update the metadata.json with a valid Semantic Version (http://semver.org).") % { module_name: mod.name, path: mod.path, version: mod.version }
version = SemanticPuppet::Version.parse("0.0.0")
end
release = "#{name}@#{version}"
super(source, name, version, {})
if mod.dependencies
mod.dependencies.each do |dependency|
results = Puppet::ModuleTool.parse_module_dependency(release, dependency)
dep_name, parsed_range, range = results
add_constraint('initialize', dep_name, range.to_s) do |node|
parsed_range === node.version
end
end
end
end
def install_dir
Pathname.new(@mod.path).dirname
end
def install(dir)
# If we're already installed, there's no need for us to faff about.
end
def prepare
# We're already installed; what preparation remains?
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/local_tarball.rb | lib/puppet/module_tool/local_tarball.rb | # frozen_string_literal: true
require 'pathname'
require 'tmpdir'
require_relative '../../puppet/forge'
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
class LocalTarball < SemanticPuppet::Dependency::Source
attr_accessor :release
def initialize(filename)
unpack(filename, tmpdir)
Puppet.debug "Unpacked local tarball to #{tmpdir}"
mod = Puppet::Module.new('tarball', tmpdir, nil)
@release = ModuleRelease.new(self, mod)
end
def fetch(name)
if @release.name == name
[@release]
else
[]
end
end
def prepare(release)
release.mod.path
end
def install(release, dir)
staging_dir = release.prepare
module_dir = dir + release.name[/-(.*)/, 1]
module_dir.rmtree if module_dir.exist?
# Make sure unpacked module has the same ownership as the folder we are moving it into.
Puppet::ModuleTool::Applications::Unpacker.harmonize_ownership(dir, staging_dir)
FileUtils.mv(staging_dir, module_dir)
end
class ModuleRelease < SemanticPuppet::Dependency::ModuleRelease
attr_reader :mod, :install_dir, :metadata
def initialize(source, mod)
@mod = mod
@metadata = mod.metadata
name = mod.forge_name.tr('/', '-')
version = SemanticPuppet::Version.parse(mod.version)
release = "#{name}@#{version}"
if mod.dependencies
dependencies = mod.dependencies.map do |dep|
Puppet::ModuleTool.parse_module_dependency(release, dep)[0..1]
end
dependencies = dependencies.to_h
end
super(source, name, version, dependencies || {})
end
def install(dir)
@source.install(self, dir)
@install_dir = dir
end
def prepare
@source.prepare(self)
end
end
private
# Obtain a suitable temporary path for unpacking tarballs
#
# @return [String] path to temporary unpacking location
# rubocop:disable Naming/MemoizedInstanceVariableName
def tmpdir
@dir ||= Dir.mktmpdir('local-tarball', Puppet::Forge::Cache.base_path)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
def unpack(file, destination)
Puppet::ModuleTool::Applications::Unpacker.unpack(file, destination)
rescue Puppet::ExecutionFailure => e
raise RuntimeError, _("Could not extract contents of module archive: %{message}") % { message: e.message }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/install_directory.rb | lib/puppet/module_tool/install_directory.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/module_tool/errors'
module Puppet
module ModuleTool
# Control the install location for modules.
class InstallDirectory
include Puppet::ModuleTool::Errors
attr_reader :target
def initialize(target)
@target = target
end
# prepare the module install location. This will create the location if
# needed.
def prepare(module_name, version)
return if @target.directory?
begin
@target.mkpath
Puppet.notice _("Created target directory %{dir}") % { dir: @target }
rescue SystemCallError => orig_error
raise converted_to_friendly_error(module_name, version, orig_error)
end
end
private
ERROR_MAPPINGS = {
Errno::EACCES => PermissionDeniedCreateInstallDirectoryError,
Errno::EEXIST => InstallPathExistsNotDirectoryError,
}
def converted_to_friendly_error(module_name, version, orig_error)
return orig_error unless ERROR_MAPPINGS.include?(orig_error.class)
ERROR_MAPPINGS[orig_error.class].new(orig_error,
:requested_module => module_name,
:requested_version => version,
:directory => @target.to_s)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/dependency.rb | lib/puppet/module_tool/dependency.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/network/format_support'
module Puppet::ModuleTool
class Dependency
include Puppet::Network::FormatSupport
attr_reader :full_module_name, :username, :name, :version_requirement, :repository
# Instantiates a new module dependency with a +full_module_name+ (e.g.
# "myuser-mymodule"), and optional +version_requirement+ (e.g. "0.0.1") and
# optional repository (a URL string).
def initialize(full_module_name, version_requirement = nil, repository = nil)
@full_module_name = full_module_name
# TODO: add error checking, the next line raises ArgumentError when +full_module_name+ is invalid
@username, @name = Puppet::ModuleTool.username_and_modname_from(full_module_name)
@version_requirement = version_requirement
@repository = repository ? Puppet::Forge::Repository.new(repository, nil) : nil
end
# We override Object's ==, eql, and hash so we can more easily find identical
# dependencies.
def ==(o)
hash == o.hash
end
alias :eql? :==
def hash
[@full_module_name, @version_requirement, @repository].hash
end
def to_data_hash
result = { :name => @full_module_name }
result[:version_requirement] = @version_requirement if @version_requirement && !@version_requirement.nil?
result[:repository] = @repository.to_s if @repository && !@repository.nil?
result
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/metadata.rb | lib/puppet/module_tool/metadata.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/network/format_support'
require 'uri'
require_relative '../../puppet/util/json'
require 'set'
module Puppet::ModuleTool
# This class provides a data structure representing a module's metadata.
# @api private
class Metadata
include Puppet::Network::FormatSupport
attr_accessor :module_name
DEFAULTS = {
'name' => nil,
'version' => nil,
'author' => nil,
'summary' => nil,
'license' => 'Apache-2.0',
'source' => '',
'project_page' => nil,
'issues_url' => nil,
'dependencies' => Set.new.freeze,
'data_provider' => nil,
}
def initialize
@data = DEFAULTS.dup
@data['dependencies'] = @data['dependencies'].dup
end
# Returns a filesystem-friendly version of this module name.
def dashed_name
@data['name'].tr('/', '-') if @data['name']
end
# Returns a string that uniquely represents this version of this module.
def release_name
return nil unless @data['name'] && @data['version']
[dashed_name, @data['version']].join('-')
end
alias :name :module_name
alias :full_module_name :dashed_name
# Merges the current set of metadata with another metadata hash. This
# method also handles the validation of module names and versions, in an
# effort to be proactive about module publishing constraints.
def update(data)
process_name(data) if data['name']
process_version(data) if data['version']
process_source(data) if data['source']
process_data_provider(data) if data['data_provider']
merge_dependencies(data) if data['dependencies']
@data.merge!(data)
self
end
# Validates the name and version_requirement for a dependency, then creates
# the Dependency and adds it.
# Returns the Dependency that was added.
def add_dependency(name, version_requirement = nil, repository = nil)
validate_name(name)
validate_version_range(version_requirement) if version_requirement
dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement }
raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } if dup
dep = Dependency.new(name, version_requirement, repository)
@data['dependencies'].add(dep)
dep
end
# Provides an accessor for the now defunct 'description' property. This
# addresses a regression in Puppet 3.6.x where previously valid templates
# referring to the 'description' property were broken.
# @deprecated
def description
@data['description']
end
def dependencies
@data['dependencies'].to_a
end
# Returns a hash of the module's metadata. Used by Puppet's automated
# serialization routines.
#
# @see Puppet::Network::FormatSupport#to_data_hash
def to_hash
@data
end
alias :to_data_hash :to_hash
def to_json
data = @data.dup.merge('dependencies' => dependencies)
contents = data.keys.map do |k|
value = begin
Puppet::Util::Json.dump(data[k], :pretty => true)
rescue
data[k].to_json
end
%Q("#{k}": #{value})
end
"{\n" + contents.join(",\n").gsub(/^/, ' ') + "\n}\n"
end
# Expose any metadata keys as callable reader methods.
def method_missing(name, *args)
return @data[name.to_s] if @data.key? name.to_s
super
end
private
# Do basic validation and parsing of the name parameter.
def process_name(data)
validate_name(data['name'])
author, @module_name = data['name'].split(%r{[-/]}, 2)
data['author'] ||= author if @data['author'] == DEFAULTS['author']
end
# Do basic validation on the version parameter.
def process_version(data)
validate_version(data['version'])
end
def process_data_provider(data)
validate_data_provider(data['data_provider'])
end
# Do basic parsing of the source parameter. If the source is hosted on
# GitHub, we can predict sensible defaults for both project_page and
# issues_url.
def process_source(data)
if data['source'] =~ %r{://}
source_uri = URI.parse(data['source'])
else
source_uri = URI.parse("http://#{data['source']}")
end
if source_uri.host =~ /^(www\.)?github\.com$/
source_uri.scheme = 'https'
source_uri.path.sub!(/\.git$/, '')
data['project_page'] ||= @data['project_page'] || source_uri.to_s
data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(%r{/*$}, '') + '/issues'
end
rescue URI::Error
nil
end
# Validates and parses the dependencies.
def merge_dependencies(data)
data['dependencies'].each do |dep|
add_dependency(dep['name'], dep['version_requirement'], dep['repository'])
end
# Clear dependencies so @data dependencies are not overwritten
data.delete 'dependencies'
end
# Validates that the given module name is both namespaced and well-formed.
def validate_name(name)
return if name =~ %r{\A[a-z0-9]+[-/][a-z][a-z0-9_]*\Z}i
namespace, modname = name.split(%r{[-/]}, 2)
modname = :namespace_missing if namespace == ''
err = case modname
when nil, '', :namespace_missing
_("the field must be a namespaced module name")
when /[^a-z0-9_]/i
_("the module name contains non-alphanumeric (or underscore) characters")
when /^[^a-z]/i
_("the module name must begin with a letter")
else
_("the namespace contains non-alphanumeric characters")
end
raise ArgumentError, _("Invalid 'name' field in metadata.json: %{err}") % { err: err }
end
# Validates that the version string can be parsed as per SemVer.
def validate_version(version)
return if SemanticPuppet::Version.valid?(version)
err = _("version string cannot be parsed as a valid Semantic Version")
raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err }
end
# Validates that the given _value_ is a symbolic name that starts with a letter
# and then contains only letters, digits, or underscore. Will raise an ArgumentError
# if that's not the case.
#
# @param value [Object] The value to be tested
def validate_data_provider(value)
if value.is_a?(String)
unless value =~ /^[a-zA-Z][a-zA-Z0-9_]*$/
if value =~ /^[a-zA-Z]/
raise ArgumentError, _("field 'data_provider' contains non-alphanumeric characters")
else
raise ArgumentError, _("field 'data_provider' must begin with a letter")
end
end
else
raise ArgumentError, _("field 'data_provider' must be a string")
end
end
# Validates that the version range can be parsed by Semantic.
def validate_version_range(version_range)
SemanticPuppet::VersionRange.parse(version_range)
rescue ArgumentError => e
raise ArgumentError, _("Invalid 'version_range' field in metadata.json: %{err}") % { err: e }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/checksums.rb | lib/puppet/module_tool/checksums.rb | # frozen_string_literal: true
require 'digest/md5'
require_relative '../../puppet/network/format_support'
module Puppet::ModuleTool
# = Checksums
#
# This class provides methods for generating checksums for data and adding
# them to +Metadata+.
class Checksums
include Puppet::Network::FormatSupport
include Enumerable
# Instantiate object with string +path+ to create checksums from.
def initialize(path)
@path = Pathname.new(path)
end
# Return checksum for the +Pathname+.
def checksum(pathname)
Digest::MD5.hexdigest(Puppet::FileSystem.binread(pathname))
end
# Return checksums for object's +Pathname+, generate if it's needed.
# Result is a hash of path strings to checksum strings.
def data
unless @data
@data = {}
@path.find do |descendant|
if Puppet::ModuleTool.artifact?(descendant)
Find.prune
elsif descendant.file?
path = descendant.relative_path_from(@path)
@data[path.to_s] = checksum(descendant)
end
end
end
@data
end
alias :to_data_hash :data
alias :to_hash :data
# TODO: Why?
def each(&block)
data.each(&block)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors/upgrader.rb | lib/puppet/module_tool/errors/upgrader.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class UpgradeError < ModuleToolError
def initialize(msg)
@action = :upgrade
super
end
end
class VersionAlreadyInstalledError < UpgradeError
attr_reader :newer_versions
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@dependency_name = options[:dependency_name]
@newer_versions = options[:newer_versions]
@possible_culprits = options[:possible_culprits]
super _("Could not upgrade '%{module_name}'; more recent versions not found") % { module_name: @module_name }
end
def multiline
message = []
message << _("Could not upgrade module '%{module_name}' (%{version})") % { module_name: @module_name, version: vstring }
if @newer_versions.empty?
message << _(" The installed version is already the latest version matching %{version}") % { version: vstring }
else
message << _(" There are %{count} newer versions") % { count: @newer_versions.length }
message << _(" No combination of dependency upgrades would satisfy all dependencies")
unless @possible_culprits.empty?
message << _(" Dependencies will not be automatically upgraded across major versions")
message << _(" Upgrading one or more of these modules may permit the upgrade to succeed:")
@possible_culprits.each do |name|
message << " - #{name}"
end
end
end
# TRANSLATORS `puppet module upgrade --force` is a command line option that should not be translated
message << _(" Use `puppet module upgrade --force` to upgrade only this module")
message.join("\n")
end
end
class DowngradingUnsupportedError < UpgradeError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@conditions = options[:conditions]
@action = options[:action]
super _("Could not %{action} '%{module_name}' (%{version}); downgrades are not allowed") % { action: @action, module_name: @module_name, version: vstring }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
message << _(" Downgrading is not allowed.")
message.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors/base.rb | lib/puppet/module_tool/errors/base.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class ModuleToolError < Puppet::Error
def v(version)
(version || '???').to_s.sub(/^(?=\d)/, 'v')
end
def vstring
if @action == :upgrade
"#{v(@installed_version)} -> #{v(@requested_version)}"
else
v(@installed_version || @requested_version).to_s
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors/installer.rb | lib/puppet/module_tool/errors/installer.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class InstallError < ModuleToolError; end
class AlreadyInstalledError < InstallError
def initialize(options)
@module_name = options[:module_name]
@installed_version = v(options[:installed_version])
@requested_version = v(options[:requested_version])
@local_changes = options[:local_changes]
super _("'%{module_name}' (%{version}) requested; '%{module_name}' (%{installed_version}) already installed") % { module_name: @module_name, version: @requested_version, installed_version: @installed_version }
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @module_name, version: @requested_version }
message << _(" Module '%{module_name}' (%{installed_version}) is already installed") % { module_name: @module_name, installed_version: @installed_version }
message << _(" Installed module has had changes made locally") unless @local_changes.empty?
# TRANSLATORS `puppet module upgrade` is a command line and should not be translated
message << _(" Use `puppet module upgrade` to install a different version")
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to re-install only this module")
message.join("\n")
end
end
class MissingPackageError < InstallError
def initialize(options)
@requested_package = options[:requested_package]
@source = options[:source]
super _("Could not install '%{requested_package}'; no releases are available from %{source}") % { requested_package: @requested_package, source: @source }
end
def multiline
message = []
message << _("Could not install '%{requested_package}'") % { requested_package: @requested_package }
message << _(" No releases are available from %{source}") % { source: @source }
message << _(" Does '%{requested_package}' have at least one published release?") % { requested_package: @requested_package }
message.join("\n")
end
end
class InstallPathExistsNotDirectoryError < InstallError
def initialize(original, options)
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@directory = options[:directory]
super(_("'%{module_name}' (%{version}) requested; Path %{dir} is not a directory.") % { module_name: @requested_module, version: @requested_version, dir: @directory }, original)
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
message << _(" Path '%{directory}' exists but is not a directory.") % { directory: @directory }
# TRANSLATORS "mkdir -p '%{directory}'" is a command line example and should not be translated
message << _(" A potential solution is to rename the path and then \"mkdir -p '%{directory}'\"") % { directory: @directory }
message.join("\n")
end
end
class PermissionDeniedCreateInstallDirectoryError < InstallError
def initialize(original, options)
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@directory = options[:directory]
super(_("'%{module_name}' (%{version}) requested; Permission is denied to create %{dir}.") % { module_name: @requested_module, version: @requested_version, dir: @directory }, original)
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
message << _(" Permission is denied when trying to create directory '%{directory}'.") % { directory: @directory }
message << _(' A potential solution is to check the ownership and permissions of parent directories.')
message.join("\n")
end
end
class InvalidPathInPackageError < InstallError
def initialize(options)
@entry_path = options[:entry_path]
@directory = options[:directory]
super _("Attempt to install file with an invalid path into %{path} under %{dir}") % { path: @entry_path.inspect, dir: @directory.inspect }
end
def multiline
message = []
message << _('Could not install package with an invalid path.')
message << _(' Package attempted to install file into %{path} under %{directory}.') % { path: @entry_path.inspect, directory: @directory.inspect }
message.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors/shared.rb | lib/puppet/module_tool/errors/shared.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class NoVersionsSatisfyError < ModuleToolError
def initialize(options)
@requested_name = options[:requested_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@conditions = options[:conditions]
@action = options[:action]
@unsatisfied = options[:unsatisfied]
super _("Could not %{action} '%{module_name}' (%{version}); no version satisfies all dependencies") % { action: @action, module_name: @requested_name, version: vstring }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @requested_name, version: vstring }
if @unsatisfied
message << _(" The requested version cannot satisfy one or more of the following installed modules:")
if @unsatisfied[:current_version]
message << _(" %{name}, installed: %{current_version}, expected: %{constraints}") % { name: @unsatisfied[:name], current_version: @unsatisfied[:current_version], constraints: @unsatisfied[:constraints][@unsatisfied[:name]] }
else
@unsatisfied[:constraints].each do |mod, range|
message << _(" %{mod}, expects '%{name}': %{range}") % { mod: mod, name: @requested_name, range: range }
end
end
message << _("")
else
message << _(" The requested version cannot satisfy all dependencies")
end
# TRANSLATORS `puppet module %{action} --ignore-dependencies` is a command line and should not be translated
message << _(" Use `puppet module %{action} '%{module_name}' --ignore-dependencies` to %{action} only this module") % { action: @action, module_name: @requested_name }
message.join("\n")
end
end
class NoCandidateReleasesError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@source = options[:source]
@action = options[:action]
if @requested_version == :latest
super _("Could not %{action} '%{module_name}'; no releases are available from %{source}") % { action: @action, module_name: @module_name, source: @source }
else
super _("Could not %{action} '%{module_name}'; no releases matching '%{version}' are available from %{source}") % { action: @action, module_name: @module_name, version: @requested_version, source: @source }
end
end
def multiline
message = []
message << _("Could not %{action} '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
if @requested_version == :latest
message << _(" No releases are available from %{source}") % { source: @source }
message << _(" Does '%{module_name}' have at least one published release?") % { module_name: @module_name }
else
message << _(" No releases matching '%{requested_version}' are available from %{source}") % { requested_version: @requested_version, source: @source }
end
message.join("\n")
end
end
class InstallConflictError < ModuleToolError
def initialize(options)
@requested_module = options[:requested_module]
@requested_version = v(options[:requested_version])
@dependency = options[:dependency]
@directory = options[:directory]
@metadata = options[:metadata]
super _("'%{module_name}' (%{version}) requested; installation conflict") % { module_name: @requested_module, version: @requested_version }
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
if @dependency
message << _(" Dependency '%{name}' (%{version}) would overwrite %{directory}") % { name: @dependency[:name], version: v(@dependency[:version]), directory: @directory }
else
message << _(" Installation would overwrite %{directory}") % { directory: @directory }
end
if @metadata
message << _(" Currently, '%{current_name}' (%{current_version}) is installed to that directory") % { current_name: @metadata["name"], current_version: v(@metadata["version"]) }
end
if @dependency
# TRANSLATORS `puppet module install --ignore-dependencies` is a command line and should not be translated
message << _(" Use `puppet module install --ignore-dependencies` to install only this module")
else
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to install this module anyway")
end
message.join("\n")
end
end
class InvalidDependencyCycleError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@conditions = options[:conditions]
@source = options[:source][1..]
super _("'%{module_name}' (%{version}) requested; Invalid dependency cycle") % { module_name: @requested_module, version: v(@requested_version) }
end
def multiline
dependency_list = []
dependency_list << _("You specified '%{name}' (%{version})") % { name: @source.first[:name], version: v(@requested_version) }
dependency_list += @source[1..].map do |m|
# TRANSLATORS This message repeats as separate lines as a list under the heading "You specified '%{name}' (%{version})\n"
_("This depends on '%{name}' (%{version})") % { name: m[:name], version: v(m[:version]) }
end
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: v(@requested_version) }
message << _(" No version of '%{module_name}' will satisfy dependencies") % { module_name: @module_name }
message << dependency_list.map { |s| " #{s}".join(",\n") }
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to install this module anyway")
message.join("\n")
end
end
class InvalidModuleNameError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@suggestion = options[:suggestion]
@action = options[:action]
super _("Could not %{action} '%{module_name}', did you mean '%{suggestion}'?") % { action: @action, module_name: @module_name, suggestion: @suggestion }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" The name '%{module_name}' is invalid") % { module_name: @module_name }
message << _(" Did you mean `puppet module %{action} %{suggestion}`?") % { action: @action, suggestion: @suggestion }
message.join("\n")
end
end
class NotInstalledError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@suggestions = options[:suggestions] || []
@action = options[:action]
super _("Could not %{action} '%{module_name}'; module is not installed") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" Module '%{module_name}' is not installed") % { module_name: @module_name }
message += @suggestions.map do |suggestion|
# TRANSLATORS `puppet module %{action} %{suggestion}` is a command line and should not be translated
_(" You may have meant `puppet module %{action} %{suggestion}`") % { action: @action, suggestion: suggestion }
end
# TRANSLATORS `puppet module install` is a command line and should not be translated
message << _(" Use `puppet module install` to install this module") if @action == :upgrade
message.join("\n")
end
end
class MultipleInstalledError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@modules = options[:installed_modules]
@action = options[:action]
# TRANSLATORS "module path" refers to a set of directories where modules may be installed
super _("Could not %{action} '%{module_name}'; module appears in multiple places in the module path") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" Module '%{module_name}' appears multiple places in the module path") % { module_name: @module_name }
message += @modules.map do |mod|
# TRANSLATORS This is repeats as separate lines as a list under "Module '%{module_name}' appears multiple places in the module path"
_(" '%{module_name}' (%{version}) was found in %{path}") % { module_name: @module_name, version: v(mod.version), path: mod.modulepath }
end
# TRANSLATORS `--modulepath` is command line option and should not be translated
message << _(" Use the `--modulepath` option to limit the search to specific directories")
message.join("\n")
end
end
class LocalChangesError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@action = options[:action]
super _("Could not %{action} '%{module_name}'; module has had changes made locally") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
message << _(" Installed module has had changes made locally")
# TRANSLATORS `puppet module %{action} --ignore-changes` is a command line and should not be translated
message << _(" Use `puppet module %{action} --ignore-changes` to %{action} this module anyway") % { action: @action }
message.join("\n")
end
end
class InvalidModuleError < ModuleToolError
def initialize(name, options)
@name = name
@action = options[:action]
@error = options[:error]
super _("Could not %{action} '%{module_name}'; %{error}") % { action: @action, module_name: @name, error: @error.message }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @name }
message << _(" Failure trying to parse metadata")
message << _(" Original message was: %{message}") % { message: @error.message }
message.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/errors/uninstaller.rb | lib/puppet/module_tool/errors/uninstaller.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class UninstallError < ModuleToolError; end
class NoVersionMatchesError < UninstallError
def initialize(options)
@module_name = options[:module_name]
@modules = options[:installed_modules]
@version = options[:version_range]
super _("Could not uninstall '%{module_name}'; no installed version matches") % { module_name: @module_name }
end
def multiline
message = []
message << _("Could not uninstall module '%{module_name}' (%{version})") % { module_name: @module_name, version: v(@version) }
message << _(" No installed version of '%{module_name}' matches (%{version})") % { module_name: @module_name, version: v(@version) }
message += @modules.map do |mod|
_(" '%{module_name}' (%{version}) is installed in %{path}") % { module_name: mod[:name], version: v(mod[:version]), path: mod[:path] }
end
message.join("\n")
end
end
class ModuleIsRequiredError < UninstallError
def initialize(options)
@module_name = options[:module_name]
@required_by = options[:required_by]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
super _("Could not uninstall '%{module_name}'; installed modules still depend upon it") % { module_name: @module_name }
end
def multiline
message = []
if @requested_version
message << _("Could not uninstall module '%{module_name}' (v%{requested_version})") % { module_name: @module_name, requested_version: @requested_version }
else
message << _("Could not uninstall module '%{module_name}'") % { module_name: @module_name }
end
message << _(" Other installed modules have dependencies on '%{module_name}' (%{version})") % { module_name: @module_name, version: v(@installed_version) }
message += @required_by.map do |mod|
_(" '%{module_name}' (%{version}) requires '%{module_dep}' (%{dep_version})") % { module_name: mod['name'], version: v(mod['version']), module_dep: @module_name, dep_version: v(mod['version_requirement']) }
end
# TRANSLATORS `puppet module uninstall --force` is a command line option that should not be translated
message << _(" Use `puppet module uninstall --force` to uninstall this module anyway")
message.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/tar/gnu.rb | lib/puppet/module_tool/tar/gnu.rb | # frozen_string_literal: true
require 'shellwords'
class Puppet::ModuleTool::Tar::Gnu
def unpack(sourcefile, destdir, owner)
safe_sourcefile = Shellwords.shellescape(File.expand_path(sourcefile))
destdir = File.expand_path(destdir)
safe_destdir = Shellwords.shellescape(destdir)
Puppet::Util::Execution.execute("gzip -dc #{safe_sourcefile} | tar --extract --no-same-owner --directory #{safe_destdir} --file -")
Puppet::Util::Execution.execute(['find', destdir, '-type', 'd', '-exec', 'chmod', '755', '{}', '+'])
Puppet::Util::Execution.execute(['find', destdir, '-type', 'f', '-exec', 'chmod', 'u+rw,g+r,a-st', '{}', '+'])
Puppet::Util::Execution.execute(['chown', '-R', owner, destdir])
end
def pack(sourcedir, destfile)
safe_sourcedir = Shellwords.shellescape(sourcedir)
safe_destfile = Shellwords.shellescape(File.basename(destfile))
Puppet::Util::Execution.execute("tar cf - #{safe_sourcedir} | gzip -c > #{safe_destfile}")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/tar/mini.rb | lib/puppet/module_tool/tar/mini.rb | # frozen_string_literal: true
class Puppet::ModuleTool::Tar::Mini
def unpack(sourcefile, destdir, _)
Zlib::GzipReader.open(sourcefile) do |reader|
args = [reader, destdir, find_valid_files(reader)]
# With minitar >= 0.9, we can prevent minitar from fsync'ing
# each extracted file and directory
args << { :fsync => false }
Minitar.unpack(*args) do |action, name, stats|
case action
when :dir
validate_entry(destdir, name)
set_dir_mode!(stats)
Puppet.debug("Extracting: #{destdir}/#{name}")
when :file_start
# Octal string of the old file mode.
validate_entry(destdir, name)
set_file_mode!(stats)
Puppet.debug("Extracting: #{destdir}/#{name}")
end
set_default_user_and_group!(stats)
stats
end
end
end
def pack(sourcedir, destfile)
Zlib::GzipWriter.open(destfile) do |writer|
Minitar.pack(sourcedir, writer) do |step, name, stats|
# TODO smcclellan 2017-10-31 Set permissions here when this yield block
# executes before the header is written. As it stands, the `stats`
# argument isn't mutable in a way that will effect the desired mode for
# the file.
end
end
end
private
EXECUTABLE = 0o755
NOT_EXECUTABLE = 0o644
USER_EXECUTE = 0o100
def set_dir_mode!(stats)
if stats.key?(:mode)
# This is only the case for `pack`, so this code will not run.
stats[:mode] = EXECUTABLE
elsif stats.key?(:entry)
old_mode = stats[:entry].instance_variable_get(:@mode)
if old_mode.is_a?(Integer)
stats[:entry].instance_variable_set(:@mode, EXECUTABLE)
end
end
end
# Sets a file mode to 0755 if the file is executable by the user.
# Sets a file mode to 0644 if the file mode is set (non-Windows).
def sanitized_mode(old_mode)
old_mode & USER_EXECUTE != 0 ? EXECUTABLE : NOT_EXECUTABLE
end
def set_file_mode!(stats)
if stats.key?(:mode)
# This is only the case for `pack`, so this code will not run.
stats[:mode] = sanitized_mode(stats[:mode])
elsif stats.key?(:entry)
old_mode = stats[:entry].instance_variable_get(:@mode)
# If the user can execute the file, set 0755, otherwise 0644.
if old_mode.is_a?(Integer)
new_mode = sanitized_mode(old_mode)
stats[:entry].instance_variable_set(:@mode, new_mode)
end
end
end
# Sets UID and GID to 0 for standardization.
def set_default_user_and_group!(stats)
stats[:uid] = 0
stats[:gid] = 0
end
# Find all the valid files in tarfile.
#
# This check was mainly added to ignore 'x' and 'g' flags from the PAX
# standard but will also ignore any other non-standard tar flags.
# tar format info: https://pic.dhe.ibm.com/infocenter/zos/v1r13/index.jsp?topic=%2Fcom.ibm.zos.r13.bpxa500%2Ftaf.htm
# pax format info: https://pic.dhe.ibm.com/infocenter/zos/v1r13/index.jsp?topic=%2Fcom.ibm.zos.r13.bpxa500%2Fpxarchfm.htm
def find_valid_files(tarfile)
Minitar.open(tarfile).collect do |entry|
flag = entry.typeflag
if flag.nil? || flag =~ /[[:digit:]]/ && (0..7).cover?(flag.to_i)
entry.full_name
else
Puppet.debug "Invalid tar flag '#{flag}' will not be extracted: #{entry.name}"
next
end
end
end
def validate_entry(destdir, path)
if Pathname.new(path).absolute?
raise Puppet::ModuleTool::Errors::InvalidPathInPackageError, :entry_path => path, :directory => destdir
end
path = Pathname.new(File.join(destdir, path)).cleanpath.to_path
if path !~ /\A#{Regexp.escape destdir}/
raise Puppet::ModuleTool::Errors::InvalidPathInPackageError, :entry_path => path, :directory => destdir
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/application.rb | lib/puppet/module_tool/applications/application.rb | # frozen_string_literal: true
require 'net/http'
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/util/colors'
module Puppet::ModuleTool
module Applications
class Application
include Puppet::Util::Colors
def self.run(*args)
new(*args).run
end
attr_accessor :options
def initialize(options = {})
@options = options
end
def run
raise NotImplementedError, "Should be implemented in child classes."
end
def discuss(response, success, failure)
case response
when Net::HTTPOK, Net::HTTPCreated
Puppet.notice success
else
errors = begin
Puppet::Util::Json.load(response.body)['error']
rescue
"HTTP #{response.code}, #{response.body}"
end
Puppet.warning "#{failure} (#{errors})"
end
end
def metadata(require_metadata = false)
return @metadata if @metadata
@metadata = Puppet::ModuleTool::Metadata.new
unless @path
raise ArgumentError, _("Could not determine module path")
end
if require_metadata && !Puppet::ModuleTool.is_module_root?(@path)
raise ArgumentError, _("Unable to find metadata.json in module root at %{path} See https://puppet.com/docs/puppet/latest/modules_publishing.html for required file format.") % { path: @path }
end
metadata_path = File.join(@path, 'metadata.json')
if File.file?(metadata_path)
File.open(metadata_path) do |f|
@metadata.update(Puppet::Util::Json.load(f))
rescue Puppet::Util::Json::ParseError => ex
raise ArgumentError, _("Could not parse JSON %{metadata_path}") % { metadata_path: metadata_path }, ex.backtrace
end
end
if File.file?(File.join(@path, 'Modulefile'))
Puppet.warning _("A Modulefile was found in the root directory of the module. This file will be ignored and can safely be removed.")
end
@metadata
end
def load_metadata!
@metadata = nil
metadata(true)
end
def parse_filename(filename)
match = /^((.*?)-(.*?))-(\d+\.\d+\.\d+.*?)$/.match(File.basename(filename, '.tar.gz'))
if match
module_name, author, shortname, version = match.captures
else
raise ArgumentError, _("Could not parse filename to obtain the username, module name and version. (%{release_name})") % { release_name: @release_name }
end
unless SemanticPuppet::Version.valid?(version)
raise ArgumentError, _("Invalid version format: %{version} (Semantic Versions are acceptable: http://semver.org)") % { version: version }
end
{
:module_name => module_name,
:author => author,
:dir_name => shortname,
:version => version
}
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/checksummer.rb | lib/puppet/module_tool/applications/checksummer.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/module_tool/checksums'
module Puppet::ModuleTool
module Applications
class Checksummer < Application
def initialize(path, options = {})
@path = Pathname.new(path)
super(options)
end
def run
changes = []
sums = Puppet::ModuleTool::Checksums.new(@path)
checksums.each do |child_path, canonical_checksum|
# Avoid checksumming the checksums.json file
next if File.basename(child_path) == "checksums.json"
path = @path + child_path
unless path.exist? && canonical_checksum == sums.checksum(path)
changes << child_path
end
end
# Return an Array of strings representing file paths of files that have
# been modified since this module was installed. All paths are relative
# to the installed module directory. This return value is used by the
# module_tool face changes action, and displayed on the console.
#
# Example return value:
#
# [ "REVISION", "manifests/init.pp"]
#
changes
end
private
def checksums
if checksums_file.exist?
Puppet::Util::Json.load(checksums_file.read)
elsif metadata_file.exist?
# Check metadata.json too; legacy modules store their checksums there.
Puppet::Util::Json.load(metadata_file.read)['checksums'] or
raise ArgumentError, _("No file containing checksums found.")
else
raise ArgumentError, _("No file containing checksums found.")
end
end
def metadata_file
@path + 'metadata.json'
end
def checksums_file
@path + 'checksums.json'
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/upgrader.rb | lib/puppet/module_tool/applications/upgrader.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../../puppet/forge'
require_relative '../../../puppet/module_tool'
require_relative '../../../puppet/module_tool/shared_behaviors'
require_relative '../../../puppet/module_tool/install_directory'
require_relative '../../../puppet/module_tool/installed_modules'
module Puppet::ModuleTool
module Applications
class Upgrader < Application
include Puppet::ModuleTool::Errors
def initialize(name, options)
super(options)
@action = :upgrade
@environment = options[:environment_instance]
@name = name
@ignore_changes = forced? || options[:ignore_changes]
@ignore_dependencies = forced? || options[:ignore_dependencies]
SemanticPuppet::Dependency.add_source(installed_modules_source)
SemanticPuppet::Dependency.add_source(module_repository)
end
def run
# Disallow anything that invokes md5 to avoid un-friendly termination due to FIPS
raise _("Module upgrade is prohibited in FIPS mode.") if Puppet.runtime[:facter].value(:fips_enabled)
name = @name.tr('/', '-')
version = options[:version] || '>= 0.0.0'
results = {
:action => :upgrade,
:requested_version => options[:version] || :latest,
}
begin
all_modules = @environment.modules_by_path.values.flatten
matching_modules = all_modules.select do |x|
x.forge_name && x.forge_name.tr('/', '-') == name
end
if matching_modules.empty?
raise NotInstalledError, results.merge(:module_name => name)
elsif matching_modules.length > 1
raise MultipleInstalledError, results.merge(:module_name => name, :installed_modules => matching_modules)
end
installed_release = installed_modules[name]
# `priority` is an attribute of a `SemanticPuppet::Dependency::Source`,
# which is delegated through `ModuleRelease` instances for the sake of
# comparison (sorting). By default, the `InstalledModules` source has
# a priority of 10 (making it the most preferable source, so that
# already installed versions of modules are selected in preference to
# modules from e.g. the Forge). Since we are specifically looking to
# upgrade this module, we don't want the installed version of this
# module to be chosen in preference to those with higher versions.
#
# This implementation is suboptimal, and since we can expect this sort
# of behavior to be reasonably common in Semantic, we should probably
# see about implementing a `ModuleRelease#override_priority` method
# (or something similar).
def installed_release.priority
0
end
mod = installed_release.mod
results[:installed_version] = SemanticPuppet::Version.parse(mod.version)
dir = Pathname.new(mod.modulepath)
vstring = mod.version ? "v#{mod.version}" : '???'
Puppet.notice _("Found '%{name}' (%{version}) in %{dir} ...") % { name: name, version: colorize(:cyan, vstring), dir: dir }
unless @ignore_changes
changes = begin
Checksummer.run(mod.path)
rescue
[]
end
if mod.has_metadata? && !changes.empty?
raise LocalChangesError,
:action => :upgrade,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => mod.version
end
end
Puppet::Forge::Cache.clean
# Ensure that there is at least one candidate release available
# for the target package.
available_versions = module_repository.fetch(name)
if available_versions.empty?
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
elsif results[:requested_version] != :latest
requested = Puppet::Module.parse_range(results[:requested_version])
unless available_versions.any? { |m| requested.include? m.version }
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
end
end
Puppet.notice _("Downloading from %{host} ...") % { host: module_repository.host }
if @ignore_dependencies
graph = build_single_module_graph(name, version)
else
graph = build_dependency_graph(name, version)
end
unless forced?
add_module_name_constraints_to_graph(graph)
end
installed_modules.each do |installed_module, release|
installed_module = installed_module.tr('/', '-')
next if installed_module == name
version = release.version
next if forced?
# Since upgrading already installed modules can be troublesome,
# we'll place constraints on the graph for each installed
# module, locking it to upgrades within the same major version.
installed_range = ">=#{version} #{version.major}.x"
graph.add_constraint('installed', installed_module, installed_range) do |node|
Puppet::Module.parse_range(installed_range).include? node.version
end
release.mod.dependencies.each do |dep|
dep_name = dep['name'].tr('/', '-')
range = dep['version_requirement']
graph.add_constraint("#{installed_module} constraint", dep_name, range) do |node|
Puppet::Module.parse_range(range).include? node.version
end
end
end
begin
Puppet.info _("Resolving dependencies ...")
releases = SemanticPuppet::Dependency.resolve(graph)
rescue SemanticPuppet::Dependency::UnsatisfiableGraph
raise NoVersionsSatisfyError, results.merge(:requested_name => name)
end
releases.each do |rel|
mod = installed_modules_source.by_name[rel.name.split('-').last]
next unless mod
next if mod.has_metadata? && mod.forge_name.tr('/', '-') == rel.name
if rel.name != name
dependency = {
:name => rel.name,
:version => rel.version
}
end
raise InstallConflictError,
:requested_module => name,
:requested_version => options[:version] || 'latest',
:dependency => dependency,
:directory => mod.path,
:metadata => mod.metadata
end
child = releases.find { |x| x.name == name }
unless forced?
if child.version == results[:installed_version]
versions = graph.dependencies[name].map(&:version)
newer_versions = versions.select { |v| v > results[:installed_version] }
raise VersionAlreadyInstalledError,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => results[:installed_version],
:newer_versions => newer_versions,
:possible_culprits => installed_modules_source.fetched.reject { |x| x == name }
elsif child.version < results[:installed_version]
raise DowngradingUnsupportedError,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => results[:installed_version]
end
end
Puppet.info _("Preparing to upgrade ...")
releases.each(&:prepare)
Puppet.notice _('Upgrading -- do not interrupt ...')
releases.each do |release|
installed = installed_modules[release.name]
if installed
release.install(Pathname.new(installed.mod.modulepath))
else
release.install(dir)
end
end
results[:result] = :success
results[:base_dir] = releases.first.install_dir
results[:affected_modules] = releases
results[:graph] = [build_install_graph(releases.first, releases)]
rescue VersionAlreadyInstalledError => e
results[:result] = (e.newer_versions.empty? ? :noop : :failure)
results[:error] = { :oneline => e.message, :multiline => e.multiline }
rescue => e
results[:error] = {
:oneline => e.message,
:multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
}
ensure
results[:result] ||= :failure
end
results
end
private
# rubocop:disable Naming/MemoizedInstanceVariableName
def module_repository
@repo ||= Puppet::Forge.new(Puppet[:module_repository])
end
def installed_modules_source
@installed ||= Puppet::ModuleTool::InstalledModules.new(@environment)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
def installed_modules
installed_modules_source.modules
end
def build_single_module_graph(name, version)
range = Puppet::Module.parse_range(version)
graph = SemanticPuppet::Dependency::Graph.new(name => range)
releases = SemanticPuppet::Dependency.fetch_releases(name)
releases.each { |release| release.dependencies.clear }
graph << releases
end
def build_dependency_graph(name, version)
SemanticPuppet::Dependency.query(name => version)
end
def build_install_graph(release, installed, graphed = [])
previous = installed_modules[release.name]
previous = previous.version if previous
action = :upgrade
unless previous && previous != release.version
action = :install
end
graphed << release
dependencies = release.dependencies.values.filter_map do |deps|
dep = (deps & installed).first
if dep == installed_modules[dep.name]
next
end
if dep && !graphed.include?(dep)
build_install_graph(dep, installed, graphed)
end
end
{
:release => release,
:name => release.name,
:path => release.install_dir,
:dependencies => dependencies.compact,
:version => release.version,
:previous_version => previous,
:action => action,
}
end
include Puppet::ModuleTool::Shared
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/installer.rb | lib/puppet/module_tool/applications/installer.rb | # frozen_string_literal: true
require 'open-uri'
require 'pathname'
require 'fileutils'
require 'tmpdir'
require_relative '../../../puppet/forge'
require_relative '../../../puppet/module_tool'
require_relative '../../../puppet/module_tool/shared_behaviors'
require_relative '../../../puppet/module_tool/install_directory'
require_relative '../../../puppet/module_tool/local_tarball'
require_relative '../../../puppet/module_tool/installed_modules'
require_relative '../../../puppet/network/uri'
module Puppet::ModuleTool
module Applications
class Installer < Application
include Puppet::ModuleTool::Errors
include Puppet::Forge::Errors
include Puppet::Network::Uri
def initialize(name, install_dir, options = {})
super(options)
@action = :install
@environment = options[:environment_instance]
@ignore_dependencies = forced? || options[:ignore_dependencies]
@name = name
@install_dir = install_dir
Puppet::Forge::Cache.clean
@local_tarball = Puppet::FileSystem.exist?(name)
if @local_tarball
release = local_tarball_source.release
@name = release.name
options[:version] = release.version.to_s
SemanticPuppet::Dependency.add_source(local_tarball_source)
# If we're operating on a local tarball and ignoring dependencies, we
# don't need to search any additional sources. This will cut down on
# unnecessary network traffic.
unless @ignore_dependencies
SemanticPuppet::Dependency.add_source(installed_modules_source)
SemanticPuppet::Dependency.add_source(module_repository)
end
else
SemanticPuppet::Dependency.add_source(installed_modules_source) unless forced?
SemanticPuppet::Dependency.add_source(module_repository)
end
end
def run
name = @name.tr('/', '-')
version = options[:version] || '>= 0.0.0'
results = { :action => :install, :module_name => name, :module_version => version }
begin
if !@local_tarball && name !~ /-/
raise InvalidModuleNameError.new(module_name: @name, suggestion: "puppetlabs-#{@name}", action: :install)
end
installed_module = installed_modules[name]
if installed_module
unless forced?
if Puppet::Module.parse_range(version).include? installed_module.version
results[:result] = :noop
results[:version] = installed_module.version
return results
else
changes = begin
Checksummer.run(installed_modules[name].mod.path)
rescue
[]
end
raise AlreadyInstalledError,
:module_name => name,
:installed_version => installed_modules[name].version,
:requested_version => options[:version] || :latest,
:local_changes => changes
end
end
end
@install_dir.prepare(name, options[:version] || 'latest')
results[:install_dir] = @install_dir.target
unless @local_tarball && @ignore_dependencies
Puppet.notice _("Downloading from %{host} ...") % {
host: mask_credentials(module_repository.host)
}
end
if @ignore_dependencies
graph = build_single_module_graph(name, version)
else
graph = build_dependency_graph(name, version)
end
unless forced?
add_module_name_constraints_to_graph(graph)
end
installed_modules.each do |mod, release|
mod = mod.tr('/', '-')
next if mod == name
version = release.version
next if forced?
# Since upgrading already installed modules can be troublesome,
# we'll place constraints on the graph for each installed module,
# locking it to upgrades within the same major version.
installed_range = ">=#{version} #{version.major}.x"
graph.add_constraint('installed', mod, installed_range) do |node|
Puppet::Module.parse_range(installed_range).include? node.version
end
release.mod.dependencies.each do |dep|
dep_name = dep['name'].tr('/', '-')
range = dep['version_requirement']
graph.add_constraint("#{mod} constraint", dep_name, range) do |node|
Puppet::Module.parse_range(range).include? node.version
end
end
end
# Ensure that there is at least one candidate release available
# for the target package.
if graph.dependencies[name].empty?
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host, :requested_version => options[:version] || :latest)
end
begin
Puppet.info _("Resolving dependencies ...")
releases = SemanticPuppet::Dependency.resolve(graph)
rescue SemanticPuppet::Dependency::UnsatisfiableGraph => e
unsatisfied = nil
if e.respond_to?(:unsatisfied) && e.unsatisfied
constraints = {}
# If the module we're installing satisfies all its
# dependencies, but would break an already installed
# module that depends on it, show what would break.
if name == e.unsatisfied
graph.constraints[name].each do |mod, range, _|
next unless mod.split.include?('constraint')
# If the user requested a specific version or range,
# only show the modules with non-intersecting ranges
if options[:version]
requested_range = SemanticPuppet::VersionRange.parse(options[:version])
constraint_range = SemanticPuppet::VersionRange.parse(range)
if requested_range.intersection(constraint_range) == SemanticPuppet::VersionRange::EMPTY_RANGE
constraints[mod.split.first] = range
end
else
constraints[mod.split.first] = range
end
end
# If the module fails to satisfy one of its
# dependencies, show the unsatisfiable module
else
dep_constraints = graph.dependencies[name].max.constraints
if dep_constraints.key?(e.unsatisfied)
unsatisfied_range = dep_constraints[e.unsatisfied].first[1]
constraints[e.unsatisfied] = unsatisfied_range
end
end
installed_module = @environment.module_by_forge_name(e.unsatisfied.tr('-', '/'))
current_version = installed_module.version if installed_module
unsatisfied = {
:name => e.unsatisfied,
:constraints => constraints,
:current_version => current_version
} if constraints.any?
end
raise NoVersionsSatisfyError, results.merge(
:requested_name => name,
:requested_version => options[:version] || graph.dependencies[name].max.version.to_s,
:unsatisfied => unsatisfied
)
end
unless forced?
# Check for module name conflicts.
releases.each do |rel|
installed_module = installed_modules_source.by_name[rel.name.split('-').last]
next unless installed_module
next if installed_module.has_metadata? && installed_module.forge_name.tr('/', '-') == rel.name
if rel.name != name
dependency = {
:name => rel.name,
:version => rel.version
}
end
raise InstallConflictError,
:requested_module => name,
:requested_version => options[:version] || 'latest',
:dependency => dependency,
:directory => installed_module.path,
:metadata => installed_module.metadata
end
end
Puppet.info _("Preparing to install ...")
releases.each(&:prepare)
Puppet.notice _('Installing -- do not interrupt ...')
releases.each do |release|
installed = installed_modules[release.name]
if forced? || installed.nil?
release.install(Pathname.new(results[:install_dir]))
else
release.install(Pathname.new(installed.mod.modulepath))
end
end
results[:result] = :success
results[:installed_modules] = releases
results[:graph] = [build_install_graph(releases.first, releases)]
rescue ModuleToolError, ForgeError => err
results[:error] = {
:oneline => err.message,
:multiline => err.multiline,
}
ensure
results[:result] ||= :failure
end
results
end
private
def module_repository
@repo ||= Puppet::Forge.new(Puppet[:module_repository])
end
def local_tarball_source
@tarball_source ||= begin
Puppet::ModuleTool::LocalTarball.new(@name)
rescue Puppet::Module::Error => e
raise InvalidModuleError.new(@name, :action => @action, :error => e)
end
end
def installed_modules_source
@installed ||= Puppet::ModuleTool::InstalledModules.new(@environment)
end
def installed_modules
installed_modules_source.modules
end
def build_single_module_graph(name, version)
range = Puppet::Module.parse_range(version)
graph = SemanticPuppet::Dependency::Graph.new(name => range)
releases = SemanticPuppet::Dependency.fetch_releases(name)
releases.each { |release| release.dependencies.clear }
graph << releases
end
def build_dependency_graph(name, version)
SemanticPuppet::Dependency.query(name => version)
end
def build_install_graph(release, installed, graphed = [])
graphed << release
dependencies = release.dependencies.values.map do |deps|
dep = (deps & installed).first
unless dep.nil? || graphed.include?(dep)
build_install_graph(dep, installed, graphed)
end
end
previous = installed_modules[release.name]
previous = previous.version if previous
{
:release => release,
:name => release.name,
:path => release.install_dir.to_s,
:dependencies => dependencies.compact,
:version => release.version,
:previous_version => previous,
:action => (previous.nil? || previous == release.version || forced? ? :install : :upgrade),
}
end
include Puppet::ModuleTool::Shared
# Return a Pathname object representing the path to the module
# release package in the `Puppet.settings[:module_working_dir]`.
def get_release_packages
get_local_constraints
if !forced? && @installed.include?(@module_name)
raise AlreadyInstalledError,
:module_name => @module_name,
:installed_version => @installed[@module_name].first.version,
:requested_version => @version || (@conditions[@module_name].empty? ? :latest : :best),
:local_changes => Puppet::ModuleTool::Applications::Checksummer.run(@installed[@module_name].first.path)
end
if @ignore_dependencies && @source == :filesystem
@urls = {}
@remote = { "#{@module_name}@#{@version}" => {} }
@versions = {
@module_name => [
{ :vstring => @version, :semver => SemanticPuppet::Version.parse(@version) }
]
}
else
get_remote_constraints(@forge)
end
@graph = resolve_constraints({ @module_name => @version })
@graph.first[:tarball] = @filename if @source == :filesystem
resolve_install_conflicts(@graph) unless forced?
# This clean call means we never "cache" the module we're installing, but this
# is desired since module authors can easily rerelease modules different content but the same
# version number, meaning someone with the old content cached will be very confused as to why
# they can't get new content.
# Long term we should just get rid of this caching behavior and cleanup downloaded modules after they install
# but for now this is a quick fix to disable caching
Puppet::Forge::Cache.clean
download_tarballs(@graph, @graph.last[:path], @forge)
end
#
# Resolve installation conflicts by checking if the requested module
# or one of its dependencies conflicts with an installed module.
#
# Conflicts occur under the following conditions:
#
# When installing 'puppetlabs-foo' and an existing directory in the
# target install path contains a 'foo' directory and we cannot determine
# the "full name" of the installed module.
#
# When installing 'puppetlabs-foo' and 'pete-foo' is already installed.
# This is considered a conflict because 'puppetlabs-foo' and 'pete-foo'
# install into the same directory 'foo'.
#
def resolve_install_conflicts(graph, is_dependency = false)
Puppet.debug("Resolving conflicts for #{graph.map { |n| n[:module] }.join(',')}")
graph.each do |release|
@environment.modules_by_path[options[:target_dir]].each do |mod|
if mod.has_metadata?
metadata = {
:name => mod.forge_name.tr('/', '-'),
:version => mod.version
}
next if release[:module] == metadata[:name]
else
metadata = nil
end
next unless release[:module] =~ /-#{mod.name}$/
dependency_info = {
:name => release[:module],
:version => release[:version][:vstring]
}
dependency = is_dependency ? dependency_info : nil
all_versions = @versions[@module_name.to_s].sort_by { |h| h[:semver] }
versions = all_versions.select { |x| x[:semver].special == '' }
versions = all_versions if versions.empty?
latest_version = versions.last[:vstring]
raise InstallConflictError,
:requested_module => @module_name,
:requested_version => @version || "latest: v#{latest_version}",
:dependency => dependency,
:directory => mod.path,
:metadata => metadata
end
deps = release[:dependencies]
if deps && !deps.empty?
resolve_install_conflicts(deps, true)
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/unpacker.rb | lib/puppet/module_tool/applications/unpacker.rb | # frozen_string_literal: true
require 'pathname'
require 'tmpdir'
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/file_system'
module Puppet::ModuleTool
module Applications
class Unpacker < Application
def self.unpack(filename, target)
app = new(filename, :target_dir => target)
app.unpack
app.sanity_check
app.move_into(target)
end
def self.harmonize_ownership(source, target)
unless Puppet::Util::Platform.windows?
source = Pathname.new(source) unless source.respond_to?(:stat)
target = Pathname.new(target) unless target.respond_to?(:stat)
FileUtils.chown_R(source.stat.uid, source.stat.gid, target)
end
end
def initialize(filename, options = {})
@filename = Pathname.new(filename)
super(options)
@module_path = Pathname(options[:target_dir])
end
def run
unpack
sanity_check
module_dir = @module_path + module_name
move_into(module_dir)
# Return the Pathname object representing the directory where the
# module release archive was unpacked the to.
module_dir
end
# @api private
# Error on symlinks and other junk
def sanity_check
symlinks = Dir.glob("#{tmpdir}/**/*", File::FNM_DOTMATCH).map { |f| Pathname.new(f) }.select { |p| Puppet::FileSystem.symlink? p }
tmpdirpath = Pathname.new tmpdir
symlinks.each do |s|
Puppet.warning _("Symlinks in modules are unsupported. Please investigate symlink %{from}->%{to}.") % { from: s.relative_path_from(tmpdirpath), to: Puppet::FileSystem.readlink(s) }
end
end
# @api private
def unpack
Puppet::ModuleTool::Tar.instance.unpack(@filename.to_s, tmpdir, [@module_path.stat.uid, @module_path.stat.gid].join(':'))
rescue Puppet::ExecutionFailure => e
raise RuntimeError, _("Could not extract contents of module archive: %{message}") % { message: e.message }
end
# @api private
def root_dir
return @root_dir if @root_dir
# Grab the first directory containing a metadata.json file
metadata_file = Dir["#{tmpdir}/**/metadata.json"].min_by(&:length)
if metadata_file
@root_dir = Pathname.new(metadata_file).dirname
else
raise _("No valid metadata.json found!")
end
end
# @api private
def module_name
metadata = Puppet::Util::Json.load((root_dir + 'metadata.json').read)
metadata['name'][/-(.*)/, 1]
end
# @api private
def move_into(dir)
dir = Pathname.new(dir)
dir.rmtree if dir.exist?
FileUtils.mv(root_dir, dir)
ensure
FileUtils.rmtree(tmpdir)
end
# Obtain a suitable temporary path for unpacking tarballs
#
# @api private
# @return [String] path to temporary unpacking location
# rubocop:disable Naming/MemoizedInstanceVariableName
def tmpdir
@dir ||= Dir.mktmpdir('tmp', Puppet::Forge::Cache.base_path)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/module_tool/applications/uninstaller.rb | lib/puppet/module_tool/applications/uninstaller.rb | # frozen_string_literal: true
module Puppet::ModuleTool
module Applications
class Uninstaller < Application
include Puppet::ModuleTool::Errors
def initialize(name, options)
@name = name
@options = options
@errors = Hash.new { |h, k| h[k] = {} }
@unfiltered = []
@installed = []
@suggestions = []
@environment = options[:environment_instance]
@ignore_changes = options[:force] || options[:ignore_changes]
end
def run
results = {
:module_name => @name,
:requested_version => @version,
}
begin
find_installed_module
validate_module
FileUtils.rm_rf(@installed.first.path, :secure => true)
results[:affected_modules] = @installed
results[:result] = :success
rescue ModuleToolError => err
results[:error] = {
:oneline => err.message,
:multiline => err.multiline,
}
rescue => e
results[:error] = {
:oneline => e.message,
:multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
}
ensure
results[:result] ||= :failure
end
results
end
private
def find_installed_module
@environment.modules_by_path.values.flatten.each do |mod|
mod_name = (mod.forge_name || mod.name).tr('/', '-')
if mod_name == @name
@unfiltered << {
:name => mod_name,
:version => mod.version,
:path => mod.modulepath,
}
if @options[:version] && mod.version
next unless Puppet::Module.parse_range(@options[:version]).include?(SemanticPuppet::Version.parse(mod.version))
end
@installed << mod
elsif mod_name =~ /#{@name}/
@suggestions << mod_name
end
end
if @installed.length > 1
raise MultipleInstalledError,
:action => :uninstall,
:module_name => @name,
:installed_modules => @installed.sort_by { |mod| @environment.modulepath.index(mod.modulepath) }
elsif @installed.empty?
if @unfiltered.empty?
raise NotInstalledError,
:action => :uninstall,
:suggestions => @suggestions,
:module_name => @name
else
raise NoVersionMatchesError,
:installed_modules => @unfiltered.sort_by { |mod| @environment.modulepath.index(mod[:path]) },
:version_range => @options[:version],
:module_name => @name
end
end
end
def validate_module
mod = @installed.first
unless @ignore_changes
raise _("Either the `--ignore_changes` or `--force` argument must be specified to uninstall modules when running in FIPS mode.") if Puppet.runtime[:facter].value(:fips_enabled)
changes = begin
Puppet::ModuleTool::Applications::Checksummer.run(mod.path)
rescue ArgumentError
[]
end
if mod.has_metadata? && !changes.empty?
raise LocalChangesError,
:action => :uninstall,
:module_name => (mod.forge_name || mod.name).tr('/', '-'),
:requested_version => @options[:version],
:installed_version => mod.version
end
end
if !@options[:force] && !mod.required_by.empty?
raise ModuleIsRequiredError,
:module_name => (mod.forge_name || mod.name).tr('/', '-'),
:required_by => mod.required_by,
:requested_version => @options[:version],
:installed_version => mod.version
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/agent/disabler.rb | lib/puppet/agent/disabler.rb | # frozen_string_literal: true
require_relative '../../puppet/util/json_lockfile'
# This module is responsible for encapsulating the logic for
# "disabling" the puppet agent during a run; in other words,
# keeping track of enough state to answer the question
# "has the puppet agent been administratively disabled?"
#
# The implementation involves writing a lockfile with JSON
# contents, and is considered part of the public Puppet API
# because it used by external tools such as mcollective.
#
# For more information, please see docs on the website.
# http://links.puppet.com/agent_lockfiles
module Puppet::Agent::Disabler
DISABLED_MESSAGE_JSON_KEY = "disabled_message"
# Let the daemon run again, freely in the filesystem.
def enable
Puppet.notice _("Enabling Puppet.")
disable_lockfile.unlock
end
# Stop the daemon from making any catalog runs.
def disable(msg = nil)
data = {}
Puppet.notice _("Disabling Puppet.")
unless msg.nil?
data[DISABLED_MESSAGE_JSON_KEY] = msg
end
disable_lockfile.lock(data)
end
def disabled?
disable_lockfile.locked?
end
def disable_message
data = disable_lockfile.lock_data
return nil if data.nil?
if data.has_key?(DISABLED_MESSAGE_JSON_KEY)
return data[DISABLED_MESSAGE_JSON_KEY]
end
nil
end
def disable_lockfile
@disable_lockfile ||= Puppet::Util::JsonLockfile.new(Puppet[:agent_disabled_lockfile])
@disable_lockfile
end
private :disable_lockfile
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/agent/locker.rb | lib/puppet/agent/locker.rb | # frozen_string_literal: true
require_relative '../../puppet/util/pidlock'
require_relative '../../puppet/error'
# This module is responsible for encapsulating the logic for "locking" the
# puppet agent during a catalog run; in other words, keeping track of enough
# state to answer the question "is there a puppet agent currently applying a
# catalog?"
#
# The implementation involves writing a lockfile whose contents are simply the
# PID of the running agent process. This is considered part of the public
# Puppet API because it used by external tools such as mcollective.
#
# For more information, please see docs on the website.
# http://links.puppet.com/agent_lockfiles
module Puppet::Agent::Locker
# Yield if we get a lock, else raise Puppet::LockError. Return
# value of block yielded.
def lock
if lockfile.lock
begin
yield
ensure
lockfile.unlock
end
else
fail Puppet::LockError, _('Failed to acquire lock')
end
end
def running?
lockfile.locked?
end
def lockfile_path
@lockfile_path ||= Puppet[:agent_catalog_run_lockfile]
end
def lockfile
@lockfile ||= Puppet::Util::Pidlock.new(lockfile_path)
@lockfile
end
private :lockfile
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/resource.rb | lib/puppet/face/resource.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:resource, '0.0.1') do
copyright "Puppet Inc.", 2011
license _("Apache 2 license; see COPYING")
summary _("API only: interact directly with resources via the RAL.")
description <<-'EOT'
API only: this face provides a Ruby API with functionality similar to the
puppet resource subcommand.
EOT
deactivate_action(:destroy)
search = get_action(:search)
search.summary _("API only: get all resources of a single type.")
search.arguments _("<resource_type>")
search.returns _("An array of Puppet::Resource objects.")
search.examples <<-'EOT'
Get a list of all user resources (API example):
all_users = Puppet::Face[:resource, '0.0.1'].search("user")
EOT
find = get_action(:find)
find.summary _("API only: get a single resource.")
find.arguments _("<type>/<title>")
find.returns _("A Puppet::Resource object.")
find.examples <<-'EOT'
Print information about a user on this system (API example):
puts Puppet::Face[:resource, '0.0.1'].find("user/luke").to_json
EOT
save = get_action(:save)
save.summary _("API only: create a new resource.")
save.description <<-EOT
API only: creates a new resource.
EOT
save.arguments _("<resource_object>")
save.returns _("The same resource object passed as an argument.")
save.examples <<-'EOT'
Create a new file resource (API example):
my_resource = Puppet::Resource.new(
:file,
"/tmp/demonstration",
:parameters => {:ensure => :present, :content => "some\nthing\n"}
)
Puppet::Face[:resource, '0.0.1'].save(my_resource)
EOT
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/report.rb | lib/puppet/face/report.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:report, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("Create, display, and submit reports.")
save = get_action(:save)
save.summary _("API only: submit a report.")
save.arguments _("<report>")
save.returns _("Nothing.")
save.examples <<-'EOT'
From the implementation of `puppet report submit` (API example):
begin
Puppet::Transaction::Report.indirection.terminus_class = :rest
Puppet::Face[:report, "0.0.1"].save(report)
Puppet.notice "Uploaded report for #{report.name}"
rescue => detail
Puppet.log_exception(detail, "Could not send report: #{detail}")
end
EOT
action(:submit) do
summary _("API only: submit a report with error handling.")
description <<-'EOT'
API only: Submits a report to the OpenVox server. This action is
essentially a shortcut and wrapper for the `save` action with the `rest`
terminus, and provides additional details in the event of a failure.
EOT
arguments _("<report>")
examples <<-'EOT'
API example:
# ...
report = Puppet::Face[:catalog, '0.0.1'].apply
Puppet::Face[:report, '0.0.1'].submit(report)
return report
EOT
when_invoked do |report, _options|
Puppet::Transaction::Report.indirection.terminus_class = :rest
Puppet::Face[:report, "0.0.1"].save(report)
Puppet.notice _("Uploaded report for %{name}") % { name: report.name }
rescue => detail
Puppet.log_exception(detail, _("Could not send report: %{detail}") % { detail: detail })
end
end
deactivate_action(:find)
deactivate_action(:search)
deactivate_action(:destroy)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/generate.rb | lib/puppet/face/generate.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/generate/type'
# Create the Generate face
Puppet::Face.define(:generate, '0.1.0') do
copyright 'Puppet Inc., Vox Pupuli', 2016
license _('Apache 2 license; see COPYING')
summary _('Generates Puppet code from Ruby definitions.')
action(:types) do
summary _('Generates Puppet code for custom types')
description <<-'EOT'
Generates definitions for custom resource types using Puppet code.
Types defined in Puppet code can be used to isolate custom type definitions
between different environments.
EOT
examples <<-'EOT'
Generate Puppet type definitions for all custom resource types in the current environment:
$ puppet generate types
Generate Puppet type definitions for all custom resource types in the specified environment:
$ puppet generate types --environment development
EOT
option '--format ' + _('<format>') do
summary _('The generation output format to use. Supported formats: pcore.')
default_to { 'pcore' }
before_action do |_, _, options|
raise ArgumentError, _("'%{format}' is not a supported format for type generation.") % { format: options[:format] } unless ['pcore'].include?(options[:format])
end
end
option '--force' do
summary _('Forces the generation of output files (skips up-to-date checks).')
default_to { false }
end
when_invoked do |options|
generator = Puppet::Generate::Type
inputs = generator.find_inputs(options[:format].to_sym)
environment = Puppet.lookup(:current_environment)
# get the common output directory (in <envroot>/.resource_types) - create it if it does not exists
# error if it exists and is not a directory
#
path_to_env = environment.configuration.path_to_env
outputdir = File.join(path_to_env, '.resource_types')
if Puppet::FileSystem.exist?(outputdir) && !Puppet::FileSystem.directory?(outputdir)
raise ArgumentError, _("The output directory '%{outputdir}' exists and is not a directory") % { outputdir: outputdir }
end
Puppet::FileSystem.mkpath(outputdir)
generator.generate(inputs, outputdir, options[:force])
exit(1) if generator.bad_input?
nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/node.rb | lib/puppet/face/node.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:node, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("View and manage node definitions.")
description <<-'EOT'
This subcommand interacts with node objects, which are used by OpenVox to
build a catalog. A node object consists of the node's facts, environment,
node parameters (exposed in the parser as top-scope variables), and classes.
EOT
deactivate_action(:destroy)
deactivate_action(:search)
deactivate_action(:save)
find = get_action(:find)
find.summary _("Retrieve a node object.")
find.arguments _("<host>")
# TRANSLATORS the following are specific names and should not be translated `classes`, `environment`, `expiration`, `name`, `parameters`, Puppet::Node
find.returns _(<<-'EOT')
A hash containing the node's `classes`, `environment`, `expiration`, `name`,
`parameters` (its facts, combined with any ENC-set parameters), and `time`.
When used from the Ruby API: a Puppet::Node object.
RENDERING ISSUES: Rendering as string and json are currently broken;
node objects can only be rendered as yaml.
EOT
find.examples <<-'EOT'
Retrieve an "empty" (no classes, no ENC-imposed parameters, and an
environment of "production") node:
$ puppet node find somenode.puppetlabs.lan --terminus plain --render-as yaml
Retrieve a node using the Puppet Server's configured ENC:
$ puppet node find somenode.puppetlabs.lan --terminus exec --run_mode server --render-as yaml
Retrieve the same node from the Puppet Server:
$ puppet node find somenode.puppetlabs.lan --terminus rest --render-as yaml
EOT
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/plugin.rb | lib/puppet/face/plugin.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/configurer/plugin_handler'
Puppet::Face.define(:plugin, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("Interact with the OpenVox plugin system.")
description <<-'EOT'
This subcommand provides network access to the OpenVox server's store of
plugins.
The OpenVox server serves Ruby code collected from the `lib` directories
of its modules. These plugins can be used on agent nodes to extend
Facter and implement custom types and providers. Plugins are normally
downloaded by the OpenVox agent during the course of a run.
EOT
action :download do
summary _("Download plugins from the puppet master.")
description <<-'EOT'
Downloads plugins from the configured OpenVox server. Any plugins
downloaded in this way will be used in all subsequent OpenVox activity.
This action modifies files on disk.
EOT
returns _(<<-'EOT')
A list of the files downloaded, or a confirmation that no files were
downloaded. When used from the Ruby API, this action returns an array of
the files downloaded, which will be empty if none were retrieved.
EOT
examples <<-'EOT'
Retrieve plugins from the puppet master:
$ puppet plugin download
Retrieve plugins from the puppet master (API example):
$ Puppet::Face[:plugin, '0.0.1'].download
EOT
when_invoked do |_options|
remote_environment_for_plugins = Puppet::Node::Environment.remote(Puppet[:environment])
begin
handler = Puppet::Configurer::PluginHandler.new
handler.download_plugins(remote_environment_for_plugins)
ensure
Puppet.runtime[:http].close
end
end
when_rendering :console do |value|
if value.empty? then
_("No plugins downloaded.")
else
_("Downloaded these plugins: %{plugins}") % { plugins: value.join(', ') }
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/parser.rb | lib/puppet/face/parser.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/parser'
Puppet::Face.define(:parser, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2014
license _("Apache 2 license; see COPYING")
summary _("Interact directly with the parser.")
action :validate do
summary _("Validate the syntax of one or more Puppet manifests.")
arguments _("[<manifest>] [<manifest> ...]")
returns _("Nothing, or the first syntax error encountered.")
description <<-'EOT'
This action validates Puppet DSL syntax without compiling a catalog or
syncing any resources. If no manifest files are provided, it will
validate the default site manifest.
When validating multiple issues per file are reported up
to the settings of max_error, and max_warnings. The processing stops
after having reported issues for the first encountered file with errors.
EOT
examples <<-'EOT'
Validate the default site manifest at /etc/puppetlabs/puppet/manifests/site.pp:
$ puppet parser validate
Validate two arbitrary manifest files:
$ puppet parser validate init.pp vhost.pp
Validate from STDIN:
$ cat init.pp \| puppet parser validate
EOT
when_invoked do |*args|
files = args.slice(0..-2)
parse_errors = {}
if files.empty?
if !STDIN.tty?
Puppet[:code] = STDIN.read
error = validate_manifest(nil)
parse_errors['STDIN'] = error if error
else
manifest = Puppet.lookup(:current_environment).manifest
files << manifest
Puppet.notice _("No manifest specified. Validating the default manifest %{manifest}") % { manifest: manifest }
end
end
missing_files = []
files.each do |file|
if Puppet::FileSystem.exist?(file)
error = validate_manifest(file)
parse_errors[file] = error if error
else
missing_files << file
end
end
unless missing_files.empty?
raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{files}") % { files: missing_files.collect { |f| " " * 3 + f + "\n" } }
end
parse_errors
end
when_rendering :console do |errors|
unless errors.empty?
errors.each { |_, error| Puppet.log_exception(error) }
exit(1)
end
# Prevent face_base renderer from outputting "null"
exit(0)
end
when_rendering :json do |errors|
unless errors.empty?
ignore_error_keys = [:arguments, :environment, :node]
data = errors.to_h do |file, error|
file_errors = error.to_h.reject { |k, _| ignore_error_keys.include?(k) }
[file, file_errors]
end
puts Puppet::Util::Json.dump(Puppet::Pops::Serialization::ToDataConverter.convert(data, rich_data: false, symbol_as_string: true), :pretty => true)
exit(1)
end
# Prevent face_base renderer from outputting "null"
exit(0)
end
end
action(:dump) do
summary _("Outputs a dump of the internal parse tree for debugging")
arguments "[--format <old|pn|json>] [--pretty] { -e <source> | [<templates> ...] } "
returns _("A dump of the resulting AST model unless there are syntax or validation errors.")
description <<-'EOT'
This action parses and validates the Puppet DSL syntax without compiling a catalog
or syncing any resources.
The output format can be controlled using the --format <old|pn|json> where:
* 'old' is the default, but now deprecated format which is not API.
* 'pn' is the Puppet Extended S-Expression Notation.
* 'json' outputs the same graph as 'pn' but with JSON syntax.
The output will be "pretty printed" when the option --pretty is given together with --format 'pn' or 'json'.
This option has no effect on the 'old' format.
The command accepts one or more manifests (.pp) files, or an -e followed by the puppet
source text.
If no arguments are given, the stdin is read (unless it is attached to a terminal)
The output format of the dumped tree is intended for debugging purposes and is
not API, it may change from time to time.
EOT
option "--e " + _("<source>") do
default_to { nil }
summary _("dump one source expression given on the command line.")
end
option("--[no-]validate") do
summary _("Whether or not to validate the parsed result, if no-validate only syntax errors are reported")
end
option('--format ' + _('<old, pn, or json>')) do
summary _("Get result in 'old' (deprecated format), 'pn' (new format), or 'json' (new format in JSON).")
end
option('--pretty') do
summary _('Pretty print output. Only applicable together with --format pn or json')
end
when_invoked do |*args|
require_relative '../../puppet/pops'
options = args.pop
if options[:e]
dump_parse(options[:e], 'command-line-string', options, false)
elsif args.empty?
if !STDIN.tty?
dump_parse(STDIN.read, 'stdin', options, false)
else
raise Puppet::Error, _("No input to parse given on command line or stdin")
end
else
files = args
available_files = files.select do |file|
Puppet::FileSystem.exist?(file)
end
missing_files = files - available_files
dumps = available_files.collect do |file|
dump_parse(Puppet::FileSystem.read(file, :encoding => 'utf-8'), file, options)
end.join("")
if missing_files.empty?
dumps
else
dumps + _("One or more file(s) specified did not exist:\n") + missing_files.collect { |f| " #{f}" }.join("\n")
end
end
end
end
def dump_parse(source, filename, options, show_filename = true)
output = ''.dup
evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new
begin
if options[:validate]
parse_result = evaluating_parser.parse_string(source, filename)
else
# side step the assert_and_report step
parse_result = evaluating_parser.parser.parse_string(source)
end
if show_filename
output << "--- #{filename}"
end
fmt = options[:format]
if fmt.nil? || fmt == 'old'
output << Puppet::Pops::Model::ModelTreeDumper.new.dump(parse_result) << "\n"
else
require_relative '../../puppet/pops/pn'
pn = Puppet::Pops::Model::PNTransformer.transform(parse_result)
case fmt
when 'json'
options[:pretty] ? JSON.pretty_unparse(pn.to_data) : JSON.dump(pn.to_data)
else
pn.format(options[:pretty] ? Puppet::Pops::PN::Indent.new(' ') : nil, output)
end
end
rescue Puppet::ParseError => detail
if show_filename
Puppet.err("--- #{filename}")
end
Puppet.err(detail.message)
""
end
end
# @api private
def validate_manifest(manifest = nil)
env = Puppet.lookup(:current_environment)
loaders = Puppet::Pops::Loaders.new(env)
Puppet.override({ :loaders => loaders }, _('For puppet parser validate')) do
validation_environment = manifest ? env.override_with(:manifest => manifest) : env
validation_environment.check_for_reparse
validation_environment.known_resource_types.clear
rescue Puppet::ParseError => parse_error
return parse_error
end
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/catalog.rb | lib/puppet/face/catalog.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:catalog, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license "Apache 2 license; see COPYING"
summary _("Compile, save, view, and convert catalogs.")
description <<-'EOT'
This subcommand deals with catalogs, which are compiled per-node artifacts
generated from a set of Puppet manifests. By default, it interacts with the
compiling subsystem and compiles a catalog using the default manifest and
`certname`, but you can change the source of the catalog with the
`--terminus` option. You can also choose to print any catalog in 'dot'
format (for easy graph viewing with OmniGraffle or Graphviz) with
'--render-as dot'.
EOT
short_description <<-'EOT'
This subcommand deals with catalogs, which are compiled per-node artifacts
generated from a set of Puppet manifests. By default, it interacts with the
compiling subsystem and compiles a catalog using the default manifest and
`certname`; use the `--terminus` option to change the source of the catalog.
EOT
deactivate_action(:destroy)
deactivate_action(:search)
action(:find) do
summary _("Retrieve the catalog for the node from which the command is run.")
arguments "<certname>, <facts>"
option("--facts_for_catalog") do
summary _("Not implemented for the CLI; facts are collected internally.")
end
returns <<-'EOT'
A serialized catalog. When used from the Ruby API, returns a
Puppet::Resource::Catalog object.
EOT
when_invoked do |*args|
# Default the key to Puppet[:certname] if none is supplied
if args.length == 1
key = Puppet[:certname]
else
key = args.shift
end
call_indirection_method :find, key, args.first
end
end
action(:apply) do
summary "Find and apply a catalog."
description <<-'EOT'
Finds and applies a catalog. This action takes no arguments, but
the source of the catalog can be managed with the `--terminus` option.
EOT
returns <<-'EOT'
Nothing. When used from the Ruby API, returns a
Puppet::Transaction::Report object.
EOT
examples <<-'EOT'
Apply the locally cached catalog:
$ puppet catalog apply --terminus yaml
Retrieve a catalog from the master and apply it, in one step:
$ puppet catalog apply --terminus rest
API example:
# ...
Puppet::Face[:catalog, '0.0.1'].download
# (Termini are singletons; catalog.download has a side effect of
# setting the catalog terminus to yaml)
report = Puppet::Face[:catalog, '0.0.1'].apply
# ...
EOT
when_invoked do |_options|
catalog = Puppet::Face[:catalog, "0.0.1"].find(Puppet[:certname]) or raise "Could not find catalog for #{Puppet[:certname]}"
catalog = catalog.to_ral
report = Puppet::Transaction::Report.new
report.configuration_version = catalog.version
report.environment = Puppet[:environment]
Puppet::Util::Log.newdestination(report)
begin
benchmark(:notice, "Finished catalog run in %{seconds} seconds") do
catalog.apply(:report => report)
end
rescue => detail
Puppet.log_exception(detail, "Failed to apply catalog: #{detail}")
end
report.finalize_report
report
end
end
action(:compile) do
summary _("Compile a catalog.")
description <<-'EOT'
Compiles a catalog locally for a node, requiring access to modules, node classifier, etc.
EOT
examples <<-'EOT'
Compile catalog for node 'mynode':
$ puppet catalog compile mynode --codedir ...
EOT
returns <<-'EOT'
A serialized catalog.
EOT
when_invoked do |*args|
Puppet.settings.preferred_run_mode = :server
Puppet::Face[:catalog, :current].find(*args)
end
end
action(:download) do
summary "Download this node's catalog from the puppet master server."
description <<-'EOT'
Retrieves a catalog from the puppet master and saves it to the local yaml
cache. This action always contacts the puppet master and will ignore
alternate termini.
The saved catalog can be used in any subsequent catalog action by specifying
'--terminus yaml' for that action.
EOT
returns "Nothing."
notes <<-'EOT'
When used from the Ruby API, this action has a side effect of leaving
Puppet::Resource::Catalog.indirection.terminus_class set to yaml. The
terminus must be explicitly re-set for subsequent catalog actions.
EOT
examples <<-'EOT'
Retrieve and store a catalog:
$ puppet catalog download
API example:
Puppet::Face[:plugin, '0.0.1'].download
Puppet::Face[:facts, '0.0.1'].upload
Puppet::Face[:catalog, '0.0.1'].download
# ...
EOT
when_invoked do |_options|
Puppet::Resource::Catalog.indirection.terminus_class = :rest
Puppet::Resource::Catalog.indirection.cache_class = nil
facts = Puppet::Face[:facts, '0.0.1'].find(Puppet[:certname])
catalog = nil
retrieval_duration = thinmark do
catalog = Puppet::Face[:catalog, '0.0.1'].find(Puppet[:certname],
{ facts_for_catalog: facts })
end
catalog.retrieval_duration = retrieval_duration
catalog.write_class_file
Puppet::Resource::Catalog.indirection.terminus_class = :yaml
Puppet::Face[:catalog, "0.0.1"].save(catalog)
Puppet.notice "Saved catalog for #{Puppet[:certname]} to #{Puppet::Resource::Catalog.indirection.terminus.path(Puppet[:certname])}"
nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/epp.rb | lib/puppet/face/epp.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/pops'
require_relative '../../puppet/parser/files'
require_relative '../../puppet/file_system'
Puppet::Face.define(:epp, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2014
license _("Apache 2 license; see COPYING")
summary _("Interact directly with the EPP template parser/renderer.")
action(:validate) do
summary _("Validate the syntax of one or more EPP templates.")
arguments _("[<template>] [<template> ...]")
returns _("Nothing, or encountered syntax errors.")
description <<-'EOT'
This action validates EPP syntax without producing any output.
When validating, multiple issues per file are reported up
to the settings of max_error, and max_warnings. The processing
stops after having reported issues for the first encountered file with errors
unless the option --continue_on_error is given.
Files can be given using the `modulename/template.epp` style to lookup the
template from a module, or be given as a reference to a file. If the reference
to a file can be resolved against a template in a module, the module version
wins - in this case use an absolute path to reference the template file
if the module version is not wanted.
Exits with 0 if there were no validation errors.
EOT
option("--[no-]continue_on_error") do
summary _("Whether or not to continue after errors are reported for a template.")
end
examples <<-'EOT'
Validate the template 'template.epp' in module 'mymodule':
$ puppet epp validate mymodule/template.epp
Validate two arbitrary template files:
$ puppet epp validate mymodule/template1.epp yourmodule/something.epp
Validate a template somewhere in the file system:
$ puppet epp validate /tmp/testing/template1.epp
Validate a template against a file relative to the current directory:
$ puppet epp validate template1.epp
$ puppet epp validate ./template1.epp
Validate from STDIN:
$ cat template.epp | puppet epp validate
Continue on error to see errors for all templates:
$ puppet epp validate mymodule/template1.epp mymodule/template2.epp --continue_on_error
EOT
when_invoked do |*args|
options = args.pop
# pass a dummy node, as facts are not needed for validation
options[:node] = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}))
compiler = create_compiler(options)
status = true # no validation error yet
files = args
if files.empty?
if !STDIN.tty?
tmp = validate_template_string(STDIN.read)
status &&= tmp
else
# This is not an error since a validate of all files in an empty
# directory should not be treated as a failed validation.
Puppet.notice _("No template specified. No action taken")
end
end
missing_files = []
files.each do |file|
break if !status && !options[:continue_on_error]
template_file = effective_template(file, compiler.environment)
if template_file
tmp = validate_template(template_file)
status &&= tmp
else
missing_files << file
end
end
if !missing_files.empty?
raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{missing_files_list}") %
{ missing_files_list: missing_files.map { |f| " #{f}" }.join("\n") }
else
# Exit with 1 if there were errors
raise Puppet::Error, _("Errors while validating epp") unless status
end
end
end
action(:dump) do
summary _("Outputs a dump of the internal template parse tree for debugging")
arguments "[--format <old|pn|json>] [--pretty] { -e <source> | [<templates> ...] } "
returns _("A dump of the resulting AST model unless there are syntax or validation errors.")
description <<-'EOT'
The dump action parses and validates the EPP syntax and dumps the resulting AST model
in a human readable (but not necessarily an easy to understand) format.
The output format can be controlled using the --format <old|pn|json> where:
* 'old' is the default, but now deprecated format which is not API.
* 'pn' is the Puppet Extended S-Expression Notation.
* 'json' outputs the same graph as 'pn' but with JSON syntax.
The output will be "pretty printed" when the option --pretty is given together with --format 'pn' or 'json'.
This option has no effect on the 'old' format.
The command accepts one or more templates (.epp) files, or an -e followed by the template
source text. The given templates can be paths to template files, or references
to templates in modules when given on the form <modulename>/<template-name>.epp.
If no arguments are given, the stdin is read (unless it is attached to a terminal)
If multiple templates are given, they are separated with a header indicating the
name of the template. This can be suppressed with the option --no-header.
The option --[no-]header has no effect when a single template is dumped.
When debugging the epp parser itself, it may be useful to suppress the validation
step with the `--no-validate` option to observe what the parser produced from the
given source.
This command ignores the --render-as setting/option.
EOT
option("--e " + _("<source>")) do
default_to { nil }
summary _("Dump one epp source expression given on the command line.")
end
option("--[no-]validate") do
summary _("Whether or not to validate the parsed result, if no-validate only syntax errors are reported.")
end
option('--format ' + _('<old, pn, or json>')) do
summary _("Get result in 'old' (deprecated format), 'pn' (new format), or 'json' (new format in JSON).")
end
option('--pretty') do
summary _('Pretty print output. Only applicable together with --format pn or json')
end
option("--[no-]header") do
summary _("Whether or not to show a file name header between files.")
end
when_invoked do |*args|
require_relative '../../puppet/pops'
options = args.pop
# pass a dummy node, as facts are not needed for dump
options[:node] = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}))
options[:header] = options[:header].nil? ? true : options[:header]
options[:validate] = options[:validate].nil? ? true : options[:validate]
compiler = create_compiler(options)
# Print to a buffer since the face needs to return the resulting string
# and the face API is "all or nothing"
#
buffer = StringIO.new
if options[:e]
buffer.print dump_parse(options[:e], 'command-line-string', options, false)
elsif args.empty?
if !STDIN.tty?
buffer.print dump_parse(STDIN.read, 'stdin', options, false)
else
raise Puppet::Error, _("No input to parse given on command line or stdin")
end
else
templates, missing_files = args.each_with_object([[], []]) do |file, memo|
template_file = effective_template(file, compiler.environment)
if template_file.nil?
memo[1] << file
else
memo[0] << template_file
end
end
show_filename = templates.count > 1
templates.each do |file|
buffer.print dump_parse(Puppet::FileSystem.read(file, :encoding => 'utf-8'), file, options, show_filename)
end
unless missing_files.empty?
raise Puppet::Error, _("One or more file(s) specified did not exist:\n%{missing_files_list}") %
{ missing_files_list: missing_files.collect { |f| " #{f}" }.join("\n") }
end
end
buffer.string
end
end
action(:render) do
summary _("Renders an epp template as text")
arguments "-e <source> | [<templates> ...] "
returns _("A rendered result of one or more given templates.")
description <<-'EOT'
This action renders one or more EPP templates.
The command accepts one or more templates (.epp files), given the same way as templates
are given to the puppet `epp` function (a full path, or a relative reference
on the form '<modulename>/<template-name>.epp'), or as a relative path.args In case
the given path matches both a modulename/template and a file, the template from
the module is used.
An inline_epp equivalent can also be performed by giving the template after
an -e, or by piping the EPP source text to the command.
Values to the template can be defined using the Puppet Language on the command
line with `--values` or in a .pp or .yaml file referenced with `--values_file`. If
specifying both the result is merged with --values having higher precedence.
The --values option allows a Puppet Language sequence of expressions to be defined on the
command line the same way as it may be given in a .pp file referenced with `--values_file`.
It may set variable values (that become available in the template), and must produce
either `undef` or a `Hash` of values (the hash may be empty). Producing `undef` simulates
that the template is called without an arguments hash and thus only references
variables in its outer scope. When a hash is given, a template is limited to seeing
only the global scope. It is thus possible to simulate the different types of
calls to the `epp` and `inline_epp` functions, with or without a given hash. Note that if
variables are given, they are always available in this simulation - to test that the
template only references variables given as arguments, produce a hash in --values or
the --values_file, do not specify any variables that are not global, and
turn on --strict_variables setting.
If multiple templates are given, the same set of values are given to each template.
If both --values and --value_file are used, the --values are merged on top of those given
in the file.
When multiple templates are rendered, a separating header is output between the templates
showing the name of the template before the output. The header output can be turned off with
`--no-header`. This also concatenates the template results without any added newline separators.
Facts from the node where the command is being run are used by default.args Facts can be obtained
for other nodes if they have called in, and reported their facts by using the `--node <nodename>`
flag.
Overriding node facts as well as additional facts can be given in a .yaml or .json file and referencing
it with the --facts option. (Values can be obtained in yaml format directly from
`facter`, or from puppet for a given node). Note that it is not possible to simulate the
reserved variable name `$facts` in any other way.
Note that it is not possible to set variables using the Puppet Language that have the same
names as facts as this result in an error; "attempt to redefine a variable" since facts
are set first.
Exits with 0 if there were no validation errors. On errors, no rendered output is produced for
that template file.
When designing EPP templates, it is strongly recommended to define all template arguments
in the template, and to give them in a hash when calling `epp` or `inline_epp` and to use
as few global variables as possible, preferably only the $facts hash. This makes templates
more free standing and are easier to reuse, and to test.
EOT
examples <<-'EOT'
Render the template in module 'mymodule' called 'mytemplate.epp', and give it two arguments
`a` and `b`:
$ puppet epp render mymodule/mytemplate.epp --values '{a => 10, b => 20}'
Render a template using an absolute path:
$ puppet epp render /tmp/testing/mytemplate.epp --values '{a => 10, b => 20}'
Render a template with data from a .pp file:
$ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp
Render a template with data from a .pp file and override one value on the command line:
$ puppet epp render /tmp/testing/mytemplate.epp --values_file mydata.pp --values '{a=>10}'
Render from STDIN:
$ cat template.epp | puppet epp render --values '{a => 10, b => 20}'
Set variables in a .pp file and render a template that uses variable references:
# data.pp file
$greeted = 'a global var'
undef
$ puppet epp render -e 'hello <%= $greeted %>' --values_file data.pp
Render a template that outputs a fact:
$ facter --yaml > data.yaml
$ puppet epp render -e '<% $facts[osfamily] %>' --facts data.yaml
EOT
option("--node " + _("<node_name>")) do
summary _("The name of the node for which facts are obtained. Defaults to facts for the local node.")
end
option("--e " + _("<source>")) do
default_to { nil }
summary _("Render one inline epp template given on the command line.")
end
option("--values " + _("<values_hash>")) do
summary _("A Hash in Puppet DSL form given as arguments to the template being rendered.")
end
option("--values_file " + _("<pp_or_yaml_file>")) do
summary _("A .pp or .yaml file that is processed to produce a hash of values for the template.")
end
option("--facts " + _("<facts_file>")) do
summary _("A .yaml or .json file containing a hash of facts made available in $facts and $trusted")
end
option("--[no-]header") do
summary _("Whether or not to show a file name header between rendered results.")
end
when_invoked do |*args|
options = args.pop
options[:header] = options[:header].nil? ? true : options[:header]
compiler = create_compiler(options)
compiler.with_context_overrides('For rendering epp') do
# Print to a buffer since the face needs to return the resulting string
# and the face API is "all or nothing"
#
buffer = StringIO.new
status = true
if options[:e]
buffer.print render_inline(options[:e], compiler, options)
elsif args.empty?
if !STDIN.tty?
buffer.print render_inline(STDIN.read, compiler, options)
else
raise Puppet::Error, _("No input to process given on command line or stdin")
end
else
show_filename = args.count > 1
file_nbr = 0
args.each do |file|
buffer.print render_file(file, compiler, options, show_filename, file_nbr += 1)
rescue Puppet::ParseError => detail
Puppet.err(detail.message)
status = false
end
end
raise Puppet::Error, _("error while rendering epp") unless status
buffer.string
end
end
end
def dump_parse(source, filename, options, show_filename = true)
output = ''.dup
evaluating_parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new
begin
if options[:validate]
parse_result = evaluating_parser.parse_string(source, filename)
else
# side step the assert_and_report step
parse_result = evaluating_parser.parser.parse_string(source)
end
if show_filename && options[:header]
output << "--- #{filename}\n"
end
fmt = options[:format]
if fmt.nil? || fmt == 'old'
output << Puppet::Pops::Model::ModelTreeDumper.new.dump(parse_result) << "\n"
else
require_relative '../../puppet/pops/pn'
pn = Puppet::Pops::Model::PNTransformer.transform(parse_result)
case fmt
when 'json'
options[:pretty] ? JSON.pretty_unparse(pn.to_data) : JSON.dump(pn.to_data)
else
pn.format(options[:pretty] ? Puppet::Pops::PN::Indent.new(' ') : nil, output)
end
end
rescue Puppet::ParseError => detail
if show_filename
Puppet.err("--- #{filename}")
end
Puppet.err(detail.message)
""
end
end
def get_values(compiler, options)
template_values = nil
values_file = options[:values_file]
if values_file
begin
case values_file
when /\.yaml$/
template_values = Puppet::Util::Yaml.safe_load_file(values_file, [Symbol])
when /\.pp$/
evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new
template_values = evaluating_parser.evaluate_file(compiler.topscope, values_file)
else
Puppet.err(_("Only .yaml or .pp can be used as a --values_file"))
end
rescue => e
Puppet.err(_("Could not load --values_file %{error}") % { error: e.message })
end
unless template_values.nil? || template_values.is_a?(Hash)
Puppet.err(_("--values_file option must evaluate to a Hash or undef/nil, got: '%{template_class}'") % { template_class: template_values.class })
end
end
values = options[:values]
if values
evaluating_parser = Puppet::Pops::Parser::EvaluatingParser.new
result = evaluating_parser.evaluate_string(compiler.topscope, values, 'values-hash')
case result
when nil
template_values
when Hash
template_values.nil? ? result : template_values.merge(result)
else
Puppet.err(_("--values option must evaluate to a Hash or undef, got: '%{values_class}'") % { values_class: result.class })
end
else
template_values
end
end
def render_inline(epp_source, compiler, options)
template_args = get_values(compiler, options)
result = Puppet::Pops::Evaluator::EppEvaluator.inline_epp(compiler.topscope, epp_source, template_args)
if result.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive)
result.unwrap
else
result
end
end
def render_file(epp_template_name, compiler, options, show_filename, file_nbr)
template_args = get_values(compiler, options)
output = ''.dup
begin
if show_filename && options[:header]
output << "\n" unless file_nbr == 1
output << "--- #{epp_template_name}\n"
end
# Change to an absolute file only if reference is to a an existing file. Note that an absolute file must be used
# or the template must be found on the module path when calling the epp evaluator.
template_file = Puppet::Parser::Files.find_template(epp_template_name, compiler.environment)
if template_file.nil? && Puppet::FileSystem.exist?(epp_template_name)
epp_template_name = File.expand_path(epp_template_name)
end
result = Puppet::Pops::Evaluator::EppEvaluator.epp(compiler.topscope, epp_template_name, compiler.environment, template_args)
if result.instance_of?(Puppet::Pops::Types::PSensitiveType::Sensitive)
output << result.unwrap
else
output << result
end
rescue Puppet::ParseError => detail
Puppet.err("--- #{epp_template_name}") if show_filename
raise detail
end
output
end
# @api private
def validate_template(template)
parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new()
parser.parse_file(template)
true
rescue => detail
Puppet.log_exception(detail)
false
end
# @api private
def validate_template_string(source)
parser = Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.new()
parser.parse_string(source, '<stdin>')
true
rescue => detail
Puppet.log_exception(detail)
false
end
# @api private
def create_compiler(options)
if options[:node]
node = options[:node]
else
node = Puppet[:node_name_value]
# If we want to lookup the node we are currently on
# we must returning these settings to their default values
Puppet.settings[:facts_terminus] = 'facter'
Puppet.settings[:node_cache_terminus] = nil
end
unless node.is_a?(Puppet::Node)
node = Puppet::Node.indirection.find(node)
# Found node must be given the environment to use in some cases, use the one configured
# or given on the command line
node.environment = Puppet[:environment]
end
fact_file = options[:facts]
if fact_file
if fact_file.is_a?(Hash) # when used via the Face API
given_facts = fact_file
elsif fact_file.end_with?("json")
given_facts = Puppet::Util::Json.load(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8'))
else
given_facts = Puppet::Util::Yaml.safe_load_file(fact_file)
end
unless given_facts.instance_of?(Hash)
raise _("Incorrect formatted data in %{fact_file} given via the --facts flag") % { fact_file: fact_file }
end
# It is difficult to add to or modify the set of facts once the node is created
# as changes does not show up in parameters. Rather than manually patching up
# a node and risking future regressions, a new node is created from scratch
node = Puppet::Node.new(node.name, :facts => Puppet::Node::Facts.new("facts", node.facts.values.merge(given_facts)))
node.environment = Puppet[:environment]
node.merge(node.facts.values)
end
compiler = Puppet::Parser::Compiler.new(node)
# configure compiler with facts and node related data
# Set all global variables from facts
compiler.send(:set_node_parameters)
# pretend that the main class (named '') has been evaluated
# since it is otherwise not possible to resolve top scope variables
# using '::' when rendering. (There is no harm doing this for the other actions)
#
compiler.topscope.class_set('', compiler.topscope)
compiler
end
# Produces the effective template file from a module/template or file reference
# @api private
def effective_template(file, env)
template_file = Puppet::Parser::Files.find_template(file, env)
if !template_file.nil?
template_file
elsif Puppet::FileSystem.exist?(file)
file
else
nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/help.rb | lib/puppet/face/help.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/application/face_base'
require_relative '../../puppet/util/constant_inflector'
require 'pathname'
require 'erb'
Puppet::Face.define(:help, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("Display OpenVox help.")
action(:help) do
summary _("Display help about OpenVox subcommands and their actions.")
arguments _("[<subcommand>] [<action>]")
returns _("Short help text for the specified subcommand or action.")
examples _(<<-'EOT')
Get help for an action:
$ puppet help
EOT
option "--version " + _("VERSION") do
summary _("The version of the subcommand for which to show help.")
end
option "--ronn" do
summary _("Whether to render the help text in ronn format.")
default_to { false }
end
default
when_invoked do |*args|
options = args.pop
unless options[:ronn]
if default_case?(args) || help_for_help?(args)
return erb('global.erb').result(binding)
end
end
if args.length > 2
# TRANSLATORS 'puppet help' is a command line and should not be translated
raise ArgumentError, _("The 'puppet help' command takes two (optional) arguments: a subcommand and an action")
end
version = :current
if options.has_key? :version
if options[:version].to_s !~ /^current$/i
version = options[:version]
elsif args.length == 0
raise ArgumentError, _("Supplying a '--version' only makes sense when a Faces subcommand is given")
# TRANSLATORS '--version' is a command line option and should not be translated
end
end
facename, actionname = args
if legacy_applications.include? facename
if actionname
raise ArgumentError, _("The legacy subcommand '%{sub_command}' does not support supplying an action") % { sub_command: facename }
end
# legacy apps already emit ronn output
return render_application_help(facename)
elsif options[:ronn]
render_face_man(facename || :help)
# Calling `puppet help <app> --ronn` normally calls this action with
# <app> as the first argument in the `args` array. However, if <app>
# happens to match the name of an action, like `puppet help help
# --ronn`, then face_base "eats" the argument and `args` will be
# empty. Rather than force users to type `puppet help help help
# --ronn`, default the facename to `:help`
else
render_face_help(facename, actionname, version)
end
end
end
def default_case?(args)
args.empty?
end
def help_for_help?(args)
args.length == 1 && args.first == 'help'
end
def render_face_man(facename)
# set 'face' as it's used in the erb processing.
face = Puppet::Face[facename.to_sym, :current]
# avoid unused variable warning
_face = face
erb('man.erb').result(binding)
end
def render_application_help(applicationname)
Puppet::Application[applicationname].help
rescue StandardError, LoadError => detail
message = []
message << _('Could not load help for the application %{application_name}.') % { application_name: applicationname }
message << _('Please check the error logs for more information.')
message << ''
message << _('Detail: "%{detail}"') % { detail: detail.message }
fail ArgumentError, message.join("\n"), detail.backtrace
end
def render_face_help(facename, actionname, version)
face, action = load_face_help(facename, actionname, version)
template_for(face, action).result(binding)
rescue StandardError, LoadError => detail
message = []
message << _('Could not load help for the face %{face_name}.') % { face_name: facename }
message << _('Please check the error logs for more information.')
message << ''
message << _('Detail: "%{detail}"') % { detail: detail.message }
fail ArgumentError, message.join("\n"), detail.backtrace
end
def load_face_help(facename, actionname, version)
face = Puppet::Face[facename.to_sym, version]
if actionname
action = face.get_action(actionname.to_sym)
unless action
fail ArgumentError, _("Unable to load action %{actionname} from %{face}") % { actionname: actionname, face: face }
end
end
[face, action]
end
def template_for(face, action)
if action.nil?
erb('face.erb')
else
erb('action.erb')
end
end
def erb(name)
template = (Pathname(__FILE__).dirname + "help" + name)
erb = Puppet::Util.create_erb(template.read)
erb.filename = template.to_s
erb
end
# Return a list of applications that are not simply just stubs for Faces.
def legacy_applications
Puppet::Application.available_application_names.reject do |appname|
is_face_app?(appname) or exclude_from_docs?(appname)
end.sort
end
def generate_summary(appname)
if is_face_app?(appname)
begin
face = Puppet::Face[appname, :current]
# Add deprecation message to summary if the face is deprecated
summary = face.deprecated? ? face.summary + ' ' + _("(Deprecated)") : face.summary
[appname, summary, ' ']
rescue StandardError, LoadError
error_message = _("!%{sub_command}! Subcommand unavailable due to error.") % { sub_command: appname }
error_message += ' ' + _("Check error logs.")
[error_message, '', ' ']
end
else
begin
summary = Puppet::Application[appname].summary
if summary.empty?
summary = horribly_extract_summary_from(appname)
end
[appname, summary, ' ']
rescue StandardError, LoadError
error_message = _("!%{sub_command}! Subcommand unavailable due to error.") % { sub_command: appname }
error_message += ' ' + _("Check error logs.")
[error_message, '', ' ']
end
end
end
# Return a list of all applications (both legacy and Face applications), along with a summary
# of their functionality.
# @return [Array] An Array of Arrays. The outer array contains one entry per application; each
# element in the outer array is a pair whose first element is a String containing the application
# name, and whose second element is a String containing the summary for that application.
def all_application_summaries
available_application_names_special_sort().inject([]) do |result, appname|
next result if exclude_from_docs?(appname)
if appname == COMMON || appname == SPECIALIZED || appname == BLANK
result << appname
else
result << generate_summary(appname)
end
end
end
COMMON = 'Common:'
SPECIALIZED = 'Specialized:'
BLANK = "\n"
COMMON_APPS = %w[apply agent config help lookup module resource]
def available_application_names_special_sort
full_list = Puppet::Application.available_application_names
a_list = full_list & COMMON_APPS
a_list = a_list.sort
also_ran = full_list - a_list
also_ran = also_ran.sort
[[COMMON], a_list, [BLANK], [SPECIALIZED], also_ran].flatten(1)
end
def common_app_summaries
COMMON_APPS.map do |appname|
generate_summary(appname)
end
end
def specialized_app_summaries
specialized_apps = Puppet::Application.available_application_names - COMMON_APPS
specialized_apps.filter_map do |appname|
generate_summary(appname) unless exclude_from_docs?(appname)
end
end
def horribly_extract_summary_from(appname)
help = Puppet::Application[appname].help.split("\n")
# Now we find the line with our summary, extract it, and return it. This
# depends on the implementation coincidence of how our pages are
# formatted. If we can't match the pattern we expect we return the empty
# string to ensure we don't blow up in the summary. --daniel 2011-04-11
while line = help.shift # rubocop:disable Lint/AssignmentInCondition
md = /^puppet-#{appname}\([^)]+\) -- (.*)$/.match(line)
if md
return md[1]
end
end
''
end
# This should absolutely be a private method, but for some reason it appears
# that you can't use the 'private' keyword inside of a Face definition.
# See #14205.
# private :horribly_extract_summary_from
def exclude_from_docs?(appname)
%w[face_base indirection_base report status].include? appname
end
# This should absolutely be a private method, but for some reason it appears
# that you can't use the 'private' keyword inside of a Face definition.
# See #14205.
# private :exclude_from_docs?
def is_face_app?(appname)
clazz = Puppet::Application.find(appname)
clazz.ancestors.include?(Puppet::Application::FaceBase)
end
# This should probably be a private method, but for some reason it appears
# that you can't use the 'private' keyword inside of a Face definition.
# See #14205.
# private :is_face_app?
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/facts.rb | lib/puppet/face/facts.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
require_relative '../../puppet/node/facts'
Puppet::Indirector::Face.define(:facts, '0.0.1') do
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("Retrieve and store facts.")
description <<-'EOT'
This subcommand manages facts, which are collections of normalized system
information used by OpenVox. It can read facts directly from the local system
(with the default `facter` terminus).
EOT
find = get_action(:find)
find.summary _("Retrieve a node's facts.")
find.arguments _("[<node_certname>]")
find.returns <<-'EOT'
A hash containing some metadata and (under the "values" key) the set
of facts for the requested node. When used from the Ruby API: A
Puppet::Node::Facts object.
RENDERING ISSUES: Facts cannot currently be rendered as a string; use yaml
or json.
EOT
find.notes <<-'EOT'
When using the `facter` terminus, the host argument is ignored.
EOT
find.examples <<-'EOT'
Get facts from the local system:
$ puppet facts find
EOT
deactivate_action(:destroy)
deactivate_action(:search)
action(:upload) do
summary _("Upload local facts to the puppet master.")
description <<-'EOT'
Reads facts from the local system using the `facter` terminus, then
saves the returned facts using the rest terminus.
EOT
returns "Nothing."
notes <<-'EOT'
This action requires that the Puppet Server's `auth.conf` file
allow `PUT` or `save` access to the `/puppet/v3/facts` API endpoint.
For details on configuring Puppet Server's `auth.conf`, see:
<https://puppet.com/docs/puppetserver/latest/config_file_auth.html>
EOT
examples <<-'EOT'
Upload facts:
$ puppet facts upload
EOT
render_as :json
when_invoked do |_options|
# Use `agent` sections settings for certificates, Puppet Server URL,
# etc. instead of `user` section settings.
Puppet.settings.preferred_run_mode = :agent
Puppet::Node::Facts.indirection.terminus_class = :facter
facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
unless Puppet[:node_name_fact].empty?
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
client = Puppet.runtime[:http]
session = client.create_session
puppet = session.route_to(:puppet)
Puppet.notice(_("Uploading facts for '%{node}' to '%{server}'") % {
node: Puppet[:node_name_value],
server: puppet.url.hostname
})
puppet.put_facts(Puppet[:node_name_value], facts: facts, environment: Puppet.lookup(:current_environment).name.to_s)
nil
end
end
action(:show) do
summary _("Retrieve current node's facts.")
arguments _("[<facts>]")
description <<-'EOT'
Reads facts from the local system using `facter` terminus.
A query can be provided to retrieve just a specific fact or a set of facts.
EOT
returns "The output of facter with added puppet specific facts."
notes <<-'EOT'
EOT
examples <<-'EOT'
retrieve facts:
$ puppet facts show os
EOT
default true
option("--config-file " + _("<path>")) do
default_to { nil }
summary _("The location of the config file for Facter.")
end
option("--custom-dir " + _("<path>")) do
default_to { nil }
summary _("The path to a directory that contains custom facts.")
end
option("--external-dir " + _("<path>")) do
default_to { nil }
summary _("The path to a directory that contains external facts.")
end
option("--no-block") do
summary _("Disable fact blocking mechanism.")
end
option("--no-cache") do
summary _("Disable fact caching mechanism.")
end
option("--show-legacy") do
summary _("Show legacy facts when querying all facts.")
end
option("--value-only") do
summary _("Show only the value when the action is called with a single query")
end
option("--timing") do
summary _("Show how much time it took to resolve each fact.")
end
when_invoked do |*args|
options = args.pop
Puppet.settings.preferred_run_mode = :agent
Puppet::Node::Facts.indirection.terminus_class = :facter
if options[:value_only] && !args.count.eql?(1)
options[:value_only] = nil
Puppet.warning("Incorrect use of --value-only argument; it can only be used when querying for a single fact!")
end
options[:user_query] = args
options[:resolve_options] = true
result = Puppet::Node::Facts.indirection.find(Puppet.settings[:certname], options)
if options[:value_only]
result.values.values.first
else
result.values
end
end
when_rendering :console do |result|
# VALID_TYPES = [Integer, Float, TrueClass, FalseClass, NilClass, Symbol, String, Array, Hash].freeze
# from https://github.com/puppetlabs/facter/blob/4.0.49/lib/facter/custom_facts/util/normalization.rb#L8
case result
when Array, Hash
# JSON < 2.8.0 would pretty print empty arrays and hashes with newlines
# Maintain that behavior for our users for now
if result.is_a?(Array) && result.empty?
"[\n\n]"
elsif result.is_a?(Hash) && result.empty?
"{\n}"
else
Puppet::Util::Json.dump(result, :pretty => true)
end
else # one of VALID_TYPES above
result
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/config.rb | lib/puppet/face/config.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/settings/ini_file'
Puppet::Face.define(:config, '0.0.1') do
extend Puppet::Util::Colors
copyright "Puppet Inc., Vox Pupuli", 2011
license _("Apache 2 license; see COPYING")
summary _("Interact with OpenVox's settings.")
description "This subcommand can inspect and modify settings from OpenVox's
'puppet.conf' configuration file. For documentation about individual settings,
see https://puppet.com/docs/puppet/latest/configuration.html."
DEFAULT_SECTION_MARKER = Object.new
DEFAULT_SECTION = "main"
option "--section " + _("SECTION_NAME") do
default_to { DEFAULT_SECTION_MARKER } # Sentinel object for default detection during commands
summary _("The section of the configuration file to interact with.")
description <<-EOT
The section of the puppet.conf configuration file to interact with.
The three most commonly used sections are 'main', 'server', and 'agent'.
'Main' is the default, and is used by all OpenVox applications. Other
sections can override 'main' values for specific applications --- the
'server' section affects Puppet Server, and the 'agent'
section affects puppet agent.
Less commonly used is the 'user' section, which affects puppet apply. Any
other section will be treated as the name of a legacy environment
(a deprecated feature), and can only include the 'manifest' and
'modulepath' settings.
EOT
end
action(:print) do
summary _("Examine OpenVox's current settings.")
arguments _("all \\| <setting> [<setting> ...]")
description <<-'EOT'
Prints the value of a single setting or a list of settings.
This action is a replacement interface to the information available with
`puppet <subcommand> --configprint`.
EOT
notes <<-'EOT'
By default, this action reads the general configuration in the 'main'
section. Use the '--section' and '--environment' flags to examine other
configuration domains.
EOT
examples <<-'EOT'
Get puppet's runfile directory:
$ puppet config print rundir
Get a list of important directories from the server's config:
$ puppet config print all --section server \| grep -E "(path\|dir)"
EOT
when_invoked do |*args|
options = args.pop
@default_section = false
if options[:section] == DEFAULT_SECTION_MARKER
options[:section] = DEFAULT_SECTION
@default_section = true
end
if Puppet::Util::Log.sendlevel?(:info)
warn_default_section(options[:section]) if @default_section
report_section_and_environment(options[:section], Puppet.settings[:environment])
end
names = if args.empty? || args == ['all']
:all
else
args
end
Puppet.settings.stringify_settings(options[:section], names)
end
when_rendering :console do |to_be_rendered|
output = ''.dup
if to_be_rendered.keys.length > 1
to_be_rendered.keys.sort.each do |setting|
output << "#{setting} = #{to_be_rendered[setting]}\n"
end
else
output << "#{to_be_rendered.to_a[0].last}\n"
end
output
end
end
def warn_default_section(section_name)
messages = []
messages << _("No section specified; defaulting to '%{section_name}'.") %
{ section_name: section_name }
# TRANSLATORS '--section' is a command line option and should not be translated
messages << _("Set the config section by using the `--section` flag.")
# TRANSLATORS `puppet config --section user print foo` is a command line example and should not be translated
messages << _("For example, `puppet config --section user print foo`.")
messages << _("For more information, see https://puppet.com/docs/puppet/latest/configuration.html")
Puppet.warning(messages.join("\n"))
end
def report_section_and_environment(section_name, environment_name)
$stderr.puts colorize(:hyellow,
_("Resolving settings from section '%{section_name}' in environment '%{environment_name}'") %
{ section_name: section_name, environment_name: environment_name })
end
action(:set) do
summary _("Set OpenVox's settings.")
arguments _("[setting_name] [setting_value]")
description <<-'EOT'
Updates values in the `puppet.conf` configuration file.
EOT
notes <<-'EOT'
By default, this action manipulates the configuration in the
'main' section. Use the '--section' flag to manipulate other
configuration domains.
EOT
examples <<-'EOT'
Set puppet's runfile directory:
$ puppet config set rundir /var/run/puppetlabs
Set the vardir for only the agent:
$ puppet config set vardir /opt/puppetlabs/puppet/cache --section agent
EOT
when_invoked do |name, value, options|
@default_section = false
if options[:section] == DEFAULT_SECTION_MARKER
options[:section] = DEFAULT_SECTION
@default_section = true
end
if name == 'environment' && options[:section] == 'main'
Puppet.warning _(<<~EOM).chomp
The environment should be set in either the `[user]`, `[agent]`, or `[server]`
section. Variables set in the `[agent]` section are used when running
`puppet agent`. Variables set in the `[user]` section are used when running
various other puppet subcommands, like `puppet apply` and `puppet module`; these
require the defined environment directory to exist locally. Set the config
section by using the `--section` flag. For example,
`puppet config --section user set environment foo`. For more information, see
https://puppet.com/docs/puppet/latest/configuration.html#environment
EOM
end
if Puppet::Util::Log.sendlevel?(:info)
report_section_and_environment(options[:section], Puppet.settings[:environment])
end
# only validate settings we recognize
setting = Puppet.settings.setting(name.to_sym)
if setting
# set the value, which will call `on_*_and_write` hooks, if any
Puppet.settings[setting.name] = value
# read the value to trigger interpolation and munge validation logic
Puppet.settings[setting.name]
end
path = Puppet::FileSystem.pathname(Puppet.settings.which_configuration_file)
Puppet::FileSystem.dir_mkpath(path)
Puppet::FileSystem.touch(path)
Puppet::FileSystem.open(path, nil, 'r+:UTF-8') do |file|
Puppet::Settings::IniFile.update(file) do |config|
if options[:section] == "master"
# delete requested master section if it exists,
# as server section should be used
setting_string = config.delete("master", name)
if setting_string
if Puppet::Util::Log.sendlevel?(:info)
report_section_and_environment(options[:section], Puppet.settings[:environment])
end
puts(_("Deleted setting from '%{section_name}': '%{setting_string}', and adding it to 'server' section") %
{ section_name: options[:section], name: name, setting_string: setting_string.strip })
end
# add the setting to the to server section instead of master section
config.set("server", name, value)
else
config.set(options[:section], name, value)
end
end
end
nil
end
end
action(:delete) do
summary _("Delete an OpenVox setting.")
arguments _("<setting>")
# TRANSLATORS 'main' is a specific section name and should not be translated
description "Deletes a setting from the specified section. (The default is the section 'main')."
notes <<-'EOT'
By default, this action deletes the configuration setting from the 'main'
configuration domain. Use the '--section' flags to delete settings from other
configuration domains.
EOT
examples <<-'EOT'
Delete the setting 'setting_name' from the 'main' configuration domain:
$ puppet config delete setting_name
Delete the setting 'setting_name' from the 'server' configuration domain:
$ puppet config delete setting_name --section server
EOT
when_invoked do |name, options|
@default_section = false
if options[:section] == DEFAULT_SECTION_MARKER
options[:section] = DEFAULT_SECTION
@default_section = true
end
path = Puppet::FileSystem.pathname(Puppet.settings.which_configuration_file)
if Puppet::FileSystem.exist?(path)
Puppet::FileSystem.open(path, nil, 'r+:UTF-8') do |file|
Puppet::Settings::IniFile.update(file) do |config|
# delete from both master section and server section
if options[:section] == "master" || options[:section] == "server"
master_setting_string = config.delete("master", name)
puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") %
{ section_name: 'master', name: name, setting_string: master_setting_string.strip[/[^=]+/] }) if master_setting_string
server_setting_string = config.delete("server", name)
puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") %
{ section_name: 'server', name: name, setting_string: server_setting_string.strip[/[^=]+/] }) if server_setting_string
else
setting_string = config.delete(options[:section], name)
if setting_string
if Puppet::Util::Log.sendlevel?(:info)
report_section_and_environment(options[:section], Puppet.settings[:environment])
end
puts(_("Deleted setting from '%{section_name}': '%{setting_string}'") %
{ section_name: options[:section], name: name, setting_string: setting_string.strip })
else
Puppet.warning(_("No setting found in configuration file for section '%{section_name}' setting name '%{name}'") %
{ section_name: options[:section], name: name })
end
end
end
end
else
# TRANSLATORS the 'puppet.conf' is a specific file and should not be translated
Puppet.warning(_("The puppet.conf file does not exist %{puppet_conf}") % { puppet_conf: path })
end
nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module.rb | lib/puppet/face/module.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
require_relative '../../puppet/module_tool'
require_relative '../../puppet/util/colors'
Puppet::Face.define(:module, '1.0.0') do
extend Puppet::Util::Colors
copyright "Puppet Inc., Vox Pupuli", 2012
license _("Apache 2 license; see COPYING")
summary _("Creates, installs and searches for modules on the Puppet Forge.")
description <<-EOT
This subcommand can find, install, and manage modules from the Puppet Forge,
a repository of user-contributed Puppet code. It can also generate empty
modules, and prepare locally developed modules for release on the Forge.
EOT
display_global_options "environment", "modulepath"
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/catalog/select.rb | lib/puppet/face/catalog/select.rb | # frozen_string_literal: true
# Select and show a list of resources of a given type.
Puppet::Face.define(:catalog, '0.0.1') do
action :select do
summary _("Retrieve a catalog and filter it for resources of a given type.")
arguments _("<host> <resource_type>")
returns _(<<-'EOT')
A list of resource references ("Type[title]"). When used from the API,
returns an array of Puppet::Resource objects excised from a catalog.
EOT
description <<-'EOT'
Retrieves a catalog for the specified host, then searches it for all
resources of the requested type.
EOT
notes <<-'NOTES'
By default, this action will retrieve a catalog from Puppet's compiler
subsystem; you must call the action with `--terminus rest` if you wish
to retrieve a catalog from the puppet master.
FORMATTING ISSUES: This action cannot currently render useful yaml;
instead, it returns an entire catalog. Use json instead.
NOTES
examples <<-'EOT'
Ask the puppet master for a list of managed file resources for a node:
$ puppet catalog select --terminus rest somenode.magpie.lan file
EOT
when_invoked do |host, type, _options|
# REVISIT: Eventually, type should have a default value that triggers
# the non-specific behaviour. For now, though, this will do.
# --daniel 2011-05-03
catalog = Puppet::Resource::Catalog.indirection.find(host)
if type == '*'
catalog.resources
else
type = type.downcase
catalog.resources.reject { |res| res.type.downcase != type }
end
end
when_rendering :console do |value|
if value.nil? then
_("no matching resources found")
else
value.map(&:to_s).join("\n")
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/node/clean.rb | lib/puppet/face/node/clean.rb | # frozen_string_literal: true
Puppet::Face.define(:node, '0.0.1') do
action(:clean) do
summary _("Clean up signed certs, cached facts, node objects, and reports for a node stored by the puppetmaster")
arguments _("<host1> [<host2> ...]")
description <<-'EOT'
Cleans up the following information a puppet master knows about a node:
<Signed certificates> - ($vardir/ssl/ca/signed/node.domain.pem)
<Cached facts> - ($vardir/yaml/facts/node.domain.yaml)
<Cached node objects> - ($vardir/yaml/node/node.domain.yaml)
<Reports> - ($vardir/reports/node.domain)
NOTE: this action now cleans up certs via Puppet Server's CA API. A running server is required for certs to be cleaned.
EOT
when_invoked do |*args|
nodes = args[0..-2]
options = args.last
raise _("At least one node should be passed") if nodes.empty? || nodes == options
# This seems really bad; run_mode should be set as part of a class
# definition, and should not be modifiable beyond that. This is one of
# the only places left in the code that tries to manipulate it. Other
# parts of code that handle certificates behave differently if the
# run_mode is server. Those other behaviors are needed for cleaning the
# certificates correctly.
Puppet.settings.preferred_run_mode = "server"
Puppet::Node::Facts.indirection.terminus_class = :yaml
Puppet::Node::Facts.indirection.cache_class = :yaml
Puppet::Node.indirection.terminus_class = :yaml
Puppet::Node.indirection.cache_class = :yaml
nodes.each { |node| cleanup(node.downcase) }
end
end
def cleanup(node)
clean_cert(node)
clean_cached_facts(node)
clean_cached_node(node)
clean_reports(node)
end
class LoggerIO
def debug(message)
Puppet.debug(message)
end
def warn(message)
Puppet.warning(message) unless message =~ /cadir is currently configured to be inside/
end
def err(message)
Puppet.err(message) unless message =~ /^\s*Error:\s*/
end
def inform(message)
Puppet.notice(message)
end
end
# clean signed cert for +host+
def clean_cert(node)
if Puppet.features.puppetserver_ca?
Puppetserver::Ca::Action::Clean.new(LoggerIO.new).run({ 'certnames' => [node] })
else
Puppet.info _("Not managing %{node} certs as this host is not a CA") % { node: node }
end
end
# clean facts for +host+
def clean_cached_facts(node)
Puppet::Node::Facts.indirection.destroy(node)
Puppet.info _("%{node}'s facts removed") % { node: node }
end
# clean cached node +host+
def clean_cached_node(node)
Puppet::Node.indirection.destroy(node)
Puppet.info _("%{node}'s cached node removed") % { node: node }
end
# clean node reports for +host+
def clean_reports(node)
Puppet::Transaction::Report.indirection.destroy(node)
Puppet.info _("%{node}'s reports removed") % { node: node }
end
def environment
@environment ||= Puppet.lookup(:current_environment)
end
def type_is_ensurable(resource)
if (type = Puppet::Type.type(resource.restype)) && type.validattr?(:ensure)
return true
else
type = environment.known_resource_types.find_definition(resource.restype)
return true if type && type.arguments.keys.include?('ensure')
end
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module/uninstall.rb | lib/puppet/face/module/uninstall.rb | # frozen_string_literal: true
Puppet::Face.define(:module, '1.0.0') do
action(:uninstall) do
summary _("Uninstall a puppet module.")
description <<-EOT
Uninstalls a puppet module from the modulepath (or a specific
target directory).
Note: Module uninstall uses MD5 checksums, which are prohibited on FIPS enabled systems.
EOT
returns _("Hash of module objects representing uninstalled modules and related errors.")
examples <<-'EOT'
Uninstall a module:
$ puppet module uninstall puppetlabs-ssh
Removed /etc/puppetlabs/code/modules/ssh (v1.0.0)
Uninstall a module from a specific directory:
$ puppet module uninstall puppetlabs-ssh --modulepath /opt/puppetlabs/puppet/modules
Removed /opt/puppetlabs/puppet/modules/ssh (v1.0.0)
Uninstall a module from a specific environment:
$ puppet module uninstall puppetlabs-ssh --environment development
Removed /etc/puppetlabs/code/environments/development/modules/ssh (v1.0.0)
Uninstall a specific version of a module:
$ puppet module uninstall puppetlabs-ssh --version 2.0.0
Removed /etc/puppetlabs/code/modules/ssh (v2.0.0)
EOT
arguments _("<name>")
option "--force", "-f" do
summary _("Force uninstall of an installed module.")
description <<-EOT
Force the uninstall of an installed module even if there are local
changes or the possibility of causing broken dependencies.
EOT
end
option "--ignore-changes", "-c" do
summary _("Ignore any local changes made. (Implied by --force.)")
description <<-EOT
Uninstall an installed module even if there are local changes to it. (Implied by --force.)
EOT
end
option "--version=" do
summary _("The version of the module to uninstall")
description <<-EOT
The version of the module to uninstall. When using this option, a module
matching the specified version must be installed or else an error is raised.
EOT
end
when_invoked do |name, options|
name = name.tr('/', '-')
Puppet::ModuleTool.set_option_defaults options
message = if options[:version]
module_version = colorize(:cyan, options[:version].sub(/^(?=\d)/, 'v'))
_("Preparing to uninstall '%{name}' (%{module_version}) ...") % { name: name, module_version: module_version }
else
_("Preparing to uninstall '%{name}' ...") % { name: name }
end
Puppet.notice message
Puppet::ModuleTool::Applications::Uninstaller.run(name, options)
end
when_rendering :console do |return_value|
if return_value[:result] == :failure
Puppet.err(return_value[:error][:multiline])
exit 1
else
mod = return_value[:affected_modules].first
message = if mod.version
module_version = colorize(:cyan, mod.version.to_s.sub(/^(?=\d)/, 'v'))
_("Removed '%{name}' (%{module_version}) from %{path}") % { name: return_value[:module_name], module_version: module_version, path: mod.modulepath }
else
_("Removed '%{name}' from %{path}") % { name: return_value[:module_name], path: mod.modulepath }
end
message
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module/changes.rb | lib/puppet/face/module/changes.rb | # frozen_string_literal: true
Puppet::Face.define(:module, '1.0.0') do
action(:changes) do
summary _("Show modified files of an installed module.")
description <<-EOT
Shows any files in a module that have been modified since it was
installed. This action compares the files on disk to the md5 checksums
included in the module's checksums.json or, if that is missing, in
metadata.json.
EOT
returns _("Array of strings representing paths of modified files.")
examples <<-EOT
Show modified files of an installed module:
$ puppet module changes /etc/puppetlabs/code/modules/vcsrepo/
warning: 1 files modified
lib/puppet/provider/vcsrepo.rb
EOT
arguments _("<path>")
when_invoked do |path, options|
Puppet::ModuleTool.set_option_defaults options
root_path = Puppet::ModuleTool.find_module_root(path)
unless root_path
raise ArgumentError, _("Could not find a valid module at %{path}") % { path: path.inspect }
end
Puppet::ModuleTool::Applications::Checksummer.run(root_path, options)
end
when_rendering :console do |return_value|
if return_value.empty?
Puppet.notice _("No modified files")
else
Puppet.warning _("%{count} files modified") % { count: return_value.size }
end
return_value.map(&:to_s).join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module/upgrade.rb | lib/puppet/face/module/upgrade.rb | # encoding: UTF-8
# frozen_string_literal: true
Puppet::Face.define(:module, '1.0.0') do
action(:upgrade) do
summary _("Upgrade a puppet module.")
description <<-EOT
Upgrades a puppet module.
Note: Module upgrade uses MD5 checksums, which are prohibited on FIPS enabled systems.
EOT
returns "Hash"
examples <<-EOT
upgrade an installed module to the latest version
$ puppet module upgrade puppetlabs-apache
/etc/puppetlabs/puppet/modules
└── puppetlabs-apache (v1.0.0 -> v2.4.0)
upgrade an installed module to a specific version
$ puppet module upgrade puppetlabs-apache --version 2.1.0
/etc/puppetlabs/puppet/modules
└── puppetlabs-apache (v1.0.0 -> v2.1.0)
upgrade an installed module for a specific environment
$ puppet module upgrade puppetlabs-apache --environment test
/etc/puppetlabs/code/environments/test/modules
└── puppetlabs-apache (v1.0.0 -> v2.4.0)
EOT
arguments _("<name>")
option "--force", "-f" do
summary _("Force upgrade of an installed module. (Implies --ignore-dependencies.)")
description <<-EOT
Force the upgrade of an installed module even if there are local
changes or the possibility of causing broken dependencies.
Implies --ignore-dependencies.
EOT
end
option "--ignore-dependencies" do
summary _("Do not attempt to install dependencies. (Implied by --force.)")
description <<-EOT
Do not attempt to install dependencies. Implied by --force.
EOT
end
option "--ignore-changes", "-c" do
summary _("Ignore and overwrite any local changes made. (Implied by --force.)")
description <<-EOT
Upgrade an installed module even if there are local changes to it. (Implied by --force.)
EOT
end
option "--version=" do
summary _("The version of the module to upgrade to.")
description <<-EOT
The version of the module to upgrade to.
EOT
end
when_invoked do |name, options|
name = name.tr('/', '-')
Puppet.notice _("Preparing to upgrade '%{name}' ...") % { name: name }
Puppet::ModuleTool.set_option_defaults options
Puppet::ModuleTool::Applications::Upgrader.new(name, options).run
end
when_rendering :console do |return_value|
case return_value[:result]
when :noop
Puppet.notice return_value[:error][:multiline]
exit 0
when :failure
Puppet.err(return_value[:error][:multiline])
exit 1
else
tree = Puppet::ModuleTool.build_tree(return_value[:graph], return_value[:base_dir])
"#{return_value[:base_dir]}\n" +
Puppet::ModuleTool.format_tree(tree)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module/list.rb | lib/puppet/face/module/list.rb | # encoding: UTF-8
# frozen_string_literal: true
Puppet::Face.define(:module, '1.0.0') do
action(:list) do
summary _("List installed modules")
description <<-HEREDOC
Lists the installed puppet modules. By default, this action scans the
modulepath from puppet.conf's `[main]` block; use the --modulepath
option to change which directories are scanned.
The output of this action includes information from the module's
metadata, including version numbers and unmet module dependencies.
HEREDOC
returns _("hash of paths to module objects")
option "--tree" do
summary _("Whether to show dependencies as a tree view")
end
examples <<-'EOT'
List installed modules:
$ puppet module list
/etc/puppetlabs/code/modules
├── bodepd-create_resources (v0.0.1)
├── puppetlabs-bacula (v0.0.2)
├── puppetlabs-mysql (v0.0.1)
├── puppetlabs-sqlite (v0.0.1)
└── puppetlabs-stdlib (v2.2.1)
/opt/puppetlabs/puppet/modules (no modules installed)
List installed modules in a tree view:
$ puppet module list --tree
/etc/puppetlabs/code/modules
└─┬ puppetlabs-bacula (v0.0.2)
├── puppetlabs-stdlib (v2.2.1)
├─┬ puppetlabs-mysql (v0.0.1)
│ └── bodepd-create_resources (v0.0.1)
└── puppetlabs-sqlite (v0.0.1)
/opt/puppetlabs/puppet/modules (no modules installed)
List installed modules from a specified environment:
$ puppet module list --environment production
/etc/puppetlabs/code/modules
├── bodepd-create_resources (v0.0.1)
├── puppetlabs-bacula (v0.0.2)
├── puppetlabs-mysql (v0.0.1)
├── puppetlabs-sqlite (v0.0.1)
└── puppetlabs-stdlib (v2.2.1)
/opt/puppetlabs/puppet/modules (no modules installed)
List installed modules from a specified modulepath:
$ puppet module list --modulepath /opt/puppetlabs/puppet/modules
/opt/puppetlabs/puppet/modules (no modules installed)
EOT
when_invoked do |options|
Puppet::ModuleTool.set_option_defaults(options)
environment = options[:environment_instance]
modules_by_path = environment.modules_by_path
{
:environment => environment,
:modules_by_path => modules_by_path,
:unmet_dependencies => unmet_dependencies(environment),
}
end
when_rendering :console do |result, options|
environment = result[:environment]
modules_by_path = result[:modules_by_path]
output = ''.dup
warn_unmet_dependencies(environment)
environment.modulepath.each do |path|
modules = modules_by_path[path]
no_mods = modules.empty? ? _(' (no modules installed)') : ''
output << "#{path}#{no_mods}\n"
if options[:tree]
# The modules with fewest things depending on them will be the
# parent of the tree. Can't assume to start with 0 dependencies
# since dependencies may be cyclical.
modules_by_num_requires = modules.sort_by { |m| m.required_by.size }
@seen = {}
tree = list_build_tree(modules_by_num_requires, [], nil,
:label_unmet => true, :path => path, :label_invalid => false)
else
tree = []
modules.sort_by { |mod| mod.forge_name or mod.name }.each do |mod|
tree << list_build_node(mod, path, :label_unmet => false,
:path => path, :label_invalid => true)
end
end
output << Puppet::ModuleTool.format_tree(tree)
end
output
end
end
def unmet_dependencies(environment)
error_types = [:non_semantic_version, :version_mismatch, :missing]
unmet_deps = {}
error_types.each do |type|
unmet_deps[type] = Hash.new do |hash, key|
hash[key] = { :errors => [], :parent => nil }
end
end
# Prepare the unmet dependencies for display on the console.
environment.modules.sort_by(&:name).each do |mod|
unmet_grouped = Hash.new { |h, k| h[k] = [] }
unmet_grouped = mod.unmet_dependencies.each_with_object(unmet_grouped) do |dep, acc|
acc[dep[:reason]] << dep
end
unmet_grouped.each do |type, deps|
next if deps.empty?
unmet_grouped[type].sort_by { |dep| dep[:name] }.each do |dep|
dep_name = dep[:name].tr('/', '-')
installed_version = dep[:mod_details][:installed_version]
version_constraint = dep[:version_constraint]
parent_name = dep[:parent][:name].tr('/', '-')
parent_version = dep[:parent][:version]
msg = _("'%{parent_name}' (%{parent_version}) requires '%{dependency_name}' (%{dependency_version})") % { parent_name: parent_name, parent_version: parent_version, dependency_name: dep_name, dependency_version: version_constraint }
unmet_deps[type][dep[:name]][:errors] << msg
unmet_deps[type][dep[:name]][:parent] = {
:name => dep[:parent][:name],
:version => parent_version
}
unmet_deps[type][dep[:name]][:version] = installed_version
end
end
end
unmet_deps
end
def warn_unmet_dependencies(environment)
@unmet_deps = unmet_dependencies(environment)
# Display unmet dependencies by category.
error_display_order = [:non_semantic_version, :version_mismatch, :missing]
error_display_order.each do |type|
next if @unmet_deps[type].empty?
@unmet_deps[type].keys.sort.each do |dep|
name = dep.tr('/', '-')
errors = @unmet_deps[type][dep][:errors]
version = @unmet_deps[type][dep][:version]
msg = case type
when :version_mismatch
_("Module '%{name}' (v%{version}) fails to meet some dependencies:\n") % { name: name, version: version }
when :non_semantic_version
_("Non semantic version dependency %{name} (v%{version}):\n") % { name: name, version: version }
else
_("Missing dependency '%{name}':\n") % { name: name }
end
errors.each { |error_string| msg << " #{error_string}\n" }
Puppet.warning msg.chomp
end
end
end
# Prepare a list of module objects and their dependencies for print in a
# tree view.
#
# Returns an Array of Hashes
#
# Example:
#
# [
# {
# :text => "puppetlabs-bacula (v0.0.2)",
# :dependencies=> [
# { :text => "puppetlabs-stdlib (v2.2.1)", :dependencies => [] },
# {
# :text => "puppetlabs-mysql (v1.0.0)"
# :dependencies => [
# {
# :text => "bodepd-create_resources (v0.0.1)",
# :dependencies => []
# }
# ]
# },
# { :text => "puppetlabs-sqlite (v0.0.1)", :dependencies => [] },
# ]
# }
# ]
#
# When the above data structure is passed to Puppet::ModuleTool.build_tree
# you end up with something like this:
#
# /etc/puppetlabs/code/modules
# └─┬ puppetlabs-bacula (v0.0.2)
# ├── puppetlabs-stdlib (v2.2.1)
# ├─┬ puppetlabs-mysql (v1.0.0)
# │ └── bodepd-create_resources (v0.0.1)
# └── puppetlabs-sqlite (v0.0.1)
#
def list_build_tree(list, ancestors = [], parent = nil, params = {})
list.filter_map do |mod|
next if @seen[(mod.forge_name or mod.name)]
node = list_build_node(mod, parent, params)
@seen[(mod.forge_name or mod.name)] = true
unless ancestors.include?(mod)
node[:dependencies] ||= []
missing_deps = mod.unmet_dependencies.select do |dep|
dep[:reason] == :missing
end
missing_deps.map do |mis_mod|
str = "#{colorize(:bg_red, _('UNMET DEPENDENCY'))} #{mis_mod[:name].tr('/', '-')} "
str << "(#{colorize(:cyan, mis_mod[:version_constraint])})"
node[:dependencies] << { :text => str }
end
node[:dependencies] += list_build_tree(mod.dependencies_as_modules,
ancestors + [mod], mod, params)
end
node
end
end
# Prepare a module object for print in a tree view. Each node in the tree
# must be a Hash in the following format:
#
# { :text => "puppetlabs-mysql (v1.0.0)" }
#
# The value of a module's :text is affected by three (3) factors: the format
# of the tree, its dependency status, and the location in the modulepath
# relative to its parent.
#
# Returns a Hash
#
def list_build_node(mod, parent, params)
str = ''.dup
str << (mod.forge_name ? mod.forge_name.tr('/', '-') : mod.name)
str << ' (' + colorize(:cyan, mod.version ? "v#{mod.version}" : '???') + ')'
unless File.dirname(mod.path) == params[:path]
str << " [#{File.dirname(mod.path)}]"
end
if @unmet_deps[:version_mismatch].include?(mod.forge_name)
if params[:label_invalid]
str << ' ' + colorize(:red, _('invalid'))
elsif parent.respond_to?(:forge_name)
unmet_parent = @unmet_deps[:version_mismatch][mod.forge_name][:parent]
if unmet_parent[:name] == parent.forge_name &&
unmet_parent[:version] == "v#{parent.version}"
str << ' ' + colorize(:red, _('invalid'))
end
end
end
{ :text => str }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/face/module/install.rb | lib/puppet/face/module/install.rb | # encoding: UTF-8
# frozen_string_literal: true
require_relative '../../../puppet/forge'
require_relative '../../../puppet/module_tool/install_directory'
require 'pathname'
Puppet::Face.define(:module, '1.0.0') do
action(:install) do
summary _("Install a module from the Puppet Forge or a release archive.")
description <<-EOT
Installs a module from the Puppet Forge or from a release archive file.
Note: Module install uses MD5 checksums, which are prohibited on FIPS enabled systems.
The specified module will be installed into the directory
specified with the `--target-dir` option, which defaults to the first
directory in the modulepath.
EOT
returns _("Pathname object representing the path to the installed module.")
examples <<-'EOT'
Install a module:
$ puppet module install puppetlabs-vcsrepo
Preparing to install into /etc/puppetlabs/code/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/etc/puppetlabs/code/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a module to a specific environment:
$ puppet module install puppetlabs-vcsrepo --environment development
Preparing to install into /etc/puppetlabs/code/environments/development/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/etc/puppetlabs/code/environments/development/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a specific module version:
$ puppet module install puppetlabs-vcsrepo -v 0.0.4
Preparing to install into /etc/puppetlabs/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/etc/puppetlabs/code/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a module into a specific directory:
$ puppet module install puppetlabs-vcsrepo --target-dir=/opt/puppetlabs/puppet/modules
Preparing to install into /opt/puppetlabs/puppet/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/opt/puppetlabs/puppet/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a module into a specific directory and check for dependencies in other directories:
$ puppet module install puppetlabs-vcsrepo --target-dir=/opt/puppetlabs/puppet/modules --modulepath /etc/puppetlabs/code/modules
Preparing to install into /opt/puppetlabs/puppet/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/opt/puppetlabs/puppet/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a module from a release archive:
$ puppet module install puppetlabs-vcsrepo-0.0.4.tar.gz
Preparing to install into /etc/puppetlabs/code/modules ...
Downloading from https://forgeapi.puppet.com ...
Installing -- do not interrupt ...
/etc/puppetlabs/code/modules
└── puppetlabs-vcsrepo (v0.0.4)
Install a module from a release archive and ignore dependencies:
$ puppet module install puppetlabs-vcsrepo-0.0.4.tar.gz --ignore-dependencies
Preparing to install into /etc/puppetlabs/code/modules ...
Installing -- do not interrupt ...
/etc/puppetlabs/code/modules
└── puppetlabs-vcsrepo (v0.0.4)
EOT
arguments _("<name>")
option "--force", "-f" do
summary _("Force overwrite of existing module, if any. (Implies --ignore-dependencies.)")
description <<-EOT
Force overwrite of existing module, if any.
Implies --ignore-dependencies.
EOT
end
option "--target-dir DIR", "-i DIR" do
summary _("The directory into which modules are installed.")
description <<-EOT
The directory into which modules are installed; defaults to the first
directory in the modulepath.
Specifying this option will change the installation directory, and
will use the existing modulepath when checking for dependencies. If
you wish to check a different set of directories for dependencies, you
must also use the `--environment` or `--modulepath` options.
EOT
end
option "--ignore-dependencies" do
summary _("Do not attempt to install dependencies. (Implied by --force.)")
description <<-EOT
Do not attempt to install dependencies. Implied by --force.
EOT
end
option "--version VER", "-v VER" do
summary _("Module version to install.")
description <<-EOT
Module version to install; can be an exact version or a requirement string,
eg '>= 1.0.3'. Defaults to latest version.
EOT
end
when_invoked do |name, options|
Puppet::ModuleTool.set_option_defaults options
Puppet.notice _("Preparing to install into %{dir} ...") % { dir: options[:target_dir] }
install_dir = Puppet::ModuleTool::InstallDirectory.new(Pathname.new(options[:target_dir]))
Puppet::ModuleTool::Applications::Installer.run(name, install_dir, options)
end
when_rendering :console do |return_value, name, _options|
case return_value[:result]
when :noop
Puppet.notice _("Module %{name} %{version} is already installed.") % { name: name, version: return_value[:version] }
exit 0
when :failure
Puppet.err(return_value[:error][:multiline])
exit 1
else
tree = Puppet::ModuleTool.build_tree(return_value[:graph], return_value[:install_dir])
"#{return_value[:install_dir]}\n" +
Puppet::ModuleTool.format_tree(tree)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/any.rb | lib/puppet/confine/any.rb | # frozen_string_literal: true
class Puppet::Confine::Any < Puppet::Confine
def self.summarize(confines)
confines.inject(0) { |count, confine| count + confine.summary }
end
def pass?(value)
!!value
end
def message(value)
"0 confines (of #{value.length}) were true"
end
def summary
result.find_all { |v| v == true }.length
end
def valid?
if @values.any? { |value| pass?(value) }
true
else
Puppet.debug { "#{label}: #{message(@values)}" }
false
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/boolean.rb | lib/puppet/confine/boolean.rb | # frozen_string_literal: true
require_relative '../../puppet/confine'
# Common module for the Boolean confines. It currently
# contains just enough code to implement PUP-9336.
class Puppet::Confine
module Boolean
# Returns the passing value for the Boolean confine.
def passing_value
raise NotImplementedError, "The Boolean confine %{confine} must provide the passing value." % { confine: self.class.name }
end
# The Boolean confines 'true' and 'false' let the user specify
# two types of values:
# * A lambda for lazy evaluation. This would be something like
# confine :true => lambda { true }
#
# * A single Boolean value, or an array of Boolean values. This would
# be something like
# confine :true => true OR confine :true => [true, false, false, true]
#
# This override distinguishes between the two cases.
def values
# Note that Puppet::Confine's constructor ensures that @values
# will always be an array, even if a lambda's passed in. This is
# why we have the length == 1 check.
unless @values.length == 1 && @values.first.respond_to?(:call)
return @values
end
# We have a lambda. Here, we want to enforce "cache positive"
# behavior, which is to cache the result _if_ it evaluates to
# the passing value (i.e. the class name).
return @cached_value unless @cached_value.nil?
# Double negate to coerce the value into a Boolean
calculated_value = !!@values.first.call
if calculated_value == passing_value
@cached_value = [calculated_value]
end
[calculated_value]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/feature.rb | lib/puppet/confine/feature.rb | # frozen_string_literal: true
require_relative '../../puppet/confine'
class Puppet::Confine::Feature < Puppet::Confine
def self.summarize(confines)
confines.collect(&:values).flatten.uniq.find_all { |value| !confines[0].pass?(value) }
end
# Is the named feature available?
def pass?(value)
Puppet.features.send(value.to_s + "?")
end
def message(value)
"feature #{value} is missing"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/false.rb | lib/puppet/confine/false.rb | # frozen_string_literal: true
require_relative '../../puppet/confine/boolean'
class Puppet::Confine::False < Puppet::Confine
include Puppet::Confine::Boolean
def passing_value
false
end
def self.summarize(confines)
confines.inject(0) { |count, confine| count + confine.summary }
end
def pass?(value)
!value
end
def message(value)
"true value when expecting false"
end
def summary
result.find_all { |v| v == false }.length
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/variable.rb | lib/puppet/confine/variable.rb | # frozen_string_literal: true
require_relative '../../puppet/confine'
# Require a specific value for a variable, either a Puppet setting
# or a Facter value. This class is a bit weird because the name
# is set explicitly by the ConfineCollection class -- from this class,
# it's not obvious how the name would ever get set.
class Puppet::Confine::Variable < Puppet::Confine
# Provide a hash summary of failing confines -- the key of the hash
# is the name of the confine, and the value is the missing yet required values.
# Only returns failed values, not all required values.
def self.summarize(confines)
result = Hash.new { |hash, key| hash[key] = [] }
confines.each_with_object(result) { |confine, total| total[confine.name] += confine.values unless confine.valid?; }
end
# This is set by ConfineCollection.
attr_accessor :name
# Retrieve the value from facter
def facter_value
@facter_value ||= Puppet.runtime[:facter].value(name).to_s.downcase
end
def initialize(values)
super
@values = @values.collect { |v| v.to_s.downcase }
end
def message(value)
"facter value '#{test_value}' for '#{name}' not in required list '#{values.join(',')}'"
end
# Compare the passed-in value to the retrieved value.
def pass?(value)
test_value.downcase.to_s == value.to_s.downcase
end
def reset
# Reset the cache. We want to cache it during a given
# run, but not across runs.
@facter_value = nil
end
def valid?
@values.include?(test_value.to_s.downcase)
ensure
reset
end
private
def setting?
Puppet.settings.valid?(name)
end
def test_value
setting? ? Puppet.settings[name] : facter_value
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/true.rb | lib/puppet/confine/true.rb | # frozen_string_literal: true
require_relative '../../puppet/confine/boolean'
class Puppet::Confine::True < Puppet::Confine
include Puppet::Confine::Boolean
def passing_value
true
end
def self.summarize(confines)
confines.inject(0) { |count, confine| count + confine.summary }
end
def pass?(value)
# Double negate, so we only get true or false.
!!value
end
def message(value)
"false value when expecting true"
end
def summary
result.find_all { |v| v == true }.length
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine/exists.rb | lib/puppet/confine/exists.rb | # frozen_string_literal: true
require_relative '../../puppet/confine'
class Puppet::Confine::Exists < Puppet::Confine
def self.summarize(confines)
confines.inject([]) { |total, confine| total + confine.summary }
end
def pass?(value)
value && (for_binary? ? which(value) : Puppet::FileSystem.exist?(value))
end
def message(value)
"file #{value} does not exist"
end
def summary
result.zip(values).each_with_object([]) { |args, array| val, f = args; array << f unless val; }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/resource.rb | lib/puppet/parser/resource.rb | # frozen_string_literal: true
require_relative '../../puppet/resource'
# The primary difference between this class and its
# parent is that this class has rules on who can set
# parameters
class Puppet::Parser::Resource < Puppet::Resource
require_relative 'resource/param'
require_relative '../../puppet/util/tagging'
include Puppet::Util
include Puppet::Util::Errors
include Puppet::Util::Logging
attr_accessor :source, :scope, :collector_id
attr_accessor :virtual, :override, :translated, :catalog, :evaluated
attr_accessor :file, :line, :kind
attr_reader :exported, :parameters
# Determine whether the provided parameter name is a relationship parameter.
def self.relationship_parameter?(name)
@relationship_names ||= Puppet::Type.relationship_params.collect(&:name)
@relationship_names.include?(name)
end
# Set up some boolean test methods
def translated?; !!@translated; end
def override?; !!@override; end
def evaluated?; !!@evaluated; end
def [](param)
param = param.intern
if param == :title
return title
end
if @parameters.has_key?(param)
@parameters[param].value
else
nil
end
end
def eachparam
@parameters.each do |_name, param|
yield param
end
end
def environment
scope.environment
end
# Process the stage metaparameter for a class. A containment edge
# is drawn from the class to the stage. The stage for containment
# defaults to main, if none is specified.
def add_edge_to_stage
return unless class?
stage = catalog.resource(:stage, self[:stage] || (scope && scope.resource && scope.resource[:stage]) || :main)
unless stage
raise ArgumentError, _("Could not find stage %{stage} specified by %{resource}") % { stage: self[:stage] || :main, resource: self }
end
self[:stage] ||= stage.title unless stage.title == :main
catalog.add_edge(stage, self)
end
# Retrieve the associated definition and evaluate it.
def evaluate
return if evaluated?
Puppet::Util::Profiler.profile(_("Evaluated resource %{res}") % { res: self }, [:compiler, :evaluate_resource, self]) do
@evaluated = true
if builtin_type?
devfail "Cannot evaluate a builtin type (#{type})"
elsif resource_type.nil?
self.fail "Cannot find definition #{type}"
else
finish_evaluation() # do not finish completely (as that destroys Sensitive data)
resource_type.evaluate_code(self)
end
end
end
# Mark this resource as both exported and virtual,
# or remove the exported mark.
def exported=(value)
if value
@virtual = true
else
end
@exported = value
end
# Finish the evaluation by assigning defaults and scope tags
# @api private
#
def finish_evaluation
return if @evaluation_finished
add_scope_tags
@evaluation_finished = true
end
# Do any finishing work on this object, called before
# storage/translation. The method does nothing the second time
# it is called on the same resource.
#
# @param do_validate [Boolean] true if validation should be performed
#
# @api private
def finish(do_validate = true)
return if finished?
@finished = true
finish_evaluation
replace_sensitive_data
validate if do_validate
end
# Has this resource already been finished?
def finished?
@finished
end
def initialize(type, title, attributes, with_defaults = true)
raise ArgumentError, _('Resources require a hash as last argument') unless attributes.is_a? Hash
raise ArgumentError, _('Resources require a scope') unless attributes[:scope]
super(type, title, attributes)
@source ||= scope.source
if with_defaults
scope.lookupdefaults(self.type).each_pair do |name, param|
next if @parameters.include?(name)
debug "Adding default for #{name}"
param = param.dup
@parameters[name] = param
tag(*param.value) if param.name == :tag
end
end
end
# Is this resource modeling an isomorphic resource type?
def isomorphic?
if builtin_type?
resource_type.isomorphic?
else
true
end
end
# Merge an override resource in. This will throw exceptions if
# any overrides aren't allowed.
def merge(resource)
# Test the resource scope, to make sure the resource is even allowed
# to override.
unless source.equal?(resource.source) || resource.source.child_of?(source)
raise Puppet::ParseError.new(_("Only subclasses can override parameters"), resource.file, resource.line)
end
if evaluated?
error_location_str = Puppet::Util::Errors.error_location(file, line)
msg = if error_location_str.empty?
_('Attempt to override an already evaluated resource with new values')
else
_('Attempt to override an already evaluated resource, defined at %{error_location}, with new values') % { error_location: error_location_str }
end
strict = Puppet[:strict]
unless strict == :off
if strict == :error
raise Puppet::ParseError.new(msg, resource.file, resource.line)
else
msg += Puppet::Util::Errors.error_location_with_space(resource.file, resource.line)
Puppet.warning(msg)
end
end
end
# Some of these might fail, but they'll fail in the way we want.
resource.parameters.each do |_name, param|
override_parameter(param)
end
end
def name
self[:name] || title
end
# A temporary occasion, until I get paths in the scopes figured out.
alias path to_s
# Define a parameter in our resource.
# if we ever receive a parameter named 'tag', set
# the resource tags with its value.
def set_parameter(param, value = nil)
unless param.is_a?(Puppet::Parser::Resource::Param)
param = param.name if param.is_a?(Puppet::Pops::Resource::Param)
param = Puppet::Parser::Resource::Param.new(
:name => param, :value => value, :source => source
)
end
tag(*param.value) if param.name == :tag
# And store it in our parameter hash.
@parameters[param.name] = param
end
alias []= set_parameter
def to_hash
parse_title.merge(@parameters.each_with_object({}) do |(_, param), result|
value = param.value
value = (:undef == value) ? nil : value
next if value.nil?
case param.name
when :before, :subscribe, :notify, :require
if value.is_a?(Array)
value = value.flatten.reject { |v| v.nil? || :undef == v }
end
else
end
result[param.name] = value
end)
end
# Convert this resource to a RAL resource.
def to_ral
copy_as_resource.to_ral
end
# Answers if this resource is tagged with at least one of the tags given in downcased string form.
#
# The method is a faster variant of the tagged? method that does no conversion of its
# arguments.
#
# The match takes into account the tags that a resource will inherit from its container
# but have not been set yet.
# It does *not* take tags set via resource defaults as these will *never* be set on
# the resource itself since all resources always have tags that are automatically
# assigned.
#
# @param tag_array [Array[String]] list tags to look for
# @return [Boolean] true if this instance is tagged with at least one of the provided tags
#
def raw_tagged?(tag_array)
super || ((scope_resource = scope.resource) && !scope_resource.equal?(self) && scope_resource.raw_tagged?(tag_array))
end
def offset
nil
end
def pos
nil
end
private
def add_scope_tags
scope_resource = scope.resource
unless scope_resource.nil? || scope_resource.equal?(self)
merge_tags_from(scope_resource)
end
end
def replace_sensitive_data
parameters.keys.each do |name|
param = parameters[name]
if param.value.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive)
@sensitive_parameters << name
parameters[name] = Puppet::Parser::Resource::Param.from_param(param, param.value.unwrap)
end
end
end
# Accept a parameter from an override.
def override_parameter(param)
# This can happen if the override is defining a new parameter, rather
# than replacing an existing one.
current = @parameters[param.name]
(set_parameter(param) and return) unless current
# Parameter is already set - if overriding with a default - simply ignore the setting of the default value
return if scope.is_default?(type, param.name, param.value)
# The parameter is already set. Fail if they're not allowed to override it.
unless param.source.child_of?(current.source) || param.source.equal?(current.source) && scope.is_default?(type, param.name, current.value)
error_location_str = Puppet::Util::Errors.error_location(current.file, current.line)
msg = if current.source.to_s == ''
if error_location_str.empty?
_("Parameter '%{name}' is already set on %{resource}; cannot redefine") %
{ name: param.name, resource: ref }
else
_("Parameter '%{name}' is already set on %{resource} at %{error_location}; cannot redefine") %
{ name: param.name, resource: ref, error_location: error_location_str }
end
elsif error_location_str.empty?
_("Parameter '%{name}' is already set on %{resource} by %{source}; cannot redefine") %
{ name: param.name, resource: ref, source: current.source.to_s }
else
_("Parameter '%{name}' is already set on %{resource} by %{source} at %{error_location}; cannot redefine") %
{ name: param.name, resource: ref, source: current.source.to_s, error_location: error_location_str }
end
raise Puppet::ParseError.new(msg, param.file, param.line)
end
# If we've gotten this far, we're allowed to override.
# Merge with previous value, if the parameter was generated with the +>
# syntax. It's important that we use a copy of the new param instance
# here, not the old one, and not the original new one, so that the source
# is registered correctly for later overrides but the values aren't
# implicitly shared when multiple resources are overridden at once (see
# ticket #3556).
if param.add
param = param.dup
param.value = [current.value, param.value].flatten
end
set_parameter(param)
end
# Make sure the resource's parameters are all valid for the type.
def validate
if builtin_type?
begin
@parameters.each { |name, _value| validate_parameter(name) }
rescue => detail
self.fail Puppet::ParseError, detail.to_s + " on #{self}", detail
end
else
resource_type.validate_resource(self)
end
end
def extract_parameters(params)
params.each do |param|
# Don't set the same parameter twice
self.fail Puppet::ParseError, _("Duplicate parameter '%{param}' for on %{resource}") % { param: param.name, resource: self } if @parameters[param.name]
set_parameter(param)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/templatewrapper.rb | lib/puppet/parser/templatewrapper.rb | # frozen_string_literal: true
require_relative '../../puppet/parser/files'
require 'erb'
require_relative '../../puppet/file_system'
# A simple wrapper for templates, so they don't have full access to
# the scope objects.
#
# @api private
class Puppet::Parser::TemplateWrapper
include Puppet::Util
Puppet::Util.logmethods(self)
def initialize(scope)
@__scope__ = scope
end
# @return [String] The full path name of the template that is being executed
# @api public
def file
@__file__
end
# @return [Puppet::Parser::Scope] The scope in which the template is evaluated
# @api public
def scope
@__scope__
end
# Find which line in the template (if any) we were called from.
# @return [String] the line number
# @api private
def script_line
identifier = Regexp.escape(@__file__ || "(erb)")
(caller.find { |l| l =~ /#{identifier}:/ } || "")[/:(\d+):/, 1]
end
private :script_line
# Should return true if a variable is defined, false if it is not
# @api public
def has_variable?(name)
scope.include?(name.to_s)
end
# @return [Array<String>] The list of defined classes
# @api public
def classes
scope.catalog.classes
end
# @return [Array<String>] The tags defined in the current scope
# @api public
def tags
raise NotImplementedError, "Call 'all_tags' instead."
end
# @return [Array<String>] All the defined tags
# @api public
def all_tags
scope.catalog.tags
end
# @api private
def file=(filename)
@__file__ = Puppet::Parser::Files.find_template(filename, scope.compiler.environment)
unless @__file__
raise Puppet::ParseError, _("Could not find template '%{filename}'") % { filename: filename }
end
end
# @api private
def result(string = nil)
if string
template_source = "inline template"
else
string = Puppet::FileSystem.read_preserve_line_endings(@__file__)
template_source = @__file__
end
# Expose all the variables in our scope as instance variables of the
# current object, making it possible to access them without conflict
# to the regular methods.
escaped_template_source = template_source.gsub(/%/, '%%')
benchmark(:debug, _("Bound template variables for %{template_source} in %%{seconds} seconds") % { template_source: escaped_template_source }) do
scope.to_hash.each do |name, value|
realname = name.gsub(/[^\w]/, "_")
instance_variable_set("@#{realname}", value)
end
end
result = nil
benchmark(:debug, _("Interpolated template %{template_source} in %%{seconds} seconds") % { template_source: escaped_template_source }) do
template = Puppet::Util.create_erb(string)
template.filename = @__file__
result = template.result(binding)
end
result
end
def to_s
"template[#{@__file__ || 'inline'}]"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/files.rb | lib/puppet/parser/files.rb | # frozen_string_literal: true
module Puppet::Parser::Files
module_function
# Return a list of manifests as absolute filenames matching the given
# pattern.
#
# @param pattern [String] A reference for a file in a module. It is the
# format "<modulename>/<file glob>"
# @param environment [Puppet::Node::Environment] the environment of modules
#
# @return [Array(String, Array<String>)] the module name and the list of files found
# @api private
def find_manifests_in_modules(pattern, environment)
module_name, file_pattern = split_file_path(pattern)
mod = environment.module(module_name)
if mod
[mod.name, mod.match_manifests(file_pattern)]
else
[nil, []]
end
end
# Find the path to the given file selector. Files can be selected in
# one of two ways:
# * absolute path: the path is simply returned
# * modulename/filename selector: a file is found in the file directory
# of the named module.
#
# The check for file existence is performed on the node compiling the
# manifest. A node running "puppet apply" compiles its own manifest, but
# a node running "puppet agent" depends on the configured puppetserver
# for compiling. In either case, a nil is returned if no file is found.
#
# @param template [String] the file selector
# @param environment [Puppet::Node::Environment] the environment in which to search
# @return [String, nil] the absolute path to the file or nil if there is no file found
#
# @api private
def find_file(file, environment)
find_in_module(file, environment) do |mod, module_file|
mod.file(module_file)
end
end
# Find the path to the given template selector. Templates can be selected in
# a couple of ways:
# * absolute path: the path is simply returned
# * modulename/filename selector: a file is found in the template directory
# of the named module.
#
# In the last two cases a nil is returned if there isn't a file found. In the
# first case (absolute path), there is no existence check done and so the
# path will be returned even if there isn't a file available.
#
# @param template [String] the template selector
# @param environment [Puppet::Node::Environment] the environment in which to search
# @return [String, nil] the absolute path to the template file or nil if there is no file found
#
# @api private
def find_template(template, environment)
find_in_module(template, environment) do |mod, template_file|
mod.template(template_file)
end
end
# @api private
def find_in_module(reference, environment)
if Puppet::Util.absolute_path?(reference)
reference
else
path, file = split_file_path(reference)
mod = environment.module(path)
if file && mod
yield(mod, file)
else
nil
end
end
end
# Split the path into the module and the rest of the path, or return
# nil if the path is empty or absolute (starts with a /).
# @api private
def split_file_path(path)
if path == "" || Puppet::Util.absolute_path?(path)
nil
else
path.split(File::SEPARATOR, 2)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/compiler.rb | lib/puppet/parser/compiler.rb | # frozen_string_literal: true
require 'forwardable'
require_relative '../../puppet/node'
require_relative '../../puppet/resource/catalog'
require_relative '../../puppet/util/errors'
require_relative '../../puppet/loaders'
require_relative '../../puppet/pops'
# Maintain a graph of scopes, along with a bunch of data
# about the individual catalog we're compiling.
class Puppet::Parser::Compiler
include Puppet::Parser::AbstractCompiler
extend Forwardable
include Puppet::Util
include Puppet::Util::Errors
include Puppet::Pops::Evaluator::Runtime3Support
def self.compile(node, code_id = nil)
node.environment.check_for_reparse
errors = node.environment.validation_errors
unless errors.empty?
errors.each { |e| Puppet.err(e) } if errors.size > 1
errmsg = [
_("Compilation has been halted because: %{error}") % { error: errors.first },
_("For more information, see https://puppet.com/docs/puppet/latest/environments_about.html")
]
raise(Puppet::Error, errmsg.join(' '))
end
new(node, :code_id => code_id).compile(&:to_resource)
rescue Puppet::ParseErrorWithIssue => detail
detail.node = node.name
Puppet.log_exception(detail)
raise
rescue => detail
message = _("%{message} on node %{node}") % { message: detail, node: node.name }
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
attr_reader :node, :facts, :collections, :catalog, :resources, :relationships, :topscope
attr_reader :qualified_variables
# Access to the configured loaders for 4x
# @return [Puppet::Pops::Loader::Loaders] the configured loaders
# @api private
attr_reader :loaders
# The id of code input to the compiler.
# @api private
attr_accessor :code_id
# Add a collection to the global list.
def_delegator :@collections, :<<, :add_collection
def_delegator :@relationships, :<<, :add_relationship
# Store a resource override.
def add_override(override)
# If possible, merge the override in immediately.
resource = @catalog.resource(override.ref)
if resource
resource.merge(override)
else
# Otherwise, store the override for later; these
# get evaluated in Resource#finish.
@resource_overrides[override.ref] << override
end
end
def add_resource(scope, resource)
@resources << resource
# Note that this will fail if the resource is not unique.
@catalog.add_resource(resource)
if !resource.class? and resource[:stage]
# TRANSLATORS "stage" is a keyword in Puppet and should not be translated
raise ArgumentError, _("Only classes can set 'stage'; normal resources like %{resource} cannot change run stage") % { resource: resource }
end
# Stages should not be inside of classes. They are always a
# top-level container, regardless of where they appear in the
# manifest.
return if resource.stage?
# This adds a resource to the class it lexically appears in in the
# manifest.
unless resource.class?
@catalog.add_edge(scope.resource, resource)
end
end
# Store the fact that we've evaluated a class
def add_class(name)
@catalog.add_class(name) unless name == ""
end
# Add a catalog validator that will run at some stage to this compiler
# @param catalog_validators [Class<CatalogValidator>] The catalog validator class to add
def add_catalog_validator(catalog_validators)
@catalog_validators << catalog_validators
nil
end
def add_catalog_validators
add_catalog_validator(CatalogValidator::RelationshipValidator)
end
# Return a list of all of the defined classes.
def_delegator :@catalog, :classes, :classlist
def with_context_overrides(description = '', &block)
Puppet.override(@context_overrides, description, &block)
end
# Compiler our catalog. This mostly revolves around finding and evaluating classes.
# This is the main entry into our catalog.
def compile
Puppet.override(@context_overrides, _("For compiling %{node}") % { node: node.name }) do
@catalog.environment_instance = environment
# Set the client's parameters into the top scope.
Puppet::Util::Profiler.profile(_("Compile: Set node parameters"), [:compiler, :set_node_params]) { set_node_parameters }
Puppet::Util::Profiler.profile(_("Compile: Created settings scope"), [:compiler, :create_settings_scope]) { create_settings_scope }
# TRANSLATORS "main" is a function name and should not be translated
Puppet::Util::Profiler.profile(_("Compile: Evaluated main"), [:compiler, :evaluate_main]) { evaluate_main }
Puppet::Util::Profiler.profile(_("Compile: Evaluated AST node"), [:compiler, :evaluate_ast_node]) { evaluate_ast_node }
Puppet::Util::Profiler.profile(_("Compile: Evaluated node classes"), [:compiler, :evaluate_node_classes]) { evaluate_node_classes }
Puppet::Util::Profiler.profile(_("Compile: Evaluated generators"), [:compiler, :evaluate_generators]) { evaluate_generators }
Puppet::Util::Profiler.profile(_("Compile: Validate Catalog pre-finish"), [:compiler, :validate_pre_finish]) do
validate_catalog(CatalogValidator::PRE_FINISH)
end
Puppet::Util::Profiler.profile(_("Compile: Finished catalog"), [:compiler, :finish_catalog]) { finish }
fail_on_unevaluated
Puppet::Util::Profiler.profile(_("Compile: Validate Catalog final"), [:compiler, :validate_final]) do
validate_catalog(CatalogValidator::FINAL)
end
if block_given?
yield @catalog
else
@catalog
end
end
end
def validate_catalog(validation_stage)
@catalog_validators.select { |vclass| vclass.validation_stage?(validation_stage) }.each { |vclass| vclass.new(@catalog).validate }
end
# Constructs the overrides for the context
def context_overrides
{
:current_environment => environment,
:global_scope => @topscope, # 4x placeholder for new global scope
:loaders => @loaders, # 4x loaders
}
end
def_delegator :@collections, :delete, :delete_collection
# Return the node's environment.
def environment
node.environment
end
# Evaluate all of the classes specified by the node.
# Classes with parameters are evaluated as if they were declared.
# Classes without parameters or with an empty set of parameters are evaluated
# as if they were included. This means classes with an empty set of
# parameters won't conflict even if the class has already been included.
def evaluate_node_classes
if @node.classes.is_a? Hash
classes_with_params, classes_without_params = @node.classes.partition { |_name, params| params and !params.empty? }
# The results from Hash#partition are arrays of pairs rather than hashes,
# so we have to convert to the forms evaluate_classes expects (Hash, and
# Array of class names)
classes_with_params = classes_with_params.to_h
classes_without_params.map!(&:first)
else
classes_with_params = {}
classes_without_params = @node.classes
end
evaluate_classes(classes_with_params, @node_scope || topscope)
evaluate_classes(classes_without_params, @node_scope || topscope)
end
# If ast nodes are enabled, then see if we can find and evaluate one.
#
# @api private
def evaluate_ast_node
krt = environment.known_resource_types
return unless krt.nodes? # ast_nodes?
# Now see if we can find the node.
astnode = nil
@node.names.each do |name|
astnode = krt.node(name.to_s.downcase)
break if astnode
end
unless astnode ||= krt.node("default")
raise Puppet::ParseError, _("Could not find node statement with name 'default' or '%{names}'") % { names: node.names.join(", ") }
end
# Create a resource to model this node, and then add it to the list
# of resources.
resource = astnode.ensure_in_catalog(topscope)
resource.evaluate
@node_scope = topscope.class_scope(astnode)
end
# Evaluates each specified class in turn. If there are any classes that
# can't be found, an error is raised. This method really just creates resource objects
# that point back to the classes, and then the resources are themselves
# evaluated later in the process.
#
def evaluate_classes(classes, scope, lazy_evaluate = true)
raise Puppet::DevError, _("No source for scope passed to evaluate_classes") unless scope.source
class_parameters = nil
# if we are a param class, save the classes hash
# and transform classes to be the keys
if classes.instance_of?(Hash)
class_parameters = classes
classes = classes.keys
end
hostclasses = classes.collect do |name|
environment.known_resource_types.find_hostclass(name) or raise Puppet::Error, _("Could not find class %{name} for %{node}") % { name: name, node: node.name }
end
if class_parameters
resources = ensure_classes_with_parameters(scope, hostclasses, class_parameters)
unless lazy_evaluate
resources.each(&:evaluate)
end
resources
else
already_included, newly_included = ensure_classes_without_parameters(scope, hostclasses)
unless lazy_evaluate
newly_included.each(&:evaluate)
end
already_included + newly_included
end
end
def evaluate_relationships
@relationships.each { |rel| rel.evaluate(catalog) }
end
# Return a resource by either its ref or its type and title.
def_delegator :@catalog, :resource, :findresource
def initialize(node, code_id: nil)
@node = sanitize_node(node)
@code_id = code_id
initvars
add_catalog_validators
# Resolutions of fully qualified variable names
@qualified_variables = {}
end
# Create a new scope, with either a specified parent scope or
# using the top scope.
def newscope(parent, options = {})
parent ||= topscope
scope = Puppet::Parser::Scope.new(self, **options)
scope.parent = parent
scope
end
# Return any overrides for the given resource.
def resource_overrides(resource)
@resource_overrides[resource.ref]
end
private
def ensure_classes_with_parameters(scope, hostclasses, parameters)
hostclasses.collect do |klass|
klass.ensure_in_catalog(scope, parameters[klass.name] || {})
end
end
def ensure_classes_without_parameters(scope, hostclasses)
already_included = []
newly_included = []
hostclasses.each do |klass|
class_scope = scope.class_scope(klass)
if class_scope
already_included << class_scope.resource
else
newly_included << klass.ensure_in_catalog(scope)
end
end
[already_included, newly_included]
end
# Evaluate our collections and return true if anything returned an object.
# The 'true' is used to continue a loop, so it's important.
def evaluate_collections
return false if @collections.empty?
exceptwrap do
# We have to iterate over a dup of the array because
# collections can delete themselves from the list, which
# changes its length and causes some collections to get missed.
Puppet::Util::Profiler.profile(_("Evaluated collections"), [:compiler, :evaluate_collections]) do
found_something = false
@collections.dup.each do |collection|
found_something = true if collection.evaluate
end
found_something
end
end
end
# Make sure all of our resources have been evaluated into native resources.
# We return true if any resources have, so that we know to continue the
# evaluate_generators loop.
def evaluate_definitions
exceptwrap do
Puppet::Util::Profiler.profile(_("Evaluated definitions"), [:compiler, :evaluate_definitions]) do
urs = unevaluated_resources.each do |resource|
resource.evaluate
rescue Puppet::Pops::Evaluator::PuppetStopIteration => detail
# needs to be handled specifically as the error has the file/line/position where this
# occurred rather than the resource
fail(Puppet::Pops::Issues::RUNTIME_ERROR, detail, { :detail => detail.message }, detail)
rescue Puppet::Error => e
# PuppetError has the ability to wrap an exception, if so, use the wrapped exception's
# call stack instead
fail(Puppet::Pops::Issues::RUNTIME_ERROR, resource, { :detail => e.message }, e.original || e)
end
!urs.empty?
end
end
end
# Iterate over collections and resources until we're sure that the whole
# compile is evaluated. This is necessary because both collections
# and defined resources can generate new resources, which themselves could
# be defined resources.
def evaluate_generators
count = 0
loop do
done = true
Puppet::Util::Profiler.profile(_("Iterated (%{count}) on generators") % { count: count + 1 }, [:compiler, :iterate_on_generators]) do
# Call collections first, then definitions.
done = false if evaluate_collections
done = false if evaluate_definitions
end
break if done
count += 1
if count > 1000
raise Puppet::ParseError, _("Somehow looped more than 1000 times while evaluating host catalog")
end
end
end
protected :evaluate_generators
# Find and evaluate our main object, if possible.
def evaluate_main
krt = environment.known_resource_types
@main = krt.find_hostclass('') || krt.add(Puppet::Resource::Type.new(:hostclass, ''))
@topscope.source = @main
@main_resource = Puppet::Parser::Resource.new('class', :main, :scope => @topscope, :source => @main)
@topscope.resource = @main_resource
add_resource(@topscope, @main_resource)
@main_resource.evaluate
end
# Make sure the entire catalog is evaluated.
def fail_on_unevaluated
fail_on_unevaluated_overrides
fail_on_unevaluated_resource_collections
end
# If there are any resource overrides remaining, then we could
# not find the resource they were supposed to override, so we
# want to throw an exception.
def fail_on_unevaluated_overrides
remaining = @resource_overrides.values.flatten.collect(&:ref)
unless remaining.empty?
raise Puppet::ParseError, _("Could not find resource(s) %{resources} for overriding") % { resources: remaining.join(', ') }
end
end
# Make sure there are no remaining collections that are waiting for
# resources that have not yet been instantiated. If this occurs it
# is an error (missing resource - it could not be realized).
#
def fail_on_unevaluated_resource_collections
remaining = @collections.collect(&:unresolved_resources).flatten.compact
unless remaining.empty?
raise Puppet::ParseError, _("Failed to realize virtual resources %{resources}") % { resources: remaining.join(', ') }
end
end
# Make sure all of our resources and such have done any last work
# necessary.
def finish
evaluate_relationships
resources.each do |resource|
# Add in any resource overrides.
overrides = resource_overrides(resource)
if overrides
overrides.each do |over|
resource.merge(over)
end
# Remove the overrides, so that the configuration knows there
# are none left.
overrides.clear
end
resource.finish if resource.respond_to?(:finish)
end
add_resource_metaparams
end
protected :finish
def add_resource_metaparams
main = catalog.resource(:class, :main)
unless main
# TRANSLATORS "main" is a function name and should not be translated
raise _("Couldn't find main")
end
names = Puppet::Type.metaparams.select do |name|
!Puppet::Parser::Resource.relationship_parameter?(name)
end
data = {}
catalog.walk(main, :out) do |source, target|
source_data = data[source] || metaparams_as_data(source, names)
if source_data
# only store anything in the data hash if we've actually got
# data
data[source] ||= source_data
source_data.each do |param, value|
target[param] = value if target[param].nil?
end
data[target] = source_data.merge(metaparams_as_data(target, names))
end
target.merge_tags_from(source)
end
end
def metaparams_as_data(resource, params)
data = nil
params.each do |param|
next if resource[param].nil?
# Because we could be creating a hash for every resource,
# and we actually probably don't often have any data here at all,
# we're optimizing a bit by only creating a hash if there's
# any data to put in it.
data ||= {}
data[param] = resource[param]
end
data
end
# Set up all of our internal variables.
def initvars
# The list of overrides. This is used to cache overrides on objects
# that don't exist yet. We store an array of each override.
@resource_overrides = Hash.new do |overs, ref|
overs[ref] = []
end
# The list of collections that have been created. This is a global list,
# but they each refer back to the scope that created them.
@collections = []
# The list of relationships to evaluate.
@relationships = []
# For maintaining the relationship between scopes and their resources.
@catalog = Puppet::Resource::Catalog.new(@node.name, @node.environment, @code_id)
# MOVED HERE - SCOPE IS NEEDED (MOVE-SCOPE)
# Create the initial scope, it is needed early
@topscope = Puppet::Parser::Scope.new(self)
# Initialize loaders and Pcore
@loaders = Puppet::Pops::Loaders.new(environment)
# Need to compute overrides here, and remember them, because we are about to
# enter the magic zone of known_resource_types and initial import.
# Expensive entries in the context are bound lazily.
@context_overrides = context_overrides()
# This construct ensures that initial import (triggered by instantiating
# the structure 'known_resource_types') has a configured context
# It cannot survive the initvars method, and is later reinstated
# as part of compiling...
#
Puppet.override(@context_overrides, _("For initializing compiler")) do
# THE MAGIC STARTS HERE ! This triggers parsing, loading etc.
@catalog.version = environment.known_resource_types.version
@loaders.pre_load
end
@catalog.add_resource(Puppet::Parser::Resource.new("stage", :main, :scope => @topscope))
# local resource array to maintain resource ordering
@resources = []
# Make sure any external node classes are in our class list
if @node.classes.instance_of?(Hash)
@catalog.add_class(*@node.classes.keys)
else
@catalog.add_class(*@node.classes)
end
@catalog_validators = []
end
def sanitize_node(node)
node.sanitize
node
end
# Set the node's parameters into the top-scope as variables.
def set_node_parameters
node.parameters.each do |param, value|
# We don't want to set @topscope['environment'] from the parameters,
# instead we want to get that from the node's environment itself in
# case a custom node terminus has done any mucking about with
# node.parameters.
next if param.to_s == 'environment'
# Ensure node does not leak Symbol instances in general
@topscope[param.to_s] = value.is_a?(Symbol) ? value.to_s : value
end
@topscope['environment'] = node.environment.name.to_s
# These might be nil.
catalog.client_version = node.parameters["clientversion"]
catalog.server_version = node.parameters["serverversion"]
@topscope.set_trusted(node.trusted_data)
@topscope.set_server_facts(node.server_facts)
facts_hash = node.facts.nil? ? {} : node.facts.values
@topscope.set_facts(facts_hash)
end
SETTINGS = 'settings'
def create_settings_scope
settings_type = create_settings_type
settings_resource = Puppet::Parser::Resource.new('class', SETTINGS, :scope => @topscope)
@catalog.add_resource(settings_resource)
settings_type.evaluate_code(settings_resource)
settings_resource.instance_variable_set(:@evaluated, true) # Prevents settings from being reevaluated
scope = @topscope.class_scope(settings_type)
scope.merge_settings(environment.name)
end
def create_settings_type
environment.lock.synchronize do
resource_types = environment.known_resource_types
settings_type = resource_types.hostclass(SETTINGS)
if settings_type.nil?
settings_type = Puppet::Resource::Type.new(:hostclass, SETTINGS)
resource_types.add(settings_type)
end
settings_type
end
end
# Return an array of all of the unevaluated resources. These will be definitions,
# which need to get evaluated into native resources.
def unevaluated_resources
# The order of these is significant for speed due to short-circuiting
resources.reject { |resource| resource.evaluated? or resource.virtual? or resource.builtin_type? }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/e4_parser_adapter.rb | lib/puppet/parser/e4_parser_adapter.rb | # frozen_string_literal: true
require_relative '../../puppet/pops'
module Puppet
module Parser
# Adapts an egrammar/eparser to respond to the public API of the classic parser
# and makes use of the new evaluator.
#
class E4ParserAdapter
def initialize
@file = ''
@string = ''
@use = :unspecified
end
def file=(file)
@file = file
@use = :file
end
def parse(string = nil)
self.string = string if string
parser = Pops::Parser::EvaluatingParser.singleton
model =
if @use == :string
# Parse with a source_file to set in created AST objects (it was either given, or it may be unknown
# if caller did not set a file and the present a string.
#
parser.parse_string(@string, @file || "unknown-source-location")
else
parser.parse_file(@file)
end
# the parse_result may be
# * empty / nil (no input)
# * a Model::Program
# * a Model::Expression
#
args = {}
Pops::Model::AstTransformer.new(@file).merge_location(args, model)
ast_code =
if model.is_a? Pops::Model::Program
AST::PopsBridge::Program.new(model, args)
else
args[:value] = model
AST::PopsBridge::Expression.new(args)
end
# Create the "main" class for the content - this content will get merged with all other "main" content
AST::Hostclass.new('', :code => ast_code)
end
def string=(string)
@string = string
@use = :string
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/relationship.rb | lib/puppet/parser/relationship.rb | # frozen_string_literal: true
class Puppet::Parser::Relationship
attr_accessor :source, :target, :type
PARAM_MAP = { :relationship => :before, :subscription => :notify }
def arrayify(resources, left)
case resources
when Puppet::Pops::Evaluator::Collectors::AbstractCollector
# on the LHS, go as far left as possible, else whatever the collected result is
left ? leftmost_alternative(resources) : resources.collected.values
when Array
resources
else
[resources]
end
end
def evaluate(catalog)
arrayify(source, true).each do |s|
arrayify(target, false).each do |t|
mk_relationship(s, t, catalog)
end
end
end
def initialize(source, target, type)
@source = source
@target = target
@type = type
end
def param_name
PARAM_MAP[type] || raise(ArgumentError, _("Invalid relationship type %{relationship_type}") % { relationship_type: type })
end
def mk_relationship(source, target, catalog)
source_ref = canonical_ref(source)
target_ref = canonical_ref(target)
rel_param = param_name
source_resource = catalog.resource(*source_ref)
unless source_resource
raise ArgumentError, _("Could not find resource '%{source}' for relationship on '%{target}'") % { source: source.to_s, target: target.to_s }
end
unless catalog.resource(*target_ref)
raise ArgumentError, _("Could not find resource '%{target}' for relationship from '%{source}'") % { target: target.to_s, source: source.to_s }
end
Puppet.debug { "Adding relationship from #{source} to #{target} with '#{param_name}'" }
if source_resource[rel_param].class != Array
source_resource[rel_param] = [source_resource[rel_param]].compact
end
source_resource[rel_param] << (target_ref[1].nil? ? target_ref[0] : "#{target_ref[0]}[#{target_ref[1]}]")
end
private
# Finds the leftmost alternative for a collector (if it is empty, try its empty alternative recursively until there is
# either nothing left, or a non empty set is found.
#
def leftmost_alternative(x)
if x.is_a?(Puppet::Pops::Evaluator::Collectors::AbstractCollector)
collected = x.collected
return collected.values unless collected.empty?
adapter = Puppet::Pops::Adapters::EmptyAlternativeAdapter.get(x)
adapter.nil? ? [] : leftmost_alternative(adapter.empty_alternative)
elsif x.is_a?(Array) && x.size == 1 && x[0].is_a?(Puppet::Pops::Evaluator::Collectors::AbstractCollector)
leftmost_alternative(x[0])
else
x
end
end
# Turns a PResourceType or PClassType into an array [type, title] and all other references to [ref, nil]
# This is needed since it is not possible to find resources in the catalog based on the type system types :-(
# (note, the catalog is also used on the agent side)
def canonical_ref(ref)
case ref
when Puppet::Pops::Types::PResourceType
[ref.type_name, ref.title]
when Puppet::Pops::Types::PClassType
['class', ref.class_name]
else
[ref.to_s, nil]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/script_compiler.rb | lib/puppet/parser/script_compiler.rb | # frozen_string_literal: true
require_relative '../../puppet/loaders'
require_relative '../../puppet/pops'
# A Script "compiler" that does not support catalog operations
#
# The Script compiler is "one shot" - it does not support rechecking if underlying source has changed or
# deal with possible errors in a cached environment.
#
class Puppet::Parser::ScriptCompiler
# Allows the ScriptCompiler to use the 3.x Scope class without being an actual "Compiler"
#
include Puppet::Parser::AbstractCompiler
# @api private
attr_reader :topscope
# @api private
attr_reader :qualified_variables
# Access to the configured loaders for 4x
# @return [Puppet::Pops::Loader::Loaders] the configured loaders
# @api private
attr_reader :loaders
# @api private
attr_reader :environment
# @api private
attr_reader :node_name
def with_context_overrides(description = '', &block)
Puppet.override(@context_overrides, description, &block)
end
# Evaluates the configured setup for a script + code in an environment with modules
#
def compile
Puppet[:strict_variables] = true
Puppet[:strict] = :error
# TRANSLATORS, "For running script" is not user facing
Puppet.override(@context_overrides, "For running script") do
# TRANSLATORS "main" is a function name and should not be translated
result = Puppet::Util::Profiler.profile(_("Script: Evaluated main"), [:script, :evaluate_main]) { evaluate_main }
if block_given?
yield self
else
result
end
end
rescue Puppet::ParseErrorWithIssue => detail
detail.node = node_name
Puppet.log_exception(detail)
raise
rescue => detail
message = "#{detail} on node #{node_name}"
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
# Constructs the overrides for the context
def context_overrides
{
:current_environment => environment,
:global_scope => @topscope, # 4x placeholder for new global scope
:loaders => @loaders, # 4x loaders
:rich_data => true,
}
end
# Create a script compiler for the given environment where errors are logged as coming
# from the given node_name
#
def initialize(environment, node_name, for_agent = false)
@environment = environment
@node_name = node_name
# Create the initial scope, it is needed early
@topscope = Puppet::Parser::Scope.new(self)
# Initialize loaders and Pcore
if for_agent
@loaders = Puppet::Pops::Loaders.new(environment, true)
else
@loaders = Puppet::Pops::Loaders.new(environment)
end
# Need to compute overrides here, and remember them, because we are about to
# Expensive entries in the context are bound lazily.
@context_overrides = context_overrides()
# Resolutions of fully qualified variable names
@qualified_variables = {}
end
# Having multiple named scopes hanging from top scope is not supported when scripting
# in the regular compiler this is used to create one named scope per class.
# When scripting, the "main class" is just a container of the top level code to evaluate
# and it is not evaluated as a class added to a catalog. Since classes are not supported
# there is no need to support the concept of "named scopes" as all variables are local
# or in the top scope itself (notably, the $settings:: namespace is initialized
# as just a set of variables in that namespace - there is no named scope for 'settings'
# when scripting.
#
# Keeping this method here to get specific error as being unsure if there are functions/logic
# that will call this. The AbstractCompiler defines this method, but maybe it does not
# have to (TODO).
#
def newscope(parent, options = {})
raise _('having multiple named scopes is not supported when scripting')
end
private
# Find and evaluate the top level code.
def evaluate_main
@loaders.pre_load
program = @loaders.load_main_manifest
program.nil? ? nil : Puppet::Pops::Parser::EvaluatingParser.singleton.evaluator.evaluate(program, @topscope)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/catalog_compiler.rb | lib/puppet/parser/catalog_compiler.rb | # frozen_string_literal: true
require_relative '../../puppet/loaders'
require_relative '../../puppet/pops'
# A Catalog "compiler" that is like the regular compiler but with an API
# that is harmonized with the ScriptCompiler
#
# The Script compiler is "one shot" - it does not support rechecking if underlying source has changed or
# deal with possible errors in a cached environment.
#
class Puppet::Parser::CatalogCompiler < Puppet::Parser::Compiler
# Evaluates the configured setup for a script + code in an environment with modules
#
def compile
Puppet[:strict_variables] = true
Puppet[:strict] = :error
Puppet.override(rich_data: true) do
super
end
rescue Puppet::ParseErrorWithIssue => detail
detail.node = node.name
Puppet.log_exception(detail)
raise
rescue => detail
message = "#{detail} on node #{node.name}"
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
# Evaluates all added constructs, and validates the resulting catalog.
# This can be called whenever a series of evaluation of puppet code strings
# have reached a stable state (essentially that there are no relationships to
# non-existing resources).
#
# Raises an error if validation fails.
#
def compile_additions
evaluate_additions
validate
end
# Evaluates added constructs that are lazily evaluated until all of them have been evaluated.
#
def evaluate_additions
evaluate_generators
finish
end
# Validates the current state of the catalog.
# Does not cause evaluation of lazy constructs.
def validate
validate_catalog(CatalogValidator::FINAL)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/scope.rb | lib/puppet/parser/scope.rb | # frozen_string_literal: true
# The scope class, which handles storing and retrieving variables and types and
# such.
require 'forwardable'
require_relative '../../puppet/parser'
require_relative '../../puppet/parser/templatewrapper'
require_relative '../../puppet/parser/resource'
# This class is part of the internal parser/evaluator/compiler functionality of Puppet.
# It is passed between the various classes that participate in evaluation.
# None of its methods are API except those that are clearly marked as such.
#
# @api public
class Puppet::Parser::Scope
extend Forwardable
# Variables that always exist with nil value even if not set
BUILT_IN_VARS = %w[module_name caller_module_name].freeze
EMPTY_HASH = {}.freeze
Puppet::Util.logmethods(self)
include Puppet::Util::Errors
attr_accessor :source, :resource
attr_reader :compiler
attr_accessor :parent
# Hash of hashes of default values per type name
attr_reader :defaults
# Alias for `compiler.environment`
def environment
@compiler.environment
end
# Alias for `compiler.catalog`
def catalog
@compiler.catalog
end
# Abstract base class for LocalScope and MatchScope
#
class Ephemeral
attr_reader :parent
def initialize(parent = nil)
@parent = parent
end
def is_local_scope?
false
end
def [](name)
if @parent
@parent[name]
end
end
def include?(name)
(@parent and @parent.include?(name))
end
def bound?(name)
false
end
def add_entries_to(target = {}, include_undef = false)
@parent.add_entries_to(target, include_undef) unless @parent.nil?
# do not include match data ($0-$n)
target
end
end
class LocalScope < Ephemeral
def initialize(parent = nil)
super parent
@symbols = {}
end
def [](name)
val = @symbols[name]
val.nil? && !@symbols.include?(name) ? super : val
end
def is_local_scope?
true
end
def []=(name, value)
@symbols[name] = value
end
def include?(name)
bound?(name) || super
end
def delete(name)
@symbols.delete(name)
end
def bound?(name)
@symbols.include?(name)
end
def add_entries_to(target = {}, include_undef = false)
super
@symbols.each do |k, v|
if (v == :undef || v.nil?) && !include_undef
target.delete(k)
else
target[k] = v
end
end
target
end
end
class MatchScope < Ephemeral
attr_accessor :match_data
def initialize(parent = nil, match_data = nil)
super parent
@match_data = match_data
end
def is_local_scope?
false
end
def [](name)
if bound?(name)
@match_data[name.to_i]
else
super
end
end
def include?(name)
bound?(name) or super
end
def bound?(name)
# A "match variables" scope reports all numeric variables to be bound if the scope has
# match_data. Without match data the scope is transparent.
#
@match_data && name =~ /^\d+$/
end
def []=(name, value)
# TODO: Bad choice of exception
raise Puppet::ParseError, _("Numerical variables cannot be changed. Attempt to set $%{name}") % { name: name }
end
def delete(name)
# TODO: Bad choice of exception
raise Puppet::ParseError, _("Numerical variables cannot be deleted: Attempt to delete: $%{name}") % { name: name }
end
def add_entries_to(target = {}, include_undef = false)
# do not include match data ($0-$n)
super
end
end
# @api private
class ParameterScope < Ephemeral
class Access
attr_accessor :value
def assigned?
instance_variable_defined?(:@value)
end
end
# A parameter default must be evaluated using a special scope. The scope that is given to this method must
# have a `ParameterScope` as its last ephemeral scope. This method will then push a `MatchScope` while the
# given `expression` is evaluated. The method will catch any throw of `:unevaluated_parameter` and produce
# an error saying that the evaluated parameter X tries to access the unevaluated parameter Y.
#
# @param name [String] the name of the currently evaluated parameter
# @param expression [Puppet::Parser::AST] the expression to evaluate
# @param scope [Puppet::Parser::Scope] a scope where a `ParameterScope` has been pushed
# @return [Object] the result of the evaluation
#
# @api private
def evaluate3x(name, expression, scope)
scope.with_guarded_scope do
bad = catch(:unevaluated_parameter) do
scope.new_match_scope(nil)
return as_read_only { expression.safeevaluate(scope) }
end
parameter_reference_failure(name, bad)
end
end
def evaluate(name, expression, scope, evaluator)
scope.with_guarded_scope do
bad = catch(:unevaluated_parameter) do
scope.new_match_scope(nil)
return as_read_only { evaluator.evaluate(expression, scope) }
end
parameter_reference_failure(name, bad)
end
end
def parameter_reference_failure(from, to)
# Parameters are evaluated in the order they have in the @params hash.
keys = @params.keys
raise Puppet::Error, _("%{callee}: expects a value for parameter $%{to}") % { callee: @callee_name, to: to } if keys.index(to) < keys.index(from)
raise Puppet::Error, _("%{callee}: default expression for $%{from} tries to illegally access not yet evaluated $%{to}") % { callee: @callee_name, from: from, to: to }
end
private :parameter_reference_failure
def initialize(parent, callee_name, param_names)
super(parent)
@callee_name = callee_name
@params = {}
param_names.each { |name| @params[name] = Access.new }
end
def [](name)
access = @params[name]
return super if access.nil?
throw(:unevaluated_parameter, name) unless access.assigned?
access.value
end
def []=(name, value)
raise Puppet::Error, _("Attempt to assign variable %{name} when evaluating parameters") % { name: name } if @read_only
@params[name] ||= Access.new
@params[name].value = value
end
def bound?(name)
@params.include?(name)
end
def include?(name)
@params.include?(name) || super
end
def is_local_scope?
true
end
def as_read_only
read_only = @read_only
@read_only = true
begin
yield
ensure
@read_only = read_only
end
end
def to_hash
@params.select { |_, access| access.assigned? }.transform_values(&:value)
end
end
# Returns true if the variable of the given name has a non nil value.
# TODO: This has vague semantics - does the variable exist or not?
# use ['name'] to get nil or value, and if nil check with exist?('name')
# this include? is only useful because of checking against the boolean value false.
#
def include?(name)
catch(:undefined_variable) {
return !self[name].nil?
}
false
end
# Returns true if the variable of the given name is set to any value (including nil)
#
# @return [Boolean] if variable exists or not
#
def exist?(name)
# Note !! ensure the answer is boolean
!!if name =~ /^(.*)::(.+)$/
class_name = ::Regexp.last_match(1)
variable_name = ::Regexp.last_match(2)
return true if class_name == '' && BUILT_IN_VARS.include?(variable_name)
# lookup class, but do not care if it is not evaluated since that will result
# in it not existing anyway. (Tests may run with just scopes and no evaluated classes which
# will result in class_scope for "" not returning topscope).
klass = find_hostclass(class_name)
other_scope = klass.nil? ? nil : class_scope(klass)
if other_scope.nil?
class_name == '' ? compiler.topscope.exist?(variable_name) : false
else
other_scope.exist?(variable_name)
end
else # rubocop:disable Layout/ElseAlignment
next_scope = inherited_scope || enclosing_scope
effective_symtable(true).include?(name) || next_scope && next_scope.exist?(name) || BUILT_IN_VARS.include?(name)
end # rubocop:disable Layout/EndAlignment
end
# Returns true if the given name is bound in the current (most nested) scope for assignments.
#
def bound?(name)
# Do not look in ephemeral (match scope), the semantics is to answer if an assignable variable is bound
effective_symtable(false).bound?(name)
end
# Is the value true? This allows us to control the definition of truth
# in one place.
def self.true?(value)
case value
when ''
false
when :undef
false
else
!!value
end
end
# Coerce value to a number, or return `nil` if it isn't one.
def self.number?(value)
case value
when Numeric
value
when /^-?\d+(:?\.\d+|(:?\.\d+)?e\d+)$/
value.to_f
when /^0x[0-9a-f]+$/i
value.to_i(16)
when /^0[0-7]+$/
value.to_i(8)
when /^-?\d+$/
value.to_i
else
nil
end
end
def find_hostclass(name)
environment.known_resource_types.find_hostclass(name)
end
def find_definition(name)
environment.known_resource_types.find_definition(name)
end
def find_global_scope
# walk upwards until first found node_scope or top_scope
if is_nodescope? || is_topscope?
self
else
next_scope = inherited_scope || enclosing_scope
if next_scope.nil?
# this happens when testing, and there is only a single test scope and no link to any
# other scopes
self
else
next_scope.find_global_scope()
end
end
end
def findresource(type, title = nil)
@compiler.catalog.resource(type, title)
end
# Initialize our new scope. Defaults to having no parent.
def initialize(compiler, source: nil, resource: nil)
if compiler.is_a? Puppet::Parser::AbstractCompiler
@compiler = compiler
else
raise Puppet::DevError, _("you must pass a compiler instance to a new scope object")
end
@source = source
@resource = resource
extend_with_functions_module
# The symbol table for this scope. This is where we store variables.
# @symtable = Ephemeral.new(nil, true)
@symtable = LocalScope.new(nil)
@ephemeral = [MatchScope.new(@symtable, nil)]
# All of the defaults set for types. It's a hash of hashes,
# with the first key being the type, then the second key being
# the parameter.
@defaults = Hash.new { |dhash, type|
dhash[type] = {}
}
# The table for storing class singletons. This will only actually
# be used by top scopes and node scopes.
@class_scopes = {}
end
# Store the fact that we've evaluated a class, and store a reference to
# the scope in which it was evaluated, so that we can look it up later.
def class_set(name, scope)
if parent
parent.class_set(name, scope)
else
@class_scopes[name] = scope
end
end
# Return the scope associated with a class. This is just here so
# that subclasses can set their parent scopes to be the scope of
# their parent class, and it's also used when looking up qualified
# variables.
def class_scope(klass)
# They might pass in either the class or class name
k = klass.respond_to?(:name) ? klass.name : klass
@class_scopes[k] || (parent && parent.class_scope(k))
end
# Collect all of the defaults set at any higher scopes.
# This is a different type of lookup because it's
# additive -- it collects all of the defaults, with defaults
# in closer scopes overriding those in later scopes.
#
# The lookupdefaults searches in the order:
#
# * inherited
# * contained (recursive)
# * self
#
def lookupdefaults(type)
values = {}
# first collect the values from the parents
if parent
parent.lookupdefaults(type).each { |var, value|
values[var] = value
}
end
# then override them with any current values
# this should probably be done differently
if @defaults.include?(type)
@defaults[type].each { |var, value|
values[var] = value
}
end
values
end
# Check if the given value is a known default for the given type
#
def is_default?(type, key, value)
defaults_for_type = @defaults[type]
unless defaults_for_type.nil?
default_param = defaults_for_type[key]
return true if !default_param.nil? && value == default_param.value
end
!parent.nil? && parent.is_default?(type, key, value)
end
# Look up a defined type.
def lookuptype(name)
# This happens a lot, avoid making a call to make a call
krt = environment.known_resource_types
krt.find_definition(name) || krt.find_hostclass(name)
end
def undef_as(x, v)
if v.nil? or v == :undef
x
else
v
end
end
# Lookup a variable within this scope using the Puppet language's
# scoping rules. Variables can be qualified using just as in a
# manifest.
#
# @param [String] name the variable name to lookup
# @param [Hash] hash of options, only internal code should give this
# @param [Boolean] if resolution is of the leaf of a qualified name - only internal code should give this
# @return Object the value of the variable, or if not found; nil if `strict_variables` is false, and thrown :undefined_variable otherwise
#
# @api public
def lookupvar(name, options = EMPTY_HASH)
unless name.is_a? String
raise Puppet::ParseError, _("Scope variable name %{name} is a %{klass}, not a string") % { name: name.inspect, klass: name.class }
end
# If name has '::' in it, it is resolved as a qualified variable
unless (idx = name.index('::')).nil?
# Always drop leading '::' if present as that is how the values are keyed.
return lookup_qualified_variable(idx == 0 ? name[2..] : name, options)
end
# At this point, search is for a non qualified (simple) name
table = @ephemeral.last
val = table[name]
return val unless val.nil? && !table.include?(name)
next_scope = inherited_scope || enclosing_scope
if next_scope
next_scope.lookupvar(name, options)
else
variable_not_found(name)
end
end
UNDEFINED_VARIABLES_KIND = 'undefined_variables'
# The exception raised when a throw is uncaught is different in different versions
# of ruby. In >=2.2.0 it is UncaughtThrowError (which did not exist prior to this)
#
UNCAUGHT_THROW_EXCEPTION = defined?(UncaughtThrowError) ? UncaughtThrowError : ArgumentError
def variable_not_found(name, reason = nil)
# Built in variables and numeric variables always exist
if BUILT_IN_VARS.include?(name) || name =~ Puppet::Pops::Patterns::NUMERIC_VAR_NAME
return nil
end
begin
throw(:undefined_variable, reason)
rescue UNCAUGHT_THROW_EXCEPTION
case Puppet[:strict]
when :off
# do nothing
when :warning
Puppet.warn_once(UNDEFINED_VARIABLES_KIND, _("Variable: %{name}") % { name: name },
_("Undefined variable '%{name}'; %{reason}") % { name: name, reason: reason })
when :error
if Puppet.lookup(:avoid_hiera_interpolation_errors) { false }
Puppet.warn_once(UNDEFINED_VARIABLES_KIND, _("Variable: %{name}") % { name: name },
_("Interpolation failed with '%{name}', but compilation continuing; %{reason}") % { name: name, reason: reason })
else
raise ArgumentError, _("Undefined variable '%{name}'; %{reason}") % { name: name, reason: reason }
end
end
end
nil
end
# Retrieves the variable value assigned to the name given as an argument. The name must be a String,
# and namespace can be qualified with '::'. The value is looked up in this scope, its parent scopes,
# or in a specific visible named scope.
#
# @param varname [String] the name of the variable (may be a qualified name using `(ns'::')*varname`
# @param options [Hash] Additional options, not part of api.
# @return [Object] the value assigned to the given varname
# @see #[]=
# @api public
#
def [](varname, options = EMPTY_HASH)
lookupvar(varname, options)
end
# The class scope of the inherited thing of this scope's resource.
#
# @return [Puppet::Parser::Scope] The scope or nil if there is not an inherited scope
def inherited_scope
if resource && resource.type == TYPENAME_CLASS && !resource.resource_type.parent.nil?
qualified_scope(resource.resource_type.parent)
else
nil
end
end
# The enclosing scope (topscope or nodescope) of this scope.
# The enclosing scopes are produced when a class or define is included at
# some point. The parent scope of the included class or define becomes the
# scope in which it was included. The chain of parent scopes is followed
# until a node scope or the topscope is found
#
# @return [Puppet::Parser::Scope] The scope or nil if there is no enclosing scope
def enclosing_scope
if has_enclosing_scope?
if parent.is_topscope? || parent.is_nodescope?
parent
else
parent.enclosing_scope
end
end
end
def is_classscope?
resource && resource.type == TYPENAME_CLASS
end
def is_nodescope?
resource && resource.type == TYPENAME_NODE
end
def is_topscope?
equal?(@compiler.topscope)
end
# @api private
def lookup_qualified_variable(fqn, options)
table = @compiler.qualified_variables
val = table[fqn]
return val if !val.nil? || table.include?(fqn)
# not found - search inherited scope for class
leaf_index = fqn.rindex('::')
unless leaf_index.nil?
leaf_name = fqn[(leaf_index + 2)..]
class_name = fqn[0, leaf_index]
begin
qs = qualified_scope(class_name)
unless qs.nil?
return qs.get_local_variable(leaf_name) if qs.has_local_variable?(leaf_name)
iscope = qs.inherited_scope
return lookup_qualified_variable("#{iscope.source.name}::#{leaf_name}", options) unless iscope.nil?
end
rescue RuntimeError => e
# because a failure to find the class, or inherited should be reported against given name
return handle_not_found(class_name, leaf_name, options, e.message)
end
end
# report with leading '::' by using empty class_name
handle_not_found('', fqn, options)
end
# @api private
def has_local_variable?(name)
@ephemeral.last.include?(name)
end
# @api private
def get_local_variable(name)
@ephemeral.last[name]
end
def handle_not_found(class_name, variable_name, position, reason = nil)
unless Puppet[:strict_variables]
# Do not issue warning if strict variables are on, as an error will be raised by variable_not_found
location = if position[:lineproc]
Puppet::Util::Errors.error_location_with_space(nil, position[:lineproc].call)
else
Puppet::Util::Errors.error_location_with_space(position[:file], position[:line])
end
variable_not_found("#{class_name}::#{variable_name}", "#{reason}#{location}")
return nil
end
variable_not_found("#{class_name}::#{variable_name}", reason)
end
def has_enclosing_scope?
!parent.nil?
end
private :has_enclosing_scope?
def qualified_scope(classname)
klass = find_hostclass(classname)
raise _("class %{classname} could not be found") % { classname: classname } unless klass
kscope = class_scope(klass)
raise _("class %{classname} has not been evaluated") % { classname: classname } unless kscope
kscope
end
private :qualified_scope
# Returns a Hash containing all variables and their values, optionally (and
# by default) including the values defined in parent. Local values
# shadow parent values. Ephemeral scopes for match results ($0 - $n) are not included.
# Optionally include the variables that are explicitly set to `undef`.
#
def to_hash(recursive = true, include_undef = false)
if recursive and has_enclosing_scope?
target = enclosing_scope.to_hash(recursive)
unless (inherited = inherited_scope).nil?
target.merge!(inherited.to_hash(recursive))
end
else
target = Hash.new
end
# add all local scopes
@ephemeral.last.add_entries_to(target, include_undef)
target
end
# Create a new scope and set these options.
def newscope(options = {})
compiler.newscope(self, options)
end
def parent_module_name
return nil unless @parent && @parent.source
@parent.source.module_name
end
# Set defaults for a type. The typename should already be downcased,
# so that the syntax is isolated. We don't do any kind of type-checking
# here; instead we let the resource do it when the defaults are used.
def define_settings(type, params)
table = @defaults[type]
# if we got a single param, it'll be in its own array
params = [params] unless params.is_a?(Array)
params.each { |param|
if table.include?(param.name)
raise Puppet::ParseError.new(_("Default already defined for %{type} { %{param} }; cannot redefine") % { type: type, param: param.name }, param.file, param.line)
end
table[param.name] = param
}
end
# Merge all settings for the given _env_name_ into this scope
# @param env_name [Symbol] the name of the environment
# @param set_in_this_scope [Boolean] if the settings variables should also be set in this instance of scope
def merge_settings(env_name, set_in_this_scope = true)
settings = Puppet.settings
table = effective_symtable(false)
global_table = compiler.qualified_variables
all_local = {}
settings.each_key do |name|
next if :name == name
key = name.to_s
value = transform_setting(settings.value_sym(name, env_name))
if set_in_this_scope
table[key] = value
end
all_local[key] = value
# also write the fqn into global table for direct lookup
global_table["settings::#{key}"] = value
end
# set the 'all_local' - a hash of all settings
global_table["settings::all_local"] = all_local
nil
end
def transform_setting(val)
case val
when String, Numeric, true, false, nil
val
when Array
val.map { |entry| transform_setting(entry) }
when Hash
result = {}
val.each { |k, v| result[transform_setting(k)] = transform_setting(v) }
result
else
# not ideal, but required as there are settings values that are special
:undef == val ? nil : val.to_s
end
end
private :transform_setting
VARNAME_TRUSTED = 'trusted'
VARNAME_FACTS = 'facts'
VARNAME_SERVER_FACTS = 'server_facts'
RESERVED_VARIABLE_NAMES = [VARNAME_TRUSTED, VARNAME_FACTS].freeze
TYPENAME_CLASS = 'Class'
TYPENAME_NODE = 'Node'
# Set a variable in the current scope. This will override settings
# in scopes above, but will not allow variables in the current scope
# to be reassigned.
# It's preferred that you use self[]= instead of this; only use this
# when you need to set options.
def setvar(name, value, options = EMPTY_HASH)
if name =~ /^[0-9]+$/
raise Puppet::ParseError, _("Cannot assign to a numeric match result variable '$%{name}'") % { name: name } # unless options[:ephemeral]
end
unless name.is_a? String
raise Puppet::ParseError, _("Scope variable name %{name} is a %{class_type}, not a string") % { name: name.inspect, class_type: name.class }
end
# Check for reserved variable names
if (name == VARNAME_TRUSTED || name == VARNAME_FACTS) && !options[:privileged]
raise Puppet::ParseError, _("Attempt to assign to a reserved variable name: '%{name}'") % { name: name }
end
# Check for server_facts reserved variable name
if name == VARNAME_SERVER_FACTS && !options[:privileged]
raise Puppet::ParseError, _("Attempt to assign to a reserved variable name: '%{name}'") % { name: name }
end
table = effective_symtable(options[:ephemeral])
if table.bound?(name)
error = Puppet::ParseError.new(_("Cannot reassign variable '$%{name}'") % { name: name })
error.file = options[:file] if options[:file]
error.line = options[:line] if options[:line]
raise error
end
table[name] = value
# Assign the qualified name in the environment
# Note that Settings scope has a source set to Boolean true.
#
# Only meaningful to set a fqn globally if table to assign to is the top of the scope's ephemeral stack
if @symtable.equal?(table)
if is_topscope?
# the scope name is '::'
compiler.qualified_variables[name] = value
elsif source.is_a?(Puppet::Resource::Type) && source.type == :hostclass
# the name is the name of the class
sourcename = source.name
compiler.qualified_variables["#{sourcename}::#{name}"] = value
end
end
value
end
def set_trusted(hash)
setvar('trusted', deep_freeze(hash), :privileged => true)
end
def set_facts(hash)
setvar('facts', deep_freeze(hash), :privileged => true)
end
def set_server_facts(hash)
setvar('server_facts', deep_freeze(hash), :privileged => true)
end
# Deeply freezes the given object. The object and its content must be of the types:
# Array, Hash, Numeric, Boolean, Regexp, NilClass, or String. All other types raises an Error.
# (i.e. if they are assignable to Puppet::Pops::Types::Data type).
#
def deep_freeze(object)
case object
when Array
object.each { |v| deep_freeze(v) }
object.freeze
when Hash
object.each { |k, v| deep_freeze(k); deep_freeze(v) }
object.freeze
when NilClass, Numeric, TrueClass, FalseClass
# do nothing
when String
object.freeze
else
raise Puppet::Error, _("Unsupported data type: '%{klass}'") % { klass: object.class }
end
object
end
private :deep_freeze
# Return the effective "table" for setting variables.
# This method returns the first ephemeral "table" that acts as a local scope, or this
# scope's symtable. If the parameter `use_ephemeral` is true, the "top most" ephemeral "table"
# will be returned (irrespective of it being a match scope or a local scope).
#
# @param use_ephemeral [Boolean] whether the top most ephemeral (of any kind) should be used or not
def effective_symtable(use_ephemeral)
s = @ephemeral[-1]
return s || @symtable if use_ephemeral
while s && !s.is_local_scope?()
s = s.parent
end
s || @symtable
end
# Sets the variable value of the name given as an argument to the given value. The value is
# set in the current scope and may shadow a variable with the same name in a visible outer scope.
# It is illegal to re-assign a variable in the same scope. It is illegal to set a variable in some other
# scope/namespace than the scope passed to a method.
#
# @param varname [String] The variable name to which the value is assigned. Must not contain `::`
# @param value [String] The value to assign to the given variable name.
# @param options [Hash] Additional options, not part of api and no longer used.
#
# @api public
#
def []=(varname, value, _ = nil)
setvar(varname, value)
end
# Used mainly for logging
def to_s
# As this is used for logging, this should really not be done in this class at all...
return "Scope(#{@resource})" unless @resource.nil?
# For logging of function-scope - it is now showing the file and line.
detail = Puppet::Pops::PuppetStack.top_of_stack
return "Scope()" if detail.empty?
# shorten the path if possible
path = detail[0]
env_path = nil
env_path = environment.configuration.path_to_env unless environment.nil? || environment.configuration.nil?
# check module paths first since they may be in the environment (i.e. they are longer)
module_path = environment.full_modulepath.detect { |m_path| path.start_with?(m_path) }
if module_path
path = "<module>" + path[module_path.length..]
elsif env_path && path && path.start_with?(env_path)
path = "<env>" + path[env_path.length..]
end
# Make the output appear as "Scope(path, line)"
"Scope(#{[path, detail[1]].join(', ')})"
end
alias_method :inspect, :to_s
# Pop ephemeral scopes up to level and return them
#
# @param level [Integer] a positive integer
# @return [Array] the removed ephemeral scopes
# @api private
def pop_ephemerals(level)
@ephemeral.pop(@ephemeral.size - level)
end
# Push ephemeral scopes onto the ephemeral scope stack
# @param ephemeral_scopes [Array]
# @api private
def push_ephemerals(ephemeral_scopes)
ephemeral_scopes.each { |ephemeral_scope| @ephemeral.push(ephemeral_scope) } unless ephemeral_scopes.nil?
end
def ephemeral_level
@ephemeral.size
end
# TODO: Who calls this?
def new_ephemeral(local_scope = false)
if local_scope
@ephemeral.push(LocalScope.new(@ephemeral.last))
else
@ephemeral.push(MatchScope.new(@ephemeral.last, nil))
end
end
# Execute given block in global scope with no ephemerals present
#
# @yieldparam [Scope] global_scope the global and ephemeral less scope
# @return [Object] the return of the block
#
# @api private
def with_global_scope(&block)
find_global_scope.without_ephemeral_scopes(&block)
end
# Execute given block with a ephemeral scope containing the given variables
# @api private
def with_local_scope(scope_variables)
local = LocalScope.new(@ephemeral.last)
scope_variables.each_pair { |k, v| local[k] = v }
@ephemeral.push(local)
begin
yield(self)
ensure
@ephemeral.pop
end
end
# Execute given block with all ephemeral popped from the ephemeral stack
#
# @api private
def without_ephemeral_scopes
save_ephemeral = @ephemeral
begin
@ephemeral = [@symtable]
yield(self)
ensure
@ephemeral = save_ephemeral
end
end
# Nests a parameter scope
# @param [String] callee_name the name of the function, template, or resource that defines the parameters
# @param [Array<String>] param_names list of parameter names
# @yieldparam [ParameterScope] param_scope the nested scope
# @api private
def with_parameter_scope(callee_name, param_names)
param_scope = ParameterScope.new(@ephemeral.last, callee_name, param_names)
with_guarded_scope do
@ephemeral.push(param_scope)
yield(param_scope)
end
end
# Execute given block and ensure that ephemeral level is restored
#
# @return [Object] the return of the block
#
# @api private
def with_guarded_scope
elevel = ephemeral_level
begin
yield
ensure
pop_ephemerals(elevel)
end
end
# Sets match data in the most nested scope (which always is a MatchScope), it clobbers match data already set there
#
def set_match_data(match_data)
@ephemeral.last.match_data = match_data
end
# Nests a match data scope
def new_match_scope(match_data)
@ephemeral.push(MatchScope.new(@ephemeral.last, match_data))
end
def ephemeral_from(match, file = nil, line = nil)
case match
when Hash
# Create local scope ephemeral and set all values from hash
new_ephemeral(true)
match.each { |k, v| setvar(k, v, :file => file, :line => line, :ephemeral => true) }
# Must always have an inner match data scope (that starts out as transparent)
# In 3x slightly wasteful, since a new nested scope is created for a match
# (TODO: Fix that problem)
new_ephemeral(false)
else
raise(ArgumentError, _("Invalid regex match data. Got a %{klass}") % { klass: match.class }) unless match.is_a?(MatchData)
# Create a match ephemeral and set values from match data
new_match_scope(match)
end
end
# @api private
def find_resource_type(type)
raise Puppet::DevError, _("Scope#find_resource_type() is no longer supported, use Puppet::Pops::Evaluator::Runtime3ResourceSupport instead")
end
# @api private
def find_builtin_resource_type(type)
raise Puppet::DevError, _("Scope#find_builtin_resource_type() is no longer supported, use Puppet::Pops::Evaluator::Runtime3ResourceSupport instead")
end
# @api private
def find_defined_resource_type(type)
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/parser_factory.rb | lib/puppet/parser/parser_factory.rb | # frozen_string_literal: true
module Puppet; end
module Puppet::Parser
# The ParserFactory makes selection of parser possible.
# Currently, it is possible to switch between two different parsers:
# * classic_parser, the parser in 3.1
# * eparser, the Expression Based Parser
#
class ParserFactory
# Produces a parser instance for the given environment
def self.parser
evaluating_parser
end
# Creates an instance of an E4ParserAdapter that adapts an
# EvaluatingParser to the 3x way of parsing.
#
def self.evaluating_parser
unless defined?(Puppet::Parser::E4ParserAdapter)
require_relative '../../puppet/parser/e4_parser_adapter'
require_relative '../../puppet/pops/parser/code_merger'
end
E4ParserAdapter.new
end
def self.code_merger
Puppet::Pops::Parser::CodeMerger.new
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/type_loader.rb | lib/puppet/parser/type_loader.rb | # frozen_string_literal: true
require 'find'
require 'forwardable'
require_relative '../../puppet/parser/parser_factory'
class Puppet::Parser::TypeLoader
extend Forwardable
class TypeLoaderError < StandardError; end
# Import manifest files that match a given file glob pattern.
#
# @param pattern [String] the file glob to apply when determining which files
# to load
# @param dir [String] base directory to use when the file is not
# found in a module
# @api private
def import(pattern, dir)
modname, files = Puppet::Parser::Files.find_manifests_in_modules(pattern, environment)
if files.empty?
abspat = File.expand_path(pattern, dir)
file_pattern = abspat + (File.extname(abspat).empty? ? '.pp' : '')
files = Dir.glob(file_pattern).uniq.reject { |f| FileTest.directory?(f) }
modname = nil
if files.empty?
raise_no_files_found(pattern)
end
end
load_files(modname, files)
end
# Load all of the manifest files in all known modules.
# @api private
def import_all
# And then load all files from each module, but (relying on system
# behavior) only load files from the first module of a given name. E.g.,
# given first/foo and second/foo, only files from first/foo will be loaded.
environment.modules.each do |mod|
load_files(mod.name, mod.all_manifests)
end
end
def_delegator :environment, :known_resource_types
def initialize(env)
self.environment = env
end
def environment
@environment
end
def environment=(env)
if env.is_a?(String) or env.is_a?(Symbol)
@environment = Puppet.lookup(:environments).get!(env)
else
@environment = env
end
end
# Try to load the object with the given fully qualified name.
def try_load_fqname(type, fqname)
return nil if fqname == "" # special-case main.
files_to_try_for(fqname).each do |filename|
imported_types = import_from_modules(filename)
result = imported_types.find { |t| t.type == type and t.name == fqname }
if result
Puppet.debug { "Automatically imported #{fqname} from #{filename} into #{environment}" }
return result
end
rescue TypeLoaderError
# I'm not convinced we should just drop these errors, but this
# preserves existing behaviours.
end
# Nothing found.
nil
end
def parse_file(file)
Puppet.debug { "importing '#{file}' in environment #{environment}" }
parser = Puppet::Parser::ParserFactory.parser
parser.file = file
parser.parse
end
private
def import_from_modules(pattern)
modname, files = Puppet::Parser::Files.find_manifests_in_modules(pattern, environment)
if files.empty?
raise_no_files_found(pattern)
end
load_files(modname, files)
end
def raise_no_files_found(pattern)
raise TypeLoaderError, _("No file(s) found for import of '%{pattern}'") % { pattern: pattern }
end
def load_files(modname, files)
@loaded ||= {}
loaded_asts = []
files.reject { |file| @loaded[file] }.each do |file|
# The squelch_parse_errors use case is for parsing for the purpose of searching
# for information and it should not abort.
# There is currently one user in indirector/resourcetype/parser
#
if Puppet.lookup(:squelch_parse_errors) { false }
begin
loaded_asts << parse_file(file)
rescue => e
# Resume from errors so that all parseable files may
# still be parsed. Mark this file as loaded so that
# it would not be parsed next time (handle it as if
# it was successfully parsed).
Puppet.debug { "Unable to parse '#{file}': #{e.message}" }
end
else
loaded_asts << parse_file(file)
end
@loaded[file] = true
end
loaded_asts.collect do |ast|
known_resource_types.import_ast(ast, modname)
end.flatten
end
# Return a list of all file basenames that should be tried in order
# to load the object with the given fully qualified name.
def files_to_try_for(qualified_name)
qualified_name.split('::').inject([]) do |paths, name|
add_path_for_name(paths, name)
end
end
def add_path_for_name(paths, name)
if paths.empty?
[name]
else
paths.unshift(File.join(paths.first, name))
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions.rb | lib/puppet/parser/functions.rb | # frozen_string_literal: true
require_relative '../../puppet/util/autoload'
require_relative '../../puppet/parser/scope'
require_relative '../../puppet/pops/adaptable'
require_relative '../../puppet/concurrent/lock'
# A module for managing parser functions. Each specified function
# is added to a central module that then gets included into the Scope
# class.
#
# @api public
module Puppet::Parser::Functions
Environment = Puppet::Node::Environment
class << self
include Puppet::Util
end
# Reset the list of loaded functions.
#
# @api private
def self.reset
# Runs a newfunction to create a function for each of the log levels
root_env = Puppet.lookup(:root_environment)
AnonymousModuleAdapter.clear(root_env)
Puppet::Util::Log.levels.each do |level|
newfunction(level,
:environment => root_env,
:doc => "Log a message on the server at level #{level}.") do |vals|
send(level, vals.join(" "))
end
end
end
class AutoloaderDelegate
attr_reader :delegatee
def initialize
@delegatee = Puppet::Util::Autoload.new(self, "puppet/parser/functions")
end
def loadall(env = Puppet.lookup(:current_environment))
if Puppet[:strict] != :off
Puppet.warn_once('deprecations', 'Puppet::Parser::Functions#loadall', _("The method 'Puppet::Parser::Functions.autoloader#loadall' is deprecated in favor of using 'Scope#call_function'."))
end
@delegatee.loadall(env)
end
def load(name, env = Puppet.lookup(:current_environment))
if Puppet[:strict] != :off
Puppet.warn_once('deprecations', "Puppet::Parser::Functions#load('#{name}')", _("The method 'Puppet::Parser::Functions.autoloader#load(\"%{name}\")' is deprecated in favor of using 'Scope#call_function'.") % { name: name })
end
@delegatee.load(name, env)
end
def loaded?(name)
if Puppet[:strict] != :off
Puppet.warn_once('deprecations', "Puppet::Parser::Functions.loaded?('#{name}')", _("The method 'Puppet::Parser::Functions.autoloader#loaded?(\"%{name}\")' is deprecated in favor of using 'Scope#call_function'.") % { name: name })
end
@delegatee.loaded?(name)
end
end
# Accessor for singleton autoloader
#
# @api private
def self.autoloader
@autoloader ||= AutoloaderDelegate.new
end
# An adapter that ties the anonymous module that acts as the container for all 3x functions to the environment
# where the functions are created. This adapter ensures that the life-cycle of those functions doesn't exceed
# the life-cycle of the environment.
#
# @api private
class AnonymousModuleAdapter < Puppet::Pops::Adaptable::Adapter
attr_accessor :module
def self.create_adapter(env)
adapter = super(env)
adapter.module = Module.new do
@metadata = {}
def self.all_function_info
@metadata
end
def self.get_function_info(name)
@metadata[name]
end
def self.add_function_info(name, info)
@metadata[name] = info
end
end
adapter
end
end
@environment_module_lock = Puppet::Concurrent::Lock.new
# Get the module that functions are mixed into corresponding to an
# environment
#
# @api private
def self.environment_module(env)
@environment_module_lock.synchronize do
AnonymousModuleAdapter.adapt(env).module
end
end
# Create a new Puppet DSL function.
#
# **The {newfunction} method provides a public API.**
#
# This method is used both internally inside of Puppet to define parser
# functions. For example, template() is defined in
# {file:lib/puppet/parser/functions/template.rb template.rb} using the
# {newfunction} method. Third party Puppet modules such as
# [stdlib](https://forge.puppetlabs.com/puppetlabs/stdlib) use this method to
# extend the behavior and functionality of Puppet.
#
# See also [Docs: Custom
# Functions](https://puppet.com/docs/puppet/5.5/lang_write_functions_in_puppet.html)
#
# @example Define a new Puppet DSL Function
# >> Puppet::Parser::Functions.newfunction(:double, :arity => 1,
# :doc => "Doubles an object, typically a number or string.",
# :type => :rvalue) {|i| i[0]*2 }
# => {:arity=>1, :type=>:rvalue,
# :name=>"function_double",
# :doc=>"Doubles an object, typically a number or string."}
#
# @example Invoke the double function from irb as is done in RSpec examples:
# >> require 'puppet_spec/scope'
# >> scope = PuppetSpec::Scope.create_test_scope_for_node('example')
# => Scope()
# >> scope.function_double([2])
# => 4
# >> scope.function_double([4])
# => 8
# >> scope.function_double([])
# ArgumentError: double(): Wrong number of arguments given (0 for 1)
# >> scope.function_double([4,8])
# ArgumentError: double(): Wrong number of arguments given (2 for 1)
# >> scope.function_double(["hello"])
# => "hellohello"
#
# @param [Symbol] name the name of the function represented as a ruby Symbol.
# The {newfunction} method will define a Ruby method based on this name on
# the parser scope instance.
#
# @param [Proc] block the block provided to the {newfunction} method will be
# executed when the Puppet DSL function is evaluated during catalog
# compilation. The arguments to the function will be passed as an array to
# the first argument of the block. The return value of the block will be
# the return value of the Puppet DSL function for `:rvalue` functions.
#
# @option options [:rvalue, :statement] :type (:statement) the type of function.
# Either `:rvalue` for functions that return a value, or `:statement` for
# functions that do not return a value.
#
# @option options [String] :doc ('') the documentation for the function.
# This string will be extracted by documentation generation tools.
#
# @option options [Integer] :arity (-1) the
# [arity](https://en.wikipedia.org/wiki/Arity) of the function. When
# specified as a positive integer the function is expected to receive
# _exactly_ the specified number of arguments. When specified as a
# negative number, the function is expected to receive _at least_ the
# absolute value of the specified number of arguments incremented by one.
# For example, a function with an arity of `-4` is expected to receive at
# minimum 3 arguments. A function with the default arity of `-1` accepts
# zero or more arguments. A function with an arity of 2 must be provided
# with exactly two arguments, no more and no less. Added in Puppet 3.1.0.
#
# @option options [Puppet::Node::Environment] :environment (nil) can
# explicitly pass the environment we wanted the function added to. Only used
# to set logging functions in root environment
#
# @return [Hash] describing the function.
#
# @api public
def self.newfunction(name, options = {}, &block)
name = name.intern
environment = options[:environment] || Puppet.lookup(:current_environment)
Puppet.warning _("Overwriting previous definition for function %{name}") % { name: name } if get_function(name, environment)
arity = options[:arity] || -1
ftype = options[:type] || :statement
unless ftype == :statement or ftype == :rvalue
raise Puppet::DevError, _("Invalid statement type %{type}") % { type: ftype.inspect }
end
# the block must be installed as a method because it may use "return",
# which is not allowed from procs.
real_fname = "real_function_#{name}"
environment_module(environment).send(:define_method, real_fname, &block)
fname = "function_#{name}"
env_module = environment_module(environment)
env_module.send(:define_method, fname) do |*args|
Puppet::Util::Profiler.profile(_("Called %{name}") % { name: name }, [:functions, name]) do
if args[0].is_a? Array
if arity >= 0 and args[0].size != arity
raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for %{arity})") % { name: name, arg_count: args[0].size, arity: arity }
elsif arity < 0 and args[0].size < (arity + 1).abs
raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for minimum %{min_arg_count})") % { name: name, arg_count: args[0].size, min_arg_count: (arity + 1).abs }
end
r = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.convert_return(send(real_fname, args[0]))
# avoid leaking aribtrary value if not being an rvalue function
options[:type] == :rvalue ? r : nil
else
raise ArgumentError, _("custom functions must be called with a single array that contains the arguments. For example, function_example([1]) instead of function_example(1)")
end
end
end
func = { :arity => arity, :type => ftype, :name => fname }
func[:doc] = options[:doc] if options[:doc]
env_module.add_function_info(name, func)
func
end
# Determine if a function is defined
#
# @param [Symbol] name the function
# @param [Puppet::Node::Environment] environment the environment to find the function in
#
# @return [Symbol, false] The name of the function if it's defined,
# otherwise false.
#
# @api public
def self.function(name, environment = Puppet.lookup(:current_environment))
name = name.intern
func = get_function(name, environment)
unless func
autoloader.delegatee.load(name, environment)
func = get_function(name, environment)
end
if func
func[:name]
else
false
end
end
def self.functiondocs(environment = Puppet.lookup(:current_environment))
autoloader.delegatee.loadall(environment)
ret = ''.dup
merged_functions(environment).sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, hash|
ret << "#{name}\n#{'-' * name.to_s.length}\n"
if hash[:doc]
ret << Puppet::Util::Docs.scrub(hash[:doc])
else
ret << "Undocumented.\n"
end
ret << "\n\n- *Type*: #{hash[:type]}\n\n"
end
ret
end
# Determine whether a given function returns a value.
#
# @param [Symbol] name the function
# @param [Puppet::Node::Environment] environment The environment to find the function in
# @return [Boolean] whether it is an rvalue function
#
# @api public
def self.rvalue?(name, environment = Puppet.lookup(:current_environment))
func = get_function(name, environment)
func ? func[:type] == :rvalue : false
end
# Return the number of arguments a function expects.
#
# @param [Symbol] name the function
# @param [Puppet::Node::Environment] environment The environment to find the function in
# @return [Integer] The arity of the function. See {newfunction} for
# the meaning of negative values.
#
# @api public
def self.arity(name, environment = Puppet.lookup(:current_environment))
func = get_function(name, environment)
func ? func[:arity] : -1
end
class << self
private
def merged_functions(environment)
root = environment_module(Puppet.lookup(:root_environment))
env = environment_module(environment)
root.all_function_info.merge(env.all_function_info)
end
def get_function(name, environment)
environment_module(environment).get_function_info(name.intern) || environment_module(Puppet.lookup(:root_environment)).get_function_info(name.intern)
end
end
class Error
def self.is4x(name)
raise Puppet::ParseError, _("%{name}() can only be called using the 4.x function API. See Scope#call_function") % { name: name }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/abstract_compiler.rb | lib/puppet/parser/abstract_compiler.rb | # frozen_string_literal: true
module Puppet::Parser::AbstractCompiler
# Returns the catalog for a compilation. Must return a Puppet::Resource::Catalog or fail with an
# error if the specific compiler does not support catalog operations.
#
def catalog
raise Puppet::DevError("Class '#{self.class}' should have implemented 'catalog'")
end
# Returns the environment for the compilation
#
def environment
raise Puppet::DevError("Class '#{self.class}' should have implemented 'environment'")
end
# Produces a new scope
# This method is here if there are functions/logic that will call this for some other purpose than to create
# a named scope for a class. It may not have to be here. (TODO)
#
def newscope(scope, options)
raise Puppet::DevError("Class '#{self.class}' should have implemented 'newscope'")
end
# Returns a hash of all externally referenceable qualified variables
#
def qualified_variables
raise Puppet::DevError("Class '#{self.class}' should have implemented 'qualified_variables'")
end
# Returns the top scope instance
def topscope
raise Puppet::DevError("Class '#{self.class}' should have implemented 'topscope'")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast.rb | lib/puppet/parser/ast.rb | # frozen_string_literal: true
# The base class for the 3x "parse tree", now only used by the top level
# constructs and the compiler.
# Handles things like file name, line #, and also does the initialization
# for all of the parameters of all of the child objects.
#
class Puppet::Parser::AST
AST = Puppet::Parser::AST
include Puppet::Util::Errors
attr_accessor :parent, :scope, :file, :line, :pos
def inspect
"( #{self.class} #{self} #{@children.inspect} )"
end
# Evaluate the current object. Just a stub method, since the subclass
# should override this method.
def evaluate(scope)
end
# The version of the evaluate method that should be called, because it
# correctly handles errors. It is critical to use this method because
# it can enable you to catch the error where it happens, rather than
# much higher up the stack.
def safeevaluate(scope)
# We duplicate code here, rather than using exceptwrap, because this
# is called so many times during parsing.
evaluate(scope)
rescue Puppet::Pops::Evaluator::PuppetStopIteration => detail
raise detail
# # Only deals with StopIteration from the break() function as a general
# # StopIteration is a general runtime problem
# raise Puppet::ParseError.new(detail.message, detail.file, detail.line, detail)
rescue Puppet::Error => detail
raise adderrorcontext(detail)
rescue => detail
error = Puppet::ParseError.new(detail.to_s, nil, nil, detail)
# We can't use self.fail here because it always expects strings,
# not exceptions.
raise adderrorcontext(error, detail)
end
def initialize(file: nil, line: nil, pos: nil)
@file = file
@line = line
@pos = pos
end
end
# And include all of the AST subclasses.
require_relative 'ast/branch'
require_relative 'ast/leaf'
require_relative 'ast/block_expression'
require_relative 'ast/hostclass'
require_relative 'ast/node'
require_relative 'ast/resource'
require_relative 'ast/resource_instance'
require_relative 'ast/resourceparam'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/resource/param.rb | lib/puppet/parser/resource/param.rb | # frozen_string_literal: true
# The parameters we stick in Resources.
class Puppet::Parser::Resource::Param
include Puppet::Util
include Puppet::Util::Errors
attr_accessor :name, :value, :source, :add, :file, :line
def initialize(name: nil, value: nil, source: nil, line: nil, file: nil, add: nil)
@value = value
@source = source
@line = line
@file = file
@add = add
unless name
# This must happen after file and line are set to have them reported in the error
self.fail(Puppet::ResourceError, "'name' is a required option for #{self.class}")
end
@name = name.intern
end
def line_to_i
line ? Integer(line) : nil
end
def to_s
"#{name} => #{value}"
end
def self.from_param(param, value)
new_param = param.dup
new_param.value = value
new_param
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/shellquote.rb | lib/puppet/parser/functions/shellquote.rb | # frozen_string_literal: true
# Copyright (C) 2009 Thomas Bellman
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of Thomas Bellman shall
# not be used in advertising or otherwise to promote the sale, use or
# other dealings in this Software without prior written authorization
# from Thomas Bellman.
Puppet::Parser::Functions.newfunction(:shellquote, :type => :rvalue, :arity => -1, :doc => "\
Quote and concatenate arguments for use in Bourne shell.
Each argument is quoted separately, and then all are concatenated
with spaces. If an argument is an array, the elements of that
array is interpolated within the rest of the arguments; this makes
it possible to have an array of arguments and pass that array to
shellquote instead of having to specify each argument
individually in the call.
") \
do |args|
safe = 'a-zA-Z0-9@%_+=:,./-' # Safe unquoted
dangerous = '!"`$\\' # Unsafe inside double quotes
result = []
args.flatten.each do |word|
if word.length != 0 and word.count(safe) == word.length
result << word
elsif word.count(dangerous) == 0
result << ('"' + word + '"')
elsif word.count("'") == 0
result << ("'" + word + "'")
else
r = '"'
word.each_byte do |c|
r += "\\" if dangerous.include?(c.chr)
r += c.chr
end
r += '"'
result << r
end
end
return result.join(" ")
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/tag.rb | lib/puppet/parser/functions/tag.rb | # frozen_string_literal: true
# Tag the current scope with each passed name
Puppet::Parser::Functions.newfunction(:tag, :arity => -2, :doc => "Add the specified tags to the containing class
or definition. All contained objects will then acquire that tag, also.
") do |vals|
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :operation => 'tag' }
)
end
resource.tag(*vals)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/find_file.rb | lib/puppet/parser/functions/find_file.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:find_file,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Finds an existing file from a module and returns its path.
The argument to this function should be a String as a `<MODULE NAME>/<FILE>`
reference, which will search for `<FILE>` relative to a module's `files`
directory. (For example, the reference `mysql/mysqltuner.pl` will search for the
file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.)
This function can also accept:
* An absolute String path, which will check for the existence of a file from anywhere on disk.
* Multiple String arguments, which will return the path of the **first** file
found, skipping non existing files.
* An array of string paths, which will return the path of the **first** file
found from the given paths in the array, skipping non existing files.
The function returns `undef` if none of the given paths were found
- since 4.8.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('find_file')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/hiera_array.rb | lib/puppet/parser/functions/hiera_array.rb | # frozen_string_literal: true
require 'hiera_puppet'
module Puppet::Parser::Functions
newfunction(
:hiera_array,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Finds all matches of a key throughout the hierarchy and returns them as a single flattened
array of unique values. If any of the matched values are arrays, they're flattened and
included in the results. This is called an
[array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge).
The `hiera_array` function takes up to three arguments, in this order:
1. A string key that Hiera searches for in the hierarchy. **Required**.
2. An optional default value to return if Hiera doesn't find anything matching the key.
* If this argument isn't provided and this function results in a lookup failure, Puppet
fails with a compilation error.
3. The optional name of an arbitrary
[hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
* If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
searching the rest of the hierarchy.
**Example**: Using `hiera_array`
~~~ yaml
# Assuming hiera.yaml
# :hierarchy:
# - web01.example.com
# - common
# Assuming common.yaml:
# users:
# - 'cdouglas = regular'
# - 'efranklin = regular'
# Assuming web01.example.com.yaml:
# users: 'abarry = admin'
~~~
~~~ puppet
$allusers = hiera_array('users', undef)
# $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].
~~~
You can optionally generate the default value with a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
takes one parameter.
**Example**: Using `hiera_array` with a lambda
~~~ puppet
# Assuming the same Hiera data as the previous example:
$allusers = hiera_array('users') | $key | { "Key \'${key}\' not found" }
# $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].
# If hiera_array couldn't match its key, it would return the lambda result,
# "Key 'users' not found".
~~~
`hiera_array` expects that all values returned will be strings or arrays. If any matched
value is a hash, Puppet raises a type mismatch error.
`hiera_array` is deprecated in favor of using `lookup` and will be removed in 6.0.0.
See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html.
Replace the calls as follows:
| from | to |
| ---- | ---|
| hiera_array($key) | lookup($key, { 'merge' => 'unique' }) |
| hiera_array($key, $default) | lookup($key, { 'default_value' => $default, 'merge' => 'unique' }) |
| hiera_array($key, $default, $level) | override level not supported |
Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced
result must be post processed to get exactly the same result, for example using simple hash/array `+` or
with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml.
See
[the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions)
for more information about Hiera lookup functions.
- Since 4.0.0
DOC
) do |*_args|
Error.is4x('hiera_array')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/binary_file.rb | lib/puppet/parser/functions/binary_file.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:binary_file,
:type => :rvalue,
:arity => 1,
:doc => <<~DOC
Loads a binary file from a module or file system and returns its contents as a Binary.
The argument to this function should be a `<MODULE NAME>/<FILE>`
reference, which will load `<FILE>` from a module's `files`
directory. (For example, the reference `mysql/mysqltuner.pl` will load the
file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.)
This function also accepts an absolute file path that allows reading
binary file content from anywhere on disk.
An error is raised if the given file does not exists.
To search for the existence of files, use the `find_file()` function.
- since 4.8.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('binary_file')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/reduce.rb | lib/puppet/parser/functions/reduce.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:reduce,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
to every value in a data structure from the first argument, carrying over the returned
value of each iteration, and returns the result of the lambda's final iteration. This
lets you create a new value or data structure by combining values from the first
argument's data structure.
This function takes two mandatory arguments, in this order:
1. An array or hash the function will iterate over.
2. A lambda, which the function calls for each element in the first argument. It takes
two mandatory parameters:
1. A memo value that is overwritten after each iteration with the iteration's result.
2. A second value that is overwritten after each iteration with the next value in the
function's first argument.
**Example**: Using the `reduce` function
`$data.reduce |$memo, $value| { ... }`
or
`reduce($data) |$memo, $value| { ... }`
You can also pass an optional "start memo" value as an argument, such as `start` below:
`$data.reduce(start) |$memo, $value| { ... }`
or
`reduce($data, start) |$memo, $value| { ... }`
When the first argument (`$data` in the above example) is an array, Puppet passes each
of the data structure's values in turn to the lambda's parameters. When the first
argument is a hash, Puppet converts each of the hash's values to an array in the form
`[key, value]`.
If you pass a start memo value, Puppet executes the lambda with the provided memo value
and the data structure's first value. Otherwise, Puppet passes the structure's first two
values to the lambda.
Puppet calls the lambda for each of the data structure's remaining values. For each
call, it passes the result of the previous call as the first parameter ($memo in the
above examples) and the next value from the data structure as the second parameter
($value).
If the structure has one value, Puppet returns the value and does not call the lambda.
**Example**: Using the `reduce` function
~~~ puppet
# Reduce the array $data, returning the sum of all values in the array.
$data = [1, 2, 3]
$sum = $data.reduce |$memo, $value| { $memo + $value }
# $sum contains 6
# Reduce the array $data, returning the sum of a start memo value and all values in the
# array.
$data = [1, 2, 3]
$sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# $sum contains 10
# Reduce the hash $data, returning the sum of all values and concatenated string of all
# keys.
$data = {a => 1, b => 2, c => 3}
$combine = $data.reduce |$memo, $value| {
$string = "${memo[0]}${value[0]}"
$number = $memo[1] + $value[1]
[$string, $number]
}
# $combine contains [abc, 6]
~~~
**Example**: Using the `reduce` function with a start memo and two-parameter lambda
~~~ puppet
# Reduce the array $data, returning the sum of all values in the array and starting
# with $memo set to an arbitrary value instead of $data's first value.
$data = [1, 2, 3]
$sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# At the start of the lambda's first iteration, $memo contains 4 and $value contains 1.
# After all iterations, $sum contains 10.
# Reduce the hash $data, returning the sum of all values and concatenated string of
# all keys, and starting with $memo set to an arbitrary array instead of $data's first
# key-value pair.
$data = {a => 1, b => 2, c => 3}
$combine = $data.reduce( [d, 4] ) |$memo, $value| {
$string = "${memo[0]}${value[0]}"
$number = $memo[1] + $value[1]
[$string, $number]
}
# At the start of the lambda's first iteration, $memo contains [d, 4] and $value
# contains [a, 1].
# $combine contains [dabc, 10]
~~~
**Example**: Using the `reduce` function to reduce a hash of hashes
~~~ puppet
# Reduce a hash of hashes $data, merging defaults into the inner hashes.
$data = {
'connection1' => {
'username' => 'user1',
'password' => 'pass1',
},
'connection_name2' => {
'username' => 'user2',
'password' => 'pass2',
},
}
$defaults = {
'maxActive' => '20',
'maxWait' => '10000',
'username' => 'defaultuser',
'password' => 'defaultpass',
}
$merged = $data.reduce( {} ) |$memo, $x| {
$memo + { $x[0] => $defaults + $data[$x[0]] }
}
# At the start of the lambda's first iteration, $memo is set to {}, and $x is set to
# the first [key, value] tuple. The key in $data is, therefore, given by $x[0]. In
# subsequent rounds, $memo retains the value returned by the expression, i.e.
# $memo + { $x[0] => $defaults + $data[$x[0]] }.
~~~
- Since 4.0.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('reduce')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/slice.rb | lib/puppet/parser/functions/slice.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:slice,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
This function takes two mandatory arguments: the first should be an array or hash, and the second specifies
the number of elements to include in each slice.
When the first argument is a hash, each key value pair is counted as one. For example, a slice size of 2 will produce
an array of two arrays with key, and value.
$a.slice(2) |$entry| { notice "first ${$entry[0]}, second ${$entry[1]}" }
$a.slice(2) |$first, $second| { notice "first ${first}, second ${second}" }
The function produces a concatenated result of the slices.
slice([1,2,3,4,5,6], 2) # produces [[1,2], [3,4], [5,6]]
slice(Integer[1,6], 2) # produces [[1,2], [3,4], [5,6]]
slice(4,2) # produces [[0,1], [2,3]]
slice('hello',2) # produces [[h, e], [l, l], [o]]
You can also optionally pass a lambda to slice.
$a.slice($n) |$x| { ... }
slice($a) |$x| { ... }
The lambda should have either one parameter (receiving an array with the slice), or the same number
of parameters as specified by the slice size (each parameter receiving its part of the slice).
If there are fewer remaining elements than the slice size for the last slice, it will contain the remaining
elements. If the lambda has multiple parameters, excess parameters are set to undef for an array, or
to empty arrays for a hash.
$a.slice(2) |$first, $second| { ... }
- Since 4.0.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('slice')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/include.rb | lib/puppet/parser/functions/include.rb | # frozen_string_literal: true
# Include the specified classes
Puppet::Parser::Functions.newfunction(:include, :arity => -2, :doc =>
"Declares one or more classes, causing the resources in them to be
evaluated and added to the catalog. Accepts a class name, an array of class
names, or a comma-separated list of class names.
The `include` function can be used multiple times on the same class and will
only declare a given class once. If a class declared with `include` has any
parameters, Puppet will automatically look up values for them in Hiera, using
`<class name>::<parameter name>` as the lookup key.
Contrast this behavior with resource-like class declarations
(`class {'name': parameter => 'value',}`), which must be used in only one place
per class and can directly set parameters. You should avoid using both `include`
and resource-like declarations with the same class.
The `include` function does not cause classes to be contained in the class
where they are declared. For that, see the `contain` function. It also
does not create a dependency relationship between the declared class and the
surrounding class; for that, see the `require` function.
You must use the class's full name;
relative names are not allowed. In addition to names in string form,
you may also directly use Class and Resource Type values that are produced by
the future parser's resource and relationship expressions.
- Since < 3.0.0
- Since 4.0.0 support for class and resource type values, absolute names
- Since 4.7.0 returns an Array[Type[Class]] of all included classes
") do |classes|
call_function('include', classes)
# TRANSLATORS "function_include", "Scope", and "Scope#call_function" refer to Puppet internals and should not be translated
Puppet.warn_once('deprecations', '3xfunction#include', _("Calling function_include via the Scope class is deprecated. Use Scope#call_function instead"))
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/generate.rb | lib/puppet/parser/functions/generate.rb | # frozen_string_literal: true
# Runs an external command and returns the results
Puppet::Parser::Functions.newfunction(:generate, :arity => -2, :type => :rvalue,
:doc => "Calls an external command on the Puppet master and returns
the results of the command. Any arguments are passed to the external command as
arguments. If the generator does not exit with return code of 0,
the generator is considered to have failed and a parse error is
thrown. Generators can only have file separators, alphanumerics, dashes,
and periods in them. This function will attempt to protect you from
malicious generator calls (e.g., those with '..' in them), but it can
never be entirely safe. No subshell is used to execute
generators, so all shell metacharacters are passed directly to
the generator, and all metacharacters are returned by the function.
Consider cleaning white space from any string generated.") do |args|
# TRANSLATORS "fully qualified" refers to a fully qualified file system path
raise Puppet::ParseError, _("Generators must be fully qualified") unless Puppet::Util.absolute_path?(args[0])
if Puppet::Util::Platform.windows?
valid = args[0] =~ %r{^[a-z]:(?:[/\\][-.~\w]+)+$}i
else
valid = args[0] =~ %r{^[-/\w.+]+$}
end
unless valid
raise Puppet::ParseError, _("Generators can only contain alphanumerics, file separators, and dashes")
end
if args[0] =~ /\.\./
raise Puppet::ParseError, _("Can not use generators with '..' in them.")
end
begin
dir = File.dirname(args[0])
Puppet::Util::Execution.execute(args, failonfail: true, combine: true, cwd: dir).to_str
rescue Puppet::ExecutionFailure => detail
raise Puppet::ParseError, _("Failed to execute generator %{generator}: %{detail}") % { generator: args[0], detail: detail }, detail.backtrace
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/fqdn_rand.rb | lib/puppet/parser/functions/fqdn_rand.rb | # frozen_string_literal: true
require 'digest/md5'
require 'digest/sha2'
Puppet::Parser::Functions.newfunction(:fqdn_rand, :arity => -2, :type => :rvalue, :doc =>
"Usage: `fqdn_rand(MAX, [SEED], [DOWNCASE])`. MAX is required and must be a positive
integer; SEED is optional and may be any number or string; DOWNCASE is optional
and should be a boolean true or false.
Generates a random Integer number greater than or equal to 0 and less than MAX,
combining the `$fqdn` fact and the value of SEED for repeatable randomness.
(That is, each node will get a different random number from this function, but
a given node's result will be the same every time unless its hostname changes.) If
DOWNCASE is true, then the `fqdn` fact will be downcased when computing the value
so that the result is not sensitive to the case of the `fqdn` fact.
This function is usually used for spacing out runs of resource-intensive cron
tasks that run on many nodes, which could cause a thundering herd or degrade
other services if they all fire at once. Adding a SEED can be useful when you
have more than one such task and need several unrelated random numbers per
node. (For example, `fqdn_rand(30)`, `fqdn_rand(30, 'expensive job 1')`, and
`fqdn_rand(30, 'expensive job 2')` will produce totally different numbers.)") do |args|
max = args.shift.to_i
initial_seed = args.shift
downcase = !!args.shift
fqdn = self['facts'].dig('networking', 'fqdn')
fqdn = fqdn.downcase if downcase
# Puppet 5.4's fqdn_rand function produces a different value than earlier versions
# for the same set of inputs.
# This causes problems because the values are often written into service configuration files.
# When they change, services get notified and restart.
# Restoring previous fqdn_rand behavior of calculating its seed value using MD5
# when running on a non-FIPS enabled platform and only using SHA256 on FIPS enabled
# platforms.
if Puppet::Util::Platform.fips_enabled?
seed = Digest::SHA256.hexdigest([fqdn, max, initial_seed].join(':')).hex
else
seed = Digest::MD5.hexdigest([fqdn, max, initial_seed].join(':')).hex
end
Puppet::Util.deterministic_rand_int(seed, max)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/type.rb | lib/puppet/parser/functions/type.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:type,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
Returns the data type of a given value with a given degree of generality.
```puppet
type InferenceFidelity = Enum[generalized, reduced, detailed]
function type(Any $value, InferenceFidelity $fidelity = 'detailed') # returns Type
```
**Example:** Using `type`
``` puppet
notice type(42) =~ Type[Integer]
```
Would notice `true`.
By default, the best possible inference is made where all details are retained.
This is good when the type is used for further type calculations but is overwhelmingly
rich in information if it is used in a error message.
The optional argument `$fidelity` may be given as (from lowest to highest fidelity):
* `generalized` - reduces to common type and drops size constraints
* `reduced` - reduces to common type in collections
* `detailed` - (default) all details about inferred types is retained
**Example:** Using `type()` with different inference fidelity:
``` puppet
notice type([3.14, 42], 'generalized')
notice type([3.14, 42], 'reduced'')
notice type([3.14, 42], 'detailed')
notice type([3.14, 42])
```
Would notice the four values:
1. 'Array[Numeric]'
2. 'Array[Numeric, 2, 2]'
3. 'Tuple[Float[3.14], Integer[42,42]]]'
4. 'Tuple[Float[3.14], Integer[42,42]]]'
* Since 4.4.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('type')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/hiera_hash.rb | lib/puppet/parser/functions/hiera_hash.rb | # frozen_string_literal: true
require 'hiera_puppet'
module Puppet::Parser::Functions
newfunction(
:hiera_hash,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Finds all matches of a key throughout the hierarchy and returns them in a merged hash.
If any of the matched hashes share keys, the final hash uses the value from the
highest priority match. This is called a
[hash merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#hash-merge).
The merge strategy is determined by Hiera's
[`:merge_behavior`](https://puppet.com/docs/hiera/latest/configuring.html#mergebehavior)
setting.
The `hiera_hash` function takes up to three arguments, in this order:
1. A string key that Hiera searches for in the hierarchy. **Required**.
2. An optional default value to return if Hiera doesn't find anything matching the key.
* If this argument isn't provided and this function results in a lookup failure, Puppet
fails with a compilation error.
3. The optional name of an arbitrary
[hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
* If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
searching the rest of the hierarchy.
**Example**: Using `hiera_hash`
~~~ yaml
# Assuming hiera.yaml
# :hierarchy:
# - web01.example.com
# - common
# Assuming common.yaml:
# users:
# regular:
# 'cdouglas': 'Carrie Douglas'
# Assuming web01.example.com.yaml:
# users:
# administrators:
# 'aberry': 'Amy Berry'
~~~
~~~ puppet
# Assuming we are not web01.example.com:
$allusers = hiera_hash('users', undef)
# $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
# administrators => {"aberry" => "Amy Berry"}}
~~~
You can optionally generate the default value with a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
takes one parameter.
**Example**: Using `hiera_hash` with a lambda
~~~ puppet
# Assuming the same Hiera data as the previous example:
$allusers = hiera_hash('users') | $key | { "Key \'${key}\' not found" }
# $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
# administrators => {"aberry" => "Amy Berry"}}
# If hiera_hash couldn't match its key, it would return the lambda result,
# "Key 'users' not found".
~~~
`hiera_hash` expects that all values returned will be hashes. If any of the values
found in the data sources are strings or arrays, Puppet raises a type mismatch error.
`hiera_hash` is deprecated in favor of using `lookup` and will be removed in 6.0.0.
See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html.
Replace the calls as follows:
| from | to |
| ---- | ---|
| hiera_hash($key) | lookup($key, { 'merge' => 'hash' }) |
| hiera_hash($key, $default) | lookup($key, { 'default_value' => $default, 'merge' => 'hash' }) |
| hiera_hash($key, $default, $level) | override level not supported |
Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced
result must be post processed to get exactly the same result, for example using simple hash/array `+` or
with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml.
See
[the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions)
for more information about Hiera lookup functions.
- Since 4.0.0
DOC
) do |*_args|
Error.is4x('hiera_hash')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/new.rb | lib/puppet/parser/functions/new.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:new,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
Creates a new instance/object of a given data type.
This function makes it possible to create new instances of
concrete data types. If a block is given it is called with the
just created instance as an argument.
Calling this function is equivalent to directly
calling the data type:
**Example:** `new` and calling type directly are equivalent
```puppet
$a = Integer.new("42")
$b = Integer("42")
```
These would both convert the string `"42"` to the decimal value `42`.
**Example:** arguments by position or by name
```puppet
$a = Integer.new("42", 8)
$b = Integer({from => "42", radix => 8})
```
This would convert the octal (radix 8) number `"42"` in string form
to the decimal value `34`.
The new function supports two ways of giving the arguments:
* by name (using a hash with property to value mapping)
* by position (as regular arguments)
Note that it is not possible to create new instances of
some abstract data types (for example `Variant`). The data type `Optional[T]` is an
exception as it will create an instance of `T` or `undef` if the
value to convert is `undef`.
The arguments that can be given is determined by the data type.
> An assertion is always made that the produced value complies with the given type constraints.
**Example:** data type constraints are checked
```puppet
Integer[0].new("-100")
```
Would fail with an assertion error (since value is less than 0).
The following sections show the arguments and conversion rules
per data type built into the Puppet Type System.
### Conversion to Optional[T] and NotUndef[T]
Conversion to these data types is the same as a conversion to the type argument `T`.
In the case of `Optional[T]` it is accepted that the argument to convert may be `undef`.
It is however not acceptable to give other arguments (than `undef`) that cannot be
converted to `T`.
### Conversion to Integer
A new `Integer` can be created from `Integer`, `Float`, `Boolean`, and `String` values.
For conversion from `String` it is possible to specify the radix (base).
```puppet
type Radix = Variant[Default, Integer[2,2], Integer[8,8], Integer[10,10], Integer[16,16]]
function Integer.new(
String $value,
Radix $radix = 10,
Boolean $abs = false
)
function Integer.new(
Variant[Numeric, Boolean] $value,
Boolean $abs = false
)
```
* When converting from `String` the default radix is 10.
* If radix is not specified an attempt is made to detect the radix from the start of the string:
* `0b` or `0B` is taken as radix 2.
* `0x` or `0X` is taken as radix 16.
* `0` as radix 8.
* All others are decimal.
* Conversion from `String` accepts an optional sign in the string.
* For hexadecimal (radix 16) conversion an optional leading "0x", or "0X" is accepted.
* For octal (radix 8) an optional leading "0" is accepted.
* For binary (radix 2) an optional leading "0b" or "0B" is accepted.
* When `radix` is set to `default`, the conversion is based on the leading.
characters in the string. A leading "0" for radix 8, a leading "0x", or "0X" for
radix 16, and leading "0b" or "0B" for binary.
* Conversion from `Boolean` results in 0 for `false` and 1 for `true`.
* Conversion from `Integer`, `Float`, and `Boolean` ignores the radix.
* `Float` value fractions are truncated (no rounding).
* When `abs` is set to `true`, the result will be an absolute integer.
Examples - Converting to Integer:
```puppet
$a_number = Integer("0xFF", 16) # results in 255
$a_number = Integer("010") # results in 8
$a_number = Integer("010", 10) # results in 10
$a_number = Integer(true) # results in 1
$a_number = Integer(-38, 10, true) # results in 38
```
### Conversion to Float
A new `Float` can be created from `Integer`, `Float`, `Boolean`, and `String` values.
For conversion from `String` both float and integer formats are supported.
```puppet
function Float.new(
Variant[Numeric, Boolean, String] $value,
Boolean $abs = true
)
```
* For an integer, the floating point fraction of `.0` is added to the value.
* A `Boolean` `true` is converted to 1.0, and a `false` to 0.0
* In `String` format, integer prefixes for hex and binary are understood (but not octal since
floating point in string format may start with a '0').
* When `abs` is set to `true`, the result will be an absolute floating point value.
### Conversion to Numeric
A new `Integer` or `Float` can be created from `Integer`, `Float`, `Boolean` and
`String` values.
```puppet
function Numeric.new(
Variant[Numeric, Boolean, String] $value,
Boolean $abs = true
)
```
* If the value has a decimal period, or if given in scientific notation
(e/E), the result is a `Float`, otherwise the value is an `Integer`. The
conversion from `String` always uses a radix based on the prefix of the string.
* Conversion from `Boolean` results in 0 for `false` and 1 for `true`.
* When `abs` is set to `true`, the result will be an absolute `Float`or `Integer` value.
Examples - Converting to Numeric
```puppet
$a_number = Numeric(true) # results in 1
$a_number = Numeric("0xFF") # results in 255
$a_number = Numeric("010") # results in 8
$a_number = Numeric("3.14") # results in 3.14 (a float)
$a_number = Numeric(-42.3, true) # results in 42.3
$a_number = Numeric(-42, true) # results in 42
```
### Conversion to Timespan
A new `Timespan` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided.
#### Timespan from seconds
When a Float is used, the decimal part represents fractions of a second.
```puppet
function Timespan.new(
Variant[Float, Integer] $value
)
```
#### Timespan from days, hours, minutes, seconds, and fractions of a second
The arguments can be passed separately in which case the first four, days, hours, minutes, and seconds are mandatory and the rest are optional.
All values may overflow and/or be negative. The internal 128-bit nano-second integer is calculated as:
```
(((((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000 + milliseconds) * 1000 + microseconds) * 1000 + nanoseconds
```
```puppet
function Timespan.new(
Integer $days, Integer $hours, Integer $minutes, Integer $seconds,
Integer $milliseconds = 0, Integer $microseconds = 0, Integer $nanoseconds = 0
)
```
or, all arguments can be passed as a `Hash`, in which case all entries are optional:
```puppet
function Timespan.new(
Struct[{
Optional[negative] => Boolean,
Optional[days] => Integer,
Optional[hours] => Integer,
Optional[minutes] => Integer,
Optional[seconds] => Integer,
Optional[milliseconds] => Integer,
Optional[microseconds] => Integer,
Optional[nanoseconds] => Integer
}] $hash
)
```
#### Timespan from String and format directive patterns
The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt
will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second
argument is omitted, an array of default formats will be used.
An exception is raised when no format was able to parse the given string.
```puppet
function Timespan.new(
String $string, Variant[String[2],Array[String[2], 1]] $format = <default format>)
)
```
the arguments may also be passed as a `Hash`:
```puppet
function Timespan.new(
Struct[{
string => String[1],
Optional[format] => Variant[String[2],Array[String[2], 1]]
}] $hash
)
```
The directive consists of a percent (%) character, zero or more flags, optional minimum field width and
a conversion specifier as follows:
```
%[Flags][Width]Conversion
```
##### Flags:
| Flag | Meaning
| ---- | ---------------
| - | Don't pad numerical output
| _ | Use spaces for padding
| 0 | Use zeros for padding
##### Format directives:
| Format | Meaning |
| ------ | ------- |
| D | Number of Days |
| H | Hour of the day, 24-hour clock |
| M | Minute of the hour (00..59) |
| S | Second of the minute (00..59) |
| L | Millisecond of the second (000..999) |
| N | Fractional seconds digits |
The format directive that represents the highest magnitude in the format will be allowed to
overflow. I.e. if no "%D" is used but a "%H" is present, then the hours may be more than 23.
The default array contains the following patterns:
```
['%D-%H:%M:%S', '%D-%H:%M', '%H:%M:%S', '%H:%M']
```
Examples - Converting to Timespan
```puppet
$duration = Timespan(13.5) # 13 seconds and 500 milliseconds
$duration = Timespan({days=>4}) # 4 days
$duration = Timespan(4, 0, 0, 2) # 4 days and 2 seconds
$duration = Timespan('13:20') # 13 hours and 20 minutes (using default pattern)
$duration = Timespan('10:03.5', '%M:%S.%L') # 10 minutes, 3 seconds, and 5 milli-seconds
$duration = Timespan('10:03.5', '%M:%S.%N') # 10 minutes, 3 seconds, and 5 nano-seconds
```
### Conversion to Timestamp
A new `Timestamp` can be created from `Integer`, `Float`, `String`, and `Hash` values. Several variants of the constructor are provided.
#### Timestamp from seconds since epoch (1970-01-01 00:00:00 UTC)
When a Float is used, the decimal part represents fractions of a second.
```puppet
function Timestamp.new(
Variant[Float, Integer] $value
)
```
#### Timestamp from String and patterns consisting of format directives
The first argument is parsed using the format optionally passed as a string or array of strings. When an array is used, an attempt
will be made to parse the string using the first entry and then with each entry in succession until parsing succeeds. If the second
argument is omitted, an array of default formats will be used.
A third optional timezone argument can be provided. The first argument will then be parsed as if it represents a local time in that
timezone. The timezone can be any timezone that is recognized when using the '%z' or '%Z' formats, or the word 'current', in which
case the current timezone of the evaluating process will be used. The timezone argument is case insensitive.
The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'.
It is illegal to provide a timezone argument other than `default` in combination with a format that contains '%z' or '%Z' since that
would introduce an ambiguity as to which timezone to use. The one extracted from the string, or the one provided as an argument.
An exception is raised when no format was able to parse the given string.
```puppet
function Timestamp.new(
String $string,
Variant[String[2],Array[String[2], 1]] $format = <default format>,
String $timezone = default)
)
```
the arguments may also be passed as a `Hash`:
```puppet
function Timestamp.new(
Struct[{
string => String[1],
Optional[format] => Variant[String[2],Array[String[2], 1]],
Optional[timezone] => String[1]
}] $hash
)
```
The directive consists of a percent (%) character, zero or more flags, optional minimum field width and
a conversion specifier as follows:
```
%[Flags][Width]Conversion
```
##### Flags:
| Flag | Meaning
| ---- | ---------------
| - | Don't pad numerical output
| _ | Use spaces for padding
| 0 | Use zeros for padding
| # | Change names to upper-case or change case of am/pm
| ^ | Use uppercase
| : | Use colons for %z
##### Format directives (names and padding can be altered using flags):
**Date (Year, Month, Day):**
| Format | Meaning |
| ------ | ------- |
| Y | Year with century, zero-padded to at least 4 digits |
| C | year / 100 (rounded down such as 20 in 2009) |
| y | year % 100 (00..99) |
| m | Month of the year, zero-padded (01..12) |
| B | The full month name ("January") |
| b | The abbreviated month name ("Jan") |
| h | Equivalent to %b |
| d | Day of the month, zero-padded (01..31) |
| e | Day of the month, blank-padded ( 1..31) |
| j | Day of the year (001..366) |
**Time (Hour, Minute, Second, Subsecond):**
| Format | Meaning |
| ------ | ------- |
| H | Hour of the day, 24-hour clock, zero-padded (00..23) |
| k | Hour of the day, 24-hour clock, blank-padded ( 0..23) |
| I | Hour of the day, 12-hour clock, zero-padded (01..12) |
| l | Hour of the day, 12-hour clock, blank-padded ( 1..12) |
| P | Meridian indicator, lowercase ("am" or "pm") |
| p | Meridian indicator, uppercase ("AM" or "PM") |
| M | Minute of the hour (00..59) |
| S | Second of the minute (00..60) |
| L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000 |
| N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up |
**Time (Hour, Minute, Second, Subsecond):**
| Format | Meaning |
| ------ | ------- |
| z | Time zone as hour and minute offset from UTC (e.g. +0900) |
| :z | hour and minute offset from UTC with a colon (e.g. +09:00) |
| ::z | hour, minute and second offset from UTC (e.g. +09:00:00) |
| Z | Abbreviated time zone name or similar information. (OS dependent) |
**Weekday:**
| Format | Meaning |
| ------ | ------- |
| A | The full weekday name ("Sunday") |
| a | The abbreviated name ("Sun") |
| u | Day of the week (Monday is 1, 1..7) |
| w | Day of the week (Sunday is 0, 0..6) |
**ISO 8601 week-based year and week number:**
The first week of YYYY starts with a Monday and includes YYYY-01-04.
The days in the year before the first week are in the last week of
the previous year.
| Format | Meaning |
| ------ | ------- |
| G | The week-based year |
| g | The last 2 digits of the week-based year (00..99) |
| V | Week number of the week-based year (01..53) |
**Week number:**
The first week of YYYY that starts with a Sunday or Monday (according to %U
or %W). The days in the year before the first week are in week 0.
| Format | Meaning |
| ------ | ------- |
| U | Week number of the year. The week starts with Sunday. (00..53) |
| W | Week number of the year. The week starts with Monday. (00..53) |
**Seconds since the Epoch:**
| Format | Meaning |
| s | Number of seconds since 1970-01-01 00:00:00 UTC. |
**Literal string:**
| Format | Meaning |
| ------ | ------- |
| n | Newline character (\n) |
| t | Tab character (\t) |
| % | Literal "%" character |
**Combination:**
| Format | Meaning |
| ------ | ------- |
| c | date and time (%a %b %e %T %Y) |
| D | Date (%m/%d/%y) |
| F | The ISO 8601 date format (%Y-%m-%d) |
| v | VMS date (%e-%^b-%4Y) |
| x | Same as %D |
| X | Same as %T |
| r | 12-hour time (%I:%M:%S %p) |
| R | 24-hour time (%H:%M) |
| T | 24-hour time (%H:%M:%S) |
The default array contains the following patterns:
When a timezone argument (other than `default`) is explicitly provided:
```
['%FT%T.L', '%FT%T', '%F']
```
otherwise:
```
['%FT%T.%L %Z', '%FT%T %Z', '%F %Z', '%FT%T.L', '%FT%T', '%F']
```
Examples - Converting to Timestamp
```puppet
$ts = Timestamp(1473150899) # 2016-09-06 08:34:59 UTC
$ts = Timestamp({string=>'2015', format=>'%Y'}) # 2015-01-01 00:00:00.000 UTC
$ts = Timestamp('Wed Aug 24 12:13:14 2016', '%c') # 2016-08-24 12:13:14 UTC
$ts = Timestamp('Wed Aug 24 12:13:14 2016 PDT', '%c %Z') # 2016-08-24 19:13:14.000 UTC
$ts = Timestamp('2016-08-24 12:13:14', '%F %T', 'PST') # 2016-08-24 20:13:14.000 UTC
$ts = Timestamp('2016-08-24T12:13:14', default, 'PST') # 2016-08-24 20:13:14.000 UTC
```
### Conversion to Type
A new `Type` can be create from its `String` representation.
**Example:** Creating a type from a string
```puppet
$t = Type.new('Integer[10]')
```
### Conversion to String
Conversion to `String` is the most comprehensive conversion as there are many
use cases where a string representation is wanted. The defaults for the many options
have been chosen with care to be the most basic "value in textual form" representation.
The more advanced forms of formatting are intended to enable writing special purposes formatting
functions in the Puppet language.
A new string can be created from all other data types. The process is performed in
several steps - first the data type of the given value is inferred, then the resulting data type
is used to find the most significant format specified for that data type. And finally,
the found format is used to convert the given value.
The mapping from data type to format is referred to as the *format map*. This map
allows different formatting depending on type.
**Example:** Positive Integers in Hexadecimal prefixed with '0x', negative in Decimal
```puppet
$format_map = {
Integer[default, 0] => "%d",
Integer[1, default] => "%#x"
}
String("-1", $format_map) # produces '-1'
String("10", $format_map) # produces '0xa'
```
A format is specified on the form:
```
%[Flags][Width][.Precision]Format
```
`Width` is the number of characters into which the value should be fitted. This allocated space is
padded if value is shorter. By default it is space padded, and the flag `0` will cause padding with `0`
for numerical formats.
`Precision` is the number of fractional digits to show for floating point, and the maximum characters
included in a string format.
Note that all data type supports the formats `s` and `p` with the meaning "default string representation" and
"default programmatic string representation" (which for example means that a String is quoted in 'p' format).
#### Signatures of String conversion
```puppet
type Format = Pattern[/^%([\s\+\-#0\[\{<\(\|]*)([1-9][0-9]*)?(?:\.([0-9]+))?([a-zA-Z])/]
type ContainerFormat = Struct[{
format => Optional[String],
separator => Optional[String],
separator2 => Optional[String],
string_formats => Hash[Type, Format]
}]
type TypeMap = Hash[Type, Variant[Format, ContainerFormat]]
type Formats = Variant[Default, String[1], TypeMap]
function String.new(
Any $value,
Formats $string_formats
)
```
Where:
* `separator` is the string used to separate entries in an array, or hash (extra space should not be included at
the end), defaults to `","`
* `separator2` is the separator between key and value in a hash entry (space padding should be included as
wanted), defaults to `" => "`.
* `string_formats` is a data type to format map for values contained in arrays and hashes - defaults to `{Any => "%p"}`. Note that
these nested formats are not applicable to data types that are containers; they are always formatted as per the top level
format specification.
**Example:** Simple Conversion to String (using defaults)
```puppet
$str = String(10) # produces '10'
$str = String([10]) # produces '["10"]'
```
**Example:** Simple Conversion to String specifying the format for the given value directly
```puppet
$str = String(10, "%#x") # produces '0x10'
$str = String([10], "%(a") # produces '("10")'
```
**Example:** Specifying type for values contained in an array
```puppet
$formats = {
Array => {
format => '%(a',
string_formats => { Integer => '%#x' }
}
}
$str = String([1,2,3], $formats) # produces '(0x1, 0x2, 0x3)'
```
The given formats are merged with the default formats, and matching of values to convert against format is based on
the specificity of the mapped type; for example, different formats can be used for short and long arrays.
#### Integer to String
| Format | Integer Formats
| ------ | ---------------
| d | Decimal, negative values produces leading '-'.
| x X | Hexadecimal in lower or upper case. Uses ..f/..F for negative values unless + is also used. A `#` adds prefix 0x/0X.
| o | Octal. Uses ..0 for negative values unless `+` is also used. A `#` adds prefix 0.
| b B | Binary with prefix 'b' or 'B'. Uses ..1/..1 for negative values unless `+` is also used.
| c | Numeric value representing a Unicode value, result is a one unicode character string, quoted if alternative flag # is used
| s | Same as d, or d in quotes if alternative flag # is used.
| p | Same as d.
| eEfgGaA | Converts integer to float and formats using the floating point rules.
Defaults to `d`.
#### Float to String
| Format | Float formats
| ------ | -------------
| f | Floating point in non exponential notation.
| e E | Exponential notation with 'e' or 'E'.
| g G | Conditional exponential with 'e' or 'E' if exponent < -4 or >= the precision.
| a A | Hexadecimal exponential form, using 'x'/'X' as prefix and 'p'/'P' before exponent.
| s | Converted to string using format p, then applying string formatting rule, alternate form # quotes result.
| p | Same as f format with minimum significant number of fractional digits, prec has no effect.
| dxXobBc | Converts float to integer and formats using the integer rules.
Defaults to `p`.
#### String to String
| Format | String
| ------ | ------
| s | Unquoted string, verbatim output of control chars.
| p | Programmatic representation - strings are quoted, interior quotes and control chars are escaped.
| C | Each `::` name segment capitalized, quoted if alternative flag `#` is used.
| c | Capitalized string, quoted if alternative flag `#` is used.
| d | Downcased string, quoted if alternative flag `#` is used.
| u | Upcased string, quoted if alternative flag `#` is used.
| t | Trims leading and trailing whitespace from the string, quoted if alternative flag `#` is used.
Defaults to `s` at top level and `p` inside array or hash.
#### Boolean to String
| Format | Boolean Formats
| ---- | -------------------
| t T | String 'true'/'false' or 'True'/'False', first char if alternate form is used (i.e. 't'/'f' or 'T'/'F').
| y Y | String 'yes'/'no', 'Yes'/'No', 'y'/'n' or 'Y'/'N' if alternative flag `#` is used.
| dxXobB | Numeric value 0/1 in accordance with the given format which must be valid integer format.
| eEfgGaA | Numeric value 0.0/1.0 in accordance with the given float format and flags.
| s | String 'true' / 'false'.
| p | String 'true' / 'false'.
#### Regexp to String
| Format | Regexp Formats
| ---- | --------------
| s | No delimiters, quoted if alternative flag `#` is used.
| p | Delimiters `/ /`.
#### Undef to String
| Format | Undef formats
| ------ | -------------
| s | Empty string, or quoted empty string if alternative flag `#` is used.
| p | String 'undef', or quoted '"undef"' if alternative flag `#` is used.
| n | String 'nil', or 'null' if alternative flag `#` is used.
| dxXobB | String 'NaN'.
| eEfgGaA | String 'NaN'.
| v | String 'n/a'.
| V | String 'N/A'.
| u | String 'undef', or 'undefined' if alternative `#` flag is used.
#### Default value to String
| Format | Default formats
| ------ | ---------------
| d D | String 'default' or 'Default', alternative form `#` causes value to be quoted.
| s | Same as d.
| p | Same as d.
#### Binary value to String
| Format | Default formats
| ------ | ---------------
| s | binary as unquoted UTF-8 characters (errors if byte sequence is invalid UTF-8). Alternate form escapes non ascii bytes.
| p | 'Binary("<base64strict>")'
| b | '<base64>' - base64 string with newlines inserted
| B | '<base64strict>' - base64 strict string (without newlines inserted)
| u | '<base64urlsafe>' - base64 urlsafe string
| t | 'Binary' - outputs the name of the type only
| T | 'BINARY' - output the name of the type in all caps only
* The alternate form flag `#` will quote the binary or base64 text output.
* The format `%#s` allows invalid UTF-8 characters and outputs all non ascii bytes
as hex escaped characters on the form `\\xHH` where `H` is a hex digit.
* The width and precision values are applied to the text part only in `%p` format.
#### Array & Tuple to String
| Format | Array/Tuple Formats
| ------ | -------------
| a | Formats with `[ ]` delimiters and `,`, alternate form `#` indents nested arrays/hashes.
| s | Same as a.
| p | Same as a.
See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for
more information about options.
The alternate form flag `#` will cause indentation of nested array or hash containers. If width is also set
it is taken as the maximum allowed length of a sequence of elements (not including delimiters). If this max length
is exceeded, each element will be indented.
#### Hash & Struct to String
| Format | Hash/Struct Formats
| ------ | -------------
| h | Formats with `{ }` delimiters, `,` element separator and ` => ` inner element separator unless overridden by flags.
| s | Same as h.
| p | Same as h.
| a | Converts the hash to an array of [k,v] tuples and formats it using array rule(s).
See "Flags" `<[({\|` for formatting of delimiters, and "Additional parameters for containers; Array and Hash" for
more information about options.
The alternate form flag `#` will format each hash key/value entry indented on a separate line.
#### Type to String
| Format | Array/Tuple Formats
| ------ | -------------
| s | The same as `p`, quoted if alternative flag `#` is used.
| p | Outputs the type in string form as specified by the Puppet Language.
#### Flags
| Flag | Effect
| ------ | ------
| (space) | A space instead of `+` for numeric output (`-` is shown), for containers skips delimiters.
| # | Alternate format; prefix 0x/0x, 0 (octal) and 0b/0B for binary, Floats force decimal '.'. For g/G keep trailing 0.
| + | Show sign +/- depending on value's sign, changes x, X, o, b, B format to not use 2's complement form.
| - | Left justify the value in the given width.
| 0 | Pad with 0 instead of space for widths larger than value.
| <[({\| | Defines an enclosing pair <> [] () {} or \| \| when used with a container type.
### Conversion to Boolean
Accepts a single value as argument:
* Float 0.0 is `false`, all other float values are `true`
* Integer 0 is `false`, all other integer values are `true`
* Strings
* `true` if 'true', 'yes', 'y' (case independent compare)
* `false` if 'false', 'no', 'n' (case independent compare)
* Boolean is already boolean and is simply returned
### Conversion to Array and Tuple
When given a single value as argument:
* A non empty `Hash` is converted to an array matching `Array[Tuple[Any,Any], 1]`.
* An empty `Hash` becomes an empty array.
* An `Array` is simply returned.
* An `Iterable[T]` is turned into an array of `T` instances.
* A `Binary` is converted to an `Array[Integer[0,255]]` of byte values
When given a second Boolean argument:
* if `true`, a value that is not already an array is returned as a one element array.
* if `false`, (the default), converts the first argument as shown above.
**Example:** Ensuring value is an array
```puppet
$arr = Array($value, true)
```
Conversion to a `Tuple` works exactly as conversion to an `Array`, only that the constructed array is
asserted against the given tuple type.
### Conversion to Hash and Struct
Accepts a single value as argument:
* An empty `Array` becomes an empty `Hash`
* An `Array` matching `Array[Tuple[Any,Any], 1]` is converted to a hash where each tuple describes a key/value entry
* An `Array` with an even number of entries is interpreted as `[key1, val1, key2, val2, ...]`
* An `Iterable` is turned into an `Array` and then converted to hash as per the array rules
* A `Hash` is simply returned
Alternatively, a tree can be constructed by giving two values; an array of tuples on the form `[path, value]`
(where the `path` is the path from the root of a tree, and `value` the value at that position in the tree), and
either the option `'tree'` (do not convert arrays to hashes except the top level), or
`'hash_tree'` (convert all arrays to hashes).
The tree/hash_tree forms of Hash creation are suited for transforming the result of an iteration
using `tree_each` and subsequent filtering or mapping.
**Example:** Mapping a hash tree
Mapping an arbitrary structure in a way that keeps the structure, but where some values are replaced
can be done by using the `tree_each` function, mapping, and then constructing a new Hash from the result:
```puppet
# A hash tree with 'water' at different locations
$h = { a => { b => { x => 'water'}}, b => { y => 'water'} }
# a helper function that turns water into wine
function make_wine($x) { if $x == 'water' { 'wine' } else { $x } }
# create a flattened tree with water turned into wine
$flat_tree = $h.tree_each.map |$entry| { [$entry[0], make_wine($entry[1])] }
# create a new Hash and log it
notice Hash($flat_tree, 'hash_tree')
```
Would notice the hash `{a => {b => {x => wine}}, b => {y => wine}}`
Conversion to a `Struct` works exactly as conversion to a `Hash`, only that the constructed hash is
asserted against the given struct type.
### Conversion to a Regexp
A `String` can be converted into a `Regexp`
**Example**: Converting a String into a Regexp
```puppet
$s = '[a-z]+\.com'
$r = Regexp($s)
if('foo.com' =~ $r) {
...
}
```
### Creating a SemVer
A SemVer object represents a single [Semantic Version](http://semver.org/).
It can be created from a String, individual values for its parts, or a hash specifying the value per part.
See the specification at [semver.org](http://semver.org/) for the meaning of the SemVer's parts.
The signatures are:
```puppet
type PositiveInteger = Integer[0,default]
type SemVerQualifier = Pattern[/\A(?<part>[0-9A-Za-z-]+)(?:\.\g<part>)*\Z/]
type SemVerString = String[1]
type SemVerHash =Struct[{
major => PositiveInteger,
minor => PositiveInteger,
patch => PositiveInteger,
Optional[prerelease] => SemVerQualifier,
Optional[build] => SemVerQualifier
}]
function SemVer.new(SemVerString $str)
function SemVer.new(
PositiveInteger $major
PositiveInteger $minor
PositiveInteger $patch
Optional[SemVerQualifier] $prerelease = undef
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/hiera_include.rb | lib/puppet/parser/functions/hiera_include.rb | # frozen_string_literal: true
require 'hiera_puppet'
module Puppet::Parser::Functions
newfunction(
:hiera_include,
:arity => -2,
:doc => <<~DOC
Assigns classes to a node using an
[array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge)
that retrieves the value for a user-specified key from Hiera's data.
The `hiera_include` function requires:
- A string key name to use for classes.
- A call to this function (i.e. `hiera_include('classes')`) in your environment's
`sites.pp` manifest, outside of any node definitions and below any top-scope variables
that Hiera uses in lookups.
- `classes` keys in the appropriate Hiera data sources, with an array for each
`classes` key and each value of the array containing the name of a class.
The function takes up to three arguments, in this order:
1. A string key that Hiera searches for in the hierarchy. **Required**.
2. An optional default value to return if Hiera doesn't find anything matching the key.
* If this argument isn't provided and this function results in a lookup failure, Puppet
fails with a compilation error.
3. The optional name of an arbitrary
[hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
* If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
searching the rest of the hierarchy.
The function uses an
[array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge)
to retrieve the `classes` array, so every node gets every class from the hierarchy.
**Example**: Using `hiera_include`
~~~ yaml
# Assuming hiera.yaml
# :hierarchy:
# - web01.example.com
# - common
# Assuming web01.example.com.yaml:
# classes:
# - apache::mod::php
# Assuming common.yaml:
# classes:
# - apache
~~~
~~~ puppet
# In site.pp, outside of any node definitions and below any top-scope variables:
hiera_include('classes', undef)
# Puppet assigns the apache and apache::mod::php classes to the web01.example.com node.
~~~
You can optionally generate the default value with a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
takes one parameter.
**Example**: Using `hiera_include` with a lambda
~~~ puppet
# Assuming the same Hiera data as the previous example:
# In site.pp, outside of any node definitions and below any top-scope variables:
hiera_include('classes') | $key | {"Key \'${key}\' not found" }
# Puppet assigns the apache and apache::mod::php classes to the web01.example.com node.
# If hiera_include couldn't match its key, it would return the lambda result,
# "Key 'classes' not found".
~~~
`hiera_include` is deprecated in favor of using a combination of `include` and `lookup` and will be
removed in Puppet 6.0.0. Replace the calls as follows:
| from | to |
| ---- | ---|
| hiera_include($key) | include(lookup($key, { 'merge' => 'unique' })) |
| hiera_include($key, $default) | include(lookup($key, { 'default_value' => $default, 'merge' => 'unique' })) |
| hiera_include($key, $default, $level) | override level not supported |
See
[the Upgrading to Hiera 5 migration guide](https://puppet.com/docs/puppet/5.5/hiera_migrate.html)
for more information.
Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced
result must be post processed to get exactly the same result, for example using simple hash/array `+` or
with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml.
- Since 4.0.0
DOC
) do |*_args|
Error.is4x('hiera_include')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/digest.rb | lib/puppet/parser/functions/digest.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/checksums'
Puppet::Parser::Functions.newfunction(:digest, :type => :rvalue, :arity => 1, :doc => "Returns a hash value from a provided string using the digest_algorithm setting from the Puppet config file.") do |args|
algo = Puppet[:digest_algorithm]
Puppet::Util::Checksums.method(algo.intern).call args[0]
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/filter.rb | lib/puppet/parser/functions/filter.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:filter,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
to every value in a data structure and returns an array or hash containing any elements
for which the lambda evaluates to a truthy value (not `false` or `undef`).
This function takes two mandatory arguments, in this order:
1. An array or hash the function will iterate over.
2. A lambda, which the function calls for each element in the first argument. It can
request one or two parameters.
**Example**: Using the `filter` function
`$filtered_data = $data.filter |$parameter| { <PUPPET CODE BLOCK> }`
or
`$filtered_data = filter($data) |$parameter| { <PUPPET CODE BLOCK> }`
When the first argument (`$data` in the above example) is an array, Puppet passes each
value in turn to the lambda and returns an array containing the results.
**Example**: Using the `filter` function with an array and a one-parameter lambda
~~~ puppet
# For the array $data, return an array containing the values that end with "berry"
$data = ["orange", "blueberry", "raspberry"]
$filtered_data = $data.filter |$items| { $items =~ /berry$/ }
# $filtered_data = [blueberry, raspberry]
~~~
When the first argument is a hash, Puppet passes each key and value pair to the lambda
as an array in the form `[key, value]` and returns a hash containing the results.
**Example**: Using the `filter` function with a hash and a one-parameter lambda
~~~ puppet
# For the hash $data, return a hash containing all values of keys that end with "berry"
$data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 }
$filtered_data = $data.filter |$items| { $items[0] =~ /berry$/ }
# $filtered_data = {blueberry => 1, raspberry => 2}
~~~
When the first argument is an array and the lambda has two parameters, Puppet passes the
array's indexes (enumerated from 0) in the first parameter and its values in the second
parameter.
**Example**: Using the `filter` function with an array and a two-parameter lambda
~~~ puppet
# For the array $data, return an array of all keys that both end with "berry" and have
# an even-numbered index
$data = ["orange", "blueberry", "raspberry"]
$filtered_data = $data.filter |$indexes, $values| { $indexes % 2 == 0 and $values =~ /berry$/ }
# $filtered_data = [raspberry]
~~~
When the first argument is a hash, Puppet passes its keys to the first parameter and its
values to the second parameter.
**Example**: Using the `filter` function with a hash and a two-parameter lambda
~~~ puppet
# For the hash $data, return a hash of all keys that both end with "berry" and have
# values less than or equal to 1
$data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 }
$filtered_data = $data.filter |$keys, $values| { $keys =~ /berry$/ and $values <= 1 }
# $filtered_data = {blueberry => 1}
~~~
- Since 4.0.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('filter')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.