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
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/ports.rb
lib/puppet/provider/package/ports.rb
# frozen_string_literal: true Puppet::Type.type(:package).provide :ports, :parent => :freebsd, :source => :freebsd do desc "Support for FreeBSD's ports. Note that this, too, mixes packages and ports." commands :portupgrade => "/usr/local/sbin/portupgrade", :portversion => "/usr/local/sbin/portversion", :portuninstall => "/usr/local/sbin/pkg_deinstall", :portinfo => "/usr/sbin/pkg_info" %w[INTERACTIVE UNAME].each do |var| ENV.delete(var) if ENV.include?(var) end def install # -N: install if the package is missing, otherwise upgrade # -M: yes, we're a batch, so don't ask any questions cmd = %w[-N -M BATCH=yes] << @resource[:name] output = portupgrade(*cmd) if output =~ /\*\* No such / raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] } end end # If there are multiple packages, we only use the last one def latest cmd = ["-v", @resource[:name]] begin output = portversion(*cmd) rescue Puppet::ExecutionFailure => e raise Puppet::Error.new(output, e) end line = output.split("\n").pop unless line =~ /^(\S+)\s+(\S)\s+(.+)$/ # There's no "latest" version, so just return a placeholder return :latest end pkgstuff = Regexp.last_match(1) match = Regexp.last_match(2) info = Regexp.last_match(3) unless pkgstuff =~ /^\S+-([^-\s]+)$/ raise Puppet::Error, _("Could not match package info '%{pkgstuff}'") % { pkgstuff: pkgstuff } end version = Regexp.last_match(1) if match == "=" or match == ">" # we're up to date or more recent return version end # Else, we need to be updated; we need to pull out the new version unless info =~ /\((\w+) has (.+)\)/ raise Puppet::Error, _("Could not match version info '%{info}'") % { info: info } end source = Regexp.last_match(1) newversion = Regexp.last_match(2) debug "Newer version in #{source}" newversion end def query # support portorigin_glob such as "mail/postfix" name = self.name if name =~ %r{/} name = self.name.split(%r{/}).slice(1) end self.class.instances.each do |instance| if instance.name == name return instance.properties end end nil end def uninstall portuninstall @resource[:name] end def update install end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pkg.rb
lib/puppet/provider/package/pkg.rb
# frozen_string_literal: true require_relative '../../../puppet/provider/package' Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package do desc "OpenSolaris image packaging system. See pkg(5) for more information. This provider supports the `install_options` attribute, which allows command-line flags to be passed to pkg. These options should be specified as an array where each element is either a string or a hash." # https://docs.oracle.com/cd/E19963-01/html/820-6572/managepkgs.html # A few notes before we start: # Opensolaris pkg has two slightly different formats (as of now.) # The first one is what is distributed with the Solaris 11 Express 11/10 dvd # The latest one is what you get when you update package. # To make things more interesting, pkg version just returns a sha sum. # dvd: pkg version => 052adf36c3f4 # updated: pkg version => 630e1ffc7a19 # Thankfully, Solaris has not changed the commands to be used. # TODO: We still have to allow packages to specify a preferred publisher. has_feature :versionable has_feature :upgradable has_feature :holdable has_feature :install_options commands :pkg => "/usr/bin/pkg" confine 'os.family' => :solaris defaultfor 'os.family' => :solaris, :kernelrelease => ['5.11', '5.12'] def self.instances pkg(:list, '-Hv').split("\n").map { |l| new(parse_line(l)) } end # The IFO flag field is just what it names, the first field can have either # i_nstalled or -, and second field f_rozen or -, and last # o_bsolate or r_rename or - # so this checks if the installed field is present, and also verifies that # if not the field is -, else we don't know what we are doing and exit with # out doing more damage. def self.ifo_flag(flags) ( case flags[0..0] when 'i' { :status => 'installed' } when '-' { :status => 'known' } else raise ArgumentError, _('Unknown format %{resource_name}: %{full_flags}[%{bad_flag}]') % { resource_name: name, full_flags: flags, bad_flag: flags[0..0] } end ).merge( case flags[1..1] when 'f' { :mark => :hold } when '-' {} else raise ArgumentError, _('Unknown format %{resource_name}: %{full_flags}[%{bad_flag}]') % { resource_name: name, full_flags: flags, bad_flag: flags[1..1] } end ) end # The UFOXI field is the field present in the older pkg # (solaris 2009.06 - snv151a) # similar to IFO, UFOXI is also an either letter or - # u_pdate indicates that an update for the package is available. # f_rozen(n/i) o_bsolete x_cluded(n/i) i_constrained(n/i) # note that u_pdate flag may not be trustable due to constraints. # so we dont rely on it # Frozen was never implemented in UFOXI so skipping frozen here. def self.ufoxi_flag(flags) {} end # pkg state was present in the older version of pkg (with UFOXI) but is # no longer available with the IFO field version. When it was present, # it was used to indicate that a particular version was present (installed) # and later versions were known. Note that according to the pkg man page, # known never lists older versions of the package. So we can rely on this # field to make sure that if a known is present, then the pkg is upgradable. def self.pkg_state(state) case state when /installed/ { :status => 'installed' } when /known/ { :status => 'known' } else raise ArgumentError, _('Unknown format %{resource_name}: %{state}') % { resource_name: name, state: state } end end # Here is (hopefully) the only place we will have to deal with multiple # formats of output for different pkg versions. def self.parse_line(line) (case line.chomp # FMRI IFO # pkg://omnios/SUNWcs@0.5.11,5.11-0.151008:20131204T022241Z --- when %r{^pkg://([^/]+)/([^@]+)@(\S+) +(...)$} { :publisher => Regexp.last_match(1), :name => Regexp.last_match(2), :ensure => Regexp.last_match(3) }.merge ifo_flag(Regexp.last_match(4)) # FMRI STATE UFOXI # pkg://solaris/SUNWcs@0.5.11,5.11-0.151.0.1:20101105T001108Z installed u---- when %r{^pkg://([^/]+)/([^@]+)@(\S+) +(\S+) +(.....)$} { :publisher => Regexp.last_match(1), :name => Regexp.last_match(2), :ensure => Regexp.last_match(3) }.merge pkg_state(Regexp.last_match(4)).merge(ufoxi_flag(Regexp.last_match(5))) else raise ArgumentError, _('Unknown line format %{resource_name}: %{parse_line}') % { resource_name: name, parse_line: line } end).merge({ :provider => name }) end def hold pkg(:freeze, @resource[:name]) end def unhold r = exec_cmd(command(:pkg), 'unfreeze', @resource[:name]) raise Puppet::Error, _("Unable to unfreeze %{package}") % { package: r[:out] } unless [0, 4].include? r[:exit] end def insync?(is) # this is called after the generic version matching logic (insync? for the # type), so we only get here if should != is, and 'should' is a version # number. 'is' might not be, though. should = @resource[:ensure] # NB: it is apparently possible for repository administrators to publish # packages which do not include build or branch versions, but component # version must always be present, and the timestamp is added by pkgsend # publish. if /^[0-9.]+(,[0-9.]+)?(-[0-9.]+)?:[0-9]+T[0-9]+Z$/ !~ should # We have a less-than-explicit version string, which we must accept for # backward compatibility. We can find the real version this would match # by asking pkg for the all matching versions, and selecting the first # installable one [0]; this can change over time when remote repositories # are updated, but the principle of least astonishment should still hold: # if we allow users to specify less-than-explicit versions, the # functionality should match that of the package manager. # # [0]: we could simply get the newest matching version with 'pkg list # -n', but that isn't always correct, since it might not be installable. # If that were the case we could potentially end up returning false for # insync? here but not actually changing the package version in install # (ie. if the currently installed version is the latest matching version # that is installable, we would falsely conclude here that since the # installed version is not the latest matching version, we're not in # sync). 'pkg list -a' instead of '-n' would solve this, but # unfortunately it doesn't consider downgrades 'available' (eg. with # installed foo@1.0, list -a foo@0.9 would fail). name = @resource[:name] potential_matches = pkg(:list, '-Hvfa', "#{name}@#{should}").split("\n").map { |l| self.class.parse_line(l) } n = potential_matches.length if n > 1 warning(_("Implicit version %{should} has %{n} possible matches") % { should: should, n: n }) end potential_matches.each { |p| command = is == :absent ? 'install' : 'update' options = ['-n'] options.concat(join_options(@resource[:install_options])) if @resource[:install_options] begin unhold if properties[:mark] == :hold status = exec_cmd(command(:pkg), command, *options, "#{name}@#{p[:ensure]}")[:exit] ensure hold if properties[:mark] == :hold end case status when 4 # if the first installable match would cause no changes, we're in sync return true when 0 warning(_("Selecting version '%{version}' for implicit '%{should}'") % { version: p[:ensure], should: should }) @resource[:ensure] = p[:ensure] return false end } raise Puppet::DevError, _("No version of %{name} matching %{should} is installable, even though the package is currently installed") % { name: name, should: should } end false end # Return the version of the package. Note that the bug # http://defect.opensolaris.org/bz/show_bug.cgi?id=19159% # notes that we can't use -Ha for the same even though the manual page reads that way. def latest # Refresh package metadata before looking for latest versions pkg(:refresh) lines = pkg(:list, "-Hvn", @resource[:name]).split("\n") # remove certificate expiration warnings from the output, but report them cert_warnings = lines.select { |line| line =~ /^Certificate/ } unless cert_warnings.empty? Puppet.warning(_("pkg warning: %{warnings}") % { warnings: cert_warnings.join(', ') }) end lst = lines.select { |line| line !~ /^Certificate/ }.map { |line| self.class.parse_line(line) } # Now we know there is a newer version. But is that installable? (i.e are there any constraints?) # return the first known we find. The only way that is currently available is to do a dry run of # pkg update and see if could get installed (`pkg update -n res`). known = lst.find { |p| p[:status] == 'known' } if known options = ['-n'] options.concat(join_options(@resource[:install_options])) if @resource[:install_options] return known[:ensure] if exec_cmd(command(:pkg), 'update', *options, @resource[:name])[:exit].zero? end # If not, then return the installed, else nil (lst.find { |p| p[:status] == 'installed' } || {})[:ensure] end # install the package and accept all licenses. def install(nofail = false) name = @resource[:name] should = @resource[:ensure] is = query if is[:ensure].to_sym == :absent command = 'install' else command = 'update' end args = ['--accept'] if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.2') >= 0 args.push('--sync-actuators-timeout', '900') end args.concat(join_options(@resource[:install_options])) if @resource[:install_options] unless should.is_a? Symbol name += "@#{should}" end unhold if properties[:mark] == :hold begin tries = 1 # pkg install exits with code 7 when the image is currently in use by another process and cannot be modified r = exec_cmd(command(:pkg), command, *args, name) while r[:exit] == 7 if tries > 4 raise Puppet::Error, _("Pkg could not install %{name} after %{tries} tries. Aborting run") % { name: name, tries: tries } end sleep 2**tries tries += 1 r = exec_cmd(command(:pkg), command, *args, name) end ensure hold if @resource[:mark] == :hold end return r if nofail raise Puppet::Error, _("Unable to update %{package}") % { package: r[:out] } if r[:exit] != 0 end # uninstall the package. The complication comes from the -r_ecursive flag which is no longer # present in newer package version. def uninstall cmd = [:uninstall] case (pkg :version).chomp when /052adf36c3f4/ cmd << '-r' end cmd << @resource[:name] unhold if properties[:mark] == :hold begin pkg cmd rescue StandardError, LoadError => e hold if properties[:mark] == :hold raise e end end # update the package to the latest version available def update r = install(true) # 4 == /No updates available for this image./ return if [0, 4].include? r[:exit] raise Puppet::Error, _("Unable to update %{package}") % { package: r[:out] } end # list a specific package def query r = exec_cmd(command(:pkg), 'list', '-Hv', @resource[:name]) return { :ensure => :absent, :name => @resource[:name] } if r[:exit] != 0 self.class.parse_line(r[:out]) end def exec_cmd(*cmd) output = Puppet::Util::Execution.execute(cmd, :failonfail => false, :combine => true) { :out => output, :exit => output.exitstatus } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/rug.rb
lib/puppet/provider/package/rug.rb
# frozen_string_literal: true Puppet::Type.type(:package).provide :rug, :parent => :rpm do desc "Support for suse `rug` package manager." has_feature :versionable commands :rug => "/usr/bin/rug" commands :rpm => "rpm" confine 'os.name' => [:suse, :sles] # Install a package using 'rug'. def install should = @resource.should(:ensure) debug "Ensuring => #{should}" wanted = @resource[:name] # XXX: We don't actually deal with epochs here. case should when true, false, Symbol # pass else # Add the package version wanted += "-#{should}" end rug "--quiet", :install, "-y", wanted unless query raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name } end end # What's the latest package version available? def latest # rug can only get a list of *all* available packages? output = rug "list-updates" if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s|]+)/ Regexp.last_match(1) else # rug didn't find updates, pretend the current # version is the latest @property_hash[:ensure] end end def update # rug install can be used for update, too install end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/windows.rb
lib/puppet/provider/package/windows.rb
# frozen_string_literal: true require_relative '../../../puppet/provider/package' require_relative '../../../puppet/util/windows' require_relative 'windows/package' Puppet::Type.type(:package).provide(:windows, :parent => Puppet::Provider::Package) do desc "Windows package management. This provider supports either MSI or self-extracting executable installers. This provider requires a `source` attribute when installing the package. It accepts paths to local files, mapped drives, or UNC paths. This provider supports the `install_options` and `uninstall_options` attributes, which allow command-line flags to be passed to the installer. These options should be specified as an array where each element is either a string or a hash. If the executable requires special arguments to perform a silent install or uninstall, then the appropriate arguments should be specified using the `install_options` or `uninstall_options` attributes, respectively. Puppet will automatically quote any option that contains spaces." confine 'os.name' => :windows defaultfor 'os.name' => :windows has_feature :installable has_feature :uninstallable has_feature :install_options has_feature :uninstall_options has_feature :versionable attr_accessor :package class << self attr_accessor :paths end def self.post_resource_eval @paths.each do |path| Puppet::FileSystem.unlink(path) rescue => detail raise Puppet::Error.new(_("Error when unlinking %{path}: %{detail}") % { path: path, detail: detail.message }, detail) end if @paths end # Return an array of provider instances def self.instances Puppet::Provider::Package::Windows::Package.map do |pkg| provider = new(to_hash(pkg)) provider.package = pkg provider end end def self.to_hash(pkg) { :name => pkg.name, :ensure => pkg.version || :installed, :provider => :windows } end # Query for the provider hash for the current resource. The provider we # are querying, may not have existed during prefetch def query Puppet::Provider::Package::Windows::Package.find do |pkg| if pkg.match?(resource) return self.class.to_hash(pkg) end end nil end def install installer = Puppet::Provider::Package::Windows::Package.installer_class(resource) command = [installer.install_command(resource), install_options].flatten.compact.join(' ') working_dir = File.dirname(resource[:source]) unless Puppet::FileSystem.exist?(working_dir) working_dir = nil end output = execute(command, :failonfail => false, :combine => true, :cwd => working_dir, :suppress_window => true) check_result(output.exitstatus) end def uninstall command = [package.uninstall_command, uninstall_options].flatten.compact.join(' ') output = execute(command, :failonfail => false, :combine => true, :suppress_window => true) check_result(output.exitstatus) end # https://msdn.microsoft.com/en-us/library/windows/desktop/aa368542(v=vs.85).aspx self::ERROR_SUCCESS = 0 self::ERROR_SUCCESS_REBOOT_INITIATED = 1641 self::ERROR_SUCCESS_REBOOT_REQUIRED = 3010 # (Un)install may "fail" because the package requested a reboot, the system requested a # reboot, or something else entirely. Reboot requests mean the package was installed # successfully, but we warn since we don't have a good reboot strategy. def check_result(hr) operation = resource[:ensure] == :absent ? 'uninstall' : 'install' case hr when self.class::ERROR_SUCCESS # yeah when self.class::ERROR_SUCCESS_REBOOT_INITIATED warning(_("The package %{operation}ed successfully and the system is rebooting now.") % { operation: operation }) when self.class::ERROR_SUCCESS_REBOOT_REQUIRED warning(_("The package %{operation}ed successfully, but the system must be rebooted.") % { operation: operation }) else raise Puppet::Util::Windows::Error.new(_("Failed to %{operation}") % { operation: operation }, hr) end end # This only gets called if there is a value to validate, but not if it's absent def validate_source(value) fail(_("The source parameter cannot be empty when using the Windows provider.")) if value.empty? end def install_options join_options(resource[:install_options]) end def uninstall_options join_options(resource[:uninstall_options]) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/gem.rb
lib/puppet/provider/package/gem.rb
# frozen_string_literal: true require_relative '../../../puppet/util/package/version/gem' require_relative '../../../puppet/util/package/version/range' require_relative '../../../puppet/provider/package_targetable' require 'uri' # Ruby gems support. Puppet::Type.type(:package).provide :gem, :parent => Puppet::Provider::Package::Targetable do desc "Ruby Gem support. If a URL is passed via `source`, then that URL is appended to the list of remote gem repositories; to ensure that only the specified source is used, also pass `--clear-sources` via `install_options`. If source is present but is not a valid URL, it will be interpreted as the path to a local gem file. If source is not present, the gem will be installed from the default gem repositories. Note that to modify this for Windows, it has to be a valid URL. This provider supports the `install_options` and `uninstall_options` attributes, which allow command-line flags to be passed to the gem command. These options should be specified as an array where each element is either a string or a hash." has_feature :versionable, :install_options, :uninstall_options, :targetable, :version_ranges GEM_VERSION = Puppet::Util::Package::Version::Gem GEM_VERSION_RANGE = Puppet::Util::Package::Version::Range # Override the specificity method to return 1 if gem is not set as default provider def self.specificity match = default_match length = match ? match.length : 0 return 1 if length == 0 super end # Define the default provider package command name when the provider is targetable. # Required by Puppet::Provider::Package::Targetable::resource_or_provider_command def self.provider_command if Puppet::Util::Platform.windows? Puppet::Util.withenv(PATH: windows_path_without_puppet_bin) { command(:gemcmd) } else command(:gemcmd) end end # Define the default provider package command as optional when the provider is targetable. # Doing do defers the evaluation of provider suitability until all commands are evaluated. has_command(:gemcmd, 'gem') do is_optional end # Having puppet/bin in PATH makes gem provider to use puppet/bin/gem # This is an utility methods that reads the PATH and returns a string # that contains the content of PATH but without puppet/bin dir. # This is used to pass a custom PATH and execute commands in a controlled environment def self.windows_path_without_puppet_bin # rubocop:disable Naming/MemoizedInstanceVariableName @path ||= ENV['PATH'].split(File::PATH_SEPARATOR) .reject { |dir| dir =~ /puppet\\bin$/ } .join(File::PATH_SEPARATOR) # rubocop:enable Naming/MemoizedInstanceVariableName end private_class_method :windows_path_without_puppet_bin # CommandDefiner in provider.rb creates convenience execution methods that set failonfail, combine, and optionally, environment. # And when a child provider defines its own command via commands() or has_command(), the provider-specific path is always returned by command(). # But when the convenience execution method is invoked, the last convenience method to be defined is executed. # This makes invoking those convenience execution methods unsuitable for inherited providers. # # In this case, causing the puppet_gem provider to inherit the parent gem provider's convenience gemcmd() methods, with the wrong path. def self.execute_gem_command(command, command_options, custom_environment = {}) validate_command(command) cmd = [command] << command_options custom_environment = { 'HOME' => ENV.fetch('HOME', nil) }.merge(custom_environment) if Puppet::Util::Platform.windows? custom_environment[:PATH] = windows_path_without_puppet_bin end # This uses an unusual form of passing the command and args as [<cmd>, [<arg1>, <arg2>, ...]] execute(cmd, { :failonfail => true, :combine => true, :custom_environment => custom_environment }) end def self.instances(target_command = nil) if target_command command = target_command else command = provider_command # The default provider package command is optional. return [] unless command end gemlist(:command => command, :local => true).collect do |pkg| # Track the command when the provider is targetable. pkg[:command] = command new(pkg) end end def self.gemlist(options) command_options = ["list"] if options[:local] command_options << "--local" else command_options << "--remote" end if options[:source] command_options << "--source" << options[:source] end name = options[:justme] if name command_options << '\A' + name + '\z' end begin list = execute_gem_command(options[:command], command_options).lines .filter_map { |set| gemsplit(set) } rescue Puppet::ExecutionFailure => detail raise Puppet::Error, _("Could not list gems: %{detail}") % { detail: detail }, detail.backtrace end if options[:justme] list.shift else list end end def self.gemsplit(desc) # `gem list` when output console has a line like: # *** LOCAL GEMS *** # but when it's not to the console that line # and all blank lines are stripped # so we don't need to check for them if desc =~ /^(\S+)\s+\((.+)\)/ gem_name = Regexp.last_match(1) versions = Regexp.last_match(2).sub('default: ', '').split(/,\s*/) { :name => gem_name, :ensure => versions.map { |v| v.split[0] }, :provider => name } else Puppet.warning _("Could not match %{desc}") % { desc: desc } unless desc.chomp.empty? nil end end def insync?(is) return false unless is && is != :absent is = [is] unless is.is_a? Array should = @resource[:ensure] unless should =~ Regexp.union(/,/, Gem::Requirement::PATTERN) begin should_range = GEM_VERSION_RANGE.parse(should, GEM_VERSION) rescue GEM_VERSION_RANGE::ValidationFailure, GEM_VERSION::ValidationFailure Puppet.debug("Cannot parse #{should} as a ruby gem version range") return false end return is.any? do |version| should_range.include?(GEM_VERSION.parse(version)) rescue GEM_VERSION::ValidationFailure Puppet.debug("Cannot parse #{version} as a ruby gem version") false end end begin # Range intersections are not supported by Gem::Requirement, so just split by comma. dependency = Gem::Dependency.new('', should.split(',')) rescue ArgumentError # Bad requirements will cause an error during gem command invocation, so just return not in sync return false end # Check if any version matches the dependency is.any? { |version| dependency.match?('', version) } end def rubygem_version(command) command_options = ["--version"] self.class.execute_gem_command(command, command_options) end def install(useversion = true) command = resource_or_provider_command command_options = ["install"] command_options += install_options if resource[:install_options] should = resource[:ensure] unless should =~ Regexp.union(/,/, Gem::Requirement::PATTERN) begin should_range = GEM_VERSION_RANGE.parse(should, GEM_VERSION) should = should_range.to_gem_version useversion = true rescue GEM_VERSION_RANGE::ValidationFailure, GEM_VERSION::ValidationFailure Puppet.debug("Cannot parse #{should} as a ruby gem version range. Falling through.") end end if Puppet::Util::Platform.windows? command_options << "-v" << %Q("#{should}") if useversion && !should.is_a?(Symbol) elsif useversion && !should.is_a?(Symbol) command_options << "-v" << should end if Puppet::Util::Package.versioncmp(rubygem_version(command), '2.0.0') == -1 command_options << "--no-rdoc" << "--no-ri" else command_options << "--no-document" end source = resource[:source] if source begin uri = URI.parse(source) rescue => detail self.fail Puppet::Error, _("Invalid source '%{uri}': %{detail}") % { uri: uri, detail: detail }, detail end case uri.scheme when nil # no URI scheme => interpret the source as a local file command_options << source when /file/i command_options << uri.path when 'puppet' # we don't support puppet:// URLs (yet) raise Puppet::Error, _("puppet:// URLs are not supported as gem sources") else # check whether it's an absolute file path to help Windows out if Puppet::Util.absolute_path?(source) command_options << source else # interpret it as a gem repository command_options << "--source" << source.to_s << resource[:name] end end else command_options << resource[:name] end output = self.class.execute_gem_command(command, command_options) # Apparently some gem versions don't exit non-0 on failure. self.fail _("Could not install: %{output}") % { output: output.chomp } if output.include?("ERROR") end def latest command = resource_or_provider_command options = { :command => command, :justme => resource[:name] } options[:source] = resource[:source] unless resource[:source].nil? pkg = self.class.gemlist(options) pkg[:ensure][0] end def query command = resource_or_provider_command options = { :command => command, :justme => resource[:name], :local => true } pkg = self.class.gemlist(options) pkg[:command] = command unless pkg.nil? pkg end def uninstall command = resource_or_provider_command command_options = ["uninstall"] command_options << "--executables" << "--all" << resource[:name] command_options += uninstall_options if resource[:uninstall_options] output = self.class.execute_gem_command(command, command_options) # Apparently some gem versions don't exit non-0 on failure. self.fail _("Could not uninstall: %{output}") % { output: output.chomp } if output.include?("ERROR") end def update install(false) end def install_options join_options(resource[:install_options]) end def uninstall_options join_options(resource[:uninstall_options]) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pkgdmg.rb
lib/puppet/provider/package/pkgdmg.rb
# frozen_string_literal: true # # Motivation: DMG files provide a true HFS file system # and are easier to manage and .pkg bundles. # # Note: the 'apple' Provider checks for the package name # in /L/Receipts. Since we install multiple pkg's from a single # source, we treat the source .pkg.dmg file as the package name. # As a result, we store installed .pkg.dmg file names # in /var/db/.puppet_pkgdmg_installed_<name> require_relative '../../../puppet/provider/package' require_relative '../../../puppet/util/plist' require_relative '../../../puppet/util/http_proxy' Puppet::Type.type(:package).provide :pkgdmg, :parent => Puppet::Provider::Package do desc "Package management based on Apple's Installer.app and DiskUtility.app. This provider works by checking the contents of a DMG image for Apple pkg or mpkg files. Any number of pkg or mpkg files may exist in the root directory of the DMG file system, and Puppet will install all of them. Subdirectories are not checked for packages. This provider can also accept plain .pkg (but not .mpkg) files in addition to .dmg files. Notes: * The `source` attribute is mandatory. It must be either a local disk path or an HTTP, HTTPS, or FTP URL to the package. * The `name` of the resource must be the filename (without path) of the DMG file. * When installing the packages from a DMG, this provider writes a file to disk at `/var/db/.puppet_pkgdmg_installed_NAME`. If that file is present, Puppet assumes all packages from that DMG are already installed. * This provider is not versionable and uses DMG filenames to determine whether a package has been installed. Thus, to install new a version of a package, you must create a new DMG with a different filename." confine 'os.name' => :darwin confine :feature => :cfpropertylist defaultfor 'os.name' => :darwin commands :installer => "/usr/sbin/installer" commands :hdiutil => "/usr/bin/hdiutil" commands :curl => "/usr/bin/curl" # JJM We store a cookie for each installed .pkg.dmg in /var/db def self.instance_by_name Dir.entries("/var/db").find_all { |f| f =~ /^\.puppet_pkgdmg_installed_/ }.collect do |f| name = f.sub(/^\.puppet_pkgdmg_installed_/, '') yield name if block_given? name end end def self.instances instance_by_name.collect do |name| new(:name => name, :provider => :pkgdmg, :ensure => :installed) end end def self.installpkg(source, name, orig_source) installer "-pkg", source, "-target", "/" # Non-zero exit status will throw an exception. Puppet::FileSystem.open("/var/db/.puppet_pkgdmg_installed_#{name}", nil, "w:UTF-8") do |t| t.print "name: '#{name}'\n" t.print "source: '#{orig_source}'\n" end end def self.installpkgdmg(source, name) unless Puppet::Util::HttpProxy.no_proxy?(source) http_proxy_host = Puppet::Util::HttpProxy.http_proxy_host http_proxy_port = Puppet::Util::HttpProxy.http_proxy_port end unless source =~ /\.dmg$/i || source =~ /\.pkg$/i raise Puppet::Error, _("Mac OS X PKG DMGs must specify a source string ending in .dmg or flat .pkg file") end require 'open-uri' # Dead code; this is never used. The File.open call 20-ish lines south of here used to be Kernel.open but changed in '09. -NF cached_source = source tmpdir = Dir.mktmpdir ext = /(\.dmg|\.pkg)$/i.match(source)[0] begin if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source cached_source = File.join(tmpdir, "#{name}#{ext}") args = ["-o", cached_source, "-C", "-", "-L", "-s", "--fail", "--url", source] if http_proxy_host and http_proxy_port args << "--proxy" << "#{http_proxy_host}:#{http_proxy_port}" elsif http_proxy_host and !http_proxy_port args << "--proxy" << http_proxy_host end begin curl(*args) Puppet.debug "Success: curl transferred [#{name}] (via: curl #{args.join(' ')})" rescue Puppet::ExecutionFailure Puppet.debug "curl #{args.join(' ')} did not transfer [#{name}]. Falling back to local file." # This used to fall back to open-uri. -NF cached_source = source end end if source =~ /\.dmg$/i # If you fix this to use open-uri again, you must update the docs above. -NF File.open(cached_source) do |dmg| xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path hdiutil_info = Puppet::Util::Plist.parse_plist(xml_str) raise Puppet::Error, _("No disk entities returned by mount at %{path}") % { path: dmg.path } unless hdiutil_info.has_key?("system-entities") mounts = hdiutil_info["system-entities"].filter_map { |entity| entity["mount-point"] } begin mounts.each do |mountpoint| Dir.entries(mountpoint).select { |f| f =~ /\.m{0,1}pkg$/i }.each do |pkg| installpkg("#{mountpoint}/#{pkg}", name, source) end end ensure mounts.each do |mountpoint| hdiutil "eject", mountpoint end end end else installpkg(cached_source, name, source) end ensure FileUtils.remove_entry_secure(tmpdir, true) end end def query if Puppet::FileSystem.exist?("/var/db/.puppet_pkgdmg_installed_#{@resource[:name]}") Puppet.debug "/var/db/.puppet_pkgdmg_installed_#{@resource[:name]} found" { :name => @resource[:name], :ensure => :present } else nil end end def install source = @resource[:source] unless source raise Puppet::Error, _("Mac OS X PKG DMGs must specify a package source.") end name = @resource[:name] unless name raise Puppet::Error, _("Mac OS X PKG DMGs must specify a package name.") end self.class.installpkgdmg(source, name) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/dpkg.rb
lib/puppet/provider/package/dpkg.rb
# frozen_string_literal: true require_relative '../../../puppet/provider/package' Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package do desc "Package management via `dpkg`. Because this only uses `dpkg` and not `apt`, you must specify the source of any packages you want to manage." has_feature :holdable, :virtual_packages commands :dpkg => "/usr/bin/dpkg" commands :dpkg_deb => "/usr/bin/dpkg-deb" commands :dpkgquery => "/usr/bin/dpkg-query" # Performs a dpkgquery call with a pipe so that output can be processed # inline in a passed block. # @param args [Array<String>] any command line arguments to be appended to the command # @param block expected to be passed on to execpipe # @return whatever the block returns # @see Puppet::Util::Execution.execpipe # @api private def self.dpkgquery_piped(*args, &block) cmd = args.unshift(command(:dpkgquery)) Puppet::Util::Execution.execpipe(cmd, &block) end def self.instances packages = [] # list out all of the packages dpkgquery_piped('-W', '--showformat', self::DPKG_QUERY_FORMAT_STRING) do |pipe| # now turn each returned line into a package object pipe.each_line do |line| hash = parse_line(line) if hash packages << new(hash) end end end packages end private # Note: self:: is required here to keep these constants in the context of what will # eventually become this Puppet::Type::Package::ProviderDpkg class. self::DPKG_QUERY_FORMAT_STRING = "'${Status} ${Package} ${Version}\\n'" self::DPKG_QUERY_PROVIDES_FORMAT_STRING = "'${Status} ${Package} ${Version} [${Provides}]\\n'" self::FIELDS_REGEX = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*)$/ self::FIELDS_REGEX_WITH_PROVIDES = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*) \[.*\]$/ self::FIELDS = [:desired, :error, :status, :name, :ensure] def self.defaultto_allow_virtual false end # @param line [String] one line of dpkg-query output # @return [Hash,nil] a hash of FIELDS or nil if we failed to match # @api private def self.parse_line(line, regex = self::FIELDS_REGEX) hash = nil match = regex.match(line) if match hash = {} self::FIELDS.zip(match.captures) do |field, value| hash[field] = value end hash[:provider] = name if hash[:status] == 'not-installed' hash[:ensure] = :purged elsif %w[config-files half-installed unpacked half-configured].include?(hash[:status]) hash[:ensure] = :absent end hash[:mark] = hash[:desired] == 'hold' ? :hold : :none else Puppet.debug("Failed to match dpkg-query line #{line.inspect}") end hash end public def install file = @resource[:source] unless file raise ArgumentError, _("You cannot install dpkg packages without a source") end args = [] if @resource[:configfiles] == :keep args << '--force-confold' else args << '--force-confnew' end args << '-i' << file unhold if properties[:mark] == :hold begin dpkg(*args) ensure hold if @resource[:mark] == :hold end end def update install end # Return the version from the package. def latest source = @resource[:source] unless source @resource.fail _("Could not update: You cannot install dpkg packages without a source") end output = dpkg_deb "--show", source matches = /^(\S+)\t(\S+)$/.match(output).captures warning _("source doesn't contain named package, but %{name}") % { name: matches[0] } unless matches[0].match(Regexp.escape(@resource[:name])) matches[1] end def query hash = nil # list out our specific package begin if @resource.allow_virtual? output = dpkgquery( "-W", "--showformat", self.class::DPKG_QUERY_PROVIDES_FORMAT_STRING # the regex searches for the resource[:name] in the dpkquery result in which the Provides field is also available # it will search for the packages only in the brackets ex: [rubygems] ).lines.find { |package| package.match(/[\[ ](#{Regexp.escape(@resource[:name])})[\],]/) } if output hash = self.class.parse_line(output, self.class::FIELDS_REGEX_WITH_PROVIDES) Puppet.info("Package #{@resource[:name]} is virtual, defaulting to #{hash[:name]}") @resource[:name] = hash[:name] end end output = dpkgquery( "-W", "--showformat", self.class::DPKG_QUERY_FORMAT_STRING, @resource[:name] ) hash = self.class.parse_line(output) rescue Puppet::ExecutionFailure # dpkg-query exits 1 if the package is not found. return { :ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok' } end hash ||= { :ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok' } if hash[:error] != "ok" raise Puppet::Error, "Package #{hash[:name]}, version #{hash[:ensure]} is in error state: #{hash[:error]}" end hash end def uninstall dpkg "-r", @resource[:name] end def purge dpkg "--purge", @resource[:name] end def hold Tempfile.open('puppet_dpkg_set_selection') do |tmpfile| tmpfile.write("#{@resource[:name]} hold\n") tmpfile.flush execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s) end end def unhold Tempfile.open('puppet_dpkg_set_selection') do |tmpfile| tmpfile.write("#{@resource[:name]} install\n") tmpfile.flush execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/fink.rb
lib/puppet/provider/package/fink.rb
# frozen_string_literal: true Puppet::Type.type(:package).provide :fink, :parent => :dpkg, :source => :dpkg do # Provide sorting functionality include Puppet::Util::Package desc "Package management via `fink`." commands :fink => "/sw/bin/fink" commands :aptget => "/sw/bin/apt-get" commands :aptcache => "/sw/bin/apt-cache" commands :dpkgquery => "/sw/bin/dpkg-query" has_feature :versionable # A derivative of DPKG; this is how most people actually manage # Debian boxes, and the only thing that differs is that it can # install packages from remote sites. def finkcmd(*args) fink(*args) end # Install a package using 'apt-get'. This function needs to support # installing a specific version. def install run_preseed if @resource[:responsefile] should = @resource.should(:ensure) str = @resource[:name] case should when true, false, Symbol # pass else # Add the package version str += "=#{should}" end cmd = %w[-b -q -y] cmd << :install << str unhold if properties[:mark] == :hold begin finkcmd(cmd) ensure hold if @resource[:mark] == :hold end end # What's the latest package version available? def latest output = aptcache :policy, @resource[:name] if output =~ /Candidate:\s+(\S+)\s/ Regexp.last_match(1) else err _("Could not find latest version") nil end end # # preseeds answers to dpkg-set-selection from the "responsefile" # def run_preseed response = @resource[:responsefile] if response && Puppet::FileSystem.exist?(response) info(_("Preseeding %{response} to debconf-set-selections") % { response: response }) preseed response else info _("No responsefile specified or non existent, not preseeding anything") end end def update install end def uninstall unhold if properties[:mark] == :hold begin finkcmd "-y", "-q", :remove, @model[:name] rescue StandardError, LoadError => e hold if properties[:mark] == :hold raise e end end def purge unhold if properties[:mark] == :hold begin aptget '-y', '-q', 'remove', '--purge', @resource[:name] rescue StandardError, LoadError => e hold if properties[:mark] == :hold raise e end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/rpm.rb
lib/puppet/provider/package/rpm.rb
# frozen_string_literal: true require_relative '../../../puppet/provider/package' require_relative '../../../puppet/util/rpm_compare' # RPM packaging. Should work anywhere that has rpm installed. Puppet::Type.type(:package).provide :rpm, :source => :rpm, :parent => Puppet::Provider::Package do # provides Rpm parsing and comparison include Puppet::Util::RpmCompare desc "RPM packaging support; should work anywhere with a working `rpm` binary. This provider supports the `install_options` and `uninstall_options` attributes, which allow command-line flags to be passed to rpm. These options should be specified as an array where each element is either a string or a hash." has_feature :versionable has_feature :install_options has_feature :uninstall_options has_feature :virtual_packages has_feature :install_only # Note: self:: is required here to keep these constants in the context of what will # eventually become this Puppet::Type::Package::ProviderRpm class. # The query format by which we identify installed packages self::NEVRA_FORMAT = '%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n' self::NEVRA_REGEX = /^'?(\S+) (\S+) (\S+) (\S+) (\S+)$/ self::NEVRA_FIELDS = [:name, :epoch, :version, :release, :arch] self::MULTIVERSION_SEPARATOR = "; " commands :rpm => "rpm" # Mixing confine statements, control expressions, and exception handling # confuses Rubocop's Layout cops, so we disable them entirely. # rubocop:disable Layout if command('rpm') confine :true => begin rpm('--version') rescue Puppet::ExecutionFailure false else true end end # rubocop:enable Layout def self.current_version return @current_version unless @current_version.nil? output = rpm "--version" @current_version = output.gsub('RPM version ', '').strip end # rpm < 4.1 does not support --nosignature def self.nosignature '--nosignature' unless Puppet::Util::Package.versioncmp(current_version, '4.1') < 0 end # rpm < 4.0.2 does not support --nodigest def self.nodigest '--nodigest' unless Puppet::Util::Package.versioncmp(current_version, '4.0.2') < 0 end def self.instances packages = [] # list out all of the packages begin execpipe("#{command(:rpm)} -qa #{nosignature} #{nodigest} --qf '#{self::NEVRA_FORMAT}' | sort") { |process| # now turn each returned line into a package object nevra_to_multiversion_hash(process).each { |hash| packages << new(hash) } } rescue Puppet::ExecutionFailure => e raise Puppet::Error, _("Failed to list packages"), e.backtrace end packages end # Find the fully versioned package name and the version alone. Returns # a hash with entries :instance => fully versioned package name, and # :ensure => version-release def query # NOTE: Prior to a fix for issue 1243, this method potentially returned a cached value # IF YOU CALL THIS METHOD, IT WILL CALL RPM # Use get(:property) to check if cached values are available cmd = ["-q", @resource[:name], self.class.nosignature.to_s, self.class.nodigest.to_s, "--qf", self.class::NEVRA_FORMAT.to_s] begin output = rpm(*cmd) rescue Puppet::ExecutionFailure return nil unless @resource.allow_virtual? # rpm -q exits 1 if package not found # retry the query for virtual packages cmd << '--whatprovides' begin output = rpm(*cmd) rescue Puppet::ExecutionFailure # couldn't find a virtual package either return nil end end @property_hash.update(self.class.nevra_to_multiversion_hash(output)) @property_hash.dup end # Here we just retrieve the version from the file specified in the source. def latest source = @resource[:source] unless source @resource.fail _("RPMs must specify a package source") end cmd = [command(:rpm), "-q", "--qf", self.class::NEVRA_FORMAT.to_s, "-p", source] h = self.class.nevra_to_multiversion_hash(execute(cmd)) h[:ensure] rescue Puppet::ExecutionFailure => e raise Puppet::Error, e.message, e.backtrace end def install source = @resource[:source] unless source @resource.fail _("RPMs must specify a package source") end version = @property_hash[:ensure] # RPM gets upset if you try to install an already installed package return if @resource.should(:ensure) == version || (@resource.should(:ensure) == :latest && version == latest) flag = ["-i"] flag = ["-U", "--oldpackage"] if version && (version != :absent && version != :purged) flag += install_options if resource[:install_options] rpm flag, source end def uninstall query # If version and release (or only version) is specified in the resource, # uninstall using them, otherwise uninstall using only the name of the package. name = get(:name) version = get(:version) release = get(:release) nav = "#{name}-#{version}" nvr = "#{nav}-#{release}" if @resource[:name].start_with? nvr identifier = nvr elsif @resource[:name].start_with? nav identifier = nav elsif @resource[:install_only] identifier = get(:ensure).split(self.class::MULTIVERSION_SEPARATOR).map { |ver| "#{name}-#{ver}" } else identifier = name end # If an arch is specified in the resource, uninstall that arch, # otherwise uninstall the arch returned by query. # If multiple arches are installed and arch is not specified, # this will uninstall all of them after successive runs. # # rpm prior to 4.2.1 cannot accept architecture as part of the package name. unless Puppet::Util::Package.versioncmp(self.class.current_version, '4.2.1') < 0 arch = ".#{get(:arch)}" if @resource[:name].end_with? arch identifier += arch end end flag = ['-e'] flag += uninstall_options if resource[:uninstall_options] rpm flag, identifier end def update install end def install_options join_options(resource[:install_options]) end def uninstall_options join_options(resource[:uninstall_options]) end def insync?(is) return false if [:purged, :absent].include?(is) return false if is.include?(self.class::MULTIVERSION_SEPARATOR) && !@resource[:install_only] should = resource[:ensure] is.split(self.class::MULTIVERSION_SEPARATOR).any? do |version| 0 == rpm_compare_evr(should, version) end end private # @param line [String] one line of rpm package query information # @return [Hash] of NEVRA_FIELDS strings parsed from package info # or an empty hash if we failed to parse # @api private def self.nevra_to_hash(line) line.strip! hash = {} match = self::NEVRA_REGEX.match(line) if match self::NEVRA_FIELDS.zip(match.captures) { |f, v| hash[f] = v } hash[:provider] = name hash[:ensure] = "#{hash[:version]}-#{hash[:release]}" hash[:ensure].prepend("#{hash[:epoch]}:") if hash[:epoch] != '0' else Puppet.debug("Failed to match rpm line #{line}") end hash end # @param line [String] multiple lines of rpm package query information # @return list of [Hash] of NEVRA_FIELDS strings parsed from package info # or an empty list if we failed to parse # @api private def self.nevra_to_multiversion_hash(multiline) list = [] multiversion_hash = {} multiline.each_line do |line| hash = nevra_to_hash(line) next if hash.empty? if multiversion_hash.empty? multiversion_hash = hash.dup next end if multiversion_hash[:name] != hash[:name] list << multiversion_hash multiversion_hash = hash.dup next end unless multiversion_hash[:ensure].include?(hash[:ensure]) multiversion_hash[:ensure].concat("#{self::MULTIVERSION_SEPARATOR}#{hash[:ensure]}") end end list << multiversion_hash if multiversion_hash if list.size == 1 return list[0] end list end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/windows/package.rb
lib/puppet/provider/package/windows/package.rb
# frozen_string_literal: true require_relative '../../../../puppet/provider/package' require_relative '../../../../puppet/util/windows' class Puppet::Provider::Package::Windows class Package extend Enumerable extend Puppet::Util::Errors include Puppet::Util::Windows::Registry extend Puppet::Util::Windows::Registry attr_reader :name, :version REG_DISPLAY_VALUE_NAMES = %w[DisplayName QuietDisplayName] def self.reg_value_names_to_load REG_DISPLAY_VALUE_NAMES | MsiPackage::REG_VALUE_NAMES | ExePackage::REG_VALUE_NAMES end # Enumerate each package. The appropriate package subclass # will be yielded. def self.each(&block) with_key do |key, values| name = key.name.match(/^.+\\([^\\]+)$/).captures[0] [MsiPackage, ExePackage].find do |klass| pkg = klass.from_registry(name, values) if pkg yield pkg end end end end # Yield each registry key and its values associated with an # installed package. This searches both per-machine and current # user contexts, as well as packages associated with 64 and # 32-bit installers. def self.with_key(&block) %w[HKEY_LOCAL_MACHINE HKEY_CURRENT_USER].each do |hive| [KEY64, KEY32].each do |mode| mode |= KEY_READ begin self.open(hive, 'Software\Microsoft\Windows\CurrentVersion\Uninstall', mode) do |uninstall| each_key(uninstall) do |name, _wtime| self.open(hive, "#{uninstall.keyname}\\#{name}", mode) do |key| yield key, values_by_name(key, reg_value_names_to_load) end end end rescue Puppet::Util::Windows::Error => e raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND end end end end # Get the class that knows how to install this resource def self.installer_class(resource) fail(_("The source parameter is required when using the Windows provider.")) unless resource[:source] case resource[:source] when /\.msi"?\Z/i # REMIND: can we install from URL? # REMIND: what about msp, etc MsiPackage when /\.exe"?\Z/i fail(_("The source does not exist: '%{source}'") % { source: resource[:source] }) unless Puppet::FileSystem.exist?(resource[:source]) || resource[:source].start_with?('http://', 'https://') ExePackage else fail(_("Don't know how to install '%{source}'") % { source: resource[:source] }) end end def self.munge(value) quote(replace_forward_slashes(value)) end def self.replace_forward_slashes(value) if value.include?('/') value = value.tr('/', "\\") Puppet.debug('Package source parameter contained /s - replaced with \\s') end value end def self.quote(value) value.include?(' ') ? %Q("#{value.gsub(/"/, '\"')}") : value end def self.get_display_name(values) return if values.nil? return values['DisplayName'] if values['DisplayName'] && values['DisplayName'].length > 0 return values['QuietDisplayName'] if values['QuietDisplayName'] && values['QuietDisplayName'].length > 0 '' end def initialize(name, version) @name = name @version = version end end end require_relative '../../../../puppet/provider/package/windows/msi_package' require_relative '../../../../puppet/provider/package/windows/exe_package'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/windows/exe_package.rb
lib/puppet/provider/package/windows/exe_package.rb
# frozen_string_literal: true require_relative '../../../../puppet/provider/package/windows/package' class Puppet::Provider::Package::Windows class ExePackage < Puppet::Provider::Package::Windows::Package attr_reader :uninstall_string # registry values to load under each product entry in # HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall # for this provider REG_VALUE_NAMES = [ 'DisplayVersion', 'UninstallString', 'ParentKeyName', 'Security Update', 'Update Rollup', 'Hotfix', 'WindowsInstaller' ] def self.register(path) Puppet::Type::Package::ProviderWindows.paths ||= [] Puppet::Type::Package::ProviderWindows.paths << path end # Return an instance of the package from the registry, or nil def self.from_registry(name, values) if valid?(name, values) ExePackage.new( get_display_name(values), values['DisplayVersion'], values['UninstallString'] ) end end # Is this a valid executable package we should manage? def self.valid?(name, values) # See http://community.spiceworks.com/how_to/show/2238 displayName = get_display_name(values) !!(displayName && displayName.length > 0 && values['UninstallString'] && values['UninstallString'].length > 0 && values['WindowsInstaller'] != 1 && # DWORD name !~ /^KB[0-9]{6}/ && values['ParentKeyName'].nil? && values['Security Update'].nil? && values['Update Rollup'].nil? && values['Hotfix'].nil?) end def initialize(name, version, uninstall_string) super(name, version) @uninstall_string = uninstall_string end # Does this package match the resource? def match?(resource) resource[:name] == name end def self.install_command(resource) file_location = resource[:source] if file_location.start_with?('http://', 'https://') tempfile = Tempfile.new(['', '.exe']) begin uri = URI(Puppet::Util.uri_encode(file_location)) client = Puppet.runtime[:http] client.get(uri, options: { include_system_store: true }) do |response| raise Puppet::HTTP::ResponseError, response unless response.success? File.open(tempfile.path, 'wb') do |file| response.read_body do |data| file.write(data) end end end rescue => detail raise Puppet::Error.new(_("Error when installing %{package}: %{detail}") % { package: resource[:name], detail: detail.message }, detail) ensure register(tempfile.path) tempfile.close() file_location = tempfile.path end end munge(file_location) end def uninstall_command # Only quote bare uninstall strings, e.g. # C:\Program Files (x86)\Notepad++\uninstall.exe # Don't quote uninstall strings that are already quoted, e.g. # "c:\ruby187\unins000.exe" # Don't quote uninstall strings that contain arguments: # "C:\Program Files (x86)\Git\unins000.exe" /SILENT if uninstall_string =~ /\A[^"]*.exe\Z/i command = "\"#{uninstall_string}\"" else command = uninstall_string end command end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/windows/msi_package.rb
lib/puppet/provider/package/windows/msi_package.rb
# frozen_string_literal: true require_relative '../../../../puppet/provider/package/windows/package' class Puppet::Provider::Package::Windows class MsiPackage < Puppet::Provider::Package::Windows::Package attr_reader :productcode, :packagecode # From msi.h INSTALLSTATE_DEFAULT = 5 # product is installed for the current user INSTALLUILEVEL_NONE = 2 # completely silent installation # registry values to load under each product entry in # HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall # for this provider REG_VALUE_NAMES = %w[ DisplayVersion WindowsInstaller ] # Get the COM installer object, it's in a separate method for testing def self.installer # REMIND: when does the COM release happen? WIN32OLE.new("WindowsInstaller.Installer") end # Return an instance of the package from the registry, or nil def self.from_registry(name, values) if valid?(name, values) inst = installer if inst.ProductState(name) == INSTALLSTATE_DEFAULT MsiPackage.new(get_display_name(values), values['DisplayVersion'], name, # productcode inst.ProductInfo(name, 'PackageCode')) end end end # Is this a valid MSI package we should manage? def self.valid?(name, values) # See http://community.spiceworks.com/how_to/show/2238 displayName = get_display_name(values) !!(displayName && displayName.length > 0 && values['WindowsInstaller'] == 1 && # DWORD name =~ /\A\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}\Z/i) end def initialize(name, version, productcode, packagecode) super(name, version) @productcode = productcode @packagecode = packagecode end # Does this package match the resource? def match?(resource) resource[:name].casecmp(packagecode) == 0 || resource[:name].casecmp(productcode) == 0 || resource[:name] == name end def self.install_command(resource) ['msiexec.exe', '/qn', '/norestart', '/i', munge(resource[:source])] end def uninstall_command ['msiexec.exe', '/qn', '/norestart', '/x', productcode] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_bucket/file.rb
lib/puppet/file_bucket/file.rb
# frozen_string_literal: true require_relative '../../puppet/file_bucket' require_relative '../../puppet/indirector' require_relative '../../puppet/util/checksums' require 'digest/md5' require 'stringio' class Puppet::FileBucket::File # This class handles the abstract notion of a file in a filebucket. # There are mechanisms to save and load this file locally and remotely in puppet/indirector/filebucketfile/* # There is a compatibility class that emulates pre-indirector filebuckets in Puppet::FileBucket::Dipper extend Puppet::Indirector indirects :file_bucket_file, :terminus_class => :selector attr_reader :bucket_path def self.supported_formats [:binary] end def initialize(contents, options = {}) case contents when String @contents = StringContents.new(contents) when Pathname @contents = FileContents.new(contents) else raise ArgumentError, _("contents must be a String or Pathname, got a %{contents_class}") % { contents_class: contents.class } end @bucket_path = options.delete(:bucket_path) @checksum_type = Puppet[:digest_algorithm].to_sym raise ArgumentError, _("Unknown option(s): %{opts}") % { opts: options.keys.join(', ') } unless options.empty? end # @return [Num] The size of the contents def size @contents.size() end # @return [IO] A stream that reads the contents def stream(&block) @contents.stream(&block) end def checksum_type @checksum_type.to_s end def checksum "{#{checksum_type}}#{checksum_data}" end def checksum_data @checksum_data ||= @contents.checksum_data(@checksum_type) end def to_s to_binary end def to_binary @contents.to_binary end def contents to_binary end def name "#{checksum_type}/#{checksum_data}" end def self.from_binary(contents) new(contents) end class StringContents def initialize(content) @contents = content; end def stream(&block) s = StringIO.new(@contents) begin block.call(s) ensure s.close end end def size @contents.size end def checksum_data(base_method) Puppet.info(_("Computing checksum on string")) Puppet::Util::Checksums.method(base_method).call(@contents) end def to_binary # This is not so horrible as for FileContent, but still possible to mutate the content that the # checksum is based on... so semi horrible... @contents; end end class FileContents def initialize(path) @path = path end def stream(&block) Puppet::FileSystem.open(@path, nil, 'rb', &block) end def size Puppet::FileSystem.size(@path) end def checksum_data(base_method) Puppet.info(_("Computing checksum on file %{path}") % { path: @path }) Puppet::Util::Checksums.method(:"#{base_method}_file").call(@path) end def to_binary Puppet::FileSystem.binread(@path) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_bucket/dipper.rb
lib/puppet/file_bucket/dipper.rb
# frozen_string_literal: true require 'pathname' require_relative '../../puppet/file_bucket' require_relative '../../puppet/file_bucket/file' require_relative '../../puppet/indirector/request' require_relative '../../puppet/util/diff' require 'tempfile' class Puppet::FileBucket::Dipper include Puppet::Util::Checksums # This is a transitional implementation that uses REST # to access remote filebucket files. attr_accessor :name # Creates a bucket client def initialize(hash = {}) # Emulate the XMLRPC client server = hash[:Server] port = hash[:Port] || Puppet[:serverport] if hash.include?(:Path) @local_path = hash[:Path] @rest_path = nil else @local_path = nil @rest_path = "filebucket://#{server}:#{port}/" end @checksum_type = Puppet[:digest_algorithm].to_sym @digest = method(@checksum_type) end def local? !!@local_path end # Backs up a file to the file bucket def backup(file) file_handle = Puppet::FileSystem.pathname(file) raise(ArgumentError, _("File %{file} does not exist") % { file: file }) unless Puppet::FileSystem.exist?(file_handle) begin file_bucket_file = Puppet::FileBucket::File.new(file_handle, :bucket_path => @local_path) files_original_path = absolutize_path(file) dest_path = "#{@rest_path}#{file_bucket_file.name}/#{files_original_path}" file_bucket_path = "#{@rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}/#{files_original_path}" # Make a HEAD request for the file so that we don't waste time # uploading it if it already exists in the bucket. unless Puppet::FileBucket::File.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path) Puppet::FileBucket::File.indirection.save(file_bucket_file, dest_path) end file_bucket_file.checksum_data rescue => detail message = _("Could not back up %{file}: %{detail}") % { file: file, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end end # Diffs two filebucket files identified by their sums def diff(checksum_a, checksum_b, file_a, file_b) raise RuntimeError, _("Diff is not supported on this platform") if Puppet[:diff] == "" if checksum_a source_path = "#{@rest_path}#{@checksum_type}/#{checksum_a}" if checksum_b file_diff = Puppet::FileBucket::File.indirection.find( source_path, :bucket_path => @local_path, :diff_with => checksum_b ) elsif file_b tmp_file = ::Tempfile.new('diff') begin restore(tmp_file.path, checksum_a) file_diff = Puppet::Util::Diff.diff(tmp_file.path, file_b) ensure tmp_file.close tmp_file.unlink end else raise Puppet::Error, _("Please provide a file or checksum to diff with") end elsif file_a if checksum_b tmp_file = ::Tempfile.new('diff') begin restore(tmp_file.path, checksum_b) file_diff = Puppet::Util::Diff.diff(file_a, tmp_file.path) ensure tmp_file.close tmp_file.unlink end elsif file_b file_diff = Puppet::Util::Diff.diff(file_a, file_b) end end raise Puppet::Error, _("Failed to diff files") unless file_diff file_diff.to_s end # Retrieves a file by sum. def getfile(sum) get_bucket_file(sum).to_s end # Retrieves a FileBucket::File by sum. def get_bucket_file(sum) source_path = "#{@rest_path}#{@checksum_type}/#{sum}" file_bucket_file = Puppet::FileBucket::File.indirection.find(source_path, :bucket_path => @local_path) raise Puppet::Error, _("File not found") unless file_bucket_file file_bucket_file end # Restores the file def restore(file, sum) restore = true file_handle = Puppet::FileSystem.pathname(file) if Puppet::FileSystem.exist?(file_handle) cursum = Puppet::FileBucket::File.new(file_handle).checksum_data() # if the checksum has changed... # this might be extra effort if cursum == sum restore = false end end if restore newcontents = get_bucket_file(sum) if newcontents newsum = newcontents.checksum_data changed = nil if Puppet::FileSystem.exist?(file_handle) and !Puppet::FileSystem.writable?(file_handle) changed = Puppet::FileSystem.stat(file_handle).mode ::File.chmod(changed | 0o200, file) end ::File.open(file, ::File::WRONLY | ::File::TRUNC | ::File::CREAT) { |of| of.binmode newcontents.stream do |source_stream| FileUtils.copy_stream(source_stream, of) end } ::File.chmod(changed, file) if changed else Puppet.err _("Could not find file with checksum %{sum}") % { sum: sum } return nil end newsum else nil end end # List Filebucket content. def list(fromdate, todate) raise Puppet::Error, _("Listing remote file buckets is not allowed") unless local? source_path = "#{@rest_path}#{@checksum_type}/" file_bucket_list = Puppet::FileBucket::File.indirection.find( source_path, :bucket_path => @local_path, :list_all => true, :fromdate => fromdate, :todate => todate ) raise Puppet::Error, _("File not found") unless file_bucket_list file_bucket_list.to_s end private def absolutize_path(path) Pathname.new(path).realpath end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/state_machine.rb
lib/puppet/ssl/state_machine.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' require_relative '../../puppet/util/pidlock' # This class implements a state machine for bootstrapping a host's CA and CRL # bundles, private key and signed client certificate. Each state has a frozen # SSLContext that it uses to make network connections. If a state makes progress # bootstrapping the host, then the state will generate a new frozen SSLContext # and pass that to the next state. For example, the NeedCACerts state will load # or download a CA bundle, and generate a new SSLContext containing those CA # certs. This way we're sure about which SSLContext is being used during any # phase of the bootstrapping process. # # @api private class Puppet::SSL::StateMachine class SSLState attr_reader :ssl_context def initialize(machine, ssl_context) @machine = machine @ssl_context = ssl_context @cert_provider = machine.cert_provider @ssl_provider = machine.ssl_provider end def to_error(message, cause) detail = Puppet::Error.new(message) detail.set_backtrace(cause.backtrace) Error.new(@machine, message, detail) end def log_error(message) # When running daemonized we set stdout to /dev/null, so write to the log instead if Puppet[:daemonize] Puppet.err(message) else $stdout.puts(message) end end end # Load existing CA certs or download them. Transition to NeedCRLs. # class NeedCACerts < SSLState def initialize(machine) super(machine, nil) @ssl_context = @ssl_provider.create_insecure_context end def next_state Puppet.debug("Loading CA certs") force_crl_refresh = false cacerts = @cert_provider.load_cacerts if cacerts next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false) now = Time.now last_update = @cert_provider.ca_last_update if needs_refresh?(now, last_update) # If we refresh the CA, then we need to force the CRL to be refreshed too, # since if there is a new CA in the chain, then we need its CRL to check # the full chain for revocation status. next_ctx, force_crl_refresh = refresh_ca(next_ctx, last_update) end else route = @machine.session.route_to(:ca, ssl_context: @ssl_context) _, pem = route.get_certificate(Puppet::SSL::CA_NAME, ssl_context: @ssl_context) if @machine.ca_fingerprint actual_digest = @machine.digest_as_hex(pem) expected_digest = @machine.ca_fingerprint.scan(/../).join(':').upcase if actual_digest == expected_digest Puppet.info(_("Verified CA bundle with digest (%{digest_type}) %{actual_digest}") % { digest_type: @machine.digest, actual_digest: actual_digest }) else e = Puppet::Error.new(_("CA bundle with digest (%{digest_type}) %{actual_digest} did not match expected digest %{expected_digest}") % { digest_type: @machine.digest, actual_digest: actual_digest, expected_digest: expected_digest }) return Error.new(@machine, e.message, e) end end cacerts = @cert_provider.load_cacerts_from_pem(pem) # verify cacerts before saving next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false) @cert_provider.save_cacerts(cacerts) end NeedCRLs.new(@machine, next_ctx, force_crl_refresh) rescue OpenSSL::X509::CertificateError => e Error.new(@machine, e.message, e) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 to_error(_('CA certificate is missing from the server'), e) else to_error(_('Could not download CA certificate: %{message}') % { message: e.message }, e) end end private def needs_refresh?(now, last_update) return true if last_update.nil? ca_ttl = Puppet[:ca_refresh_interval] return false unless ca_ttl now.to_i > last_update.to_i + ca_ttl end def refresh_ca(ssl_ctx, last_update) Puppet.info(_("Refreshing CA certificate")) # return the next_ctx containing the updated ca next_ctx = [download_ca(ssl_ctx, last_update), true] # After a successful refresh, update ca_last_update @cert_provider.ca_last_update = Time.now next_ctx rescue Puppet::HTTP::ResponseError => e if e.response.code == 304 Puppet.info(_("CA certificate is unmodified, using existing CA certificate")) else Puppet.info(_("Failed to refresh CA certificate, using existing CA certificate: %{message}") % { message: e.message }) end # return the original ssl_ctx [ssl_ctx, false] rescue Puppet::HTTP::HTTPError => e Puppet.warning(_("Failed to refresh CA certificate, using existing CA certificate: %{message}") % { message: e.message }) # return the original ssl_ctx [ssl_ctx, false] end def download_ca(ssl_ctx, last_update) route = @machine.session.route_to(:ca, ssl_context: ssl_ctx) _, pem = route.get_certificate(Puppet::SSL::CA_NAME, if_modified_since: last_update, ssl_context: ssl_ctx) cacerts = @cert_provider.load_cacerts_from_pem(pem) # verify cacerts before saving next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false) @cert_provider.save_cacerts(cacerts) Puppet.info("Refreshed CA certificate: #{@machine.digest_as_hex(pem)}") next_ctx end end # If revocation is enabled, load CRLs or download them, using the CA bundle # from the previous state. Transition to NeedKey. Even if Puppet[:certificate_revocation] # is leaf or chain, disable revocation when downloading the CRL, since 1) we may # not have one yet or 2) the connection will fail if NeedCACerts downloaded a new CA # for which we don't have a CRL # class NeedCRLs < SSLState attr_reader :force_crl_refresh def initialize(machine, ssl_context, force_crl_refresh = false) super(machine, ssl_context) @force_crl_refresh = force_crl_refresh end def next_state Puppet.debug("Loading CRLs") case Puppet[:certificate_revocation] when :chain, :leaf crls = @cert_provider.load_crls if crls next_ctx = @ssl_provider.create_root_context(cacerts: ssl_context[:cacerts], crls: crls) now = Time.now last_update = @cert_provider.crl_last_update if needs_refresh?(now, last_update) next_ctx = refresh_crl(next_ctx, last_update) end else next_ctx = download_crl(@ssl_context, nil) end else Puppet.info("Certificate revocation is disabled, skipping CRL download") next_ctx = @ssl_provider.create_root_context(cacerts: ssl_context[:cacerts], crls: []) end NeedKey.new(@machine, next_ctx) rescue OpenSSL::X509::CRLError => e Error.new(@machine, e.message, e) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 to_error(_('CRL is missing from the server'), e) else to_error(_('Could not download CRLs: %{message}') % { message: e.message }, e) end end private def needs_refresh?(now, last_update) return true if @force_crl_refresh || last_update.nil? crl_ttl = Puppet[:crl_refresh_interval] return false unless crl_ttl now.to_i > last_update.to_i + crl_ttl end def refresh_crl(ssl_ctx, last_update) Puppet.info(_("Refreshing CRL")) # return the next_ctx containing the updated crl next_ctx = download_crl(ssl_ctx, last_update) # After a successful refresh, update crl_last_update @cert_provider.crl_last_update = Time.now next_ctx rescue Puppet::HTTP::ResponseError => e if e.response.code == 304 Puppet.info(_("CRL is unmodified, using existing CRL")) else Puppet.info(_("Failed to refresh CRL, using existing CRL: %{message}") % { message: e.message }) end # return the original ssl_ctx ssl_ctx rescue Puppet::HTTP::HTTPError => e Puppet.warning(_("Failed to refresh CRL, using existing CRL: %{message}") % { message: e.message }) # return the original ssl_ctx ssl_ctx end def download_crl(ssl_ctx, last_update) route = @machine.session.route_to(:ca, ssl_context: ssl_ctx) _, pem = route.get_certificate_revocation_list(if_modified_since: last_update, ssl_context: ssl_ctx) crls = @cert_provider.load_crls_from_pem(pem) # verify crls before saving next_ctx = @ssl_provider.create_root_context(cacerts: ssl_ctx[:cacerts], crls: crls) @cert_provider.save_crls(crls) Puppet.info("Refreshed CRL: #{@machine.digest_as_hex(pem)}") next_ctx end end # Load or generate a private key. If the key exists, try to load the client cert # and transition to Done. If the cert is mismatched or otherwise fails valiation, # raise an error. If the key doesn't exist yet, generate one, and save it. If the # cert doesn't exist yet, transition to NeedSubmitCSR. # class NeedKey < SSLState def next_state Puppet.debug(_("Loading/generating private key")) password = @cert_provider.load_private_key_password key = @cert_provider.load_private_key(Puppet[:certname], password: password) if key cert = @cert_provider.load_client_cert(Puppet[:certname]) if cert next_ctx = @ssl_provider.create_context( cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: key, client_cert: cert ) if needs_refresh?(cert) return NeedRenewedCert.new(@machine, next_ctx, key) else return Done.new(@machine, next_ctx) end end else if Puppet[:key_type] == 'ec' Puppet.info _("Creating a new EC SSL key for %{name} using curve %{curve}") % { name: Puppet[:certname], curve: Puppet[:named_curve] } key = OpenSSL::PKey::EC.generate(Puppet[:named_curve]) else Puppet.info _("Creating a new RSA SSL key for %{name}") % { name: Puppet[:certname] } key = OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i) end @cert_provider.save_private_key(Puppet[:certname], key, password: password) end NeedSubmitCSR.new(@machine, @ssl_context, key) end private def needs_refresh?(cert) cert_ttl = Puppet[:hostcert_renewal_interval] return false unless cert_ttl Time.now.to_i >= (cert.not_after.to_i - cert_ttl) end end # Base class for states with a private key. # class KeySSLState < SSLState attr_reader :private_key def initialize(machine, ssl_context, private_key) super(machine, ssl_context) @private_key = private_key end end # Generate and submit a CSR using the CA cert bundle and optional CRL bundle # from earlier states. If the request is submitted, proceed to NeedCert, # otherwise Wait. This could be due to the server already having a CSR # for this host (either the same or different CSR content), having a # signed certificate, or a revoked certificate. # class NeedSubmitCSR < KeySSLState def next_state Puppet.debug(_("Generating and submitting a CSR")) csr = @cert_provider.create_request(Puppet[:certname], @private_key) route = @machine.session.route_to(:ca, ssl_context: @ssl_context) route.put_certificate_request(Puppet[:certname], csr, ssl_context: @ssl_context) @cert_provider.save_request(Puppet[:certname], csr) NeedCert.new(@machine, @ssl_context, @private_key) rescue Puppet::HTTP::ResponseError => e if e.response.code == 400 NeedCert.new(@machine, @ssl_context, @private_key) else to_error(_("Failed to submit the CSR, HTTP response was %{code}") % { code: e.response.code }, e) end end end # Attempt to load or retrieve our signed cert. # class NeedCert < KeySSLState def next_state Puppet.debug(_("Downloading client certificate")) route = @machine.session.route_to(:ca, ssl_context: @ssl_context) cert = OpenSSL::X509::Certificate.new( route.get_certificate(Puppet[:certname], ssl_context: @ssl_context)[1] ) Puppet.info _("Downloaded certificate for %{name} from %{url}") % { name: Puppet[:certname], url: route.url } # verify client cert before saving next_ctx = @ssl_provider.create_context( cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: @private_key, client_cert: cert ) @cert_provider.save_client_cert(Puppet[:certname], cert) @cert_provider.delete_request(Puppet[:certname]) Done.new(@machine, next_ctx) rescue Puppet::SSL::SSLError => e Error.new(@machine, e.message, e) rescue OpenSSL::X509::CertificateError => e Error.new(@machine, _("Failed to parse certificate: %{message}") % { message: e.message }, e) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 Puppet.info(_("Certificate for %{certname} has not been signed yet") % { certname: Puppet[:certname] }) $stdout.puts _("Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate (%{name}).") % { name: Puppet[:certname] } Wait.new(@machine) else to_error(_("Failed to retrieve certificate for %{certname}: %{message}") % { certname: Puppet[:certname], message: e.message }, e) end end end # Class to renew a client/host certificate automatically. # class NeedRenewedCert < KeySSLState def next_state Puppet.debug(_("Renewing client certificate")) route = @machine.session.route_to(:ca, ssl_context: @ssl_context) cert = OpenSSL::X509::Certificate.new( route.post_certificate_renewal(@ssl_context)[1] ) # verify client cert before saving next_ctx = @ssl_provider.create_context( cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: @private_key, client_cert: cert ) @cert_provider.save_client_cert(Puppet[:certname], cert) Puppet.info(_("Renewed client certificate: %{cert_digest}, not before '%{not_before}', not after '%{not_after}'") % { cert_digest: @machine.digest_as_hex(cert.to_pem), not_before: cert.not_before, not_after: cert.not_after }) Done.new(@machine, next_ctx) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 Puppet.info(_("Certificate autorenewal has not been enabled on the server.")) else Puppet.warning(_("Failed to automatically renew certificate: %{code} %{reason}") % { code: e.response.code, reason: e.response.reason }) end Done.new(@machine, @ssl_context) rescue => e Puppet.warning(_("Unable to automatically renew certificate: %{message}") % { message: e.message }) Done.new(@machine, @ssl_context) end end # We cannot make progress, so wait if allowed to do so, or exit. # class Wait < SSLState def initialize(machine) super(machine, nil) end def next_state time = @machine.waitforcert if time < 1 log_error(_("Exiting now because the waitforcert setting is set to 0.")) exit(1) elsif Time.now.to_i > @machine.wait_deadline log_error(_("Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate (%{name}). Exiting now because the maxwaitforcert timeout has been exceeded.") % { name: Puppet[:certname] }) exit(1) else Puppet.info(_("Will try again in %{time} seconds.") % { time: time }) # close http/tls and session state before sleeping Puppet.runtime[:http].close @machine.session = Puppet.runtime[:http].create_session @machine.unlock Kernel.sleep(time) NeedLock.new(@machine) end end end # Acquire the ssl lock or return LockFailure causing us to exit. # class NeedLock < SSLState def initialize(machine) super(machine, nil) end def next_state if @machine.lock # our ssl directory may have been cleaned while we were # sleeping, start over from the top NeedCACerts.new(@machine) elsif @machine.waitforlock < 1 LockFailure.new(@machine, _("Another puppet instance is already running and the waitforlock setting is set to 0; exiting")) elsif Time.now.to_i >= @machine.waitlock_deadline LockFailure.new(@machine, _("Another puppet instance is already running and the maxwaitforlock timeout has been exceeded; exiting")) else Puppet.info _("Another puppet instance is already running; waiting for it to finish") Puppet.info _("Will try again in %{time} seconds.") % { time: @machine.waitforlock } Kernel.sleep @machine.waitforlock # try again self end end end # We failed to acquire the lock, so exit # class LockFailure < SSLState attr_reader :message def initialize(machine, message) super(machine, nil) @message = message end end # We cannot make progress due to an error. # class Error < SSLState attr_reader :message, :error def initialize(machine, message, error) super(machine, nil) @message = message @error = error end def next_state Puppet.log_exception(@error, @message) Wait.new(@machine) end end # We have a CA bundle, optional CRL bundle, a private key and matching cert # that chains to one of the root certs in our bundle. # class Done < SSLState; end attr_reader :waitforcert, :wait_deadline, :waitforlock, :waitlock_deadline, :cert_provider, :ssl_provider, :ca_fingerprint, :digest attr_accessor :session # Construct a state machine to manage the SSL initialization process. By # default, if the state machine encounters an exception, it will log the # exception and wait for `waitforcert` seconds and retry, restarting from the # beginning of the state machine. # # However, if `onetime` is true, then the state machine will raise the first # error it encounters, instead of waiting. Otherwise, if `waitforcert` is 0, # then then state machine will exit instead of wait. # # @param waitforcert [Integer] how many seconds to wait between attempts # @param maxwaitforcert [Integer] maximum amount of seconds to wait for the # server to sign the certificate request # @param waitforlock [Integer] how many seconds to wait between attempts for # acquiring the ssl lock # @param maxwaitforlock [Integer] maximum amount of seconds to wait for an # already running process to release the ssl lock # @param onetime [Boolean] whether to run onetime # @param lockfile [Puppet::Util::Pidlock] lockfile to protect against # concurrent modification by multiple processes # @param cert_provider [Puppet::X509::CertProvider] cert provider to use # to load and save X509 objects. # @param ssl_provider [Puppet::SSL::SSLProvider] ssl provider to use # to construct ssl contexts. # @param digest [String] digest algorithm to use for certificate fingerprinting # @param ca_fingerprint [String] optional fingerprint to verify the # downloaded CA bundle def initialize(waitforcert: Puppet[:waitforcert], maxwaitforcert: Puppet[:maxwaitforcert], waitforlock: Puppet[:waitforlock], maxwaitforlock: Puppet[:maxwaitforlock], onetime: Puppet[:onetime], cert_provider: Puppet::X509::CertProvider.new, ssl_provider: Puppet::SSL::SSLProvider.new, lockfile: Puppet::Util::Pidlock.new(Puppet[:ssl_lockfile]), digest: 'SHA256', ca_fingerprint: Puppet[:ca_fingerprint]) @waitforcert = waitforcert @wait_deadline = Time.now.to_i + maxwaitforcert @waitforlock = waitforlock @waitlock_deadline = Time.now.to_i + maxwaitforlock @onetime = onetime @cert_provider = cert_provider @ssl_provider = ssl_provider @lockfile = lockfile @digest = digest @ca_fingerprint = ca_fingerprint @session = Puppet.runtime[:http].create_session end # Run the state machine for CA certs and CRLs. # # @return [Puppet::SSL::SSLContext] initialized SSLContext # @raise [Puppet::Error] If we fail to generate an SSLContext # @api private def ensure_ca_certificates final_state = run_machine(NeedLock.new(self), NeedKey) final_state.ssl_context end # Run the state machine for client certs. # # @return [Puppet::SSL::SSLContext] initialized SSLContext # @raise [Puppet::Error] If we fail to generate an SSLContext # @api private def ensure_client_certificate final_state = run_machine(NeedLock.new(self), Done) ssl_context = final_state.ssl_context @ssl_provider.print(ssl_context, @digest) ssl_context end def lock @lockfile.lock end def unlock @lockfile.unlock end def digest_as_hex(str) Puppet::SSL::Digest.new(digest, str).to_hex end private def run_machine(state, stop) loop do state = run_step(state) case state when stop break when LockFailure raise Puppet::Error, state.message when Error if @onetime Puppet.log_exception(state.error) raise state.error end else # fall through end end state ensure @lockfile.unlock if @lockfile.locked? end def run_step(state) state.next_state rescue => e state.to_error(e.message, e) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/ssl_context.rb
lib/puppet/ssl/ssl_context.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' module Puppet::SSL # The `keyword_init: true` option is no longer needed in Ruby >= 3.2 SSLContext = Struct.new( :store, :cacerts, :crls, :private_key, :client_cert, :client_chain, :revocation, :verify_peer, keyword_init: true ) do def initialize(*) super self[:cacerts] ||= [] self[:crls] ||= [] self[:client_chain] ||= [] self[:revocation] = true if self[:revocation].nil? self[:verify_peer] = true if self[:verify_peer].nil? end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/verifier.rb
lib/puppet/ssl/verifier.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' # Verify an SSL connection. # # @api private class Puppet::SSL::Verifier FIVE_MINUTES_AS_SECONDS = 5 * 60 attr_reader :ssl_context # Create a verifier using an `ssl_context`. # # @param hostname [String] FQDN of the server we're attempting to connect to # @param ssl_context [Puppet::SSL::SSLContext] ssl_context containing CA certs, # CRLs, etc needed to verify the server's certificate chain # @api private def initialize(hostname, ssl_context) @hostname = hostname @ssl_context = ssl_context end # Return true if `self` is reusable with `verifier` meaning they # are using the same `ssl_context`, so there's no loss of security # when using a cached connection. # # @param verifier [Puppet::SSL::Verifier] the verifier to compare against # @return [Boolean] return true if a cached connection can be used, false otherwise # @api private def reusable?(verifier) verifier.instance_of?(self.class) && verifier.ssl_context.equal?(@ssl_context) # same object? end # Configure the `http` connection based on the current `ssl_context`. # # @param http [Net::HTTP] connection # @api private def setup_connection(http) http.cert_store = @ssl_context[:store] http.cert = @ssl_context[:client_cert] http.key = @ssl_context[:private_key] # default to VERIFY_PEER http.verify_mode = if !@ssl_context[:verify_peer] OpenSSL::SSL::VERIFY_NONE else OpenSSL::SSL::VERIFY_PEER end http.verify_callback = self end # This method is called if `Net::HTTP#start` raises an exception, which # could be a result of an openssl error during cert verification, due # to ruby's `Socket#post_connection_check`, or general SSL connection # error. # # @param http [Net::HTTP] connection # @param error [OpenSSL::SSL::SSLError] connection error # @raise [Puppet::SSL::CertVerifyError] SSL connection failed due to a # verification error with the server's certificate or chain # @raise [Puppet::Error] server hostname does not match certificate # @raise [OpenSSL::SSL::SSLError] low-level SSL connection failure # @api private def handle_connection_error(http, error) raise @last_error if @last_error # ruby can pass SSL validation but fail post_connection_check peer_cert = http.peer_cert if peer_cert && !OpenSSL::SSL.verify_certificate_identity(peer_cert, @hostname) raise Puppet::SSL::CertMismatchError.new(peer_cert, @hostname) else raise error end end # OpenSSL will call this method with the verification result for each cert in # the server's chain, working from the root CA to the server's cert. If # preverify_ok is `true`, then that cert passed verification. If it's `false` # then the current verification error is contained in `store_context.error`. # and the current cert is in `store_context.current_cert`. # # If this method returns `false`, then verification stops and ruby will raise # an `OpenSSL::SSL::Error` with "certificate verification failed". If this # method returns `true`, then verification continues. # # If this method ignores a verification error, such as the cert's CRL will be # valid within the next 5 minutes, then this method may be called with a # different verification error for the same cert. # # WARNING: If `store_context.error` returns `OpenSSL::X509::V_OK`, don't # assume verification passed. Ruby 2.4+ implements certificate hostname # checking by default, and if the cert doesn't match the hostname, then the # error will be V_OK. Always use `preverify_ok` to determine if verification # succeeded or not. # # @param preverify_ok [Boolean] if `true` the current certificate in `store_context` # was verified. Otherwise, check for the current error in `store_context.error` # @param store_context [OpenSSL::X509::StoreContext] The context holding the # verification result for one certificate # @return [Boolean] If `true`, continue verifying the chain, even if that means # ignoring the current verification error. If `false`, abort the connection. # # @api private def call(preverify_ok, store_context) return true if preverify_ok peer_cert = store_context.current_cert case store_context.error when OpenSSL::X509::V_OK # chain is from leaf to root, opposite of the order that `call` is invoked chain_cert = store_context.chain.first # ruby 2.4 doesn't compare certs based on value, so force to DER byte array if peer_cert && chain_cert && peer_cert.to_der == chain_cert.to_der && !OpenSSL::SSL.verify_certificate_identity(peer_cert, @hostname) @last_error = Puppet::SSL::CertMismatchError.new(peer_cert, @hostname) return false end # ruby-openssl#74ef8c0cc56b840b772240f2ee2b0fc0aafa2743 now sets the # store_context error when the cert is mismatched when OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH @last_error = Puppet::SSL::CertMismatchError.new(peer_cert, @hostname) return false when OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID crl = store_context.current_crl if crl && crl.last_update && crl.last_update < Time.now + FIVE_MINUTES_AS_SECONDS Puppet.debug("Ignoring CRL not yet valid, current time #{Time.now.utc}, CRL last updated #{crl.last_update.utc}") return true end end # TRANSLATORS: `error` is an untranslated message from openssl describing why a certificate in the server's chain is invalid, and `subject` is the identity/name of the failed certificate @last_error = Puppet::SSL::CertVerifyError.new( _("certificate verify failed [%{error} for %{subject}]") % { error: store_context.error_string, subject: peer_cert.subject.to_utf8 }, store_context.error, peer_cert ) false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/digest.rb
lib/puppet/ssl/digest.rb
# frozen_string_literal: true class Puppet::SSL::Digest attr_reader :digest def initialize(algorithm, content) algorithm ||= 'SHA256' @digest = OpenSSL::Digest.new(algorithm, content) end def to_s "(#{name}) #{to_hex}" end def to_hex @digest.hexdigest.scan(/../).join(':').upcase end def name @digest.name.upcase end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/certificate_request.rb
lib/puppet/ssl/certificate_request.rb
# frozen_string_literal: true require_relative '../../puppet/ssl/base' require_relative '../../puppet/ssl/certificate_signer' # This class creates and manages X509 certificate signing requests. # # ## CSR attributes # # CSRs may contain a set of attributes that includes supplementary information # about the CSR or information for the signed certificate. # # PKCS#9/RFC 2985 section 5.4 formally defines the "Challenge password", # "Extension request", and "Extended-certificate attributes", but this # implementation only handles the "Extension request" attribute. Other # attributes may be defined on a CSR, but the RFC doesn't define behavior for # any other attributes so we treat them as only informational. # # ## CSR Extension request attribute # # CSRs may contain an optional set of extension requests, which allow CSRs to # include additional information that may be included in the signed # certificate. Any additional information that should be copied from the CSR # to the signed certificate MUST be included in this attribute. # # This behavior is dictated by PKCS#9/RFC 2985 section 5.4.2. # # @see https://tools.ietf.org/html/rfc2985 "RFC 2985 Section 5.4.2 Extension request" # class Puppet::SSL::CertificateRequest < Puppet::SSL::Base wraps OpenSSL::X509::Request # Because of how the format handler class is included, this # can't be in the base class. def self.supported_formats [:s] end def extension_factory # rubocop:disable Naming/MemoizedInstanceVariableName @ef ||= OpenSSL::X509::ExtensionFactory.new # rubocop:enable Naming/MemoizedInstanceVariableName end # Create a certificate request with our system settings. # # @param key [OpenSSL::X509::Key] The private key associated with this CSR. # @param options [Hash] # @option options [String] :dns_alt_names A comma separated list of # Subject Alternative Names to include in the CSR extension request. # @option options [Hash<String, String, Array<String>>] :csr_attributes A hash # of OIDs and values that are either a string or array of strings. # @option options [Array<String, String>] :extension_requests A hash of # certificate extensions to add to the CSR extReq attribute, excluding # the Subject Alternative Names extension. # # @raise [Puppet::Error] If the generated CSR signature couldn't be verified # # @return [OpenSSL::X509::Request] The generated CSR def generate(key, options = {}) Puppet.info _("Creating a new SSL certificate request for %{name}") % { name: name } # If we're a CSR for the CA, then use the real ca_name, rather than the # fake 'ca' name. This is mostly for backward compatibility with 0.24.x, # but it's also just a good idea. common_name = name == Puppet::SSL::CA_NAME ? Puppet.settings[:ca_name] : name csr = OpenSSL::X509::Request.new csr.version = 0 csr.subject = OpenSSL::X509::Name.new([["CN", common_name]]) csr.public_key = if key.is_a?(OpenSSL::PKey::EC) # EC#public_key doesn't follow the PKey API, # see https://github.com/ruby/openssl/issues/29 key else key.public_key end if options[:csr_attributes] add_csr_attributes(csr, options[:csr_attributes]) end if (ext_req_attribute = extension_request_attribute(options)) csr.add_attribute(ext_req_attribute) end signer = Puppet::SSL::CertificateSigner.new signer.sign(csr, key) raise Puppet::Error, _("CSR sign verification failed; you need to clean the certificate request for %{name} on the server") % { name: name } unless csr.verify(csr.public_key) @content = csr # we won't be able to get the digest on jruby if @content.signature_algorithm Puppet.info _("Certificate Request fingerprint (%{digest}): %{hex_digest}") % { digest: digest.name, hex_digest: digest.to_hex } end @content end def ext_value_to_ruby_value(asn1_arr) # A list of ASN1 types than can't be directly converted to a Ruby type @non_convertible ||= [OpenSSL::ASN1::EndOfContent, OpenSSL::ASN1::BitString, OpenSSL::ASN1::Null, OpenSSL::ASN1::Enumerated, OpenSSL::ASN1::UTCTime, OpenSSL::ASN1::GeneralizedTime, OpenSSL::ASN1::Sequence, OpenSSL::ASN1::Set] begin # Attempt to decode the extension's DER data located in the original OctetString asn1_val = OpenSSL::ASN1.decode(asn1_arr.last.value) rescue OpenSSL::ASN1::ASN1Error # This is to allow supporting the old-style of not DER encoding trusted facts return asn1_arr.last.value end # If the extension value can not be directly converted to an atomic Ruby # type, use the original ASN1 value. This is needed to work around a bug # in Ruby's OpenSSL library which doesn't convert the value of unknown # extension OIDs properly. See PUP-3560 if @non_convertible.include?(asn1_val.class) then # Allows OpenSSL to take the ASN1 value and turn it into something Ruby understands OpenSSL::X509::Extension.new(asn1_arr.first.value, asn1_val.to_der).value else asn1_val.value end end # Return the set of extensions requested on this CSR, in a form designed to # be useful to Ruby: an array of hashes. Which, not coincidentally, you can pass # successfully to the OpenSSL constructor later, if you want. # # @return [Array<Hash{String => String}>] An array of two or three element # hashes, with key/value pairs for the extension's oid, its value, and # optionally its critical state. def request_extensions raise Puppet::Error, _("CSR needs content to extract fields") unless @content # Prefer the standard extReq, but accept the Microsoft specific version as # a fallback, if the standard version isn't found. attribute = @content.attributes.find { |x| x.oid == "extReq" } attribute ||= @content.attributes.find { |x| x.oid == "msExtReq" } return [] unless attribute extensions = unpack_extension_request(attribute) index = -1 extensions.map do |ext_values| index += 1 value = ext_value_to_ruby_value(ext_values) # OK, turn that into an extension, to unpack the content. Lovely that # we have to swap the order of arguments to the underlying method, or # perhaps that the ASN.1 representation chose to pack them in a # strange order where the optional component comes *earlier* than the # fixed component in the sequence. case ext_values.length when 2 { "oid" => ext_values[0].value, "value" => value } when 3 { "oid" => ext_values[0].value, "value" => value, "critical" => ext_values[1].value } else raise Puppet::Error, _("In %{attr}, expected extension record %{index} to have two or three items, but found %{count}") % { attr: attribute.oid, index: index, count: ext_values.length } end end end def subject_alt_names @subject_alt_names ||= request_extensions .select { |x| x["oid"] == "subjectAltName" } .map { |x| x["value"].split(/\s*,\s*/) } .flatten .sort .uniq end # Return all user specified attributes attached to this CSR as a hash. IF an # OID has a single value it is returned as a string, otherwise all values are # returned as an array. # # The format of CSR attributes is specified in PKCS#10/RFC 2986 # # @see https://tools.ietf.org/html/rfc2986 "RFC 2986 Certification Request Syntax Specification" # # @api public # # @return [Hash<String, String>] def custom_attributes x509_attributes = @content.attributes.reject do |attr| PRIVATE_CSR_ATTRIBUTES.include? attr.oid end x509_attributes.map do |attr| { "oid" => attr.oid, "value" => attr.value.value.first.value } end end private # Exclude OIDs that may conflict with how Puppet creates CSRs. # # We only have nominal support for Microsoft extension requests, but since we # ultimately respect that field when looking for extension requests in a CSR # we need to prevent that field from being written to directly. PRIVATE_CSR_ATTRIBUTES = [ 'extReq', '1.2.840.113549.1.9.14', 'msExtReq', '1.3.6.1.4.1.311.2.1.14' ] def add_csr_attributes(csr, csr_attributes) csr_attributes.each do |oid, value| if PRIVATE_CSR_ATTRIBUTES.include? oid raise ArgumentError, _("Cannot specify CSR attribute %{oid}: conflicts with internally used CSR attribute") % { oid: oid } end encoded = OpenSSL::ASN1::PrintableString.new(value.to_s) attr_set = OpenSSL::ASN1::Set.new([encoded]) csr.add_attribute(OpenSSL::X509::Attribute.new(oid, attr_set)) Puppet.debug("Added csr attribute: #{oid} => #{attr_set.inspect}") rescue OpenSSL::X509::AttributeError => e raise Puppet::Error, _("Cannot create CSR with attribute %{oid}: %{message}") % { oid: oid, message: e.message }, e.backtrace end end PRIVATE_EXTENSIONS = [ 'subjectAltName', '2.5.29.17' ] # @api private def extension_request_attribute(options) extensions = [] if options[:extension_requests] options[:extension_requests].each_pair do |oid, value| if PRIVATE_EXTENSIONS.include? oid raise Puppet::Error, _("Cannot specify CSR extension request %{oid}: conflicts with internally used extension request") % { oid: oid } end ext = OpenSSL::X509::Extension.new(oid, OpenSSL::ASN1::UTF8String.new(value.to_s).to_der, false) extensions << ext rescue OpenSSL::X509::ExtensionError => e raise Puppet::Error, _("Cannot create CSR with extension request %{oid}: %{message}") % { oid: oid, message: e.message }, e.backtrace end end if options[:dns_alt_names] raw_names = options[:dns_alt_names].split(/\s*,\s*/).map(&:strip) + [name] parsed_names = raw_names.map do |name| if !name.start_with?("IP:") && !name.start_with?("DNS:") "DNS:#{name}" else name end end.sort.uniq.join(", ") alt_names_ext = extension_factory.create_extension("subjectAltName", parsed_names, false) extensions << alt_names_ext end unless extensions.empty? seq = OpenSSL::ASN1::Sequence(extensions) ext_req = OpenSSL::ASN1::Set([seq]) OpenSSL::X509::Attribute.new("extReq", ext_req) end end # Unpack the extReq attribute into an array of Extensions. # # The extension request attribute is structured like # `Set[Sequence[Extensions]]` where the outer Set only contains a single # sequence. # # In addition the Ruby implementation of ASN1 requires that all ASN1 values # contain a single value, so Sets and Sequence have to contain an array # that in turn holds the elements. This is why we have to unpack an array # every time we unpack a Set/Seq. # # @see https://tools.ietf.org/html/rfc2985#ref-10 5.4.2 CSR Extension Request structure # @see https://tools.ietf.org/html/rfc5280 4.1 Certificate Extension structure # # @api private # # @param attribute [OpenSSL::X509::Attribute] The X509 extension request # # @return [Array<Array<Object>>] A array of arrays containing the extension # OID the critical state if present, and the extension value. def unpack_extension_request(attribute) unless attribute.value.is_a? OpenSSL::ASN1::Set raise Puppet::Error, _("In %{attr}, expected Set but found %{klass}") % { attr: attribute.oid, klass: attribute.value.class } end unless attribute.value.value.is_a? Array raise Puppet::Error, _("In %{attr}, expected Set[Array] but found %{klass}") % { attr: attribute.oid, klass: attribute.value.value.class } end unless attribute.value.value.size == 1 raise Puppet::Error, _("In %{attr}, expected Set[Array] with one value but found %{count} elements") % { attr: attribute.oid, count: attribute.value.value.size } end unless attribute.value.value.first.is_a? OpenSSL::ASN1::Sequence raise Puppet::Error, _("In %{attr}, expected Set[Array[Sequence[...]]], but found %{klass}") % { attr: attribute.oid, klass: extension.class } end unless attribute.value.value.first.value.is_a? Array raise Puppet::Error, _("In %{attr}, expected Set[Array[Sequence[Array[...]]]], but found %{klass}") % { attr: attribute.oid, klass: extension.value.class } end extensions = attribute.value.value.first.value extensions.map(&:value) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/base.rb
lib/puppet/ssl/base.rb
# frozen_string_literal: true require_relative '../../puppet/ssl/openssl_loader' require_relative '../../puppet/ssl' require_relative '../../puppet/ssl/digest' # The base class for wrapping SSL instances. class Puppet::SSL::Base # For now, use the YAML separator. SEPARATOR = "\n---\n" # Only allow printing ascii characters, excluding / VALID_CERTNAME = /\A[ -.0-~]+\Z/ def self.from_multiple_s(text) text.split(SEPARATOR).collect { |inst| from_s(inst) } end def self.to_multiple_s(instances) instances.collect(&:to_s).join(SEPARATOR) end def self.wraps(klass) @wrapped_class = klass end def self.wrapped_class raise(Puppet::DevError, _("%{name} has not declared what class it wraps") % { name: self }) unless defined?(@wrapped_class) @wrapped_class end def self.validate_certname(name) raise _("Certname %{name} must not contain unprintable or non-ASCII characters") % { name: name.inspect } unless name =~ VALID_CERTNAME end attr_accessor :name, :content def generate raise Puppet::DevError, _("%{class_name} did not override 'generate'") % { class_name: self.class } end def initialize(name) @name = name.to_s.downcase self.class.validate_certname(@name) end ## # name_from_subject extracts the common name attribute from the subject of an # x.509 certificate certificate # # @api private # # @param [OpenSSL::X509::Name] subject The full subject (distinguished name) of the x.509 # certificate. # # @return [String] the name (CN) extracted from the subject. def self.name_from_subject(subject) if subject.respond_to? :to_a (subject.to_a.assoc('CN') || [])[1] end end # Create an instance of our Puppet::SSL::* class using a given instance of the wrapped class def self.from_instance(instance, name = nil) unless instance.is_a?(wrapped_class) raise ArgumentError, _("Object must be an instance of %{class_name}, %{actual_class} given") % { class_name: wrapped_class, actual_class: instance.class } end if name.nil? and !instance.respond_to?(:subject) raise ArgumentError, _("Name must be supplied if it cannot be determined from the instance") end name ||= name_from_subject(instance.subject) result = new(name) result.content = instance result end # Convert a string into an instance def self.from_s(string, name = nil) instance = wrapped_class.new(string) from_instance(instance, name) end # Read content from disk appropriately. def read(path) # applies to Puppet::SSL::Certificate, Puppet::SSL::CertificateRequest # nothing derives from Puppet::SSL::Certificate, but it is called by a number of other SSL Indirectors: # Puppet::Indirector::CertificateStatus::File (.indirection.find) # Puppet::Network::HTTP::WEBrick (.indirection.find) # Puppet::Network::HTTP::RackREST (.from_instance) # Puppet::Network::HTTP::WEBrickREST (.from_instance) # Puppet::SSL::Inventory (.indirection.search, implements its own add / rebuild / serials with encoding UTF8) @content = wrapped_class.new(Puppet::FileSystem.read(path, :encoding => Encoding::ASCII)) end # Convert our thing to pem. def to_s return "" unless content content.to_pem end def to_data_hash to_s end # Provide the full text of the thing we're dealing with. def to_text return "" unless content content.to_text end def fingerprint(md = :SHA256) mds = md.to_s.upcase digest(mds).to_hex end def digest(algorithm = nil) algorithm ||= digest_algorithm Puppet::SSL::Digest.new(algorithm, content.to_der) end def digest_algorithm # The signature_algorithm on the X509 cert is a combination of the digest # algorithm and the encryption algorithm # e.g. md5WithRSAEncryption, sha256WithRSAEncryption # Unfortunately there isn't a consistent pattern # See RFCs 3279, 5758 digest_re = Regexp.union( /ripemd160/i, /md[245]/i, /sha\d*/i ) ln = content.signature_algorithm match = digest_re.match(ln) if match match[0].downcase else raise Puppet::Error, _("Unknown signature algorithm '%{ln}'") % { ln: ln } end end private def wrapped_class self.class.wrapped_class end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/ssl_provider.rb
lib/puppet/ssl/ssl_provider.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' # SSL Provider creates `SSLContext` objects that can be used to create # secure connections. # # @example To load an SSLContext from an existing private key and related certs/crls: # ssl_context = provider.load_context # # @example To load an SSLContext from an existing password-protected private key and related certs/crls: # ssl_context = provider.load_context(password: 'opensesame') # # @example To create an SSLContext from in-memory certs and keys: # cacerts = [<OpenSSL::X509::Certificate>] # crls = [<OpenSSL::X509::CRL>] # key = <OpenSSL::X509::PKey> # cert = <OpenSSL::X509::Certificate> # ssl_context = provider.create_context(cacerts: cacerts, crls: crls, private_key: key, client_cert: cert) # # @example To create an SSLContext to connect to non-puppet HTTPS servers: # cacerts = [<OpenSSL::X509::Certificate>] # ssl_context = provider.create_root_context(cacerts: cacerts) # # @api private class Puppet::SSL::SSLProvider # Create an insecure `SSLContext`. Connections made from the returned context # will not authenticate the server, i.e. `VERIFY_NONE`, and are vulnerable to # MITM. Do not call this method. # # @return [Puppet::SSL::SSLContext] A context to use to create connections # @api private def create_insecure_context store = create_x509_store([], [], false) Puppet::SSL::SSLContext.new(store: store, verify_peer: false).freeze end # Create an `SSLContext` using the trusted `cacerts` and optional `crls`. # Connections made from the returned context will authenticate the server, # i.e. `VERIFY_PEER`, but will not use a client certificate. # # The `crls` parameter must contain CRLs corresponding to each CA in `cacerts` # depending on the `revocation` mode. See {#create_context}. # # @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs # @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs # @param revocation [:chain, :leaf, false] revocation mode # @return [Puppet::SSL::SSLContext] A context to use to create connections # @raise (see #create_context) # @api private def create_root_context(cacerts:, crls: [], revocation: Puppet[:certificate_revocation]) store = create_x509_store(cacerts, crls, revocation) Puppet::SSL::SSLContext.new(store: store, cacerts: cacerts, crls: crls, revocation: revocation).freeze end # Create an `SSLContext` using the trusted `cacerts` and any certs in OpenSSL's # default verify path locations. When running puppet as a gem, the location is # system dependent. When running puppet from puppet-agent packages, the location # refers to the cacerts bundle in the puppet-agent package. # # Connections made from the returned context will authenticate the server, # i.e. `VERIFY_PEER`, but will not use a client certificate (unless requested) # and will not perform revocation checking. # # @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs # @param path [String, nil] A file containing additional trusted CA certs. # @param include_client_cert [true, false] If true, the client cert will be added to the context # allowing mutual TLS authentication. The default is false. If the client cert doesn't exist # then the option will be ignored. # @return [Puppet::SSL::SSLContext] A context to use to create connections # @raise (see #create_context) # @api private def create_system_context(cacerts:, path: Puppet[:ssl_trust_store], include_client_cert: false) store = create_x509_store(cacerts, [], false, include_system_store: true) if path stat = Puppet::FileSystem.stat(path) if stat if stat.ftype == 'file' # don't add empty files as ruby/openssl will raise if stat.size > 0 begin store.add_file(path) rescue => e Puppet.err(_("Failed to add '%{path}' as a trusted CA file: %{detail}" % { path: path, detail: e.message }, e)) end end else Puppet.warning(_("The 'ssl_trust_store' setting does not refer to a file and will be ignored: '%{path}'" % { path: path })) end end end if include_client_cert cert_provider = Puppet::X509::CertProvider.new private_key = cert_provider.load_private_key(Puppet[:certname], required: false) unless private_key Puppet.warning("Private key for '#{Puppet[:certname]}' does not exist") end client_cert = cert_provider.load_client_cert(Puppet[:certname], required: false) unless client_cert Puppet.warning("Client certificate for '#{Puppet[:certname]}' does not exist") end if private_key && client_cert client_chain = resolve_client_chain(store, client_cert, private_key) return Puppet::SSL::SSLContext.new( store: store, cacerts: cacerts, crls: [], private_key: private_key, client_cert: client_cert, client_chain: client_chain, revocation: false ).freeze end end Puppet::SSL::SSLContext.new(store: store, cacerts: cacerts, crls: [], revocation: false).freeze end # Create an `SSLContext` using the trusted `cacerts`, `crls`, `private_key`, # `client_cert`, and `revocation` mode. Connections made from the returned # context will be mutually authenticated. # # The `crls` parameter must contain CRLs corresponding to each CA in `cacerts` # depending on the `revocation` mode: # # * `:chain` - `crls` must contain a CRL for every CA in `cacerts` # * `:leaf` - `crls` must contain (at least) the CRL for the leaf CA in `cacerts` # * `false` - `crls` can be empty # # The `private_key` and public key from the `client_cert` must match. # # @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs # @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs # @param private_key [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] client's private key # @param client_cert [OpenSSL::X509::Certificate] client's cert whose public # key matches the `private_key` # @param revocation [:chain, :leaf, false] revocation mode # @param include_system_store [true, false] Also trust system CA # @return [Puppet::SSL::SSLContext] A context to use to create connections # @raise [Puppet::SSL::CertVerifyError] There was an issue with # one of the certs or CRLs. # @raise [Puppet::SSL::SSLError] There was an issue with the # `private_key`. # @api private def create_context(cacerts:, crls:, private_key:, client_cert:, revocation: Puppet[:certificate_revocation], include_system_store: false) raise ArgumentError, _("CA certs are missing") unless cacerts raise ArgumentError, _("CRLs are missing") unless crls raise ArgumentError, _("Private key is missing") unless private_key raise ArgumentError, _("Client cert is missing") unless client_cert store = create_x509_store(cacerts, crls, revocation, include_system_store: include_system_store) client_chain = resolve_client_chain(store, client_cert, private_key) Puppet::SSL::SSLContext.new( store: store, cacerts: cacerts, crls: crls, private_key: private_key, client_cert: client_cert, client_chain: client_chain, revocation: revocation ).freeze end # Load an `SSLContext` using available certs and keys. An exception is raised # if any component is missing or is invalid, such as a mismatched client cert # and private key. Connections made from the returned context will be mutually # authenticated. # # @param certname [String] Which cert & key to load # @param revocation [:chain, :leaf, false] revocation mode # @param password [String, nil] If the private key is encrypted, decrypt # it using the password. If the key is encrypted, but a password is # not specified, then the key cannot be loaded. # @param include_system_store [true, false] Also trust system CA # @return [Puppet::SSL::SSLContext] A context to use to create connections # @raise [Puppet::SSL::CertVerifyError] There was an issue with # one of the certs or CRLs. # @raise [Puppet::Error] There was an issue with one of the required components. # @api private def load_context(certname: Puppet[:certname], revocation: Puppet[:certificate_revocation], password: nil, include_system_store: false) cert = Puppet::X509::CertProvider.new cacerts = cert.load_cacerts(required: true) crls = case revocation when :chain, :leaf cert.load_crls(required: true) else [] end private_key = cert.load_private_key(certname, required: true, password: password) client_cert = cert.load_client_cert(certname, required: true) create_context(cacerts: cacerts, crls: crls, private_key: private_key, client_cert: client_cert, revocation: revocation, include_system_store: include_system_store) rescue OpenSSL::PKey::PKeyError => e raise Puppet::SSL::SSLError.new(_("Failed to load private key for host '%{name}': %{message}") % { name: certname, message: e.message }, e) end # Verify the `csr` was signed with a private key corresponding to the # `public_key`. This ensures the CSR was signed by someone in possession # of the private key, and that it hasn't been tampered with since. # # @param csr [OpenSSL::X509::Request] certificate signing request # @param public_key [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] public key # @raise [Puppet::SSL:SSLError] The private_key for the given `public_key` was # not used to sign the CSR. # @api private def verify_request(csr, public_key) unless csr.verify(public_key) raise Puppet::SSL::SSLError, _("The CSR for host '%{name}' does not match the public key") % { name: subject(csr) } end csr end def print(ssl_context, alg = 'SHA256') if Puppet::Util::Log.sendlevel?(:debug) chain = ssl_context.client_chain # print from root to client chain.reverse.each_with_index do |cert, i| digest = Puppet::SSL::Digest.new(alg, cert.to_der) if i == chain.length - 1 Puppet.debug(_("Verified client certificate '%{subject}' fingerprint %{digest}") % { subject: cert.subject.to_utf8, digest: digest }) else Puppet.debug(_("Verified CA certificate '%{subject}' fingerprint %{digest}") % { subject: cert.subject.to_utf8, digest: digest }) end end ssl_context.crls.each do |crl| oid_values = crl.extensions.to_h { |ext| [ext.oid, ext.value] } crlNumber = oid_values['crlNumber'] || 'unknown' authKeyId = (oid_values['authorityKeyIdentifier'] || 'unknown').chomp Puppet.debug("Using CRL '#{crl.issuer.to_utf8}' authorityKeyIdentifier '#{authKeyId}' crlNumber '#{crlNumber}'") end end end private def default_flags # checking the signature of the self-signed cert doesn't add any security, # but it's a sanity check to make sure the cert isn't corrupt. This option # is not available in JRuby's OpenSSL library. if defined?(OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE) OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE else 0 end end def create_x509_store(roots, crls, revocation, include_system_store: false) store = OpenSSL::X509::Store.new store.purpose = OpenSSL::X509::PURPOSE_ANY store.flags = default_flags | revocation_mode(revocation) roots.each { |cert| store.add_cert(cert) } crls.each { |crl| store.add_crl(crl) } store.set_default_paths if include_system_store store end def subject(x509) x509.subject.to_utf8 end def issuer(x509) x509.issuer.to_utf8 end def revocation_mode(mode) case mode when false 0 when :leaf OpenSSL::X509::V_FLAG_CRL_CHECK else # :chain is the default OpenSSL::X509::V_FLAG_CRL_CHECK | OpenSSL::X509::V_FLAG_CRL_CHECK_ALL end end def resolve_client_chain(store, client_cert, private_key) client_chain = verify_cert_with_store(store, client_cert) if !private_key.is_a?(OpenSSL::PKey::RSA) && !private_key.is_a?(OpenSSL::PKey::EC) raise Puppet::SSL::SSLError, _("Unsupported key '%{type}'") % { type: private_key.class.name } end unless client_cert.check_private_key(private_key) raise Puppet::SSL::SSLError, _("The certificate for '%{name}' does not match its private key") % { name: subject(client_cert) } end client_chain end def verify_cert_with_store(store, cert) # StoreContext#initialize accepts a chain argument, but it's set to [] because # puppet requires any intermediate CA certs needed to complete the client's # chain to be in the CA bundle that we downloaded from the server, and # they've already been added to the store. See PUP-9500. store_context = OpenSSL::X509::StoreContext.new(store, cert, []) unless store_context.verify current_cert = store_context.current_cert # If the client cert's intermediate CA is not in the CA bundle, then warn, # but don't error, because SSL allows the client to send an incomplete # chain, and have the server resolve it. if store_context.error == OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY Puppet.warning _("The issuer '%{issuer}' of certificate '%{subject}' cannot be found locally") % { issuer: issuer(current_cert), subject: subject(current_cert) } else raise_cert_verify_error(store_context, current_cert) end end # resolved chain from leaf to root store_context.chain end def raise_cert_verify_error(store_context, current_cert) message = case store_context.error when OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID _("The certificate '%{subject}' is not yet valid, verify time is synchronized") % { subject: subject(current_cert) } when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED _("The certificate '%{subject}' has expired, verify time is synchronized") % { subject: subject(current_cert) } when OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID _("The CRL issued by '%{issuer}' is not yet valid, verify time is synchronized") % { issuer: issuer(current_cert) } when OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED _("The CRL issued by '%{issuer}' has expired, verify time is synchronized") % { issuer: issuer(current_cert) } when OpenSSL::X509::V_ERR_CERT_SIGNATURE_FAILURE _("Invalid signature for certificate '%{subject}'") % { subject: subject(current_cert) } when OpenSSL::X509::V_ERR_CRL_SIGNATURE_FAILURE _("Invalid signature for CRL issued by '%{issuer}'") % { issuer: issuer(current_cert) } when OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT _("The issuer '%{issuer}' of certificate '%{subject}' is missing") % { issuer: issuer(current_cert), subject: subject(current_cert) } when OpenSSL::X509::V_ERR_UNABLE_TO_GET_CRL _("The CRL issued by '%{issuer}' is missing") % { issuer: issuer(current_cert) } when OpenSSL::X509::V_ERR_CERT_REVOKED _("Certificate '%{subject}' is revoked") % { subject: subject(current_cert) } else # error_string is labeled ASCII-8BIT, but is encoded based on Encoding.default_external err_utf8 = Puppet::Util::CharacterEncoding.convert_to_utf_8(store_context.error_string) _("Certificate '%{subject}' failed verification (%{err}): %{err_utf8}") % { subject: subject(current_cert), err: store_context.error, err_utf8: err_utf8 } end raise Puppet::SSL::CertVerifyError.new(message, store_context.error, current_cert) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/openssl_loader.rb
lib/puppet/ssl/openssl_loader.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' # This file should be required instead of writing `require 'openssl'` # or any library that loads openssl like `net/https`. This allows the # core Puppet code to load correctly in JRuby environments that do not # have a functioning openssl (eg a FIPS enabled one). if Puppet::Util::Platform.jruby_fips? # Even in JRuby we need to define the constants that are wrapped in # Indirections: Puppet::SSL::{Key, Certificate, CertificateRequest} module OpenSSL module PKey class RSA; end end module X509 class Request; end class Certificate; end end end else require 'openssl' require 'net/https' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/certificate_request_attributes.rb
lib/puppet/ssl/certificate_request_attributes.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' require_relative '../../puppet/util/yaml' # This class transforms simple key/value pairs into the equivalent ASN1 # structures. Values may be strings or arrays of strings. # # @api private class Puppet::SSL::CertificateRequestAttributes attr_reader :path, :custom_attributes, :extension_requests def initialize(path) @path = path @custom_attributes = {} @extension_requests = {} end # Attempt to load a yaml file at the given @path. # @return true if we are able to load the file, false otherwise # @raise [Puppet::Error] if there are unexpected attribute keys def load Puppet.info(_("csr_attributes file loading from %{path}") % { path: path }) if Puppet::FileSystem.exist?(path) hash = Puppet::Util::Yaml.safe_load_file(path, [Symbol]) || {} unless hash.is_a?(Hash) raise Puppet::Error, _("invalid CSR attributes, expected instance of Hash, received instance of %{klass}") % { klass: hash.class } end @custom_attributes = hash.delete('custom_attributes') || {} @extension_requests = hash.delete('extension_requests') || {} unless hash.keys.empty? raise Puppet::Error, _("unexpected attributes %{keys} in %{path}") % { keys: hash.keys.inspect, path: @path.inspect } end return true end false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/certificate_signer.rb
lib/puppet/ssl/certificate_signer.rb
# frozen_string_literal: true # Take care of signing a certificate in a FIPS 140-2 compliant manner. # # @see https://projects.puppetlabs.com/issues/17295 # # @api private class Puppet::SSL::CertificateSigner # @!attribute [r] digest # @return [OpenSSL::Digest] attr_reader :digest def initialize if OpenSSL::Digest.const_defined?('SHA256') @digest = OpenSSL::Digest::SHA256 elsif OpenSSL::Digest.const_defined?('SHA1') @digest = OpenSSL::Digest::SHA1 elsif OpenSSL::Digest.const_defined?('SHA512') @digest = OpenSSL::Digest::SHA512 elsif OpenSSL::Digest.const_defined?('SHA384') @digest = OpenSSL::Digest::SHA384 elsif OpenSSL::Digest.const_defined?('SHA224') @digest = OpenSSL::Digest::SHA224 else raise Puppet::Error, "No FIPS 140-2 compliant digest algorithm in OpenSSL::Digest" end end # Sign a certificate signing request (CSR) with a private key. # # @param [OpenSSL::X509::Request] content The CSR to sign # @param [OpenSSL::X509::PKey] key The private key to sign with # # @api private def sign(content, key) content.sign(key, @digest.new) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/error.rb
lib/puppet/ssl/error.rb
# frozen_string_literal: true module Puppet::SSL class SSLError < Puppet::Error; end class CertVerifyError < Puppet::SSL::SSLError attr_reader :code, :cert def initialize(message, code, cert) super(message) @code = code @cert = cert end end class CertMismatchError < Puppet::SSL::SSLError def initialize(peer_cert, host) valid_certnames = [peer_cert.subject.to_utf8.sub(/.*=/, ''), *Puppet::SSL::Certificate.subject_alt_names_for(peer_cert)].uniq if valid_certnames.size > 1 expected_certnames = _("expected one of %{certnames}") % { certnames: valid_certnames.join(', ') } else expected_certnames = _("expected %{certname}") % { certname: valid_certnames.first } end super(_("Server hostname '%{host}' did not match server certificate; %{expected_certnames}") % { host: host, expected_certnames: expected_certnames }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/certificate.rb
lib/puppet/ssl/certificate.rb
# frozen_string_literal: true require_relative '../../puppet/ssl/base' # Manage certificates themselves. This class has no # 'generate' method because the CA is responsible # for turning CSRs into certificates; we can only # retrieve them from the CA (or not, as is often # the case). # # @deprecated Use {Puppet::SSL::SSLProvider} instead. class Puppet::SSL::Certificate < Puppet::SSL::Base # This is defined from the base class wraps OpenSSL::X509::Certificate # Because of how the format handler class is included, this # can't be in the base class. def self.supported_formats [:s] end def self.subject_alt_names_for(cert) alts = cert.extensions.find { |ext| ext.oid == "subjectAltName" } return [] unless alts alts.value.split(/\s*,\s*/) end def subject_alt_names self.class.subject_alt_names_for(content) end def expiration return nil unless content content.not_after end # This name is what gets extracted from the subject before being passed # to the constructor, so it's not downcased def unmunged_name self.class.name_from_subject(content.subject.to_utf8) end # Any extensions registered with custom OIDs as defined in module # Puppet::SSL::Oids may be looked up here. # # A cert with a 'pp_uuid' extension having the value 'abcd' would return: # # [{ 'oid' => 'pp_uuid', 'value' => 'abcd'}] # # @return [Array<Hash{String => String}>] An array of two element hashes, # with key/value pairs for the extension's oid, and its value. def custom_extensions custom_exts = content.extensions.select do |ext| Puppet::SSL::Oids.subtree_of?('ppRegCertExt', ext.oid) or Puppet::SSL::Oids.subtree_of?('ppPrivCertExt', ext.oid) or Puppet::SSL::Oids.subtree_of?('ppAuthCertExt', ext.oid) end custom_exts.map do |ext| { 'oid' => ext.oid, 'value' => get_ext_val(ext.oid) } end end private # Extract the extensions sequence from the wrapped certificate's raw ASN.1 form def exts_seq # See RFC-2459 section 4.1 (https://tools.ietf.org/html/rfc2459#section-4.1) # to see where this is defined. Essentially this is saying "in the first # sequence in the certificate, find the item that's tagged with 3. This # is where the extensions are stored." @extensions_tag ||= 3 @exts_seq ||= OpenSSL::ASN1.decode(content.to_der).value[0].value.find do |data| (data.tag == @extensions_tag) && (data.tag_class == :CONTEXT_SPECIFIC) end.value[0] end # Get the DER parsed value of an X.509 extension by it's OID, or short name # if one has been registered with OpenSSL. def get_ext_val(oid) ext_obj = exts_seq.value.find do |ext_seq| ext_seq.value[0].value == oid end raw_val = ext_obj.value.last.value begin OpenSSL::ASN1.decode(raw_val).value rescue OpenSSL::ASN1::ASN1Error # This is required to maintain backward compatibility with the previous # way trusted facts were signed. See PUP-3560 raw_val end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ssl/oids.rb
lib/puppet/ssl/oids.rb
# frozen_string_literal: true require_relative '../../puppet/ssl' # This module defines OIDs for use within Puppet. # # # ASN.1 Definition # # The following is the formal definition of OIDs specified in this file. # # ``` # puppetCertExtensions OBJECT IDENTIFIER ::= {iso(1) identified-organization(3) # dod(6) internet(1) private(4) enterprise(1) 34380 1} # # -- the tree under registeredExtensions 'belongs' to puppetlabs # -- privateExtensions can be extended by enterprises to suit their own needs # registeredExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 1 } # privateExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 2 } # authorizationExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 3 } # # -- subtree of common registered extensions # -- The short names for these OIDs are intentionally lowercased and formatted # -- since they may be exposed inside the Puppet DSL as variables. # pp_uuid OBJECT IDENTIFIER ::= { registeredExtensions 1 } # pp_instance_id OBJECT IDENTIFIER ::= { registeredExtensions 2 } # pp_image_name OBJECT IDENTIFIER ::= { registeredExtensions 3 } # pp_preshared_key OBJECT IDENTIFIER ::= { registeredExtensions 4 } # ``` # # @api private module Puppet::SSL::Oids # Note: When updating the following OIDs make sure to also update the OID # definitions here: # https://github.com/puppetlabs/puppetserver/blob/master/src/clj/puppetlabs/puppetserver/certificate_authority.clj#L122-L159 PUPPET_OIDS = [ ["1.3.6.1.4.1.34380", 'puppetlabs', 'Puppet Labs'], ["1.3.6.1.4.1.34380.1", 'ppCertExt', 'Puppet Certificate Extension'], ["1.3.6.1.4.1.34380.1.1", 'ppRegCertExt', 'Puppet Registered Certificate Extension'], ["1.3.6.1.4.1.34380.1.1.1", 'pp_uuid', 'Puppet Node UUID'], ["1.3.6.1.4.1.34380.1.1.2", 'pp_instance_id', 'Puppet Node Instance ID'], ["1.3.6.1.4.1.34380.1.1.3", 'pp_image_name', 'Puppet Node Image Name'], ["1.3.6.1.4.1.34380.1.1.4", 'pp_preshared_key', 'Puppet Node Preshared Key'], ["1.3.6.1.4.1.34380.1.1.5", 'pp_cost_center', 'Puppet Node Cost Center Name'], ["1.3.6.1.4.1.34380.1.1.6", 'pp_product', 'Puppet Node Product Name'], ["1.3.6.1.4.1.34380.1.1.7", 'pp_project', 'Puppet Node Project Name'], ["1.3.6.1.4.1.34380.1.1.8", 'pp_application', 'Puppet Node Application Name'], ["1.3.6.1.4.1.34380.1.1.9", 'pp_service', 'Puppet Node Service Name'], ["1.3.6.1.4.1.34380.1.1.10", 'pp_employee', 'Puppet Node Employee Name'], ["1.3.6.1.4.1.34380.1.1.11", 'pp_created_by', 'Puppet Node created_by Tag'], ["1.3.6.1.4.1.34380.1.1.12", 'pp_environment', 'Puppet Node Environment Name'], ["1.3.6.1.4.1.34380.1.1.13", 'pp_role', 'Puppet Node Role Name'], ["1.3.6.1.4.1.34380.1.1.14", 'pp_software_version', 'Puppet Node Software Version'], ["1.3.6.1.4.1.34380.1.1.15", 'pp_department', 'Puppet Node Department Name'], ["1.3.6.1.4.1.34380.1.1.16", 'pp_cluster', 'Puppet Node Cluster Name'], ["1.3.6.1.4.1.34380.1.1.17", 'pp_provisioner', 'Puppet Node Provisioner Name'], ["1.3.6.1.4.1.34380.1.1.18", 'pp_region', 'Puppet Node Region Name'], ["1.3.6.1.4.1.34380.1.1.19", 'pp_datacenter', 'Puppet Node Datacenter Name'], ["1.3.6.1.4.1.34380.1.1.20", 'pp_zone', 'Puppet Node Zone Name'], ["1.3.6.1.4.1.34380.1.1.21", 'pp_network', 'Puppet Node Network Name'], ["1.3.6.1.4.1.34380.1.1.22", 'pp_securitypolicy', 'Puppet Node Security Policy Name'], ["1.3.6.1.4.1.34380.1.1.23", 'pp_cloudplatform', 'Puppet Node Cloud Platform Name'], ["1.3.6.1.4.1.34380.1.1.24", 'pp_apptier', 'Puppet Node Application Tier'], ["1.3.6.1.4.1.34380.1.1.25", 'pp_hostname', 'Puppet Node Hostname'], ["1.3.6.1.4.1.34380.1.1.26", 'pp_owner', 'Puppet Node Owner'], ["1.3.6.1.4.1.34380.1.2", 'ppPrivCertExt', 'Puppet Private Certificate Extension'], ["1.3.6.1.4.1.34380.1.3", 'ppAuthCertExt', 'Puppet Certificate Authorization Extension'], ["1.3.6.1.4.1.34380.1.3.1", 'pp_authorization', 'Certificate Extension Authorization'], ["1.3.6.1.4.1.34380.1.3.2", 'pp_auth_auto_renew', 'Auto-Renew Certificate Attribute'], ["1.3.6.1.4.1.34380.1.3.13", 'pp_auth_role', 'Puppet Node Role Name for Authorization'], ["1.3.6.1.4.1.34380.1.3.39", 'pp_cli_auth', 'Puppetserver CA CLI Authorization'] ] @did_register_puppet_oids = false # Register our custom Puppet OIDs with OpenSSL so they can be used as CSR # extensions. Without registering these OIDs, OpenSSL will fail when it # encounters such an extension in a CSR. def self.register_puppet_oids unless @did_register_puppet_oids PUPPET_OIDS.each do |oid_defn| OpenSSL::ASN1::ObjectId.register(*oid_defn) end @did_register_puppet_oids = true end end # Parse custom OID mapping file that enables custom OIDs to be resolved # into user-friendly names. # # @param custom_oid_file [String] File to obtain custom OIDs mapping from # @param map_key [String] Hash key in which custom OIDs mapping is stored # # @example Custom OID mapping file # --- # oid_mapping: # '1.3.6.1.4.1.34380.1.2.1.1': # shortname : 'myshortname' # longname : 'Long name' # '1.3.6.1.4.1.34380.1.2.1.2': # shortname: 'myothershortname' # longname: 'Other Long name' def self.parse_custom_oid_file(custom_oid_file, map_key = 'oid_mapping') if File.exist?(custom_oid_file) && File.readable?(custom_oid_file) mapping = nil begin mapping = Puppet::Util::Yaml.safe_load_file(custom_oid_file, [Symbol]) rescue => err raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': %{err}") % { custom_oid_file: custom_oid_file, err: err }, err.backtrace end unless mapping.has_key?(map_key) raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': no such index '%{map_key}'") % { custom_oid_file: custom_oid_file, map_key: map_key } end unless mapping[map_key].is_a?(Hash) raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': data under index '%{map_key}' must be a Hash") % { custom_oid_file: custom_oid_file, map_key: map_key } end oid_defns = [] mapping[map_key].keys.each do |oid| shortname, longname = mapping[map_key][oid].values_at("shortname", "longname") if shortname.nil? || longname.nil? raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': incomplete definition of oid '%{oid}'") % { custom_oid_file: custom_oid_file, oid: oid } end oid_defns << [oid, shortname, longname] end oid_defns end end # Load custom OID mapping file that enables custom OIDs to be resolved # into user-friendly names. # # @param custom_oid_file [String] File to obtain custom OIDs mapping from # @param map_key [String] Hash key in which custom OIDs mapping is stored # # @example Custom OID mapping file # --- # oid_mapping: # '1.3.6.1.4.1.34380.1.2.1.1': # shortname : 'myshortname' # longname : 'Long name' # '1.3.6.1.4.1.34380.1.2.1.2': # shortname: 'myothershortname' # longname: 'Other Long name' def self.load_custom_oid_file(custom_oid_file, map_key = 'oid_mapping') oid_defns = parse_custom_oid_file(custom_oid_file, map_key) unless oid_defns.nil? begin oid_defns.each do |oid_defn| OpenSSL::ASN1::ObjectId.register(*oid_defn) end rescue => err raise ArgumentError, _("Error registering ssl custom OIDs mapping from file '%{custom_oid_file}': %{err}") % { custom_oid_file: custom_oid_file, err: err }, err.backtrace end end end # Determine if the first OID contains the second OID # # @param first [String] The containing OID, in dotted form or as the short name # @param second [String] The contained OID, in dotted form or as the short name # @param exclusive [true, false] If an OID should not be considered as a subtree of itself # # @example Comparing two dotted OIDs # Puppet::SSL::Oids.subtree_of?('1.3.6.1', '1.3.6.1.4.1') #=> true # Puppet::SSL::Oids.subtree_of?('1.3.6.1', '1.3.6') #=> false # # @example Comparing an OID short name with a dotted OID # Puppet::SSL::Oids.subtree_of?('IANA', '1.3.6.1.4.1') #=> true # Puppet::SSL::Oids.subtree_of?('1.3.6.1', 'enterprises') #=> true # # @example Comparing an OID against itself # Puppet::SSL::Oids.subtree_of?('IANA', 'IANA') #=> true # Puppet::SSL::Oids.subtree_of?('IANA', 'IANA', true) #=> false # # @return [true, false] def self.subtree_of?(first, second, exclusive = false) first_oid = OpenSSL::ASN1::ObjectId.new(first).oid second_oid = OpenSSL::ASN1::ObjectId.new(second).oid if exclusive and first_oid == second_oid false else second_oid.index(first_oid) == 0 end rescue OpenSSL::ASN1::ASN1Error, TypeError false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/posix.rb
lib/puppet/ffi/posix.rb
# frozen_string_literal: true require 'ffi' module Puppet module FFI module POSIX require_relative 'posix/functions' require_relative 'posix/constants' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/windows.rb
lib/puppet/ffi/windows.rb
# frozen_string_literal: true require 'ffi' module Puppet module FFI module Windows require_relative 'windows/api_types' require_relative 'windows/constants' require_relative 'windows/structs' require_relative 'windows/functions' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/posix/constants.rb
lib/puppet/ffi/posix/constants.rb
# frozen_string_literal: true require_relative '../../../puppet/ffi/posix' module Puppet::FFI::POSIX module Constants extend FFI::Library # Maximum number of supplementary groups (groups # that a user can be in plus its primary group) # (64 + 1 primary group) # Chosen a reasonable middle number from the list # https://www.j3e.de/ngroups.html MAXIMUM_NUMBER_OF_GROUPS = 65 end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/posix/functions.rb
lib/puppet/ffi/posix/functions.rb
# frozen_string_literal: true require_relative '../../../puppet/ffi/posix' module Puppet::FFI::POSIX module Functions extend FFI::Library ffi_convention :stdcall # https://man7.org/linux/man-pages/man3/getgrouplist.3.html # int getgrouplist ( # const char *user, # gid_t group, # gid_t *groups, # int *ngroups # ); begin ffi_lib FFI::Library::LIBC attach_function :getgrouplist, [:string, :uint, :pointer, :pointer], :int rescue FFI::NotFoundError # Do nothing end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/windows/api_types.rb
lib/puppet/ffi/windows/api_types.rb
# frozen_string_literal: true require_relative '../../../puppet/ffi/windows' require_relative '../../../puppet/util/windows/string' module Puppet::FFI::Windows module APITypes module ::FFI WIN32_FALSE = 0 # standard Win32 error codes ERROR_SUCCESS = 0 end module ::FFI::Library # Wrapper method for attach_function + private def attach_function_private(*args) attach_function(*args) private args[0] end end class ::FFI::Pointer NULL_HANDLE = 0 WCHAR_NULL = String.new("\0\0").force_encoding('UTF-16LE').freeze def self.from_string_to_wide_string(str, &block) str = Puppet::Util::Windows::String.wide_string(str) FFI::MemoryPointer.from_wide_string(str, &block) # ptr has already had free called, so nothing to return nil end def read_win32_bool # BOOL is always a 32-bit integer in Win32 # some Win32 APIs return 1 for true, while others are non-0 read_int32 != FFI::WIN32_FALSE end alias_method :read_dword, :read_uint32 alias_method :read_win32_ulong, :read_uint32 alias_method :read_qword, :read_uint64 alias_method :read_hresult, :read_int32 def read_handle type_size == 4 ? read_uint32 : read_uint64 end alias_method :read_wchar, :read_uint16 alias_method :read_word, :read_uint16 alias_method :read_array_of_wchar, :read_array_of_uint16 def read_wide_string(char_length, dst_encoding = Encoding::UTF_8, strip = false, encode_options = {}) # char_length is number of wide chars (typically excluding NULLs), *not* bytes str = get_bytes(0, char_length * 2).force_encoding('UTF-16LE') if strip i = str.index(WCHAR_NULL) str = str[0, i] if i end str.encode(dst_encoding, str.encoding, **encode_options) rescue EncodingError => e Puppet.debug { "Unable to convert value #{str.nil? ? 'nil' : str.dump} to encoding #{dst_encoding} due to #{e.inspect}" } raise end # @param max_char_length [Integer] Maximum number of wide chars to return (typically excluding NULLs), *not* bytes # @param null_terminator [Symbol] Number of number of null wchar characters, *not* bytes, that determine the end of the string # null_terminator = :single_null, then the terminating sequence is two bytes of zero. This is UNIT16 = 0 # null_terminator = :double_null, then the terminating sequence is four bytes of zero. This is UNIT32 = 0 # @param encode_options [Hash] Accepts the same option hash that may be passed to String#encode in Ruby def read_arbitrary_wide_string_up_to(max_char_length = 512, null_terminator = :single_null, encode_options = {}) idx = case null_terminator when :single_null # find index of wide null between 0 and max (exclusive) (0...max_char_length).find do |i| get_uint16(i * 2) == 0 end when :double_null # find index of double-wide null between 0 and max - 1 (exclusive) (0...max_char_length - 1).find do |i| get_uint32(i * 2) == 0 end else raise _("Unable to read wide strings with %{null_terminator} terminal nulls") % { null_terminator: null_terminator } end read_wide_string(idx || max_char_length, Encoding::UTF_8, false, encode_options) end def read_win32_local_pointer(&block) ptr = read_pointer begin yield ptr ensure if !ptr.null? && FFI::WIN32::LocalFree(ptr.address) != FFI::Pointer::NULL_HANDLE Puppet.debug "LocalFree memory leak" end end # ptr has already had LocalFree called, so nothing to return nil end def read_com_memory_pointer(&block) ptr = read_pointer begin yield ptr ensure FFI::WIN32::CoTaskMemFree(ptr) unless ptr.null? end # ptr has already had CoTaskMemFree called, so nothing to return nil end alias_method :write_dword, :write_uint32 alias_method :write_word, :write_uint16 end class FFI::MemoryPointer # Return a MemoryPointer that points to wide string. This is analogous to the # FFI::MemoryPointer.from_string method. def self.from_wide_string(wstr) ptr = FFI::MemoryPointer.new(:uchar, wstr.bytesize + 2) ptr.put_array_of_uchar(0, wstr.bytes.to_a) ptr.put_uint16(wstr.bytesize, 0) yield ptr if block_given? ptr end end # FFI Types # https://github.com/ffi/ffi/wiki/Types # Windows - Common Data Types # https://msdn.microsoft.com/en-us/library/cc230309.aspx # Windows Data Types # https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx FFI.typedef :uint16, :word FFI.typedef :uint32, :dword # uintptr_t is defined in an FFI conf as platform specific, either # ulong_long on x64 or just ulong on x86 FFI.typedef :uintptr_t, :handle FFI.typedef :uintptr_t, :hwnd # buffer_inout is similar to pointer (platform specific), but optimized for buffers FFI.typedef :buffer_inout, :lpwstr # buffer_in is similar to pointer (platform specific), but optimized for CONST read only buffers FFI.typedef :buffer_in, :lpcwstr FFI.typedef :buffer_in, :lpcolestr # string is also similar to pointer, but should be used for const char * # NOTE that this is not wide, useful only for A suffixed functions FFI.typedef :string, :lpcstr # pointer in FFI is platform specific # NOTE: for API calls with reserved lpvoid parameters, pass a FFI::Pointer::NULL FFI.typedef :pointer, :lpcvoid FFI.typedef :pointer, :lpvoid FFI.typedef :pointer, :lpword FFI.typedef :pointer, :lpbyte FFI.typedef :pointer, :lpdword FFI.typedef :pointer, :pdword FFI.typedef :pointer, :phandle FFI.typedef :pointer, :ulong_ptr FFI.typedef :pointer, :pbool FFI.typedef :pointer, :lpunknown # any time LONG / ULONG is in a win32 API definition DO NOT USE platform specific width # which is what FFI uses by default # instead create new aliases for these very special cases # NOTE: not a good idea to redefine FFI :ulong since other typedefs may rely on it FFI.typedef :uint32, :win32_ulong FFI.typedef :int32, :win32_long # FFI bool can be only 1 byte at times, # Win32 BOOL is a signed int, and is always 4 bytes, even on x64 # https://blogs.msdn.com/b/oldnewthing/archive/2011/03/28/10146459.aspx FFI.typedef :int32, :win32_bool # BOOLEAN (unlike BOOL) is a BYTE - typedef unsigned char BYTE; FFI.typedef :uchar, :boolean # Same as a LONG, a 32-bit signed integer FFI.typedef :int32, :hresult # NOTE: FFI already defines (u)short as a 16-bit (un)signed like this: # FFI.typedef :uint16, :ushort # FFI.typedef :int16, :short # 8 bits per byte FFI.typedef :uchar, :byte FFI.typedef :uint16, :wchar # Definitions for data types used in LSA structures and functions # https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/ # https://docs.microsoft.com/sr-latn-rs/windows/win32/secmgmt/management-data-types FFI.typedef :pointer, :pwstr FFI.typedef :pointer, :pulong FFI.typedef :pointer, :lsa_handle FFI.typedef :pointer, :plsa_handle FFI.typedef :pointer, :psid FFI.typedef :pointer, :pvoid FFI.typedef :pointer, :plsa_unicode_string FFI.typedef :pointer, :plsa_object_attributes FFI.typedef :uint32, :ntstatus FFI.typedef :dword, :access_mask module ::FFI::WIN32 extend ::FFI::Library # https://msdn.microsoft.com/en-us/library/windows/desktop/aa373931(v=vs.85).aspx # typedef struct _GUID { # DWORD Data1; # WORD Data2; # WORD Data3; # BYTE Data4[8]; # } GUID; class GUID < FFI::Struct layout :Data1, :dword, :Data2, :word, :Data3, :word, :Data4, [:byte, 8] def self.[](s) raise _('Bad GUID format.') unless s =~ /^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/i new.tap do |guid| guid[:Data1] = s[0, 8].to_i(16) guid[:Data2] = s[9, 4].to_i(16) guid[:Data3] = s[14, 4].to_i(16) guid[:Data4][0] = s[19, 2].to_i(16) guid[:Data4][1] = s[21, 2].to_i(16) s[24, 12].split('').each_slice(2).with_index do |a, i| guid[:Data4][i + 2] = a.join('').to_i(16) end end end def ==(other) Windows.memcmp(other, self, size) == 0 end end # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx # typedef struct _SYSTEMTIME { # WORD wYear; # WORD wMonth; # WORD wDayOfWeek; # WORD wDay; # WORD wHour; # WORD wMinute; # WORD wSecond; # WORD wMilliseconds; # } SYSTEMTIME, *PSYSTEMTIME; class SYSTEMTIME < FFI::Struct layout :wYear, :word, :wMonth, :word, :wDayOfWeek, :word, :wDay, :word, :wHour, :word, :wMinute, :word, :wSecond, :word, :wMilliseconds, :word def to_local_time Time.local(self[:wYear], self[:wMonth], self[:wDay], self[:wHour], self[:wMinute], self[:wSecond], self[:wMilliseconds] * 1000) end end # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx # Contains a 64-bit value representing the number of 100-nanosecond # intervals since January 1, 1601 (UTC). # typedef struct _FILETIME { # DWORD dwLowDateTime; # DWORD dwHighDateTime; # } FILETIME, *PFILETIME; class FILETIME < FFI::Struct layout :dwLowDateTime, :dword, :dwHighDateTime, :dword end ffi_convention :stdcall # https://msdn.microsoft.com/en-us/library/windows/desktop/aa366730(v=vs.85).aspx # HLOCAL WINAPI LocalFree( # _In_ HLOCAL hMem # ); ffi_lib :kernel32 attach_function :LocalFree, [:handle], :handle # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx # BOOL WINAPI CloseHandle( # _In_ HANDLE hObject # ); ffi_lib :kernel32 attach_function_private :CloseHandle, [:handle], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms680722(v=vs.85).aspx # void CoTaskMemFree( # _In_opt_ LPVOID pv # ); ffi_lib :ole32 attach_function :CoTaskMemFree, [:lpvoid], :void end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/windows/constants.rb
lib/puppet/ffi/windows/constants.rb
# frozen_string_literal: true require_relative '../../../puppet/ffi/windows' module Puppet::FFI::Windows module Constants extend FFI::Library FILE_ATTRIBUTE_READONLY = 0x00000001 FILE_ATTRIBUTE_DIRECTORY = 0x00000010 # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379607(v=vs.85).aspx # The right to use the object for synchronization. This enables a thread to # wait until the object is in the signaled state. Some object types do not # support this access right. SYNCHRONIZE = 0x100000 # The right to delete the object. DELETE = 0x00010000 # The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). # READ_CONTROL = 0x00020000 # The right to modify the discretionary access control list (DACL) in the object's security descriptor. WRITE_DAC = 0x00040000 # The right to change the owner in the object's security descriptor. WRITE_OWNER = 0x00080000 # Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access. STANDARD_RIGHTS_REQUIRED = 0xf0000 # Currently defined to equal READ_CONTROL. STANDARD_RIGHTS_READ = 0x20000 # Currently defined to equal READ_CONTROL. STANDARD_RIGHTS_WRITE = 0x20000 # Currently defined to equal READ_CONTROL. STANDARD_RIGHTS_EXECUTE = 0x20000 # Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and SYNCHRONIZE access. STANDARD_RIGHTS_ALL = 0x1F0000 SPECIFIC_RIGHTS_ALL = 0xFFFF FILE_READ_DATA = 1 FILE_WRITE_DATA = 2 FILE_APPEND_DATA = 4 FILE_READ_EA = 8 FILE_WRITE_EA = 16 FILE_EXECUTE = 32 FILE_DELETE_CHILD = 64 FILE_READ_ATTRIBUTES = 128 FILE_WRITE_ATTRIBUTES = 256 FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF FILE_GENERIC_READ = STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE REPLACEFILE_WRITE_THROUGH = 0x1 REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2 REPLACEFILE_IGNORE_ACL_ERRORS = 0x3 INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF # define INVALID_FILE_ATTRIBUTES (DWORD (-1)) IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 IO_REPARSE_TAG_HSM = 0xC0000004 IO_REPARSE_TAG_HSM2 = 0x80000006 IO_REPARSE_TAG_SIS = 0x80000007 IO_REPARSE_TAG_WIM = 0x80000008 IO_REPARSE_TAG_CSV = 0x80000009 IO_REPARSE_TAG_DFS = 0x8000000A IO_REPARSE_TAG_SYMLINK = 0xA000000C IO_REPARSE_TAG_DFSR = 0x80000012 IO_REPARSE_TAG_DEDUP = 0x80000013 IO_REPARSE_TAG_NFS = 0x80000014 FILE_ATTRIBUTE_REPARSE_POINT = 0x400 GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 GENERIC_EXECUTE = 0x20000000 GENERIC_ALL = 0x10000000 METHOD_BUFFERED = 0 FILE_SHARE_READ = 1 FILE_SHARE_WRITE = 2 OPEN_EXISTING = 3 FILE_DEVICE_FILE_SYSTEM = 0x00000009 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 SHGFI_DISPLAYNAME = 0x000000200 SHGFI_PIDL = 0x000000008 ERROR_FILE_NOT_FOUND = 2 ERROR_PATH_NOT_FOUND = 3 ERROR_ALREADY_EXISTS = 183 # https://msdn.microsoft.com/en-us/library/windows/desktop/aa364571(v=vs.85).aspx FSCTL_GET_REPARSE_POINT = 0x900a8 MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16_384 # Priority constants # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setpriorityclass ABOVE_NORMAL_PRIORITY_CLASS = 0x0008000 BELOW_NORMAL_PRIORITY_CLASS = 0x0004000 HIGH_PRIORITY_CLASS = 0x0000080 IDLE_PRIORITY_CLASS = 0x0000040 NORMAL_PRIORITY_CLASS = 0x0000020 REALTIME_PRIORITY_CLASS = 0x0000010 # Process Access Rights # https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights PROCESS_TERMINATE = 0x00000001 PROCESS_SET_INFORMATION = 0x00000200 PROCESS_QUERY_INFORMATION = 0x00000400 PROCESS_ALL_ACCESS = 0x001F0FFF PROCESS_VM_READ = 0x00000010 # Process creation flags # https://docs.microsoft.com/en-us/windows/win32/procthread/process-creation-flags CREATE_BREAKAWAY_FROM_JOB = 0x01000000 CREATE_DEFAULT_ERROR_MODE = 0x04000000 CREATE_NEW_CONSOLE = 0x00000010 CREATE_NEW_PROCESS_GROUP = 0x00000200 CREATE_NO_WINDOW = 0x08000000 CREATE_PROTECTED_PROCESS = 0x00040000 CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000 CREATE_SEPARATE_WOW_VDM = 0x00000800 CREATE_SHARED_WOW_VDM = 0x00001000 CREATE_SUSPENDED = 0x00000004 CREATE_UNICODE_ENVIRONMENT = 0x00000400 DEBUG_ONLY_THIS_PROCESS = 0x00000002 DEBUG_PROCESS = 0x00000001 DETACHED_PROCESS = 0x00000008 INHERIT_PARENT_AFFINITY = 0x00010000 # Logon options LOGON_WITH_PROFILE = 0x00000001 # STARTUPINFOA constants # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa STARTF_USESTDHANDLES = 0x00000100 # Miscellaneous HANDLE_FLAG_INHERIT = 0x00000001 SEM_FAILCRITICALERRORS = 0x00000001 SEM_NOGPFAULTERRORBOX = 0x00000002 # Error constants INVALID_HANDLE_VALUE = FFI::Pointer.new(-1).address # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379626(v=vs.85).aspx TOKEN_INFORMATION_CLASS = enum( :TokenUser, 1, :TokenGroups, :TokenPrivileges, :TokenOwner, :TokenPrimaryGroup, :TokenDefaultDacl, :TokenSource, :TokenType, :TokenImpersonationLevel, :TokenStatistics, :TokenRestrictedSids, :TokenSessionId, :TokenGroupsAndPrivileges, :TokenSessionReference, :TokenSandBoxInert, :TokenAuditPolicy, :TokenOrigin, :TokenElevationType, :TokenLinkedToken, :TokenElevation, :TokenHasRestrictions, :TokenAccessInformation, :TokenVirtualizationAllowed, :TokenVirtualizationEnabled, :TokenIntegrityLevel, :TokenUIAccess, :TokenMandatoryPolicy, :TokenLogonSid, :TokenIsAppContainer, :TokenCapabilities, :TokenAppContainerSid, :TokenAppContainerNumber, :TokenUserClaimAttributes, :TokenDeviceClaimAttributes, :TokenRestrictedUserClaimAttributes, :TokenRestrictedDeviceClaimAttributes, :TokenDeviceGroups, :TokenRestrictedDeviceGroups, :TokenSecurityAttributes, :TokenIsRestricted, :MaxTokenInfoClass ) # Service error codes # https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes--1000-1299- ERROR_SERVICE_DOES_NOT_EXIST = 0x00000424 # Service control codes # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-controlserviceexw SERVICE_CONTROL_STOP = 0x00000001 SERVICE_CONTROL_PAUSE = 0x00000002 SERVICE_CONTROL_CONTINUE = 0x00000003 SERVICE_CONTROL_INTERROGATE = 0x00000004 SERVICE_CONTROL_SHUTDOWN = 0x00000005 SERVICE_CONTROL_PARAMCHANGE = 0x00000006 SERVICE_CONTROL_NETBINDADD = 0x00000007 SERVICE_CONTROL_NETBINDREMOVE = 0x00000008 SERVICE_CONTROL_NETBINDENABLE = 0x00000009 SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A SERVICE_CONTROL_DEVICEEVENT = 0x0000000B SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C SERVICE_CONTROL_POWEREVENT = 0x0000000D SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E SERVICE_CONTROL_PRESHUTDOWN = 0x0000000F SERVICE_CONTROL_TIMECHANGE = 0x00000010 SERVICE_CONTROL_TRIGGEREVENT = 0x00000020 SERVICE_CONTROL_SIGNALS = { SERVICE_CONTROL_STOP => :SERVICE_CONTROL_STOP, SERVICE_CONTROL_PAUSE => :SERVICE_CONTROL_PAUSE, SERVICE_CONTROL_CONTINUE => :SERVICE_CONTROL_CONTINUE, SERVICE_CONTROL_INTERROGATE => :SERVICE_CONTROL_INTERROGATE, SERVICE_CONTROL_SHUTDOWN => :SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_PARAMCHANGE => :SERVICE_CONTROL_PARAMCHANGE, SERVICE_CONTROL_NETBINDADD => :SERVICE_CONTROL_NETBINDADD, SERVICE_CONTROL_NETBINDREMOVE => :SERVICE_CONTROL_NETBINDREMOVE, SERVICE_CONTROL_NETBINDENABLE => :SERVICE_CONTROL_NETBINDENABLE, SERVICE_CONTROL_NETBINDDISABLE => :SERVICE_CONTROL_NETBINDDISABLE, SERVICE_CONTROL_DEVICEEVENT => :SERVICE_CONTROL_DEVICEEVENT, SERVICE_CONTROL_HARDWAREPROFILECHANGE => :SERVICE_CONTROL_HARDWAREPROFILECHANGE, SERVICE_CONTROL_POWEREVENT => :SERVICE_CONTROL_POWEREVENT, SERVICE_CONTROL_SESSIONCHANGE => :SERVICE_CONTROL_SESSIONCHANGE, SERVICE_CONTROL_PRESHUTDOWN => :SERVICE_CONTROL_PRESHUTDOWN, SERVICE_CONTROL_TIMECHANGE => :SERVICE_CONTROL_TIMECHANGE, SERVICE_CONTROL_TRIGGEREVENT => :SERVICE_CONTROL_TRIGGEREVENT } # Service start type codes # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-changeserviceconfigw SERVICE_AUTO_START = 0x00000002 SERVICE_BOOT_START = 0x00000000 SERVICE_DEMAND_START = 0x00000003 SERVICE_DISABLED = 0x00000004 SERVICE_SYSTEM_START = 0x00000001 SERVICE_START_TYPES = { SERVICE_AUTO_START => :SERVICE_AUTO_START, SERVICE_BOOT_START => :SERVICE_BOOT_START, SERVICE_DEMAND_START => :SERVICE_DEMAND_START, SERVICE_DISABLED => :SERVICE_DISABLED, SERVICE_SYSTEM_START => :SERVICE_SYSTEM_START, } # Service type codes # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-changeserviceconfigw SERVICE_FILE_SYSTEM_DRIVER = 0x00000002 SERVICE_KERNEL_DRIVER = 0x00000001 SERVICE_WIN32_OWN_PROCESS = 0x00000010 SERVICE_WIN32_SHARE_PROCESS = 0x00000020 SERVICE_USER_OWN_PROCESS = 0x00000050 SERVICE_USER_SHARE_PROCESS = 0x00000060 # Available only if service is also SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS SERVICE_INTERACTIVE_PROCESS = 0x00000100 ALL_SERVICE_TYPES = SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS # Current state codes # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process SERVICE_CONTINUE_PENDING = 0x00000005 SERVICE_PAUSE_PENDING = 0x00000006 SERVICE_PAUSED = 0x00000007 SERVICE_RUNNING = 0x00000004 SERVICE_START_PENDING = 0x00000002 SERVICE_STOP_PENDING = 0x00000003 SERVICE_STOPPED = 0x00000001 UNSAFE_PENDING_STATES = [SERVICE_START_PENDING, SERVICE_STOP_PENDING] FINAL_STATES = { SERVICE_CONTINUE_PENDING => SERVICE_RUNNING, SERVICE_PAUSE_PENDING => SERVICE_PAUSED, SERVICE_START_PENDING => SERVICE_RUNNING, SERVICE_STOP_PENDING => SERVICE_STOPPED } SERVICE_STATES = { SERVICE_CONTINUE_PENDING => :SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING => :SERVICE_PAUSE_PENDING, SERVICE_PAUSED => :SERVICE_PAUSED, SERVICE_RUNNING => :SERVICE_RUNNING, SERVICE_START_PENDING => :SERVICE_START_PENDING, SERVICE_STOP_PENDING => :SERVICE_STOP_PENDING, SERVICE_STOPPED => :SERVICE_STOPPED, } # Service accepts control codes # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process SERVICE_ACCEPT_STOP = 0x00000001 SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002 SERVICE_ACCEPT_SHUTDOWN = 0x00000004 SERVICE_ACCEPT_PARAMCHANGE = 0x00000008 SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010 SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020 SERVICE_ACCEPT_POWEREVENT = 0x00000040 SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080 SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100 SERVICE_ACCEPT_TIMECHANGE = 0x00000200 SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400 SERVICE_ACCEPT_USER_LOGOFF = 0x00000800 # Service manager access codes # https://docs.microsoft.com/en-us/windows/desktop/Services/service-security-and-access-rights SC_MANAGER_CREATE_SERVICE = 0x00000002 SC_MANAGER_CONNECT = 0x00000001 SC_MANAGER_ENUMERATE_SERVICE = 0x00000004 SC_MANAGER_LOCK = 0x00000008 SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00000020 SC_MANAGER_QUERY_LOCK_STATUS = 0x00000010 SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_MODIFY_BOOT_CONFIG | SC_MANAGER_QUERY_LOCK_STATUS # Service access codes # https://docs.microsoft.com/en-us/windows/desktop/Services/service-security-and-access-rights SERVICE_CHANGE_CONFIG = 0x0002 SERVICE_ENUMERATE_DEPENDENTS = 0x0008 SERVICE_INTERROGATE = 0x0080 SERVICE_PAUSE_CONTINUE = 0x0040 SERVICE_QUERY_STATUS = 0x0004 SERVICE_QUERY_CONFIG = 0x0001 SERVICE_START = 0x0010 SERVICE_STOP = 0x0020 SERVICE_USER_DEFINED_CONTROL = 0x0100 SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_CHANGE_CONFIG | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_INTERROGATE | SERVICE_PAUSE_CONTINUE | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG | SERVICE_START | SERVICE_STOP | SERVICE_USER_DEFINED_CONTROL # Service config codes # From the windows 10 SDK: # // # // Value to indicate no change to an optional parameter # // # #define SERVICE_NO_CHANGE 0xffffffff # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-changeserviceconfig2w SERVICE_CONFIG_DESCRIPTION = 0x00000001 SERVICE_CONFIG_FAILURE_ACTIONS = 0x00000002 SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x00000003 SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 0x00000004 SERVICE_CONFIG_SERVICE_SID_INFO = 0x00000005 SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 0x00000006 SERVICE_CONFIG_PRESHUTDOWN_INFO = 0x00000007 SERVICE_CONFIG_TRIGGER_INFO = 0x00000008 SERVICE_CONFIG_PREFERRED_NODE = 0x00000009 SERVICE_CONFIG_LAUNCH_PROTECTED = 0x0000000C SERVICE_NO_CHANGE = 0xffffffff SERVICE_CONFIG_TYPES = { SERVICE_CONFIG_DESCRIPTION => :SERVICE_CONFIG_DESCRIPTION, SERVICE_CONFIG_FAILURE_ACTIONS => :SERVICE_CONFIG_FAILURE_ACTIONS, SERVICE_CONFIG_DELAYED_AUTO_START_INFO => :SERVICE_CONFIG_DELAYED_AUTO_START_INFO, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG => :SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, SERVICE_CONFIG_SERVICE_SID_INFO => :SERVICE_CONFIG_SERVICE_SID_INFO, SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO => :SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO, SERVICE_CONFIG_PRESHUTDOWN_INFO => :SERVICE_CONFIG_PRESHUTDOWN_INFO, SERVICE_CONFIG_TRIGGER_INFO => :SERVICE_CONFIG_TRIGGER_INFO, SERVICE_CONFIG_PREFERRED_NODE => :SERVICE_CONFIG_PREFERRED_NODE, SERVICE_CONFIG_LAUNCH_PROTECTED => :SERVICE_CONFIG_LAUNCH_PROTECTED, } # Service enum codes # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-enumservicesstatusexa SERVICE_ACTIVE = 0x00000001 SERVICE_INACTIVE = 0x00000002 SERVICE_STATE_ALL = SERVICE_ACTIVE | SERVICE_INACTIVE # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_enum_service_status_processw SERVICENAME_MAX = 256 end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/windows/structs.rb
lib/puppet/ffi/windows/structs.rb
# coding: utf-8 # frozen_string_literal: true require_relative '../../../puppet/ffi/windows' module Puppet::FFI::Windows module Structs extend FFI::Library extend Puppet::FFI::Windows::APITypes # https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85) # typedef struct _SECURITY_ATTRIBUTES { # DWORD nLength; # LPVOID lpSecurityDescriptor; # BOOL bInheritHandle; # } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; class SECURITY_ATTRIBUTES < FFI::Struct layout( :nLength, :dword, :lpSecurityDescriptor, :lpvoid, :bInheritHandle, :win32_bool ) end private_constant :SECURITY_ATTRIBUTES # sizeof(STARTUPINFO) == 68 # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa # typedef struct _STARTUPINFOA { # DWORD cb; # LPSTR lpReserved; # LPSTR lpDesktop; # LPSTR lpTitle; # DWORD dwX; # DWORD dwY; # DWORD dwXSize; # DWORD dwYSize; # DWORD dwXCountChars; # DWORD dwYCountChars; # DWORD dwFillAttribute; # DWORD dwFlags; # WORD wShowWindow; # WORD cbReserved2; # LPBYTE lpReserved2; # HANDLE hStdInput; # HANDLE hStdOutput; # HANDLE hStdError; # } STARTUPINFOA, *LPSTARTUPINFOA; class STARTUPINFO < FFI::Struct layout( :cb, :dword, :lpReserved, :lpcstr, :lpDesktop, :lpcstr, :lpTitle, :lpcstr, :dwX, :dword, :dwY, :dword, :dwXSize, :dword, :dwYSize, :dword, :dwXCountChars, :dword, :dwYCountChars, :dword, :dwFillAttribute, :dword, :dwFlags, :dword, :wShowWindow, :word, :cbReserved2, :word, :lpReserved2, :pointer, :hStdInput, :handle, :hStdOutput, :handle, :hStdError, :handle ) end private_constant :STARTUPINFO # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information # typedef struct _PROCESS_INFORMATION { # HANDLE hProcess; # HANDLE hThread; # DWORD dwProcessId; # DWORD dwThreadId; # } PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION; class PROCESS_INFORMATION < FFI::Struct layout( :hProcess, :handle, :hThread, :handle, :dwProcessId, :dword, :dwThreadId, :dword ) end private_constant :PROCESS_INFORMATION # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379261(v=vs.85).aspx # typedef struct _LUID { # DWORD LowPart; # LONG HighPart; # } LUID, *PLUID; class LUID < FFI::Struct layout :LowPart, :dword, :HighPart, :win32_long end # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379263(v=vs.85).aspx # typedef struct _LUID_AND_ATTRIBUTES { # LUID Luid; # DWORD Attributes; # } LUID_AND_ATTRIBUTES, *PLUID_AND_ATTRIBUTES; class LUID_AND_ATTRIBUTES < FFI::Struct layout :Luid, LUID, :Attributes, :dword end # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx # typedef struct _TOKEN_PRIVILEGES { # DWORD PrivilegeCount; # LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]; # } TOKEN_PRIVILEGES, *PTOKEN_PRIVILEGES; class TOKEN_PRIVILEGES < FFI::Struct layout :PrivilegeCount, :dword, :Privileges, [LUID_AND_ATTRIBUTES, 1] # placeholder for offset end # https://msdn.microsoft.com/en-us/library/windows/desktop/bb530717(v=vs.85).aspx # typedef struct _TOKEN_ELEVATION { # DWORD TokenIsElevated; # } TOKEN_ELEVATION, *PTOKEN_ELEVATION; class TOKEN_ELEVATION < FFI::Struct layout :TokenIsElevated, :dword end # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process # typedef struct _SERVICE_STATUS_PROCESS { # DWORD dwServiceType; # DWORD dwCurrentState; # DWORD dwControlsAccepted; # DWORD dwWin32ExitCode; # DWORD dwServiceSpecificExitCode; # DWORD dwCheckPoint; # DWORD dwWaitHint; # DWORD dwProcessId; # DWORD dwServiceFlags; # } SERVICE_STATUS_PROCESS, *LPSERVICE_STATUS_PROCESS; class SERVICE_STATUS_PROCESS < FFI::Struct layout( :dwServiceType, :dword, :dwCurrentState, :dword, :dwControlsAccepted, :dword, :dwWin32ExitCode, :dword, :dwServiceSpecificExitCode, :dword, :dwCheckPoint, :dword, :dwWaitHint, :dword, :dwProcessId, :dword, :dwServiceFlags, :dword ) end # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_delayed_auto_start_info # typedef struct _SERVICE_DELAYED_AUTO_START_INFO { # BOOL fDelayedAutostart; # } SERVICE_DELAYED_AUTO_START_INFO, *LPSERVICE_DELAYED_AUTO_START_INFO; class SERVICE_DELAYED_AUTO_START_INFO < FFI::Struct layout(:fDelayedAutostart, :int) alias aset []= # Intercept the accessor so that we can handle either true/false or 1/0. # Since there is only one member, there’s no need to check the key name. def []=(key, value) [0, false].include?(value) ? aset(key, 0) : aset(key, 1) end end # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_enum_service_status_processw # typedef struct _ENUM_SERVICE_STATUS_PROCESSW { # LPWSTR lpServiceName; # LPWSTR lpDisplayName; # SERVICE_STATUS_PROCESS ServiceStatusProcess; # } ENUM_SERVICE_STATUS_PROCESSW, *LPENUM_SERVICE_STATUS_PROCESSW; class ENUM_SERVICE_STATUS_PROCESSW < FFI::Struct layout( :lpServiceName, :pointer, :lpDisplayName, :pointer, :ServiceStatusProcess, SERVICE_STATUS_PROCESS ) end # typedef struct _SERVICE_STATUS { # DWORD dwServiceType; # DWORD dwCurrentState; # DWORD dwControlsAccepted; # DWORD dwWin32ExitCode; # DWORD dwServiceSpecificExitCode; # DWORD dwCheckPoint; # DWORD dwWaitHint; # } SERVICE_STATUS, *LPSERVICE_STATUS; class SERVICE_STATUS < FFI::Struct layout( :dwServiceType, :dword, :dwCurrentState, :dword, :dwControlsAccepted, :dword, :dwWin32ExitCode, :dword, :dwServiceSpecificExitCode, :dword, :dwCheckPoint, :dword, :dwWaitHint, :dword ) end # typedef struct _QUERY_SERVICE_CONFIGW { # DWORD dwServiceType; # DWORD dwStartType; # DWORD dwErrorControl; # LPWSTR lpBinaryPathName; # LPWSTR lpLoadOrderGroup; # DWORD dwTagId; # LPWSTR lpDependencies; # LPWSTR lpServiceStartName; # LPWSTR lpDisplayName; # } QUERY_SERVICE_CONFIGW, *LPQUERY_SERVICE_CONFIGW; class QUERY_SERVICE_CONFIGW < FFI::Struct layout( :dwServiceType, :dword, :dwStartType, :dword, :dwErrorControl, :dword, :lpBinaryPathName, :pointer, :lpLoadOrderGroup, :pointer, :dwTagId, :dword, :lpDependencies, :pointer, :lpServiceStartName, :pointer, :lpDisplayName, :pointer ) end # typedef struct _SERVICE_TABLE_ENTRYW { # LPWSTR lpServiceName; # LPSERVICE_MAIN_FUNCTIONW lpServiceProc; # } SERVICE_TABLE_ENTRYW, *LPSERVICE_TABLE_ENTRYW; class SERVICE_TABLE_ENTRYW < FFI::Struct layout( :lpServiceName, :pointer, :lpServiceProc, :pointer ) end # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724834%28v=vs.85%29.aspx # typedef struct _OSVERSIONINFO { # DWORD dwOSVersionInfoSize; # DWORD dwMajorVersion; # DWORD dwMinorVersion; # DWORD dwBuildNumber; # DWORD dwPlatformId; # TCHAR szCSDVersion[128]; # } OSVERSIONINFO; class OSVERSIONINFO < FFI::Struct layout( :dwOSVersionInfoSize, :dword, :dwMajorVersion, :dword, :dwMinorVersion, :dword, :dwBuildNumber, :dword, :dwPlatformId, :dword, :szCSDVersion, [:wchar, 128] ) end MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16_384 # SYMLINK_REPARSE_DATA_BUFFER # https://msdn.microsoft.com/en-us/library/cc232006.aspx # https://msdn.microsoft.com/en-us/library/windows/hardware/ff552012(v=vs.85).aspx # struct is always MAXIMUM_REPARSE_DATA_BUFFER_SIZE bytes class SYMLINK_REPARSE_DATA_BUFFER < FFI::Struct layout :ReparseTag, :win32_ulong, :ReparseDataLength, :ushort, :Reserved, :ushort, :SubstituteNameOffset, :ushort, :SubstituteNameLength, :ushort, :PrintNameOffset, :ushort, :PrintNameLength, :ushort, :Flags, :win32_ulong, # max less above fields dword / uint 4 bytes, ushort 2 bytes # technically a WCHAR buffer, but we care about size in bytes here :PathBuffer, [:byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 20] end # MOUNT_POINT_REPARSE_DATA_BUFFER # https://msdn.microsoft.com/en-us/library/cc232007.aspx # https://msdn.microsoft.com/en-us/library/windows/hardware/ff552012(v=vs.85).aspx # struct is always MAXIMUM_REPARSE_DATA_BUFFER_SIZE bytes class MOUNT_POINT_REPARSE_DATA_BUFFER < FFI::Struct layout :ReparseTag, :win32_ulong, :ReparseDataLength, :ushort, :Reserved, :ushort, :SubstituteNameOffset, :ushort, :SubstituteNameLength, :ushort, :PrintNameOffset, :ushort, :PrintNameLength, :ushort, # max less above fields dword / uint 4 bytes, ushort 2 bytes # technically a WCHAR buffer, but we care about size in bytes here :PathBuffer, [:byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16] end # SHFILEINFO # https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shfileinfow # typedef struct _SHFILEINFOW { # HICON hIcon; # int iIcon; # DWORD dwAttributes; # WCHAR szDisplayName[MAX_PATH]; # WCHAR szTypeName[80]; # } SHFILEINFOW; class SHFILEINFO < FFI::Struct layout( :hIcon, :ulong, :iIcon, :int, :dwAttributes, :ulong, :szDisplayName, [:char, 256], :szTypeName, [:char, 80] ) end # REPARSE_JDATA_BUFFER class REPARSE_JDATA_BUFFER < FFI::Struct layout( :ReparseTag, :ulong, :ReparseDataLength, :ushort, :Reserved, :ushort, :SubstituteNameOffset, :ushort, :SubstituteNameLength, :ushort, :PrintNameOffset, :ushort, :PrintNameLength, :ushort, :PathBuffer, [:char, 1024] ) # The REPARSE_DATA_BUFFER_HEADER_SIZE which is calculated as: # # sizeof(ReparseTag) + sizeof(ReparseDataLength) + sizeof(Reserved) # def header_size FFI::Type::ULONG.size + FFI::Type::USHORT.size + FFI::Type::USHORT.size end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/ffi/windows/functions.rb
lib/puppet/ffi/windows/functions.rb
# frozen_string_literal: true require_relative '../../../puppet/ffi/windows' module Puppet::FFI::Windows module Functions extend FFI::Library include Puppet::FFI::Windows::Constants ffi_convention :stdcall # https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-sethandleinformation # BOOL SetHandleInformation( # HANDLE hObject, # DWORD dwMask, # DWORD dwFlags # ); ffi_lib :kernel32 attach_function_private :SetHandleInformation, [:handle, :dword, :dword], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode # UINT SetErrorMode( # UINT uMode # ); ffi_lib :kernel32 attach_function_private :SetErrorMode, [:uint], :uint # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw # BOOL CreateProcessW( # LPCWSTR lpApplicationName, # LPWSTR lpCommandLine, # LPSECURITY_ATTRIBUTES lpProcessAttributes, # LPSECURITY_ATTRIBUTES lpThreadAttributes, # BOOL bInheritHandles, # DWORD dwCreationFlags, # LPVOID lpEnvironment, # LPCWSTR lpCurrentDirectory, # LPSTARTUPINFOW lpStartupInfo, # LPPROCESS_INFORMATION lpProcessInformation # ); ffi_lib :kernel32 attach_function_private :CreateProcessW, [:lpcwstr, :lpwstr, :pointer, :pointer, :win32_bool, :dword, :lpvoid, :lpcwstr, :pointer, :pointer], :bool # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess # HANDLE OpenProcess( # DWORD dwDesiredAccess, # BOOL bInheritHandle, # DWORD dwProcessId # ); ffi_lib :kernel32 attach_function_private :OpenProcess, [:dword, :win32_bool, :dword], :handle # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setpriorityclass # BOOL SetPriorityClass( # HANDLE hProcess, # DWORD dwPriorityClass # ); ffi_lib :kernel32 attach_function_private :SetPriorityClass, [:handle, :dword], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithlogonw # BOOL CreateProcessWithLogonW( # LPCWSTR lpUsername, # LPCWSTR lpDomain, # LPCWSTR lpPassword, # DWORD dwLogonFlags, # LPCWSTR lpApplicationName, # LPWSTR lpCommandLine, # DWORD dwCreationFlags, # LPVOID lpEnvironment, # LPCWSTR lpCurrentDirectory, # LPSTARTUPINFOW lpStartupInfo, # LPPROCESS_INFORMATION lpProcessInformation # ); ffi_lib :advapi32 attach_function_private :CreateProcessWithLogonW, [:lpcwstr, :lpcwstr, :lpcwstr, :dword, :lpcwstr, :lpwstr, :dword, :lpvoid, :lpcwstr, :pointer, :pointer], :bool # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=vs-2019 # intptr_t _get_osfhandle( # int fd # ); ffi_lib FFI::Library::LIBC attach_function_private :get_osfhandle, :_get_osfhandle, [:int], :intptr_t begin # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-errno?view=vs-2019 # errno_t _get_errno( # int * pValue # ); attach_function_private :get_errno, :_get_errno, [:pointer], :int rescue FFI::NotFoundError # Do nothing, Windows XP or earlier. end # https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx # DWORD WINAPI WaitForSingleObject( # _In_ HANDLE hHandle, # _In_ DWORD dwMilliseconds # ); ffi_lib :kernel32 attach_function_private :WaitForSingleObject, [:handle, :dword], :dword, :blocking => true # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjects # DWORD WaitForMultipleObjects( # DWORD nCount, # const HANDLE *lpHandles, # BOOL bWaitAll, # DWORD dwMilliseconds # ); ffi_lib :kernel32 attach_function_private :WaitForMultipleObjects, [:dword, :phandle, :win32_bool, :dword], :dword # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventw # HANDLE CreateEventW( # LPSECURITY_ATTRIBUTES lpEventAttributes, # BOOL bManualReset, # BOOL bInitialState, # LPCWSTR lpName # ); ffi_lib :kernel32 attach_function_private :CreateEventW, [:pointer, :win32_bool, :win32_bool, :lpcwstr], :handle # https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread # HANDLE CreateThread( # LPSECURITY_ATTRIBUTES lpThreadAttributes, # SIZE_T dwStackSize, # LPTHREAD_START_ROUTINE lpStartAddress, # __drv_aliasesMem LPVOID lpParameter, # DWORD dwCreationFlags, # LPDWORD lpThreadId # ); ffi_lib :kernel32 attach_function_private :CreateThread, [:pointer, :size_t, :pointer, :lpvoid, :dword, :lpdword], :handle, :blocking => true # https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setevent # BOOL SetEvent( # HANDLE hEvent # ); ffi_lib :kernel32 attach_function_private :SetEvent, [:handle], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx # BOOL WINAPI GetExitCodeProcess( # _In_ HANDLE hProcess, # _Out_ LPDWORD lpExitCode # ); ffi_lib :kernel32 attach_function_private :GetExitCodeProcess, [:handle, :lpdword], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms683179(v=vs.85).aspx # HANDLE WINAPI GetCurrentProcess(void); ffi_lib :kernel32 attach_function_private :GetCurrentProcess, [], :handle # https://msdn.microsoft.com/en-us/library/windows/desktop/ms683187(v=vs.85).aspx # LPTCH GetEnvironmentStrings(void); ffi_lib :kernel32 attach_function_private :GetEnvironmentStringsW, [], :pointer # https://msdn.microsoft.com/en-us/library/windows/desktop/ms683151(v=vs.85).aspx # BOOL FreeEnvironmentStrings( # _In_ LPTCH lpszEnvironmentBlock # ); ffi_lib :kernel32 attach_function_private :FreeEnvironmentStringsW, [:pointer], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms686206(v=vs.85).aspx # BOOL WINAPI SetEnvironmentVariableW( # _In_ LPCTSTR lpName, # _In_opt_ LPCTSTR lpValue # ); ffi_lib :kernel32 attach_function_private :SetEnvironmentVariableW, [:lpcwstr, :lpcwstr], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx # HANDLE WINAPI OpenProcess( # _In_ DWORD DesiredAccess, # _In_ BOOL InheritHandle, # _In_ DWORD ProcessId # ); ffi_lib :kernel32 attach_function_private :OpenProcess, [:dword, :win32_bool, :dword], :handle # https://msdn.microsoft.com/en-us/library/windows/desktop/aa379295(v=vs.85).aspx # BOOL WINAPI OpenProcessToken( # _In_ HANDLE ProcessHandle, # _In_ DWORD DesiredAccess, # _Out_ PHANDLE TokenHandle # ); ffi_lib :advapi32 attach_function_private :OpenProcessToken, [:handle, :dword, :phandle], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-queryfullprocessimagenamew # BOOL WINAPI QueryFullProcessImageName( # _In_ HANDLE hProcess, # _In_ DWORD dwFlags, # _Out_ LPWSTR lpExeName, # _In_ PDWORD lpdwSize, # ); ffi_lib :kernel32 attach_function_private :QueryFullProcessImageNameW, [:handle, :dword, :lpwstr, :pdword], :win32_bool # https://msdn.microsoft.com/en-us/library/Windows/desktop/aa379180(v=vs.85).aspx # BOOL WINAPI LookupPrivilegeValue( # _In_opt_ LPCTSTR lpSystemName, # _In_ LPCTSTR lpName, # _Out_ PLUID lpLuid # ); ffi_lib :advapi32 attach_function_private :LookupPrivilegeValueW, [:lpcwstr, :lpcwstr, :pointer], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/aa446671(v=vs.85).aspx # BOOL WINAPI GetTokenInformation( # _In_ HANDLE TokenHandle, # _In_ TOKEN_INFORMATION_CLASS TokenInformationClass, # _Out_opt_ LPVOID TokenInformation, # _In_ DWORD TokenInformationLength, # _Out_ PDWORD ReturnLength # ); ffi_lib :advapi32 attach_function_private :GetTokenInformation, [:handle, TOKEN_INFORMATION_CLASS, :lpvoid, :dword, :pdword], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx # BOOL WINAPI GetVersionEx( # _Inout_ LPOSVERSIONINFO lpVersionInfo # ); ffi_lib :kernel32 attach_function_private :GetVersionExW, [:pointer], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/dd318123(v=vs.85).aspx # LANGID GetSystemDefaultUILanguage(void); ffi_lib :kernel32 attach_function_private :GetSystemDefaultUILanguage, [], :word # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-openscmanagerw # SC_HANDLE OpenSCManagerW( # LPCWSTR lpMachineName, # LPCWSTR lpDatabaseName, # DWORD dwDesiredAccess # ); ffi_lib :advapi32 attach_function_private :OpenSCManagerW, [:lpcwstr, :lpcwstr, :dword], :handle # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-openservicew # SC_HANDLE OpenServiceW( # SC_HANDLE hSCManager, # LPCWSTR lpServiceName, # DWORD dwDesiredAccess # ); ffi_lib :advapi32 attach_function_private :OpenServiceW, [:handle, :lpcwstr, :dword], :handle # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-closeservicehandle # BOOL CloseServiceHandle( # SC_HANDLE hSCObject # ); ffi_lib :advapi32 attach_function_private :CloseServiceHandle, [:handle], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-queryservicestatusex # BOOL QueryServiceStatusEx( # SC_HANDLE hService, # SC_STATUS_TYPE InfoLevel, # LPBYTE lpBuffer, # DWORD cbBufSize, # LPDWORD pcbBytesNeeded # ); SC_STATUS_TYPE = enum( :SC_STATUS_PROCESS_INFO, 0 ) ffi_lib :advapi32 attach_function_private :QueryServiceStatusEx, [:handle, SC_STATUS_TYPE, :lpbyte, :dword, :lpdword], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-queryserviceconfigw # BOOL QueryServiceConfigW( # SC_HANDLE hService, # LPQUERY_SERVICE_CONFIGW lpServiceConfig, # DWORD cbBufSize, # LPDWORD pcbBytesNeeded # ); ffi_lib :advapi32 attach_function_private :QueryServiceConfigW, [:handle, :lpbyte, :dword, :lpdword], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-queryserviceconfig2w # BOOL QueryServiceConfig2W( # SC_HANDLE hService, # DWORD dwInfoLevel, # LPBYTE lpBuffer, # DWORD cbBufSize, # LPDWORD pcbBytesNeeded # ); ffi_lib :advapi32 attach_function_private :QueryServiceConfig2W, [:handle, :dword, :lpbyte, :dword, :lpdword], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-startservicew # BOOL StartServiceW( # SC_HANDLE hService, # DWORD dwNumServiceArgs, # LPCWSTR *lpServiceArgVectors # ); ffi_lib :advapi32 attach_function_private :StartServiceW, [:handle, :dword, :pointer], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatcherw # BOOL StartServiceCtrlDispatcherW( # const SERVICE_TABLE_ENTRYW *lpServiceStartTable # ); ffi_lib :advapi32 attach_function_private :StartServiceCtrlDispatcherW, [:pointer], :win32_bool, :blocking => true # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-setservicestatus # BOOL SetServiceStatus( # SERVICE_STATUS_HANDLE hServiceStatus, # LPSERVICE_STATUS lpServiceStatus # ); ffi_lib :advapi32 attach_function_private :SetServiceStatus, [:handle, :pointer], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-controlservice # BOOL ControlService( # SC_HANDLE hService, # DWORD dwControl, # LPSERVICE_STATUS lpServiceStatus # ); ffi_lib :advapi32 attach_function_private :ControlService, [:handle, :dword, :pointer], :win32_bool # DWORD LphandlerFunctionEx( # DWORD dwControl, # DWORD dwEventType, # LPVOID lpEventData, # LPVOID lpContext # ) callback :handler_ex, [:dword, :dword, :lpvoid, :lpvoid], :void # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-registerservicectrlhandlerexw # SERVICE_STATUS_HANDLE RegisterServiceCtrlHandlerExW( # LPCWSTR lpServiceName, # LPHANDLER_FUNCTION_EX lpHandlerProc, # LPVOID lpContext # ); ffi_lib :advapi32 attach_function_private :RegisterServiceCtrlHandlerExW, [:lpcwstr, :handler_ex, :lpvoid], :handle # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-changeserviceconfigw # BOOL ChangeServiceConfigW( # SC_HANDLE hService, # DWORD dwServiceType, # DWORD dwStartType, # DWORD dwErrorControl, # LPCWSTR lpBinaryPathName, # LPCWSTR lpLoadOrderGroup, # LPDWORD lpdwTagId, # LPCWSTR lpDependencies, # LPCWSTR lpServiceStartName, # LPCWSTR lpPassword, # LPCWSTR lpDisplayName # ); ffi_lib :advapi32 attach_function_private :ChangeServiceConfigW, [ :handle, :dword, :dword, :dword, :lpcwstr, :lpcwstr, :lpdword, :lpcwstr, :lpcwstr, :lpcwstr, :lpcwstr ], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-changeserviceconfig2w # BOOL ChangeServiceConfig2W( # SC_HANDLE hService, # DWORD dwInfoLevel, # LPVOID lpInfo # ); ffi_lib :advapi32 attach_function_private :ChangeServiceConfig2W, [:handle, :dword, :lpvoid], :win32_bool # https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-enumservicesstatusexw # BOOL EnumServicesStatusExW( # SC_HANDLE hSCManager, # SC_ENUM_TYPE InfoLevel, # DWORD dwServiceType, # DWORD dwServiceState, # LPBYTE lpServices, # DWORD cbBufSize, # LPDWORD pcbBytesNeeded, # LPDWORD lpServicesReturned, # LPDWORD lpResumeHandle, # LPCWSTR pszGroupName # ); SC_ENUM_TYPE = enum( :SC_ENUM_PROCESS_INFO, 0 ) ffi_lib :advapi32 attach_function_private :EnumServicesStatusExW, [ :handle, SC_ENUM_TYPE, :dword, :dword, :lpbyte, :dword, :lpdword, :lpdword, :lpdword, :lpcwstr ], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365512(v=vs.85).aspx # BOOL WINAPI ReplaceFile( # _In_ LPCTSTR lpReplacedFileName, # _In_ LPCTSTR lpReplacementFileName, # _In_opt_ LPCTSTR lpBackupFileName, # _In_ DWORD dwReplaceFlags - 0x1 REPLACEFILE_WRITE_THROUGH, # 0x2 REPLACEFILE_IGNORE_MERGE_ERRORS, # 0x4 REPLACEFILE_IGNORE_ACL_ERRORS # _Reserved_ LPVOID lpExclude, # _Reserved_ LPVOID lpReserved # ); ffi_lib :kernel32 attach_function_private :ReplaceFileW, [:lpcwstr, :lpcwstr, :lpcwstr, :dword, :lpvoid, :lpvoid], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240(v=vs.85).aspx # BOOL WINAPI MoveFileEx( # _In_ LPCTSTR lpExistingFileName, # _In_opt_ LPCTSTR lpNewFileName, # _In_ DWORD dwFlags # ); ffi_lib :kernel32 attach_function_private :MoveFileExW, [:lpcwstr, :lpcwstr, :dword], :win32_bool # BOOLEAN WINAPI CreateSymbolicLink( # _In_ LPTSTR lpSymlinkFileName, - symbolic link to be created # _In_ LPTSTR lpTargetFileName, - name of target for symbolic link # _In_ DWORD dwFlags - 0x0 target is a file, 0x1 target is a directory # ); # rescue on Windows < 6.0 so that code doesn't explode begin ffi_lib :kernel32 attach_function_private :CreateSymbolicLinkW, [:lpwstr, :lpwstr, :dword], :boolean rescue LoadError end # https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory # DWORD GetCurrentDirectory( # DWORD nBufferLength, # LPTSTR lpBuffer # ); ffi_lib :kernel32 attach_function_private :GetCurrentDirectoryW, [:dword, :lpwstr], :dword # https://msdn.microsoft.com/en-us/library/windows/desktop/aa364944(v=vs.85).aspx # DWORD WINAPI GetFileAttributes( # _In_ LPCTSTR lpFileName # ); ffi_lib :kernel32 attach_function_private :GetFileAttributesW, [:lpcwstr], :dword # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365535(v=vs.85).aspx # BOOL WINAPI SetFileAttributes( # _In_ LPCTSTR lpFileName, # _In_ DWORD dwFileAttributes # ); ffi_lib :kernel32 attach_function_private :SetFileAttributesW, [:lpcwstr, :dword], :win32_bool # HANDLE WINAPI CreateFile( # _In_ LPCTSTR lpFileName, # _In_ DWORD dwDesiredAccess, # _In_ DWORD dwShareMode, # _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, # _In_ DWORD dwCreationDisposition, # _In_ DWORD dwFlagsAndAttributes, # _In_opt_ HANDLE hTemplateFile # ); ffi_lib :kernel32 attach_function_private :CreateFileW, [:lpcwstr, :dword, :dword, :pointer, :dword, :dword, :handle], :handle # https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectoryw # BOOL CreateDirectoryW( # LPCWSTR lpPathName, # LPSECURITY_ATTRIBUTES lpSecurityAttributes # ); ffi_lib :kernel32 attach_function_private :CreateDirectoryW, [:lpcwstr, :pointer], :win32_bool # https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-removedirectoryw # BOOL RemoveDirectoryW( # LPCWSTR lpPathName # ); ffi_lib :kernel32 attach_function_private :RemoveDirectoryW, [:lpcwstr], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216(v=vs.85).aspx # BOOL WINAPI DeviceIoControl( # _In_ HANDLE hDevice, # _In_ DWORD dwIoControlCode, # _In_opt_ LPVOID lpInBuffer, # _In_ DWORD nInBufferSize, # _Out_opt_ LPVOID lpOutBuffer, # _In_ DWORD nOutBufferSize, # _Out_opt_ LPDWORD lpBytesReturned, # _Inout_opt_ LPOVERLAPPED lpOverlapped # ); ffi_lib :kernel32 attach_function_private :DeviceIoControl, [:handle, :dword, :lpvoid, :dword, :lpvoid, :dword, :lpdword, :pointer], :win32_bool # https://msdn.microsoft.com/en-us/library/windows/desktop/aa364980(v=vs.85).aspx # DWORD WINAPI GetLongPathName( # _In_ LPCTSTR lpszShortPath, # _Out_ LPTSTR lpszLongPath, # _In_ DWORD cchBuffer # ); ffi_lib :kernel32 attach_function_private :GetLongPathNameW, [:lpcwstr, :lpwstr, :dword], :dword # https://msdn.microsoft.com/en-us/library/windows/desktop/aa364989(v=vs.85).aspx # DWORD WINAPI GetShortPathName( # _In_ LPCTSTR lpszLongPath, # _Out_ LPTSTR lpszShortPath, # _In_ DWORD cchBuffer # ); ffi_lib :kernel32 attach_function_private :GetShortPathNameW, [:lpcwstr, :lpwstr, :dword], :dword # https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew # DWORD GetFullPathNameW( # LPCWSTR lpFileName, # DWORD nBufferLength, # LPWSTR lpBuffer, # LPWSTR *lpFilePart # ); ffi_lib :kernel32 attach_function_private :GetFullPathNameW, [:lpcwstr, :dword, :lpwstr, :pointer], :dword # https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpathw # SHFOLDERAPI SHGetFolderPathW( # HWND hwnd, # int csidl, # HANDLE hToken, # DWORD dwFlags, # LPWSTR pszPath # ); ffi_lib :shell32 attach_function_private :SHGetFolderPathW, [:hwnd, :int, :handle, :dword, :lpwstr], :dword # https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderlocation # SHSTDAPI SHGetFolderLocation( # HWND hwnd, # int csidl, # HANDLE hToken, # DWORD dwFlags, # PIDLIST_ABSOLUTE *ppidl # ); ffi_lib :shell32 attach_function_private :SHGetFolderLocation, [:hwnd, :int, :handle, :dword, :pointer], :dword # https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shgetfileinfoa # DWORD_PTR SHGetFileInfoA( # LPCSTR pszPath, # DWORD dwFileAttributes, # SHFILEINFOA *psfi, # UINT cbFileInfo, # UINT uFlags # ); ffi_lib :shell32 attach_function_private :SHGetFileInfo, [:dword, :dword, :pointer, :uint, :uint], :dword # https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathisdirectoryemptyw # BOOL PathIsDirectoryEmptyW( # LPCWSTR pszPath # ); ffi_lib :shlwapi attach_function_private :PathIsDirectoryEmptyW, [:lpcwstr], :win32_bool end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/gettext/stubs.rb
lib/puppet/gettext/stubs.rb
# frozen_string_literal: true # These stub the translation methods normally brought in # by FastGettext. Used when Gettext could not be properly # initialized. def _(msg) msg end def n_(*args, &block) plural = args[2] == 1 ? args[0] : args[1] block ? block.call : plural end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/gettext/module_translations.rb
lib/puppet/gettext/module_translations.rb
# frozen_string_literal: true require_relative '../../puppet/gettext/config' module Puppet::ModuleTranslations # @api private # Loads translation files for each of the specified modules, # if present. Requires the modules to have `forge_name` specified. # @param [[Module]] modules a list of modules for which to # load translations def self.load_from_modulepath(modules) modules.each do |mod| next unless mod.forge_name && mod.has_translations?(Puppet::GettextConfig.current_locale) module_name = mod.forge_name.tr('/', '-') if Puppet::GettextConfig.load_translations(module_name, mod.locale_directory, :po) Puppet.debug { "Loaded translations for #{module_name}." } elsif Puppet::GettextConfig.gettext_loaded? Puppet.debug { "Could not find translation files for #{module_name} at #{mod.locale_directory}. Skipping translation initialization." } else Puppet.warn_once("gettext_unavailable", "gettext_unavailable", "No gettext library found, skipping translation initialization.") end end end # @api private # Loads translation files that have been pluginsync'd for modules # from the $vardir. # @param [String] vardir the path to Puppet's vardir def self.load_from_vardir(vardir) locale = Puppet::GettextConfig.current_locale Dir.glob("#{vardir}/locales/#{locale}/*.po") do |f| module_name = File.basename(f, ".po") if Puppet::GettextConfig.load_translations(module_name, File.join(vardir, "locales"), :po) Puppet.debug { "Loaded translations for #{module_name}." } elsif Puppet::GettextConfig.gettext_loaded? Puppet.debug { "Could not load translations for #{module_name}." } else Puppet.warn_once("gettext_unavailable", "gettext_unavailable", "No gettext library found, skipping translation initialization.") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/gettext/config.rb
lib/puppet/gettext/config.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' require_relative '../../puppet/file_system' module Puppet::GettextConfig LOCAL_PATH = File.absolute_path('../../../locales', File.dirname(__FILE__)) POSIX_PATH = File.absolute_path('../../../../../share/locale', File.dirname(__FILE__)) WINDOWS_PATH = File.absolute_path('../../../../../../puppet/share/locale', File.dirname(__FILE__)) # This is the only domain name that won't be a symbol, making it unique from environments. DEFAULT_TEXT_DOMAIN = 'default-text-domain' # Load gettext helpers and track whether they're available. # Used instead of features because we initialize gettext before features is available. begin require 'fast_gettext' require 'locale' # Make translation methods (e.g. `_()` and `n_()`) available everywhere. class ::Object include FastGettext::Translation end @gettext_loaded = true rescue LoadError # Stub out gettext's `_` and `n_()` methods, which attempt to load translations, # with versions that do nothing require_relative '../../puppet/gettext/stubs' @gettext_loaded = false end # @api private # Whether we were able to require fast_gettext and locale # @return [Boolean] true if translation gems were successfully loaded def self.gettext_loaded? @gettext_loaded end # @api private # Returns the currently selected locale from FastGettext, # or 'en' of gettext has not been loaded # @return [String] the active locale def self.current_locale if gettext_loaded? FastGettext.default_locale else 'en' end end # @api private # Returns a list of the names of the loaded text domains # @return [[String]] the names of the loaded text domains def self.loaded_text_domains return [] if @gettext_disabled || !gettext_loaded? FastGettext.translation_repositories.keys end # @api private # Clears the translation repository for the given text domain, # creating it if it doesn't exist, then adds default translations # and switches to using this domain. # @param [String, Symbol] domain_name the name of the domain to create def self.reset_text_domain(domain_name) return if @gettext_disabled || !gettext_loaded? domain_name = domain_name.to_sym Puppet.debug { "Reset text domain to #{domain_name.inspect}" } FastGettext.add_text_domain(domain_name, type: :chain, chain: [], report_warning: false) copy_default_translations(domain_name) FastGettext.text_domain = domain_name end # @api private # Resets the thread's configured text_domain to the default text domain. # In Puppet Server, thread A may process a compile request that configures # a domain, while thread B may invalidate that environment and delete the # domain. That leaves thread A with an invalid text_domain selected. # To avoid that, clear_text_domain after any processing that needs the # non-default text domain. def self.clear_text_domain return if @gettext_disabled || !gettext_loaded? FastGettext.text_domain = nil end # @api private # Creates a default text domain containing the translations for # Puppet as the start of chain. When semantic_puppet gets initialized, # its translations are added to this chain. This is used as a cache # so that all non-module translations only need to be loaded once as # we create and reset environment-specific text domains. # # @return true if Puppet translations were successfully loaded, false # otherwise def self.create_default_text_domain return if @gettext_disabled || !gettext_loaded? FastGettext.add_text_domain(DEFAULT_TEXT_DOMAIN, type: :chain, chain: [], report_warning: false) FastGettext.default_text_domain = DEFAULT_TEXT_DOMAIN load_translations('puppet', puppet_locale_path, translation_mode(puppet_locale_path), DEFAULT_TEXT_DOMAIN) end # @api private # Switches the active text domain, if the requested domain exists. # @param [String, Symbol] domain_name the name of the domain to switch to def self.use_text_domain(domain_name) return if @gettext_disabled || !gettext_loaded? domain_name = domain_name.to_sym if FastGettext.translation_repositories.include?(domain_name) Puppet.debug { "Use text domain #{domain_name.inspect}" } FastGettext.text_domain = domain_name else Puppet.debug { "Requested unknown text domain #{domain_name.inspect}" } end end # @api private # Delete all text domains. def self.delete_all_text_domains FastGettext.translation_repositories.clear FastGettext.default_text_domain = nil FastGettext.text_domain = nil end # @api private # Deletes the text domain with the given name # @param [String, Symbol] domain_name the name of the domain to delete def self.delete_text_domain(domain_name) return if @gettext_disabled || !gettext_loaded? domain_name = domain_name.to_sym deleted = FastGettext.translation_repositories.delete(domain_name) if FastGettext.text_domain == domain_name Puppet.debug { "Deleted current text domain #{domain_name.inspect}: #{!deleted.nil?}" } FastGettext.text_domain = nil else Puppet.debug { "Deleted text domain #{domain_name.inspect}: #{!deleted.nil?}" } end end # @api private # Deletes all text domains except the default one def self.delete_environment_text_domains return if @gettext_disabled || !gettext_loaded? FastGettext.translation_repositories.keys.each do |key| # do not clear default translations next if key == DEFAULT_TEXT_DOMAIN FastGettext.translation_repositories.delete(key) end FastGettext.text_domain = nil end # @api private # Adds translations from the default text domain to the specified # text domain. Creates the default text domain if one does not exist # (this will load Puppet's translations). # # Since we are currently (Nov 2017) vendoring semantic_puppet, in normal # flows these translations will be copied along with Puppet's. # # @param [Symbol] domain_name the name of the domain to add translations to def self.copy_default_translations(domain_name) return if @gettext_disabled || !gettext_loaded? if FastGettext.default_text_domain.nil? create_default_text_domain end puppet_translations = FastGettext.translation_repositories[FastGettext.default_text_domain].chain FastGettext.translation_repositories[domain_name].chain.push(*puppet_translations) end # @api private # Search for puppet gettext config files # @return [String] path to the config, or nil if not found def self.puppet_locale_path if Puppet::FileSystem.exist?(LOCAL_PATH) LOCAL_PATH elsif Puppet::Util::Platform.windows? && Puppet::FileSystem.exist?(WINDOWS_PATH) WINDOWS_PATH elsif !Puppet::Util::Platform.windows? && Puppet::FileSystem.exist?(POSIX_PATH) POSIX_PATH else nil end end # @api private # Determine which translation file format to use # @param [String] conf_path the path to the gettext config file # @return [Symbol] :mo if in a package structure, :po otherwise def self.translation_mode(conf_path) if WINDOWS_PATH == conf_path || POSIX_PATH == conf_path :mo else :po end end # @api private # Prevent future gettext initializations def self.disable_gettext @gettext_disabled = true end # @api private # Attempt to load translations for the given project. # @param [String] project_name the project whose translations we want to load # @param [String] locale_dir the path to the directory containing translations # @param [Symbol] file_format translation file format to use, either :po or :mo # @return true if initialization succeeded, false otherwise def self.load_translations(project_name, locale_dir, file_format, text_domain = FastGettext.text_domain) if project_name.nil? || project_name.empty? raise Puppet::Error, "A project name must be specified in order to initialize translations." end return false if @gettext_disabled || !@gettext_loaded return false unless locale_dir && Puppet::FileSystem.exist?(locale_dir) unless file_format == :po || file_format == :mo raise Puppet::Error, "Unsupported translation file format #{file_format}; please use :po or :mo" end add_repository_to_domain(project_name, locale_dir, file_format, text_domain) true end # @api private # Add the translations for this project to the domain's repository chain # chain for the currently selected text domain, if needed. # @param [String] project_name the name of the project for which to load translations # @param [String] locale_dir the path to the directory containing translations # @param [Symbol] file_format the format of the translations files, :po or :mo def self.add_repository_to_domain(project_name, locale_dir, file_format, text_domain = FastGettext.text_domain) return if @gettext_disabled || !gettext_loaded? current_chain = FastGettext.translation_repositories[text_domain].chain repository = FastGettext::TranslationRepository.build(project_name, path: locale_dir, type: file_format, report_warning: false) current_chain << repository end # @api private # Sets FastGettext's locale to the current system locale def self.setup_locale return if @gettext_disabled || !gettext_loaded? set_locale(Locale.current.language) end # @api private # Sets the language in which to display strings. # @param [String] locale the language portion of a locale string (e.g. "ja") def self.set_locale(locale) return if @gettext_disabled || !gettext_loaded? # make sure we're not using the `available_locales` machinery FastGettext.default_available_locales = nil FastGettext.default_locale = locale end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/module_directory.rb
lib/puppet/functions/module_directory.rb
# frozen_string_literal: true # Finds an existing module and returns the path to its root directory. # # The argument to this function should be a module name String # For example, the reference `mysql` will search for the # directory `<MODULES DIRECTORY>/mysql` and return the first # found on the modulepath. # # This function can also accept: # # * Multiple String arguments, which will return the path of the **first** module # found, skipping non existing modules. # * An array of module names, which will return the path of the **first** module # found from the given names in the array, skipping non existing modules. # # The function returns `undef` if none of the given modules were found # # @since 5.4.0 # Puppet::Functions.create_function(:module_directory, Puppet::Functions::InternalFunction) do dispatch :module_directory do scope_param repeated_param 'String', :names end dispatch :module_directory_array do scope_param repeated_param 'Array[String]', :names end def module_directory_array(scope, names) module_directory(scope, *names) end def module_directory(scope, *names) names.each do |module_name| found = scope.compiler.environment.module(module_name) return found.path if found end nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/ceiling.rb
lib/puppet/functions/ceiling.rb
# frozen_string_literal: true # Returns the smallest `Integer` greater or equal to the argument. # Takes a single numeric value as an argument. # # This function is backwards compatible with the same function in stdlib # and accepts a `Numeric` value. A `String` that can be converted # to a floating point number can also be used in this version - but this # is deprecated. # # In general convert string input to `Numeric` before calling this function # to have full control over how the conversion is done. # Puppet::Functions.create_function(:ceiling) do dispatch :on_numeric do param 'Numeric', :val end dispatch :on_string do param 'String', :val end def on_numeric(x) x.ceil end def on_string(x) Puppet.warn_once('deprecations', 'ceiling_function_numeric_coerce_string', _("The ceiling() function's auto conversion of String to Float is deprecated - change to convert input before calling")) begin Float(x).ceil rescue TypeError, ArgumentError => _e # TRANSLATORS: 'ceiling' is a name and should not be translated raise(ArgumentError, _('ceiling(): cannot convert given value to a floating point value.')) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/find_file.rb
lib/puppet/functions/find_file.rb
# frozen_string_literal: true # Finds an existing file from a module and returns its path. # # This function accepts an argument that is a String as a `<MODULE NAME>/<FILE>` # reference, which searches 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`.) # # If this function is run via puppet agent, it checks for file existence on the # Puppet Primary server. If run via puppet apply, it checks on the local host. # In both cases, the check is performed before any resources are changed. # # This function can also accept: # # * An absolute String path, which checks for the existence of a file from anywhere on disk. # * Multiple String arguments, which returns the path of the **first** file # found, skipping nonexistent files. # * An array of string paths, which returns the path of the **first** file # found from the given paths in the array, skipping nonexistent files. # # The function returns `undef` if none of the given paths were found. # # @since 4.8.0 # Puppet::Functions.create_function(:find_file, Puppet::Functions::InternalFunction) do dispatch :find_file do scope_param repeated_param 'String', :paths end dispatch :find_file_array do scope_param repeated_param 'Array[String]', :paths_array end def find_file_array(scope, array) find_file(scope, *array) end def find_file(scope, *args) args.each do |file| found = Puppet::Parser::Files.find_file(file, scope.compiler.environment) if found && Puppet::FileSystem.exist?(found) return found end end nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/hiera_array.rb
lib/puppet/functions/hiera_array.rb
# frozen_string_literal: true require 'hiera/puppet_function' # 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). # # This function is deprecated in favor of the `lookup` function. While this function # continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # 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. # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera_array, Hiera::PuppetFunction) do init_dispatch def merge_type :unique end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/binary_file.rb
lib/puppet/functions/binary_file.rb
# frozen_string_literal: true # 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 # # @since 4.8.0 # Puppet::Functions.create_function(:binary_file, Puppet::Functions::InternalFunction) do dispatch :binary_file do scope_param param 'String', :path end def binary_file(scope, unresolved_path) path = Puppet::Parser::Files.find_file(unresolved_path, scope.compiler.environment) unless path && Puppet::FileSystem.exist?(path) # TRANSLATORS the string "binary_file()" should not be translated raise Puppet::ParseError, _("binary_file(): The given file '%{unresolved_path}' does not exist") % { unresolved_path: unresolved_path } end Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(Puppet::FileSystem.binread(path)) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/reduce.rb
lib/puppet/functions/reduce.rb
# frozen_string_literal: true # 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, hash, or other iterable object that 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`). # # @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 # Puppet::Functions.create_function(:reduce) do dispatch :reduce_without_memo do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :reduce_with_memo do param 'Iterable', :enumerable param 'Any', :memo block_param 'Callable[2,2]', :block end def reduce_without_memo(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) enum.reduce do |memo, x| yield(memo, x) rescue StopIteration return memo end end def reduce_with_memo(enumerable, given_memo) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) enum.reduce(given_memo) do |memo, x| yield(memo, x) rescue StopIteration return memo end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/slice.rb
lib/puppet/functions/slice.rb
# frozen_string_literal: true # Slices an array or hash into pieces of a given size. # # 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. # # @example Slicing a Hash # # ```puppet # $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. # # @example Slicing an Array # # ```puppet # 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]] # ``` # # @example Passing a lambda to a slice (optional) # # ```puppet # $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. # # @example Getting individual values of a slice # # ```puppet # $a.slice(2) |$first, $second| { ... } # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:slice) do dispatch :slice_Hash do param 'Hash[Any, Any]', :hash param 'Integer[1, default]', :slice_size optional_block_param end dispatch :slice_Enumerable do param 'Iterable', :enumerable param 'Integer[1, default]', :slice_size optional_block_param end def slice_Hash(hash, slice_size, &pblock) result = slice_Common(hash, slice_size, [], block_given? ? pblock : nil) block_given? ? hash : result end def slice_Enumerable(enumerable, slice_size, &pblock) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) result = slice_Common(enum, slice_size, nil, block_given? ? pblock : nil) block_given? ? enumerable : result end def slice_Common(o, slice_size, filler, pblock) serving_size = asserted_slice_serving_size(pblock, slice_size) enumerator = o.each_slice(slice_size) result = [] if serving_size == 1 begin if pblock loop do pblock.call(enumerator.next) end else loop do result << enumerator.next end end rescue StopIteration end else begin loop do a = enumerator.next if a.size < serving_size a = a.dup.fill(filler, a.length...serving_size) end pblock.call(*a) end rescue StopIteration end end if pblock o else result end end def asserted_slice_serving_size(pblock, slice_size) if pblock arity = pblock.arity serving_size = arity < 0 ? slice_size : arity else serving_size = 1 end if serving_size == 0 raise ArgumentError, _("slice(): block must define at least one parameter. Block has 0.") end unless serving_size == 1 || serving_size == slice_size raise ArgumentError, _("slice(): block must define one parameter, or the same number of parameters as the given size of the slice (%{slice_size}). Block has %{serving_size}; %{parameter_names}") % { slice_size: slice_size, serving_size: serving_size, parameter_names: pblock.parameter_names.join(', ') } end serving_size end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/empty.rb
lib/puppet/functions/empty.rb
# frozen_string_literal: true # Returns `true` if the given argument is an empty collection of values. # # This function can answer if one of the following is empty: # * `Array`, `Hash` - having zero entries # * `String`, `Binary` - having zero length # # For backwards compatibility with the stdlib function with the same name the # following data types are also accepted by the function instead of raising an error. # Using these is deprecated and will raise a warning: # # * `Numeric` - `false` is returned for all `Numeric` values. # * `Undef` - `true` is returned for all `Undef` values. # # @example Using `empty` # # ```puppet # notice([].empty) # notice(empty([])) # # would both notice 'true' # ``` # # @since Puppet 5.5.0 - support for Binary # Puppet::Functions.create_function(:empty) do dispatch :collection_empty do param 'Collection', :coll end dispatch :sensitive_string_empty do param 'Sensitive[String]', :str end dispatch :string_empty do param 'String', :str end dispatch :numeric_empty do param 'Numeric', :num end dispatch :binary_empty do param 'Binary', :bin end dispatch :undef_empty do param 'Undef', :x end def collection_empty(coll) coll.empty? end def sensitive_string_empty(str) str.unwrap.empty? end def string_empty(str) str.empty? end # For compatibility reasons - return false rather than error on floats and integers # (Yes, it is strange) # def numeric_empty(num) deprecation_warning_for('Numeric') false end def binary_empty(bin) bin.length == 0 end # For compatibility reasons - return true rather than error on undef # (Yes, it is strange, but undef was passed as empty string in 3.x API) # def undef_empty(x) true end def deprecation_warning_for(arg_type) file, line = Puppet::Pops::PuppetStack.top_of_stack msg = _("Calling function empty() with %{arg_type} value is deprecated.") % { arg_type: arg_type } Puppet.warn_once('deprecations', "empty-from-#{file}-#{line}", msg, file, line) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/include.rb
lib/puppet/functions/include.rb
# frozen_string_literal: true # 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 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 # Puppet::Functions.create_function(:include, Puppet::Functions::InternalFunction) do dispatch :include do scope_param # The function supports what the type system sees as Ruby runtime objects, and # they cannot be parameterized to find what is actually valid instances. # The validation is instead done in the function body itself via a call to # `transform_and_assert_classnames` on the calling scope. required_repeated_param 'Any', :names end def include(scope, *classes) if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'include' } ) end classes = scope.transform_and_assert_classnames(classes.flatten) result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) } scope.compiler.evaluate_classes(classes, scope, false) # Result is an Array[Class, 1, n] which allows chaining other operations result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/yaml_data.rb
lib/puppet/functions/yaml_data.rb
# frozen_string_literal: true require 'yaml' # The `yaml_data` is a hiera 5 `data_hash` data provider function. # See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for # how to use this function. # # @since 4.8.0 # Puppet::Functions.create_function(:yaml_data) do # @since 4.8.0 dispatch :yaml_data do param 'Struct[{path=>String[1]}]', :options param 'Puppet::LookupContext', :context end argument_mismatch :missing_path do param 'Hash', :options param 'Puppet::LookupContext', :context end def yaml_data(options, context) path = options['path'] context.cached_file_data(path) do |content| data = Puppet::Util::Yaml.safe_load(content, [Symbol], path) if data.is_a?(Hash) Puppet::Pops::Lookup::HieraConfig.symkeys_to_string(data) else msg = _("%{path}: file does not contain a valid yaml hash" % { path: path }) raise Puppet::DataBinding::LookupError, msg if Puppet[:strict] == :error && data != false Puppet.warning(msg) {} end rescue Puppet::Util::Yaml::YamlLoadError => ex # YamlLoadErrors include the absolute path to the file, so no need to add that raise Puppet::DataBinding::LookupError, _("Unable to parse %{message}") % { message: ex.message } end end def missing_path(options, context) "one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/tree_each.rb
lib/puppet/functions/tree_each.rb
# frozen_string_literal: true # Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # recursively and repeatedly using values from a data structure, then returns the unchanged data structure, or if # a lambda is not given, returns an `Iterator` for the tree. # # This function takes one mandatory argument, one optional, and an optional block in this order: # # 1. An `Array`, `Hash`, `Iterator`, or `Object` that the function will iterate over. # 2. An optional hash with the options: # * `include_containers` => `Optional[Boolean]` # default `true` - if containers should be given to the lambda # * `include_values` => `Optional[Boolean]` # default `true` - if non containers should be given to the lambda # * `include_root` => `Optional[Boolean]` # default `true` - if the root container should be given to the lambda # * `container_type` => `Optional[Type[Variant[Array, Hash, Object]]]` # a type that determines what a container is - can only # be set to a type that matches the default `Variant[Array, Hash, Object]`. # * `order` => `Enum[depth_first, breadth_first]` # default ´depth_first`, the order in which elements are visited # * `include_refs` => `Optional[Boolean]` # default `false`, if attributes in objects marked as bing of `reference` kind # should be included. # 3. An optional lambda, which the function calls for each element in the first argument. It must # accept one or two arguments; either `$path`, and `$value`, or just `$value`. # # @example Using the `tree_each` function # # `$data.tree_each |$path, $value| { <PUPPET CODE BLOCK> }` # `$data.tree_each |$value| { <PUPPET CODE BLOCK> }` # # or # # `tree_each($data) |$path, $value| { <PUPPET CODE BLOCK> }` # `tree_each($data) |$value| { <PUPPET CODE BLOCK> }` # # The parameter `$path` is always given as an `Array` containing the path that when applied to # the tree as `$data.dig(*$path) yields the `$value`. # The `$value` is the value at that path. # # For `Array` values, the path will contain `Integer` entries with the array index, # and for `Hash` values, the path will contain the hash key, which may be `Any` value. # For `Object` containers, the entry is the name of the attribute (a `String`). # # The tree is walked in either depth-first order, or in breadth-first order under the control of the # `order` option, yielding each `Array`, `Hash`, `Object`, and each entry/attribute. # The default is `depth_first` which means that children are processed before siblings. # An order of `breadth_first` means that siblings are processed before children. # # @example depth- or breadth-first order # # ```puppet # [1, [2, 3], 4] # ``` # # If containers are skipped, results in: # # * `depth_first` order `1`, `2`, `3`, `4` # * `breadth_first` order `1`, `4`,`2`, `3` # # If containers and root are included, results in: # # * `depth_first` order `[1, [2, 3], 4]`, `1`, `[2, 3]`, `2`, `3`, `4` # * `breadth_first` order `[1, [2, 3], 4]`, `1`, `[2, 3]`, `4`, `2`, `3` # # Typical use of the `tree_each` function include: # * a more efficient way to iterate over a tree than first using `flatten` on an array # as that requires a new (potentially very large) array to be created # * when a tree needs to be transformed and 'pretty printed' in a template # * avoiding having to write a special recursive function when tree contains hashes (flatten does # not work on hashes) # # @example A flattened iteration over a tree excluding Collections # # ```puppet # $data = [1, 2, [3, [4, 5]]] # $data.tree_each({include_containers => false}) |$v| { notice "$v" } # ``` # # This would call the lambda 5 times with with the following values in sequence: `1`, `2`, `3`, `4`, `5` # # @example A flattened iteration over a tree (including containers by default) # # ```puppet # $data = [1, 2, [3, [4, 5]]] # $data.tree_each |$v| { notice "$v" } # ``` # # This would call the lambda 7 times with the following values in sequence: # `1`, `2`, `[3, [4, 5]]`, `3`, `[4, 5]`, `4`, `5` # # @example A flattened iteration over a tree (including only non root containers) # # ```puppet # $data = [1, 2, [3, [4, 5]]] # $data.tree_each({include_values => false, include_root => false}) |$v| { notice "$v" } # ``` # # This would call the lambda 2 times with the following values in sequence: # `[3, [4, 5]]`, `[4, 5]` # # Any Puppet Type system data type can be used to filter what is # considered to be a container, but it must be a narrower type than one of # the default `Array`, `Hash`, `Object` types - for example it is not possible to make a # `String` be a container type. # # @example Only `Array` as container type # # ```puppet # $data = [1, {a => 'hello', b => [100, 200]}, [3, [4, 5]]] # $data.tree_each({container_type => Array, include_containers => false} |$v| { notice "$v" } # ``` # # Would call the lambda 5 times with `1`, `{a => 'hello', b => [100, 200]}`, `3`, `4`, `5` # # **Chaining** When calling `tree_each` without a lambda the function produces an `Iterator` # that can be chained into another iteration. Thus it is easy to use one of: # # * `reverse_each` - get "leaves before root" # * `filter` - prune the tree # * `map` - transform each element # # Note than when chaining, the value passed on is a `Tuple` with `[path, value]`. # # @example Pruning a tree # # ```puppet # # A tree of some complexity (here very simple for readability) # $tree = [ # { name => 'user1', status => 'inactive', id => '10'}, # { name => 'user2', status => 'active', id => '20'} # ] # notice $tree.tree_each.filter |$v| { # $value = $v[1] # $value =~ Hash and $value[status] == active # } # ``` # # Would notice `[[[1], {name => user2, status => active, id => 20}]]`, which can then be processed # further as each filtered result appears as a `Tuple` with `[path, value]`. # # # For general examples that demonstrates iteration see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 5.0.0 # Puppet::Functions.create_function(:tree_each) do local_types do type "OptionsType = Struct[{\ container_type => Optional[Type],\ include_root => Optional[Boolean], include_containers => Optional[Boolean],\ include_values => Optional[Boolean],\ order => Optional[Enum[depth_first, breadth_first]],\ include_refs => Optional[Boolean]\ }]" end dispatch :tree_Enumerable2 do param 'Variant[Iterator, Array, Hash, Object]', :tree optional_param 'OptionsType', :options block_param 'Callable[2,2]', :block end dispatch :tree_Enumerable1 do param 'Variant[Iterator, Array, Hash, Object]', :tree optional_param 'OptionsType', :options block_param 'Callable[1,1]', :block end dispatch :tree_Iterable do param 'Variant[Iterator, Array, Hash, Object]', :tree optional_param 'OptionsType', :options end def tree_Enumerable1(enum, options = {}, &block) iterator(enum, options).each { |_, v| yield(v) } enum end def tree_Enumerable2(enum, options = {}, &block) iterator(enum, options).each { |path, v| yield(path, v) } enum end def tree_Iterable(enum, options = {}, &block) Puppet::Pops::Types::Iterable.on(iterator(enum, options)) end def iterator(enum, options) if depth_first?(options) Puppet::Pops::Types::Iterable::DepthFirstTreeIterator.new(enum, options) else Puppet::Pops::Types::Iterable::BreadthFirstTreeIterator.new(enum, options) end end def depth_first?(options) (order = options['order']).nil? ? true : order == 'depth_first' end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/eyaml_lookup_key.rb
lib/puppet/functions/eyaml_lookup_key.rb
# frozen_string_literal: true # The `eyaml_lookup_key` is a hiera 5 `lookup_key` data provider function. # See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-hiera-eyaml) for # how to use this function. # # @since 5.0.0 # Puppet::Functions.create_function(:eyaml_lookup_key) do unless Puppet.features.hiera_eyaml? raise Puppet::DataBinding::LookupError, 'Lookup using eyaml lookup_key function is only supported when the hiera_eyaml library is present' end require 'hiera/backend/eyaml/encryptor' require 'hiera/backend/eyaml/utils' require 'hiera/backend/eyaml/options' require 'hiera/backend/eyaml/parser/parser' dispatch :eyaml_lookup_key do param 'String[1]', :key param 'Hash[String[1],Any]', :options param 'Puppet::LookupContext', :context end def eyaml_lookup_key(key, options, context) return context.cached_value(key) if context.cache_has_key(key) # Can't do this with an argument_mismatch dispatcher since there is no way to declare a struct that at least # contains some keys but may contain other arbitrary keys. unless options.include?('path') # TRANSLATORS 'eyaml_lookup_key':, 'path', 'paths' 'glob', 'globs', 'mapped_paths', and lookup_key should not be translated raise ArgumentError, _("'eyaml_lookup_key': one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml"\ " when using this lookup_key function") end # nil key is used to indicate that the cache contains the raw content of the eyaml file raw_data = context.cached_value(nil) if raw_data.nil? raw_data = load_data_hash(options, context) context.cache(nil, raw_data) end context.not_found unless raw_data.include?(key) context.cache(key, decrypt_value(raw_data[key], context, options, key)) end def load_data_hash(options, context) path = options['path'] context.cached_file_data(path) do |content| data = Puppet::Util::Yaml.safe_load(content, [Symbol], path) if data.is_a?(Hash) Puppet::Pops::Lookup::HieraConfig.symkeys_to_string(data) else msg = _("%{path}: file does not contain a valid yaml hash") % { path: path } raise Puppet::DataBinding::LookupError, msg if Puppet[:strict] == :error && data != false Puppet.warning(msg) {} end rescue Puppet::Util::Yaml::YamlLoadError => ex # YamlLoadErrors include the absolute path to the file, so no need to add that raise Puppet::DataBinding::LookupError, _("Unable to parse %{message}") % { message: ex.message } end end def decrypt_value(value, context, options, key) case value when String decrypt(value, context, options, key) when Hash result = {} value.each_pair { |k, v| result[context.interpolate(k)] = decrypt_value(v, context, options, key) } result when Array value.map { |v| decrypt_value(v, context, options, key) } else value end end def decrypt(data, context, options, key) if encrypted?(data) # Options must be set prior to each call to #parse since they end up as static variables in # the Options class. They cannot be set once before #decrypt_value is called, since each #decrypt # might cause a new lookup through interpolation. That lookup in turn, might use a different eyaml # config. # Hiera::Backend::Eyaml::Options.set(options) begin tokens = Hiera::Backend::Eyaml::Parser::ParserFactory.hiera_backend_parser.parse(data) data = tokens.map(&:to_plain_text).join.chomp rescue StandardError => ex raise Puppet::DataBinding::LookupError, _("hiera-eyaml backend error decrypting %{data} when looking up %{key} in %{path}. Error was %{message}") % { data: data, key: key, path: options['path'], message: ex.message } end end context.interpolate(data) end def encrypted?(data) /.*ENC\[.*?\]/ =~ data ? true : false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/upcase.rb
lib/puppet/functions/upcase.rb
# frozen_string_literal: true # Converts a String, Array or Hash (recursively) into upper case. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String`, its upper case version is returned. This is done using Ruby system locale which handles some, but not all # special international up-casing rules (for example German double-s ß is upcased to "SS", whereas upper case double-s # is downcased to ß). # * For `Array` and `Hash` the conversion to upper case is recursive and each key and value must be convertible by # this function. # * When a `Hash` is converted, some keys could result in the same key - in those cases, the # latest key-value wins. For example if keys "aBC", and "abC" where both present, after upcase there would only be one # key "ABC". # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible. # To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # @example Converting a String to upper case # ```puppet # 'hello'.upcase() # upcase('hello') # ``` # Would both result in `"HELLO"` # # @example Converting an Array to upper case # ```puppet # ['a', 'b'].upcase() # upcase(['a', 'b']) # ``` # Would both result in `['A', 'B']` # # @example Converting a Hash to upper case # ```puppet # {'a' => 'hello', 'b' => 'goodbye'}.upcase() # ``` # Would result in `{'A' => 'HELLO', 'B' => 'GOODBYE'}` # # @example Converting a recursive structure # ```puppet # ['a', 'b', ['c', ['d']], {'x' => 'y'}].upcase # ``` # Would result in `['A', 'B', ['C', ['D']], {'X' => 'Y'}]` # Puppet::Functions.create_function(:upcase) do local_types do type 'StringData = Variant[String, Numeric, Array[StringData], Hash[StringData, StringData]]' end dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_array do param 'Array[StringData]', :arg end dispatch :on_hash do param 'Hash[StringData, StringData]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.upcase end def on_array(a) a.map { |x| do_upcase(x) } end def on_hash(h) result = {} h.each_pair { |k, v| result[do_upcase(k)] = do_upcase(v) } result end def do_upcase(x) x.is_a?(String) ? x.upcase : call_function('upcase', x) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/type.rb
lib/puppet/functions/type.rb
# frozen_string_literal: true # 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 # Puppet::Functions.create_function(:type) do dispatch :type_detailed do param 'Any', :value optional_param 'Enum[detailed]', :inference_method end dispatch :type_parameterized do param 'Any', :value param 'Enum[reduced]', :inference_method end dispatch :type_generalized do param 'Any', :value param 'Enum[generalized]', :inference_method end def type_detailed(value, _ = nil) Puppet::Pops::Types::TypeCalculator.infer_set(value) end def type_parameterized(value, _) Puppet::Pops::Types::TypeCalculator.infer(value) end def type_generalized(value, _) Puppet::Pops::Types::TypeCalculator.infer(value).generalize end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/hiera_hash.rb
lib/puppet/functions/hiera_hash.rb
# frozen_string_literal: true require 'hiera/puppet_function' # Finds all matches of a key throughout the hierarchy and returns them in a merged hash. # # This function is deprecated in favor of the `lookup` function. While this function # continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # 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. # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera_hash, Hiera::PuppetFunction) do init_dispatch def merge_type :hash end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/annotate.rb
lib/puppet/functions/annotate.rb
# frozen_string_literal: true # Handles annotations on objects. The function can be used in four different ways. # # With two arguments, an `Annotation` type and an object, the function returns the annotation # for the object of the given type, or `undef` if no such annotation exists. # # @example Using `annotate` with two arguments # # ```puppet # $annotation = Mod::NickNameAdapter.annotate(o) # # $annotation = annotate(Mod::NickNameAdapter.annotate, o) # ``` # # With three arguments, an `Annotation` type, an object, and a block, the function returns the # annotation for the object of the given type, or annotates it with a new annotation initialized # from the hash returned by the given block when no such annotation exists. The block will not # be called when an annotation of the given type is already present. # # @example Using `annotate` with two arguments and a block # # ```puppet # $annotation = Mod::NickNameAdapter.annotate(o) || { { 'nick_name' => 'Buddy' } } # # $annotation = annotate(Mod::NickNameAdapter.annotate, o) || { { 'nick_name' => 'Buddy' } } # ``` # # With three arguments, an `Annotation` type, an object, and an `Hash`, the function will annotate # the given object with a new annotation of the given type that is initialized from the given hash. # An existing annotation of the given type is discarded. # # @example Using `annotate` with three arguments where third argument is a Hash # # ```puppet # $annotation = Mod::NickNameAdapter.annotate(o, { 'nick_name' => 'Buddy' }) # # $annotation = annotate(Mod::NickNameAdapter.annotate, o, { 'nick_name' => 'Buddy' }) # ``` # # With three arguments, an `Annotation` type, an object, and an the string `clear`, the function will # clear the annotation of the given type in the given object. The old annotation is returned if # it existed. # # @example Using `annotate` with three arguments where third argument is the string 'clear' # # ```puppet # $annotation = Mod::NickNameAdapter.annotate(o, clear) # # $annotation = annotate(Mod::NickNameAdapter.annotate, o, clear) # ``` # # With three arguments, the type `Pcore`, an object, and a Hash of hashes keyed by `Annotation` types, # the function will annotate the given object with all types used as keys in the given hash. Each annotation # is initialized with the nested hash for the respective type. The annotated object is returned. # # @example Add multiple annotations to a new instance of `Mod::Person` using the `Pcore` type. # # ```puppet # $person = Pcore.annotate(Mod::Person({'name' => 'William'}), { # Mod::NickNameAdapter >= { 'nick_name' => 'Bill' }, # Mod::HobbiesAdapter => { 'hobbies' => ['Ham Radio', 'Philatelist'] } # }) # ``` # # @since 5.0.0 # Puppet::Functions.create_function(:annotate) do dispatch :annotate do param 'Type[Annotation]', :type param 'Any', :value optional_block_param 'Callable[0, 0]', :block end dispatch :annotate_new do param 'Type[Annotation]', :type param 'Any', :value param 'Variant[Enum[clear],Hash[Pcore::MemberName,Any]]', :annotation_hash end dispatch :annotate_multi do param 'Type[Pcore]', :type param 'Any', :value param 'Hash[Type[Annotation], Hash[Pcore::MemberName,Any]]', :annotations end # @param type [Annotation] the annotation type # @param value [Object] the value to annotate # @param block [Proc] optional block to produce the annotation hash # def annotate(type, value, &block) type.implementation_class.annotate(value, &block) end # @param type [Annotation] the annotation type # @param value [Object] the value to annotate # @param annotation_hash [Hash{String => Object}] the annotation hash # def annotate_new(type, value, annotation_hash) type.implementation_class.annotate_new(value, annotation_hash) end # @param type [Type] the Pcore type # @param value [Object] the value to annotate # @param annotations [Hash{Annotation => Hash{String => Object}}] hash of annotation hashes # def annotate_multi(type, value, annotations) type.implementation_class.annotate(value, annotations) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/index.rb
lib/puppet/functions/index.rb
# frozen_string_literal: true # Returns the index (or key in a hash) to a first-found value in an `Iterable` value. # # When called with a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # the lambda is called repeatedly using each value in a data structure until the lambda returns a "truthy" value which # makes the function return the index or key, or if the end of the iteration is reached, undef is returned. # # This function can be called in two different ways; with a value to be searched for, or with # a lambda that determines if an entry in the iterable matches. # # When called with a lambda the function takes two mandatory arguments, in this order: # # 1. An array, hash, string, or other iterable object that the function will iterate over. # 2. A lambda, which the function calls for each element in the first argument. It can request one (value) or two (index/key, value) parameters. # # @example Using the `index` function # # `$data.index |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `index($data) |$parameter| { <PUPPET CODE BLOCK> }` # # @example Using the `index` function with an Array and a one-parameter lambda # # ```puppet # $data = ["routers", "servers", "workstations"] # notice $data.index |$value| { $value == 'servers' } # notices 1 # notice $data.index |$value| { $value == 'hosts' } # notices undef # ``` # # @example Using the `index` function with a Hash and a one-parameter lambda # # ```puppet # $data = {types => ["routers", "servers", "workstations"], colors => ['red', 'blue', 'green']} # notice $data.index |$value| { 'servers' in $value } # notices 'types' # notice $data.index |$value| { 'red' in $value } # notices 'colors' # ``` # Note that the lambda gets the value and not an array with `[key, value]` as in other # iterative functions. # # Using a lambda that accepts two values works the same way. The lambda gets the index/key # as the first parameter and the value as the second parameter. # # @example Using the `index` function with an Array and a two-parameter lambda # # ```puppet # # Find the first even numbered index that has a non String value # $data = [key1, 1, 3, 5] # notice $data.index |$idx, $value| { $idx % 2 == 0 and $value !~ String } # notices 2 # ``` # # When called on a `String`, the lambda is given each character as a value. What is typically wanted is to # find a sequence of characters which is achieved by calling the function with a value to search for instead # of giving a lambda. # # # @example Using the `index` function with a String, search for first occurrence of a sequence of characters # # ```puppet # # Find first occurrence of 'ah' # $data = "blablahbleh" # notice $data.index('ah') # notices 5 # ``` # # @example Using the `index` function with a String, search for first occurrence of a regular expression # # ```puppet # # Find first occurrence of 'la' or 'le' # $data = "blablahbleh" # notice $data.index(/l(a|e)/ # notices 1 # ``` # # When searching in a `String` with a given value that is neither `String` nor `Regexp` the answer is always `undef`. # When searching in any other iterable, the value is matched against each value in the iteration using strict # Ruby `==` semantics. If Puppet Language semantics are wanted (where string compare is case insensitive) use a # lambda and the `==` operator in Puppet. # # @example Using the `index` function to search for a given value in an Array # # ```puppet # $data = ['routers', 'servers', 'WORKstations'] # notice $data.index('servers') # notices 1 # notice $data.index('workstations') # notices undef (not matching case) # ``` # # For an general examples that demonstrates iteration, see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 6.3.0 # Puppet::Functions.create_function(:index) do dispatch :index_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :index_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :index_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :index_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end dispatch :string_index do param 'String', :str param 'Variant[String,Regexp]', :match end dispatch :index_value do param 'Iterable', :enumerable param 'Any', :match end def index_Hash_1(hash) hash.each_pair { |x, y| return x if yield(y) } nil end def index_Hash_2(hash) hash.each_pair.any? { |x, y| return x if yield(x, y) } nil end def index_Enumerable_1(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if yield(entry[1]) } else enum.each_with_index { |e, i| return i if yield(e) } end nil end def index_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if yield(*entry) } else enum.each_with_index { |e, i| return i if yield(i, e) } end nil end def string_index(str, match) str.index(match) end def index_value(enumerable, match) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.each { |entry| return entry[0] if entry[1] == match } else enum.each_with_index { |e, i| return i if e == match } end nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/new.rb
lib/puppet/functions/new.rb
# frozen_string_literal: true # 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. # # @example Converting to Integer in multiple ways # # ```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. # # @example Converting to Numeric in different ways # # ```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 created 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 '0xa' # $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. Selects single or double quotes based on content, or uses double quotes if alternative flag `#` is used. # | 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 # Optional[SemVerQualifier] $build = undef # ) # # function SemVer.new(SemVerHash $hash_args) # ``` # # @example `SemVer` and `SemVerRange` usage # # ```puppet # # As a type, SemVer can describe disjunct ranges which versions can be # # matched against - here the type is constructed with two # # SemVerRange objects. # # # $t = SemVer[ # SemVerRange('>=1.0.0 <2.0.0'), # SemVerRange('>=3.0.0 <4.0.0') # ] # notice(SemVer('1.2.3') =~ $t) # true # notice(SemVer('2.3.4') =~ $t) # false # notice(SemVer('3.4.5') =~ $t) # true # ``` # # ### Creating a `SemVerRange` # # A `SemVerRange` object represents a range of `SemVer`. It can be created from # a `String`, or from two `SemVer` instances, where either end can be given as
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/hiera_include.rb
lib/puppet/functions/hiera_include.rb
# frozen_string_literal: true require 'hiera/puppet_function' # 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. # # This function is deprecated in favor of the `lookup` function in combination with `include`. # While this function continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # @example Using `lookup` and `include` instead of of the deprecated `hiera_include` # # ```puppet # # In site.pp, outside of any node definitions and below any top-scope variables: # lookup('classes', Array[String], 'unique').include # ``` # # 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". # ``` # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera_include, Hiera::PuppetFunction) do init_dispatch def merge_type :unique end def post_lookup(scope, key, value) raise Puppet::ParseError, _("Could not find data item %{key}") % { key: key } if value.nil? call_function_with_scope(scope, 'include', value) unless value.empty? end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/keys.rb
lib/puppet/functions/keys.rb
# frozen_string_literal: true # Returns the keys of a hash as an Array # # @example Using `keys` # # ```puppet # $hsh = {"apples" => 3, "oranges" => 4 } # $hsh.keys() # keys($hsh) # # both results in the array ["apples", "oranges"] # ``` # # * Note that a hash in the puppet language accepts any data value (including `undef`) unless # it is constrained with a `Hash` data type that narrows the allowed data types. # * For an empty hash, an empty array is returned. # * The order of the keys is the same as the order in the hash (typically the order in which they were added). # Puppet::Functions.create_function(:keys) do dispatch :keys do param 'Hash', :hsh end def keys(hsh) hsh.keys end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/filter.rb
lib/puppet/functions/filter.rb
# frozen_string_literal: true # 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, hash, or other iterable object that 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 # @since 6.0.0 does not filter if truthy value is returned from block # Puppet::Functions.create_function(:filter) do dispatch :filter_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :filter_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :filter_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :filter_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def filter_Hash_1(hash) result = hash.select { |x, y| yield([x, y]) } # Ruby 1.8.7 returns Array result = result.to_h unless result.is_a? Hash result end def filter_Hash_2(hash) result = hash.select { |x, y| yield(x, y) } # Ruby 1.8.7 returns Array result = result.to_h unless result.is_a? Hash result end def filter_Enumerable_1(enumerable) result = [] enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) begin enum.each do |value| result << value if yield(value) end rescue StopIteration end result end def filter_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? result = {} enum.each { |k, v| result[k] = v if yield(k, v) } else result = [] begin enum.each_with_index do |value, index| result << value if yield(index, value) end rescue StopIteration end end result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/sort.rb
lib/puppet/functions/sort.rb
# frozen_string_literal: true # Sorts an Array numerically or lexicographically or the characters of a String lexicographically. # Please note: This function is based on Ruby String comparison and as such may not be entirely UTF8 compatible. # To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # This function is compatible with the function `sort()` in `stdlib`. # * Comparison of characters in a string always uses a system locale and may not be what is expected for a particular locale # * Sorting is based on Ruby's `<=>` operator unless a lambda is given that performs the comparison. # * comparison of strings is case dependent (use lambda with `compare($a,$b)` to ignore case) # * comparison of mixed data types raises an error (if there is the need to sort mixed data types use a lambda) # # Also see the `compare()` function for information about comparable data types in general. # # @example Sorting a String # # ```puppet # notice(sort("xadb")) # notices 'abdx' # ``` # # @example Sorting an Array # # ```puppet # notice(sort([3,6,2])) # notices [2, 3, 6] # ``` # # @example Sorting with a lambda # # ```puppet # notice(sort([3,6,2]) |$a,$b| { compare($a, $b) }) # notices [2, 3, 6] # notice(sort([3,6,2]) |$a,$b| { compare($b, $a) }) # notices [6, 3, 2] # ``` # # @example Case independent sorting with a lambda # # ```puppet # notice(sort(['A','b','C'])) # notices ['A', 'C', 'b'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b) }) # notices ['A', 'b', 'C'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b, true) }) # notices ['A', 'b', 'C'] # notice(sort(['A','b','C']) |$a,$b| { compare($a, $b, false) }) # notices ['A','C', 'b'] # ``` # # @example Sorting Array with Numeric and String so that numbers are before strings # # ```puppet # notice(sort(['b', 3, 'a', 2]) |$a, $b| { # case [$a, $b] { # [String, Numeric] : { 1 } # [Numeric, String] : { -1 } # default: { compare($a, $b) } # } # }) # ``` # Would notice `[2,3,'a','b']` # # @since 6.0.0 - supporting a lambda to do compare # Puppet::Functions.create_function(:sort) do dispatch :sort_string do param 'String', :string_value optional_block_param 'Callable[2,2]', :block end dispatch :sort_array do param 'Array', :array_value optional_block_param 'Callable[2,2]', :block end def sort_string(s, &block) sort_array(s.split(''), &block).join('') end def sort_array(a, &block) a.sort(&block) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/chomp.rb
lib/puppet/functions/chomp.rb
# frozen_string_literal: true # Returns a new string with the record separator character(s) removed. # The record separator is the line ending characters `\r` and `\n`. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes `\r\n`, `\n` or `\r` from the end of a string. # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing line endings # ```puppet # "hello\r\n".chomp() # chomp("hello\r\n") # ``` # Would both result in `"hello"` # # @example Removing line endings in an array # ```puppet # ["hello\r\n", "hi\r\n"].chomp() # chomp(["hello\r\n", "hi\r\n"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:chomp) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.chomp end def on_iterable(a) a.map { |x| do_chomp(x) } end def do_chomp(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.chomp : x end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/length.rb
lib/puppet/functions/length.rb
# frozen_string_literal: true # Returns the length of an Array, Hash, String, or Binary value. # # The returned value is a positive integer indicating the number # of elements in the container; counting (possibly multibyte) characters for a `String`, # bytes in a `Binary`, number of elements in an `Array`, and number of # key-value associations in a Hash. # # @example Using `length` # # ```puppet # "roses".length() # 5 # length("violets") # 7 # [10, 20].length # 2 # {a => 1, b => 3}.length # 2 # ``` # # @since 5.5.0 - also supporting Binary # Puppet::Functions.create_function(:length) do dispatch :collection_length do param 'Collection', :arg end dispatch :string_length do param 'String', :arg end dispatch :binary_length do param 'Binary', :arg end def collection_length(col) col.size end def string_length(s) s.length end def binary_length(bin) bin.length end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/unique.rb
lib/puppet/functions/unique.rb
# frozen_string_literal: true # Produces a unique set of values from an `Iterable` argument. # # * If the argument is a `String`, the unique set of characters are returned as a new `String`. # * If the argument is a `Hash`, the resulting hash associates a set of keys with a set of unique values. # * For all other types of `Iterable` (`Array`, `Iterator`) the result is an `Array` with # a unique set of entries. # * Comparison of all `String` values are case sensitive. # * An optional code block can be given - if present it is given each candidate value and its return is used instead of the given value. This # enables transformation of the value before comparison. The result of the lambda is only used for comparison. # * The optional code block when used with a hash is given each value (not the keys). # # @example Using unique with a String # # ```puppet # # will produce 'abc' # "abcaabb".unique # ``` # # @example Using unique with an Array # # ```puppet # # will produce ['a', 'b', 'c'] # ['a', 'b', 'c', 'a', 'a', 'b'].unique # ``` # # @example Using unique with a Hash # # ```puppet # # will produce { ['a', 'b'] => [10], ['c'] => [20]} # {'a' => 10, 'b' => 10, 'c' => 20}.unique # # # will produce { 'a' => 10, 'c' => 20 } (use first key with first value) # Hash.new({'a' => 10, 'b' => 10, 'c' => 20}.unique.map |$k, $v| { [ $k[0] , $v[0]] }) # # # will produce { 'b' => 10, 'c' => 20 } (use last key with first value) # Hash.new({'a' => 10, 'b' => 10, 'c' => 20}.unique.map |$k, $v| { [ $k[-1] , $v[0]] }) # ``` # # @example Using unique with an Iterable # # ``` # # will produce [3, 2, 1] # [1,2,2,3,3].reverse_each.unique # ``` # # @example Using unique with a lambda # # ```puppet # # will produce [['sam', 'smith'], ['sue', 'smith']] # [['sam', 'smith'], ['sam', 'brown'], ['sue', 'smith']].unique |$x| { $x[0] } # # # will produce [['sam', 'smith'], ['sam', 'brown']] # [['sam', 'smith'], ['sam', 'brown'], ['sue', 'smith']].unique |$x| { $x[1] } # # # will produce ['aBc', 'bbb'] (using a lambda to make comparison using downcased (%d) strings) # ['aBc', 'AbC', 'bbb'].unique |$x| { String($x,'%d') } # # # will produce {[a] => [10], [b, c, d, e] => [11, 12, 100]} # {a => 10, b => 11, c => 12, d => 100, e => 11}.unique |$v| { if $v > 10 { big } else { $v } } # ``` # # Note that for `Hash` the result is slightly different than for the other data types. For those the result contains the # *first-found* unique value, but for `Hash` it contains associations from a set of keys to the set of values clustered by the # equality lambda (or the default value equality if no lambda was given). This makes the `unique` function more versatile for hashes # in general, while requiring that the simple computation of "hash's unique set of values" is performed as `$hsh.map |$k, $v| { $v }.unique`. # (Generally, it's meaningless to compute the unique set of hash keys because they are unique by definition. However, the # situation can change if the hash keys are processed with a different lambda for equality. For this unique computation, # first map the hash to an array of its keys.) # If the more advanced clustering is wanted for one of the other data types, simply transform it into a `Hash` as shown in the # following example. # # @example turning a string or array into a hash with index keys # # ```puppet # # Array ['a', 'b', 'c'] to Hash with index results in # # {0 => 'a', 1 => 'b', 2 => 'c'} # Hash(['a', 'b', 'c'].map |$i, $v| { [$i, $v]}) # # # String "abc" to Hash with index results in # # {0 => 'a', 1 => 'b', 2 => 'c'} # Hash(Array("abc").map |$i,$v| { [$i, $v]}) # "abc".to(Array).map |$i,$v| { [$i, $v]}.to(Hash) # ``` # # @since Puppet 5.0.0 # Puppet::Functions.create_function(:unique) do dispatch :unique_string do param 'String', :string optional_block_param 'Callable[String]', :block end dispatch :unique_hash do param 'Hash', :hash optional_block_param 'Callable[Any]', :block end dispatch :unique_array do param 'Array', :array optional_block_param 'Callable[Any]', :block end dispatch :unique_iterable do param 'Iterable', :iterable optional_block_param 'Callable[Any]', :block end def unique_string(string, &block) string.split('').uniq(&block).join('') end def unique_hash(hash, &block) block = ->(v) { v } unless block_given? result = Hash.new { |h, k| h[k] = { :keys => [], :values => [] } } hash.each_pair do |k, v| rc = result[block.call(v)] rc[:keys] << k rc[:values] << v end # reduce the set of possibly duplicated value entries inverted = {} result.each_pair { |_k, v| inverted[v[:keys]] = v[:values].uniq } inverted end def unique_array(array, &block) array.uniq(&block) end def unique_iterable(iterable, &block) Puppet::Pops::Types::Iterable.on(iterable).uniq(&block) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/getvar.rb
lib/puppet/functions/getvar.rb
# frozen_string_literal: true # Digs into a variable with dot notation to get a value from a structure. # # **To get the value from a variable** (that may or may not exist), call the function with # one or two arguments: # # * The **first** argument must be a string, and must start with a variable name without leading `$`, # for example `get('facts')`. The variable name can be followed # by a _dot notation navigation string_ to dig out a value in the array or hash value # of the variable. # * The **optional second** argument can be any type of value and it is used as the # _default value_ if the function would otherwise return `undef`. # * An **optional lambda** for error handling taking one `Error` argument. # # **Dot notation navigation string** - # The dot string consists of period `.` separated segments where each # segment is either the index into an array or the value of a hash key. # If a wanted key contains a period it must be quoted to avoid it being # taken as a segment separator. Quoting can be done with either # single quotes `'` or double quotes `"`. If a segment is # a decimal number it is converted to an Integer index. This conversion # can be prevented by quoting the value. # # @example Getting the value of a variable # ```puppet # getvar('facts') # results in the value of $facts # ``` # # @example Navigating into a variable # ```puppet # getvar('facts.os.family') # results in the value of $facts['os']['family'] # ``` # # @example Using a default value # ```puppet # $x = [1,2,[{'name' =>'waldo'}]] # getvar('x.2.1.name', 'not waldo') # # results in 'not waldo' # ``` # # For further examples and how to perform error handling, see the `get()` function # which this function delegates to after having resolved the variable value. # # @since 6.0.0 - the ability to dig into the variable's value with dot notation. # Puppet::Functions.create_function(:getvar, Puppet::Functions::InternalFunction) do dispatch :get_from_navigation do scope_param param 'Pattern[/\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*(?:\.|\Z)/]', :get_string optional_param 'Any', :default_value optional_block_param 'Callable[1,1]', :block end argument_mismatch :invalid_variable_error do param 'String', :get_string optional_param 'Any', :default_value optional_block_param 'Callable', :block end def invalid_variable_error(navigation, default_value = nil, &block) _("The given string does not start with a valid variable name") end # Gets a result from a navigation string starting with $var # def get_from_navigation(scope, navigation, default_value = nil, &block) # asserted to start with a valid variable name - dig out the variable matches = navigation.match(/^((::)?(\w+::)*\w+)(.*)\z/) navigation = matches[4] if navigation[0] == '.' navigation = navigation[1..] else unless navigation.empty? raise ArgumentError, _("First character after var name in get string must be a '.' - got %{char}") % { char: navigation[0] } end end get_from_var_name(scope, matches[1], navigation, default_value, &block) end # Gets a result from a $var name and a navigation string # def get_from_var_name(scope, var_string, navigation, default_value = nil, &block) catch(:undefined_variable) do return call_function_with_scope(scope, 'get', scope.lookupvar(var_string), navigation, default_value, &block) end default_value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/max.rb
lib/puppet/functions/max.rb
# frozen_string_literal: true # Returns the highest value among a variable number of arguments. # Takes at least one argument. # # This function is (with one exception) compatible with the stdlib function # with the same name and performs deprecated type conversion before # comparison as follows: # # * If a value converted to String is an optionally '-' prefixed, # string of digits, one optional decimal point, followed by optional # decimal digits - then the comparison is performed on the values # converted to floating point. # * If a value is not considered convertible to float, it is converted # to a `String` and the comparison is a lexical compare where min is # the lexicographical later value. # * A lexicographical compare is performed in a system locale - international # characters may therefore not appear in what a user thinks is the correct order. # * The conversion rules apply to values in pairs - the rule must hold for both # values - a value may therefore be compared using different rules depending # on the "other value". # * The returned result found to be the "highest" is the original unconverted value. # # The above rules have been deprecated in Puppet 6.0.0 as they produce strange results when # given values of mixed data types. In general, either convert values to be # all `String` or all `Numeric` values before calling the function, or call the # function with a lambda that performs type conversion and comparison. This because one # simply cannot compare `Boolean` with `Regexp` and with any arbitrary `Array`, `Hash` or # `Object` and getting a meaningful result. # # The one change in the function's behavior is when the function is given a single # array argument. The stdlib implementation would return that array as the result where # it now instead returns the max value from that array. # # @example 'max of values - stdlib compatible' # # ```puppet # notice(max(1)) # would notice 1 # notice(max(1,2)) # would notice 2 # notice(max("1", 2)) # would notice 2 # notice(max("0777", 512)) # would notice "0777", since "0777" is not converted from octal form # notice(max(0777, 512)) # would notice 512, since 0777 is decimal 511 # notice(max('aa', 'ab')) # would notice 'ab' # notice(max(['a'], ['b'])) # would notice ['b'], since "['b']" is after "['a']" # ``` # # @example find 'max' value in an array - stdlib compatible # # ```puppet # $x = [1,2,3,4] # notice(max(*$x)) # would notice 4 # ``` # # @example find 'max' value in an array directly - since Puppet 6.0.0 # # ```puppet # $x = [1,2,3,4] # notice(max($x)) # would notice 4 # notice($x.max) # would notice 4 # ``` # This example shows that a single array argument is used as the set of values # as opposed to being a single returned value. # # When calling with a lambda, it must accept two variables and it must return # one of -1, 0, or 1 depending on if first argument is before/lower than, equal to, # or higher/after the second argument. # # @example 'max of values using a lambda - since Puppet 6.0.0' # # ```puppet # notice(max("2", "10", "100") |$a, $b| { compare($a, $b) }) # ``` # # Would notice "2" as higher since it is lexicographically higher/after the other values. Without the # lambda the stdlib compatible (deprecated) behavior would have been to return "100" since number conversion # kicks in. # Puppet::Functions.create_function(:max) do dispatch :on_numeric do repeated_param 'Numeric', :values end dispatch :on_string do repeated_param 'String', :values end dispatch :on_semver do repeated_param 'Semver', :values end dispatch :on_timespan do repeated_param 'Timespan', :values end dispatch :on_timestamp do repeated_param 'Timestamp', :values end dispatch :on_single_numeric_array do param 'Array[Numeric]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_string_array do param 'Array[String]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_semver_array do param 'Array[Semver]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timespan_array do param 'Array[Timespan]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_timestamp_array do param 'Array[Timestamp]', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_single_any_array do param 'Array', :values optional_block_param 'Callable[2,2]', :block end dispatch :on_any_with_block do repeated_param 'Any', :values block_param 'Callable[2,2]', :block end dispatch :on_any do repeated_param 'Any', :values end # All are Numeric - ok now, will be ok later def on_numeric(*args) assert_arg_count(args) args.max end # All are String, may convert to numeric (which is deprecated) def on_string(*args) assert_arg_count(args) args.max do |a, b| if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else # case sensitive as in the stdlib function a <=> b end end end def on_semver(*args) assert_arg_count(args) args.max end def on_timespan(*args) assert_arg_count(args) args.max end def on_timestamp(*args) assert_arg_count(args) args.max end def on_any_with_block(*args, &block) args.max { |x, y| block.call(x, y) } end def on_single_numeric_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_numeric(*array) end end def on_single_string_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_string(*array) end end def on_single_semver_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_semver(*array) end end def on_single_timespan_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timespan(*array) end end def on_single_timestamp_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_timestamp(*array) end end def on_single_any_array(array, &block) if block_given? on_any_with_block(*array, &block) else on_any(*array) end end # Mix of data types - while only some compares are actually bad it will deprecate # the entire call # def on_any(*args) assert_arg_count(args) args.max do |a, b| as = a.to_s bs = b.to_s if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/ Puppet.warn_once('deprecations', 'max_function_numeric_coerce_string', _("The max() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda")) a.to_f <=> b.to_f else Puppet.warn_once('deprecations', 'max_function_string_coerce_any', _("The max() function's auto conversion of Any to String is deprecated - change to convert input before calling, or use lambda")) as <=> bs end end end def assert_arg_count(args) raise(ArgumentError, 'max(): Wrong number of arguments need at least one') if args.empty? end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/any.rb
lib/puppet/functions/any.rb
# frozen_string_literal: true # Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # repeatedly using each value in a data structure until the lambda returns a "truthy" value which # makes the function return `true`, or if the end of the iteration is reached, false is returned. # # This function takes two mandatory arguments, in this order: # # 1. An array, hash, or other iterable object that 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 `any` function # # `$data.any |$parameter| { <PUPPET CODE BLOCK> }` # # or # # `any($data) |$parameter| { <PUPPET CODE BLOCK> }` # # @example Using the `any` function with an Array and a one-parameter lambda # # ```puppet # # For the array $data, run a lambda that checks if an unknown hash contains those keys # $data = ["routers", "servers", "workstations"] # $looked_up = lookup('somekey', Hash) # notice $data.any |$item| { $looked_up[$item] } # ``` # # Would notice `true` if the looked up hash had a value that is neither `false` nor `undef` for at least # one of the keys. That is, it is equivalent to the expression # `$looked_up[routers] || $looked_up[servers] || $looked_up[workstations]`. # # 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]`. # # @example Using the `any` function with a `Hash` and a one-parameter lambda # # ```puppet # # For the hash $data, run a lambda using each item as a key-value array. # $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"} # $looked_up = lookup('somekey', Hash) # notice $data.any |$item| { $looked_up[$item[0]] } # ``` # # Would notice `true` if the looked up hash had a value for one of the wanted key that is # neither `false` nor `undef`. # # When the lambda accepts two arguments, the first argument gets the index in an array # or the key from a hash, and the second argument the value. # # # @example Using the `any` function with an array and a two-parameter lambda # # ```puppet # # Check if there is an even numbered index that has a non String value # $data = [key1, 1, 2, 2] # notice $data.any |$index, $value| { $index % 2 == 0 and $value !~ String } # ``` # # Would notice true as the index `2` is even and not a `String` # # For an general examples that demonstrates iteration, see the Puppet # [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html) # documentation. # # @since 5.2.0 # Puppet::Functions.create_function(:any) do dispatch :any_Hash_2 do param 'Hash[Any, Any]', :hash block_param 'Callable[2,2]', :block end dispatch :any_Hash_1 do param 'Hash[Any, Any]', :hash block_param 'Callable[1,1]', :block end dispatch :any_Enumerable_2 do param 'Iterable', :enumerable block_param 'Callable[2,2]', :block end dispatch :any_Enumerable_1 do param 'Iterable', :enumerable block_param 'Callable[1,1]', :block end def any_Hash_1(hash) hash.each_pair.any? { |x| yield(x) } end def any_Hash_2(hash) hash.each_pair.any? { |x, y| yield(x, y) } end def any_Enumerable_1(enumerable) Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable).any? { |e| yield(e) } end def any_Enumerable_2(enumerable) enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable) if enum.hash_style? enum.any? { |entry| yield(*entry) } else enum.each_with_index { |e, i| return true if yield(i, e) } false end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/chop.rb
lib/puppet/functions/chop.rb
# frozen_string_literal: true # Returns a new string with the last character removed. # If the string ends with `\r\n`, both characters are removed. Applying chop to an empty # string returns an empty string. If you wish to merely remove record # separators then you should use the `chomp` function. # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes the last character, or if it ends with \r\n` it removes both. If String is empty # an empty string is returned. # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing line endings # ```puppet # "hello\r\n".chop() # chop("hello\r\n") # ``` # Would both result in `"hello"` # # @example Removing last char # ```puppet # "hello".chop() # chop("hello") # ``` # Would both result in `"hell"` # # @example Removing last char in an array # ```puppet # ["hello\r\n", "hi\r\n"].chop() # chop(["hello\r\n", "hi\r\n"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:chop) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.chop end def on_iterable(a) a.map { |x| do_chop(x) } end def do_chop(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.chop : x end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/warning.rb
lib/puppet/functions/warning.rb
# frozen_string_literal: true # Logs a message on the server at level `warning`. Puppet::Functions.create_function(:warning, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :warning do scope_param repeated_param 'Any', :values return_type 'Undef' end def warning(scope, *values) Puppet::Util::Log.log_func(scope, :warning, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/json_data.rb
lib/puppet/functions/json_data.rb
# frozen_string_literal: true # The `json_data` is a hiera 5 `data_hash` data provider function. # See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for # how to use this function. # # @since 4.8.0 # Puppet::Functions.create_function(:json_data) do dispatch :json_data do param 'Struct[{path=>String[1]}]', :options param 'Puppet::LookupContext', :context end argument_mismatch :missing_path do param 'Hash', :options param 'Puppet::LookupContext', :context end def json_data(options, context) path = options['path'] context.cached_file_data(path) do |content| Puppet::Util::Json.load(content) rescue Puppet::Util::Json::ParseError => ex # Filename not included in message, so we add it here. raise Puppet::DataBinding::LookupError, "Unable to parse (%{path}): %{message}" % { path: path, message: ex.message } end end def missing_path(options, context) "one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/abs.rb
lib/puppet/functions/abs.rb
# frozen_string_literal: true # Returns the absolute value of a Numeric value, for example -34.56 becomes # 34.56. Takes a single `Integer` or `Float` value as an argument. # # *Deprecated behavior* # # For backwards compatibility reasons this function also works when given a # number in `String` format such that it first attempts to covert it to either a `Float` or # an `Integer` and then taking the absolute value of the result. Only strings representing # a number in decimal format is supported - an error is raised if # value is not decimal (using base 10). Leading 0 chars in the string # are ignored. A floating point value in string form can use some forms of # scientific notation but not all. # # Callers should convert strings to `Numeric` before calling # this function to have full control over the conversion. # # @example Converting to Numeric before calling # ```puppet # abs(Numeric($str_val)) # ``` # # It is worth noting that `Numeric` can convert to absolute value # directly as in the following examples: # # @example Absolute value and String to Numeric # ```puppet # Numeric($strval, true) # Converts to absolute Integer or Float # Integer($strval, 10, true) # Converts to absolute Integer using base 10 (decimal) # Integer($strval, 16, true) # Converts to absolute Integer using base 16 (hex) # Float($strval, true) # Converts to absolute Float # ``` # Puppet::Functions.create_function(:abs) do dispatch :on_numeric do param 'Numeric', :val end dispatch :on_string do param 'String', :val end def on_numeric(x) x.abs end def on_string(x) Puppet.warn_once('deprecations', 'abs_function_numeric_coerce_string', _("The abs() function's auto conversion of String to Numeric is deprecated - change to convert input before calling")) # These patterns for conversion are backwards compatible with the stdlib # version of this function. # case x when /^-?(?:\d+)(?:\.\d+){1}$/ x.to_f.abs when /^-?\d+$/ x.to_i.abs else raise(ArgumentError, 'abs(): Requires float or integer to work with - was given non decimal string') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/crit.rb
lib/puppet/functions/crit.rb
# frozen_string_literal: true # Logs a message on the server at level `crit`. Puppet::Functions.create_function(:crit, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :crit do scope_param repeated_param 'Any', :values return_type 'Undef' end def crit(scope, *values) Puppet::Util::Log.log_func(scope, :crit, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/size.rb
lib/puppet/functions/size.rb
# frozen_string_literal: true # The same as length() - returns the size of an Array, Hash, String, or Binary value. # # @since 6.0.0 - also supporting Binary # Puppet::Functions.create_function(:size) do dispatch :generic_size do param 'Variant[Collection, String, Binary]', :arg end def generic_size(arg) call_function('length', arg) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/strip.rb
lib/puppet/functions/strip.rb
# frozen_string_literal: true # Strips leading and trailing spaces from a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes all leading and trailing ASCII white space characters such as space, tab, newline, and return. # It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression # matches all space-like characters). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing leading and trailing space from a String # ```puppet # " hello\n\t".strip() # strip(" hello\n\t") # ``` # Would both result in `"hello"` # # @example Removing trailing space from strings in an Array # ```puppet # [" hello\n\t", " hi\n\t"].strip() # strip([" hello\n\t", " hi\n\t"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:strip) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.strip end def on_iterable(a) a.map { |x| do_strip(x) } end def do_strip(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.strip : x end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/rstrip.rb
lib/puppet/functions/rstrip.rb
# frozen_string_literal: true # Strips trailing spaces from a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion removes all trailing ASCII white space characters such as space, tab, newline, and return. # It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression # matches all space-like characters). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # # @example Removing trailing space from a String # ```puppet # " hello\n\t".rstrip() # rstrip(" hello\n\t") # ``` # Would both result in `"hello"` # # @example Removing trailing space from strings in an Array # ```puppet # [" hello\n\t", " hi\n\t"].rstrip() # rstrip([" hello\n\t", " hi\n\t"]) # ``` # Would both result in `['hello', 'hi']` # Puppet::Functions.create_function(:rstrip) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.rstrip end def on_iterable(a) a.map { |x| do_rstrip(x) } end def do_rstrip(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? x.rstrip : x end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/hiera.rb
lib/puppet/functions/hiera.rb
# frozen_string_literal: true require 'hiera/puppet_function' # Performs a standard priority lookup of the hierarchy and returns the most specific value # for a given key. The returned value can be any type of data. # # This function is deprecated in favor of the `lookup` function. While this function # continues to work, it does **not** support: # * `lookup_options` stored in the data # * lookup across global, environment, and module layers # # 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 `hiera` function does **not** find all matches throughout a hierarchy, instead # returning the first specific value starting at the top of the hierarchy. To search # throughout a hierarchy, use the `hiera_array` or `hiera_hash` functions. # # @example Using `hiera` # # ```yaml # # Assuming hiera.yaml # # :hierarchy: # # - web01.example.com # # - common # # # Assuming web01.example.com.yaml: # # users: # # - "Amy Barry" # # - "Carrie Douglas" # # # Assuming common.yaml: # users: # admins: # - "Edith Franklin" # - "Ginny Hamilton" # regular: # - "Iris Jackson" # - "Kelly Lambert" # ``` # # ```puppet # # Assuming we are not web01.example.com: # # $users = hiera('users', undef) # # # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # # regular => ["Iris Jackson", "Kelly Lambert"]} # ``` # # 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` with a lambda # # ```puppet # # Assuming the same Hiera data as the previous example: # # $users = hiera('users') | $key | { "Key \'${key}\' not found" } # # # $users contains {admins => ["Edith Franklin", "Ginny Hamilton"], # # regular => ["Iris Jackson", "Kelly Lambert"]} # # If hiera couldn't match its key, it would return the lambda result, # # "Key 'users' not found". # ``` # # The returned value's data type depends on the types of the results. In the example # above, Hiera matches the 'users' key and returns it as a hash. # # See # [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data. # Also see # [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) # for more information about the Hiera 3 functions. # # @since 4.0.0 # Puppet::Functions.create_function(:hiera, Hiera::PuppetFunction) do init_dispatch end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/step.rb
lib/puppet/functions/step.rb
# frozen_string_literal: true # Provides stepping with given interval over elements in an iterable and optionally runs a # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each # element. # # This function takes two to three arguments: # # 1. An 'Iterable' that the function will iterate over. # 2. An `Integer` step factor. This must be a positive integer. # 3. An optional lambda, which the function calls for each element in the interval. It must # request one parameter. # # @example Using the `step` function # # ```puppet # $data.step(<n>) |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $stepped_data = $data.step(<n>) # ``` # # or # # ```puppet # step($data, <n>) |$parameter| { <PUPPET CODE BLOCK> } # ``` # # or # # ```puppet # $stepped_data = step($data, <n>) # ``` # # When no block is given, Puppet returns an `Iterable` that yields the first element and every nth successor # element, from its first argument. This allows functions on iterables to be chained. # When a block is given, Puppet iterates and calls the block with the first element and then with # every nth successor element. It then returns `undef`. # # @example Using the `step` function with an array, a step factor, and a one-parameter block # # ```puppet # # For the array $data, call a block with the first element and then with each 3rd successor element # $data = [1,2,3,4,5,6,7,8] # $data.step(3) |$item| { # notice($item) # } # # Puppet notices the values '1', '4', '7'. # ``` # When no block is given, Puppet returns a new `Iterable` which allows it to be directly chained into # another function that takes an `Iterable` as an argument. # # @example Using the `step` function chained with a `map` function. # # ```puppet # # For the array $data, return an array, set to the first element and each 5th successor element, in reverse # # order multiplied by 10 # $data = Integer[0,20] # $transformed_data = $data.step(5).map |$item| { $item * 10 } # $transformed_data contains [0,50,100,150,200] # ``` # # @example The same example using `step` function chained with a `map` in alternative syntax # # ```puppet # # For the array $data, return an array, set to the first and each 5th # # successor, in reverse order, multiplied by 10 # $data = Integer[0,20] # $transformed_data = map(step($data, 5)) |$item| { $item * 10 } # $transformed_data contains [0,50,100,150,200] # ``` # # @since 4.4.0 # Puppet::Functions.create_function(:step) do dispatch :step do param 'Iterable', :iterable param 'Integer[1]', :step end dispatch :step_block do param 'Iterable', :iterable param 'Integer[1]', :step block_param 'Callable[1,1]', :block end def step(iterable, step) # produces an Iterable Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable, true).step(step) end def step_block(iterable, step, &block) Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).step(step, &block) nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/floor.rb
lib/puppet/functions/floor.rb
# frozen_string_literal: true # Returns the largest `Integer` less or equal to the argument. # Takes a single numeric value as an argument. # # This function is backwards compatible with the same function in stdlib # and accepts a `Numeric` value. A `String` that can be converted # to a floating point number can also be used in this version - but this # is deprecated. # # In general convert string input to `Numeric` before calling this function # to have full control over how the conversion is done. # Puppet::Functions.create_function(:floor) do dispatch :on_numeric do param 'Numeric', :val end dispatch :on_string do param 'String', :val end def on_numeric(x) x.floor end def on_string(x) Puppet.warn_once('deprecations', 'floor_function_numeric_coerce_string', _("The floor() function's auto conversion of String to Float is deprecated - change to convert input before calling")) begin Float(x).floor rescue TypeError, ArgumentError => _e # TRANSLATORS: 'floor' is a name and should not be translated raise(ArgumentError, _('floor(): cannot convert given value to a floating point value.')) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/epp.rb
lib/puppet/functions/epp.rb
# frozen_string_literal: true # Evaluates an Embedded Puppet (EPP) template file and returns the rendered text # result as a String. # # `epp('<MODULE NAME>/<TEMPLATE FILE>', <PARAMETER HASH>)` # # The first argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>` # reference, which loads `<TEMPLATE FILE>` from `<MODULE NAME>`'s `templates` # directory. In most cases, the last argument is optional; if used, it should be a # [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to # pass to the template. # # - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html) # documentation for general template usage information. # - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html) # documentation for examples of EPP. # # For example, to call the apache module's `templates/vhost/_docroot.epp` # template and pass the `docroot` and `virtual_docroot` parameters, call the `epp` # function like this: # # `epp('apache/vhost/_docroot.epp', { 'docroot' => '/var/www/html', # 'virtual_docroot' => '/var/www/example' })` # # This function can also accept an absolute path, which can load a template file # from anywhere on disk. # # Puppet produces a syntax error if you pass more parameters than are declared in # the template's parameter tag. When passing parameters to a template that # contains a parameter tag, use the same names as the tag's declared parameters. # # Parameters are required only if they are declared in the called template's # parameter tag without default values. Puppet produces an error if the `epp` # function fails to pass any required parameter. # # @since 4.0.0 # Puppet::Functions.create_function(:epp, Puppet::Functions::InternalFunction) do dispatch :epp do scope_param param 'String', :path optional_param 'Hash[Pattern[/^\w+$/], Any]', :parameters return_type 'Variant[String, Sensitive[String]]' end def epp(scope, path, parameters = nil) Puppet::Pops::Evaluator::EppEvaluator.epp(scope, path, scope.compiler.environment, parameters) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/defined.rb
lib/puppet/functions/defined.rb
# frozen_string_literal: true # Determines whether a given class or resource type is defined and returns a Boolean # value. You can also use `defined` to determine whether a specific resource is defined, # or whether a variable has a value (including `undef`, as opposed to the variable never # being declared or assigned). # # This function takes at least one string argument, which can be a class name, type name, # resource reference, or variable reference of the form `'$name'`. (Note that the `$` sign # is included in the string which must be in single quotes to prevent the `$` character # to be interpreted as interpolation. # # The `defined` function checks both native and defined types, including types # provided by modules. Types and classes are matched by their names. The function matches # resource declarations by using resource references. # # @example Different types of `defined` function matches # # ```puppet # # Matching resource types # defined("file") # defined("customtype") # # # Matching defines and classes # defined("foo") # defined("foo::bar") # # # Matching variables (note the single quotes) # defined('$name') # # # Matching declared resources # defined(File['/tmp/file']) # ``` # # Puppet depends on the configuration's evaluation order when checking whether a resource # is declared. # # @example Importance of evaluation order when using `defined` # # ```puppet # # Assign values to $is_defined_before and $is_defined_after using identical `defined` # # functions. # # $is_defined_before = defined(File['/tmp/file']) # # file { "/tmp/file": # ensure => present, # } # # $is_defined_after = defined(File['/tmp/file']) # # # $is_defined_before returns false, but $is_defined_after returns true. # ``` # # This order requirement only refers to evaluation order. The order of resources in the # configuration graph (e.g. with `before` or `require`) does not affect the `defined` # function's behavior. # # > **Warning:** Avoid relying on the result of the `defined` function in modules, as you # > might not be able to guarantee the evaluation order well enough to produce consistent # > results. This can cause other code that relies on the function's result to behave # > inconsistently or fail. # # If you pass more than one argument to `defined`, the function returns `true` if _any_ # of the arguments are defined. You can also match resources by type, allowing you to # match conditions of different levels of specificity, such as whether a specific resource # is of a specific data type. # # @example Matching multiple resources and resources by different types with `defined` # # ```puppet # file { "/tmp/file1": # ensure => file, # } # # $tmp_file = file { "/tmp/file2": # ensure => file, # } # # # Each of these statements return `true` ... # defined(File['/tmp/file1']) # defined(File['/tmp/file1'],File['/tmp/file2']) # defined(File['/tmp/file1'],File['/tmp/file2'],File['/tmp/file3']) # # ... but this returns `false`. # defined(File['/tmp/file3']) # # # Each of these statements returns `true` ... # defined(Type[Resource['file','/tmp/file2']]) # defined(Resource['file','/tmp/file2']) # defined(File['/tmp/file2']) # defined('$tmp_file') # # ... but each of these returns `false`. # defined(Type[Resource['exec','/tmp/file2']]) # defined(Resource['exec','/tmp/file2']) # defined(File['/tmp/file3']) # defined('$tmp_file2') # ``` # # @since 2.7.0 # @since 3.6.0 variable reference and future parser types # @since 3.8.1 type specific requests with future parser # @since 4.0.0 # Puppet::Functions.create_function(:defined, Puppet::Functions::InternalFunction) do dispatch :is_defined do scope_param required_repeated_param 'Variant[String, Type[CatalogEntry], Type[Type[CatalogEntry]]]', :vals end def is_defined(scope, *vals) # rubocop:disable Naming/PredicateName vals.any? do |val| case val when String if val =~ /^\$(.+)$/ scope.exist?(Regexp.last_match(1)) else case val when '' next nil when 'main' # Find the main class (known as ''), it does not have to be in the catalog Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_main_class(scope) else # Find a resource type, definition or class definition Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type_or_class(scope, val) end end when Puppet::Resource # Find instance of given resource type and title that is in the catalog scope.compiler.findresource(val.resource_type, val.title) when Puppet::Pops::Types::PResourceType raise ArgumentError, _('The given resource type is a reference to all kind of types') if val.type_name.nil? type = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, val.type_name) val.title.nil? ? type : scope.compiler.findresource(type, val.title) when Puppet::Pops::Types::PClassType raise ArgumentError, _('The given class type is a reference to all classes') if val.class_name.nil? scope.compiler.findresource(:class, val.class_name) when Puppet::Pops::Types::PTypeType case val.type when Puppet::Pops::Types::PResourceType # It is most reasonable to take Type[File] and Type[File[foo]] to mean the same as if not wrapped in a Type # Since the difference between File and File[foo] already captures the distinction of type vs instance. is_defined(scope, val.type) when Puppet::Pops::Types::PClassType # Interpreted as asking if a class (and nothing else) is defined without having to be included in the catalog # (this is the same as asking for just the class' name, but with the added certainty that it cannot be a defined type. # raise ArgumentError, _('The given class type is a reference to all classes') if val.type.class_name.nil? Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_hostclass(scope, val.type.class_name) end else raise ArgumentError, _("Invalid argument of type '%{value_class}' to 'defined'") % { value_class: val.class } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/info.rb
lib/puppet/functions/info.rb
# frozen_string_literal: true # Logs a message on the server at level `info`. Puppet::Functions.create_function(:info, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :info do scope_param repeated_param 'Any', :values return_type 'Undef' end def info(scope, *values) Puppet::Util::Log.log_func(scope, :info, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/contain.rb
lib/puppet/functions/contain.rb
# frozen_string_literal: true # Makes one or more classes be contained inside the current class. # If any of these classes are undeclared, they will be declared as if # there were declared with the `include` function. # Accepts a class name, an array of class names, or a comma-separated # list of class names. # # A contained class will not be applied before the containing class is # begun, and will be finished before the containing class is finished. # # 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 # evaluating resource and relationship expressions. # # The function returns an array of references to the classes that were contained thus # allowing the function call to `contain` to directly continue. # # - Since 4.0.0 support for `Class` and `Resource` `Type`-values, absolute names # - Since 4.7.0 a value of type `Array[Type[Class[n]]]` is returned with all the contained classes # Puppet::Functions.create_function(:contain, Puppet::Functions::InternalFunction) do dispatch :contain do scope_param # The function supports what the type system sees as Ruby runtime objects, and # they cannot be parameterized to find what is actually valid instances. # The validation is instead done in the function body itself via a call to # `transform_and_assert_classnames` on the calling scope. required_repeated_param 'Any', :names end def contain(scope, *classes) if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'contain' } ) end # Make call patterns uniform and protected against nested arrays, also make # names absolute if so desired. classes = scope.transform_and_assert_classnames(classes.flatten) result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) } containing_resource = scope.resource # This is the same as calling the include function but faster and does not rely on the include # function. (scope.compiler.evaluate_classes(classes, scope, false) || []).each do |resource| unless scope.catalog.edge?(containing_resource, resource) scope.catalog.add_edge(containing_resource, resource) end end # Result is an Array[Class, 1, n] which allows chaining other operations result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/debug.rb
lib/puppet/functions/debug.rb
# frozen_string_literal: true # Logs a message on the server at level `debug`. Puppet::Functions.create_function(:debug, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :debug do scope_param repeated_param 'Any', :values return_type 'Undef' end def debug(scope, *values) Puppet::Util::Log.log_func(scope, :debug, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/partition.rb
lib/puppet/functions/partition.rb
# frozen_string_literal: true # Returns two arrays, the first containing the elements of enum for which the block evaluates to true, # the second containing the rest. Puppet::Functions.create_function(:partition) do # @param collection A collection of things to partition. # @example Partition array of empty strings, results in e.g. `[[''], [b, c]]` # ```puppet # ['', b, c].partition |$s| { $s.empty } # ``` # @example Partition array of strings using index, results in e.g. `[['', 'ab'], ['b']]` # ```puppet # ['', b, ab].partition |$i, $s| { $i == 2 or $s.empty } # ``` # @example Partition hash of strings by key-value pair, results in e.g. `[[['b', []]], [['a', [1, 2]]]]` # ```puppet # { a => [1, 2], b => [] }.partition |$kv| { $kv[1].empty } # ``` # @example Partition hash of strings by key and value, results in e.g. `[[['b', []]], [['a', [1, 2]]]]` # ```puppet # { a => [1, 2], b => [] }.partition |$k, $v| { $v.empty } # ``` dispatch :partition_1 do required_param 'Collection', :collection block_param 'Callable[1,1]', :block return_type 'Tuple[Array, Array]' end dispatch :partition_2a do required_param 'Array', :array block_param 'Callable[2,2]', :block return_type 'Tuple[Array, Array]' end dispatch :partition_2 do required_param 'Collection', :collection block_param 'Callable[2,2]', :block return_type 'Tuple[Array, Array]' end def partition_1(collection) collection.partition do |item| yield(item) end.freeze end def partition_2a(array) partitioned = array.size.times.zip(array).partition do |k, v| yield(k, v) end partitioned.map do |part| part.map { |item| item[1] } end.freeze end def partition_2(collection) collection.partition do |k, v| yield(k, v) end.freeze end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/strftime.rb
lib/puppet/functions/strftime.rb
# frozen_string_literal: true # Formats timestamp or timespan according to the directives in the given format string. The directives begins with a percent (%) character. # Any text not listed as a directive will be passed through to the output string. # # A third optional timezone argument can be provided. The first argument will then be formatted to represent 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'. # # 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 that controls padding # # | Flag | Meaning # | ---- | --------------- # | - | Don't pad numerical output # | _ | Use spaces for padding # | 0 | Use zeros for padding # # ### `Timestamp` specific flags # # | Flag | Meaning # | ---- | --------------- # | # | Change case # | ^ | Use uppercase # | : | Use colons for %z # # ### Format directives applicable to `Timestamp` (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) | # # @example Using `strftime` with a `Timestamp`: # # ```puppet # $timestamp = Timestamp('2016-08-24T12:13:14') # # # Notice the timestamp using a format that notices the ISO 8601 date format # notice($timestamp.strftime('%F')) # outputs '2016-08-24' # # # Notice the timestamp using a format that notices weekday, month, day, time (as UTC), and year # notice($timestamp.strftime('%c')) # outputs 'Wed Aug 24 12:13:14 2016' # # # Notice the timestamp using a specific timezone # notice($timestamp.strftime('%F %T %z', 'PST')) # outputs '2016-08-24 04:13:14 -0800' # # # Notice the timestamp using timezone that is current for the evaluating process # notice($timestamp.strftime('%F %T', 'current')) # outputs the timestamp using the timezone for the current process # ``` # # ### Format directives applicable to `Timespan`: # # | 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). Digits under millisecond are truncated to not produce 1000. | # | N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified length are truncated to avoid carry up | # # 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 will be more than 23 in case the # timespan reflects more than a day. # # @example Using `strftime` with a Timespan and a format # # ```puppet # $duration = Timespan({ hours => 3, minutes => 20, seconds => 30 }) # # # Notice the duration using a format that outputs <hours>:<minutes>:<seconds> # notice($duration.strftime('%H:%M:%S')) # outputs '03:20:30' # # # Notice the duration using a format that outputs <minutes>:<seconds> # notice($duration.strftime('%M:%S')) # outputs '200:30' # ``` # # - Since 4.8.0 # Puppet::Functions.create_function(:strftime) do dispatch :format_timespan do param 'Timespan', :time_object param 'String', :format end dispatch :format_timestamp do param 'Timestamp', :time_object param 'String', :format optional_param 'String', :timezone end dispatch :legacy_strftime do param 'String', :format optional_param 'String', :timezone end def format_timespan(time_object, format) time_object.format(format) end def format_timestamp(time_object, format, timezone = nil) time_object.format(format, timezone) end def legacy_strftime(format, timezone = nil) file, line = Puppet::Pops::PuppetStack.top_of_stack Puppet.warn_once('deprecations', 'legacy#strftime', _('The argument signature (String format, [String timezone]) is deprecated for #strftime. See #strftime documentation and Timespan type for more info'), file, line) Puppet::Pops::Time::Timestamp.format_time(format, Time.now.utc, timezone) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/match.rb
lib/puppet/functions/match.rb
# frozen_string_literal: true # Matches a regular expression against a string and returns an array containing the match # and any matched capturing groups. # # The first argument is a string or array of strings. The second argument is either a # regular expression, regular expression represented as a string, or Regex or Pattern # data type that the function matches against the first argument. # # The returned array contains the entire match at index 0, and each captured group at # subsequent index values. If the value or expression being matched is an array, the # function returns an array with mapped match results. # # If the function doesn't find a match, it returns 'undef'. # # @example Matching a regular expression in a string # # ```puppet # $matches = "abc123".match(/[a-z]+[1-9]+/) # # $matches contains [abc123] # ``` # # @example Matching a regular expressions with grouping captures in a string # # ```puppet # $matches = "abc123".match(/([a-z]+)([1-9]+)/) # # $matches contains [abc123, abc, 123] # ``` # # @example Matching a regular expression with grouping captures in an array of strings # # ```puppet # $matches = ["abc123","def456"].match(/([a-z]+)([1-9]+)/) # # $matches contains [[abc123, abc, 123], [def456, def, 456]] # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:match) do dispatch :match do param 'String', :string param 'Variant[Any, Type]', :pattern end dispatch :enumerable_match do param 'Array[String]', :string param 'Variant[Any, Type]', :pattern end def initialize(closure_scope, loader) super # Make this visitor shared among all instantiations of this function since it is faster. # This can be used because it is not possible to replace # a puppet runtime (where this function is) without a reboot. If you model a function in a module after # this class, use a regular instance variable instead to enable reloading of the module without reboot # @@match_visitor ||= Puppet::Pops::Visitor.new(self, "match", 1, 1) end # Matches given string against given pattern and returns an Array with matches. # @param string [String] the string to match # @param pattern [String, Regexp, Puppet::Pops::Types::PPatternType, Puppet::Pops::PRegexpType, Array] the pattern # @return [Array<String>] matches where first match is the entire match, and index 1-n are captures from left to right # def match(string, pattern) @@match_visitor.visit_this_1(self, pattern, string) end # Matches given Array[String] against given pattern and returns an Array with mapped match results. # # @param array [Array<String>] the array of strings to match # @param pattern [String, Regexp, Puppet::Pops::Types::PPatternType, Puppet::Pops::PRegexpType, Array] the pattern # @return [Array<Array<String, nil>>] Array with matches (see {#match}), non matching entries produce a nil entry # def enumerable_match(array, pattern) array.map { |s| match(s, pattern) } end protected def match_Object(obj, s) msg = _("match() expects pattern of T, where T is String, Regexp, Regexp[r], Pattern[p], or Array[T]. Got %{klass}") % { klass: obj.class } raise ArgumentError, msg end def match_String(pattern_string, s) do_match(s, Regexp.new(pattern_string)) end def match_Regexp(regexp, s) do_match(s, regexp) end def match_PTypeAliasType(alias_t, s) match(s, alias_t.resolved_type) end def match_PVariantType(var_t, s) # Find first matching type (or error out if one of the variants is not acceptable) result = nil var_t.types.find { |t| result = match(s, t) } result end def match_PRegexpType(regexp_t, s) raise ArgumentError, _("Given Regexp Type has no regular expression") unless regexp_t.pattern do_match(s, regexp_t.regexp) end def match_PPatternType(pattern_t, s) # Since we want the actual match result (not just a boolean), an iteration over # Pattern's regular expressions is needed. (They are of PRegexpType) result = nil pattern_t.patterns.find { |pattern| result = match(s, pattern) } result end # Returns the first matching entry def match_Array(array, s) result = nil array.flatten.find { |entry| result = match(s, entry) } result end private def do_match(s, regexp) result = regexp.match(s) result.to_a if result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/values.rb
lib/puppet/functions/values.rb
# frozen_string_literal: true # Returns the values of a hash as an Array # # @example Using `values` # # ```puppet # $hsh = {"apples" => 3, "oranges" => 4 } # $hsh.values() # values($hsh) # # both results in the array [3, 4] # ``` # # * Note that a hash in the puppet language accepts any data value (including `undef`) unless # it is constrained with a `Hash` data type that narrows the allowed data types. # * For an empty hash, an empty array is returned. # * The order of the values is the same as the order in the hash (typically the order in which they were added). # Puppet::Functions.create_function(:values) do dispatch :values do param 'Hash', :hsh end def values(hsh) hsh.values end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/unwrap.rb
lib/puppet/functions/unwrap.rb
# frozen_string_literal: true # Unwraps a Sensitive value and returns the wrapped object. # Returns the Value itself, if it is not Sensitive. # # @example Usage of unwrap # # ```puppet # $plaintext = 'hunter2' # $pw = Sensitive.new($plaintext) # notice("Wrapped object is $pw") #=> Prints "Wrapped object is Sensitive [value redacted]" # $unwrapped = $pw.unwrap # notice("Unwrapped object is $unwrapped") #=> Prints "Unwrapped object is hunter2" # ``` # # You can optionally pass a block to unwrap in order to limit the scope where the # unwrapped value is visible. # # @example Unwrapping with a block of code # # ```puppet # $pw = Sensitive.new('hunter2') # notice("Wrapped object is $pw") #=> Prints "Wrapped object is Sensitive [value redacted]" # $pw.unwrap |$unwrapped| { # $conf = inline_template("password: ${unwrapped}\n") # Sensitive.new($conf) # } #=> Returns a new Sensitive object containing an interpolated config file # # $unwrapped is now out of scope # ``` # # @since 4.0.0 # Puppet::Functions.create_function(:unwrap) do dispatch :from_sensitive do param 'Sensitive', :arg optional_block_param end dispatch :from_any do param 'Any', :arg optional_block_param end def from_sensitive(arg) unwrapped = arg.unwrap if block_given? yield(unwrapped) else unwrapped end end def from_any(arg) unwrapped = arg if block_given? yield(unwrapped) else unwrapped end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/lest.rb
lib/puppet/functions/lest.rb
# frozen_string_literal: true # Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # without arguments if the value given to `lest` is `undef`. # Returns the result of calling the lambda if the argument is `undef`, otherwise the # given argument. # # The `lest` function is useful in a chain of `then` calls, or in general # as a guard against `undef` values. The function can be used to call `fail`, or to # return a default value. # # These two expressions are equivalent: # # ```puppet # if $x == undef { do_things() } # lest($x) || { do_things() } # ``` # # @example Using the `lest` function # # ```puppet # $data = {a => [ b, c ] } # notice $data.dig(a, b, c) # .then |$x| { $x * 2 } # .lest || { fail("no value for $data[a][b][c]" } # ``` # # Would fail the operation because `$data[a][b][c]` results in `undef` # (there is no `b` key in `a`). # # In contrast - this example: # # ```puppet # $data = {a => { b => { c => 10 } } } # notice $data.dig(a, b, c) # .then |$x| { $x * 2 } # .lest || { fail("no value for $data[a][b][c]" } # ``` # # Would notice the value `20` # # @since 4.5.0 # Puppet::Functions.create_function(:lest) do dispatch :lest do param 'Any', :arg block_param 'Callable[0,0]', :block end def lest(arg) if arg.nil? yield() else arg end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/join.rb
lib/puppet/functions/join.rb
# frozen_string_literal: true # Joins the values of an Array into a string with elements separated by a delimiter. # # Supports up to two arguments # * **values** - first argument is required and must be an an `Array` # * **delimiter** - second arguments is the delimiter between elements, must be a `String` if given, and defaults to an empty string. # # @example Typical use of `join` # # ```puppet # join(['a','b','c'], ",") # # Would result in: "a,b,c" # ``` # # Note that array is flattened before elements are joined, but flattening does not extend to arrays nested in hashes or other objects. # # @example Arrays nested in hashes are not joined # # ```puppet # $a = [1,2, undef, 'hello', [x,y,z], {a => 2, b => [3, 4]}] # notice join($a, ', ') # # # would result in noticing: # # 1, 2, , hello, x, y, z, {"a"=>2, "b"=>[3, 4]} # ``` # # For joining iterators and other containers of elements a conversion must first be made to # an `Array`. The reason for this is that there are many options how such a conversion should # be made. # # @example Joining the result of a reverse_each converted to an array # # ```puppet # [1,2,3].reverse_each.convert_to(Array).join(', ') # # would result in: "3, 2, 1" # ``` # @example Joining a hash # # ```puppet # {a => 1, b => 2}.convert_to(Array).join(', ') # # would result in "a, 1, b, 2" # ``` # # For more detailed control over the formatting (including indentations and line breaks, delimiters around arrays # and hash entries, between key/values in hash entries, and individual formatting of values in the array) # see the `new` function for `String` and its formatting options for `Array` and `Hash`. # Puppet::Functions.create_function(:join) do dispatch :join do param 'Array', :arg optional_param 'String', :delimiter end def join(arg, delimiter = '', puppet_formatting = false) arg.join(delimiter) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/compare.rb
lib/puppet/functions/compare.rb
# frozen_string_literal: true # Compares two values and returns -1, 0 or 1 if first value is smaller, equal or larger than the second value. # The compare function accepts arguments of the data types `String`, `Numeric`, `Timespan`, `Timestamp`, and `Semver`, # such that: # # * two of the same data type can be compared # * `Timespan` and `Timestamp` can be compared with each other and with `Numeric` # # When comparing two `String` values the comparison can be made to consider case by passing a third (optional) # boolean `false` value - the default is `true` which ignores case as the comparison operators # in the Puppet Language. # Puppet::Functions.create_function(:compare) do local_types do type 'TimeComparable = Variant[Numeric, Timespan, Timestamp]' type 'Comparable = Variant[String, Semver, TimeComparable]' end dispatch :on_numeric do param 'Numeric', :a param 'Numeric', :b end dispatch :on_string do param 'String', :a param 'String', :b optional_param 'Boolean', :ignore_case end dispatch :on_version do param 'Semver', :a param 'Semver', :b end dispatch :on_time_num_first do param 'Numeric', :a param 'Variant[Timespan, Timestamp]', :b end dispatch :on_timestamp do param 'Timestamp', :a param 'Variant[Timestamp, Numeric]', :b end dispatch :on_timespan do param 'Timespan', :a param 'Variant[Timespan, Numeric]', :b end argument_mismatch :on_error do param 'Comparable', :a param 'Comparable', :b repeated_param 'Any', :ignore_case end argument_mismatch :on_not_comparable do param 'Any', :a param 'Any', :b repeated_param 'Any', :ignore_case end def on_numeric(a, b) a <=> b end def on_string(a, b, ignore_case = true) if ignore_case a.casecmp(b) else a <=> b end end def on_version(a, b) a <=> b end def on_time_num_first(a, b) # Time data types can compare against Numeric but not the other way around # the comparison is therefore done in reverse and the answer is inverted. -(b <=> a) end def on_timespan(a, b) a <=> b end def on_timestamp(a, b) a <=> b end def on_not_comparable(a, b, *ignore_case) # TRANSLATORS 'compare' is a name _("compare(): Non comparable type. Only values of the types Numeric, String, Semver, Timestamp and Timestamp can be compared. Got %{type_a} and %{type_b}") % { type_a: type_label(a), type_b: type_label(b) } end def on_error(a, b, *ignore_case) unless ignore_case.empty? unless a.is_a?(String) && b.is_a?(String) # TRANSLATORS 'compare' is a name return _("compare(): The third argument (ignore case) can only be used when comparing strings") end unless ignore_case.size == 1 # TRANSLATORS 'compare' is a name return _("compare(): Accepts at most 3 arguments, got %{actual_number}") % { actual_number: 2 + ignore_case.size } end unless ignore_case[0].is_a?(Boolean) # TRANSLATORS 'compare' is a name return _("compare(): The third argument (ignore case) must be a Boolean. Got %{type}") % { type: type_label(ignore_case[0]) } end end if a.class != b.class # TRANSLATORS 'compare' is a name _("compare(): Can only compare values of the same type (or for Timestamp/Timespan also against Numeric). Got %{type_a} and %{type_b}") % { type_a: type_label(a), type_b: type_label(b) } end end def type_label(x) Puppet::Pops::Model::ModelLabelProvider.new.label(x) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/emerg.rb
lib/puppet/functions/emerg.rb
# frozen_string_literal: true # Logs a message on the server at level `emerg`. Puppet::Functions.create_function(:emerg, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :emerg do scope_param repeated_param 'Any', :values return_type 'Undef' end def emerg(scope, *values) Puppet::Util::Log.log_func(scope, :emerg, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/notice.rb
lib/puppet/functions/notice.rb
# frozen_string_literal: true # Logs a message on the server at level `notice`. Puppet::Functions.create_function(:notice, Puppet::Functions::InternalFunction) do # @param values The values to log. # @return [Undef] dispatch :notice do scope_param repeated_param 'Any', :values return_type 'Undef' end def notice(scope, *values) Puppet::Util::Log.log_func(scope, :notice, values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/require.rb
lib/puppet/functions/require.rb
# frozen_string_literal: true # Requires the specified classes. # Evaluate one or more classes, adding the required class as a dependency. # # The relationship metaparameters work well for specifying relationships # between individual resources, but they can be clumsy for specifying # relationships between classes. This function is a superset of the # `include` function, adding a class relationship so that the requiring # class depends on the required class. # # Warning: using `require` in place of `include` can lead to unwanted dependency cycles. # # For instance, the following manifest, with `require` instead of `include`, would produce a nasty # dependence cycle, because `notify` imposes a `before` between `File[/foo]` and `Service[foo]`: # # ```puppet # class myservice { # service { foo: ensure => running } # } # # class otherstuff { # include myservice # file { '/foo': notify => Service[foo] } # } # ``` # # Note that this function only works with clients 0.25 and later, and it will # fail if used with earlier clients. # # 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 when evaluating # resource and relationship expressions. # # - Since 4.0.0 Class and Resource types, absolute names # - Since 4.7.0 Returns an `Array[Type[Class]]` with references to the required classes # Puppet::Functions.create_function(:require, Puppet::Functions::InternalFunction) do dispatch :require_impl do scope_param # The function supports what the type system sees as Ruby runtime objects, and # they cannot be parameterized to find what is actually valid instances. # The validation is instead done in the function body itself via a call to # `transform_and_assert_classnames` on the calling scope. required_repeated_param 'Any', :names end def require_impl(scope, *classes) if Puppet[:tasks] raise Puppet::ParseErrorWithIssue.from_issue_and_stack( Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING, { :operation => 'require' } ) end # Make call patterns uniform and protected against nested arrays, also make # names absolute if so desired. classes = scope.transform_and_assert_classnames(classes.flatten) result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) } # This is the same as calling the include function (but faster) since it again # would otherwise need to perform the optional absolute name transformation # (for no reason since they are already made absolute here). # scope.compiler.evaluate_classes(classes, scope, false) krt = scope.environment.known_resource_types classes.each do |klass| # lookup the class in the scopes klass = (classobj = krt.find_hostclass(klass)) ? classobj.name : nil raise Puppet::ParseError, _("Could not find class %{klass}") % { klass: klass } unless klass ref = Puppet::Resource.new(:class, klass) resource = scope.resource resource.set_parameter(:require, [resource[:require]].flatten.compact << ref) end result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/camelcase.rb
lib/puppet/functions/camelcase.rb
# frozen_string_literal: true # Creates a Camel Case version of a String # # This function is compatible with the stdlib function with the same name. # # The function does the following: # * For a `String` the conversion replaces all combinations of `*_<char>*` with an upcased version of the # character following the _. This is done using Ruby system locale which handles some, but not all # special international up-casing rules (for example German double-s ß is upcased to "Ss"). # * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is capitalized and the conversion is not recursive. # * If the value is `Numeric` it is simply returned (this is for backwards compatibility). # * An error is raised for all other data types. # * The result will not contain any underscore characters. # # Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible. # To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # # @example Camelcase a String # ```puppet # 'hello_friend'.camelcase() # camelcase('hello_friend') # ``` # Would both result in `"HelloFriend"` # # @example Camelcase of strings in an Array # ```puppet # ['abc_def', 'bcd_xyz'].camelcase() # camelcase(['abc_def', 'bcd_xyz']) # ``` # Would both result in `['AbcDef', 'BcdXyz']` # Puppet::Functions.create_function(:camelcase) do dispatch :on_numeric do param 'Numeric', :arg end dispatch :on_string do param 'String', :arg end dispatch :on_iterable do param 'Iterable[Variant[String, Numeric]]', :arg end # unit function - since the old implementation skipped Numeric values def on_numeric(n) n end def on_string(s) s.split('_').map(&:capitalize).join('') end def on_iterable(a) a.map { |x| do_camelcase(x) } end def do_camelcase(x) # x can only be a String or Numeric because type constraints have been automatically applied x.is_a?(String) ? on_string(x) : x end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/get.rb
lib/puppet/functions/get.rb
# frozen_string_literal: true # Digs into a value with dot notation to get a value from within a structure. # # **To dig into a given value**, call the function with (at least) two arguments: # # * The **first** argument must be an Array, or Hash. Value can also be `undef` # (which also makes the result `undef` unless a _default value_ is given). # * The **second** argument must be a _dot notation navigation string_. # * The **optional third** argument can be any type of value and it is used # as the _default value_ if the function would otherwise return `undef`. # * An **optional lambda** for error handling taking one `Error` argument. # # **Dot notation navigation string** - # The dot string consists of period `.` separated segments where each # segment is either the index into an array or the value of a hash key. # If a wanted key contains a period it must be quoted to avoid it being # taken as a segment separator. Quoting can be done with either # single quotes `'` or double quotes `"`. If a segment is # a decimal number it is converted to an Integer index. This conversion # can be prevented by quoting the value. # # @example Navigating into a value # ```puppet # #get($facts, 'os.family') # $facts.get('os.family') # ``` # Would both result in the value of `$facts['os']['family']` # # @example Getting the value from an expression # ```puppet # get([1,2,[{'name' =>'waldo'}]], '2.0.name') # ``` # Would result in `'waldo'` # # @example Using a default value # ```puppet # get([1,2,[{'name' =>'waldo'}]], '2.1.name', 'not waldo') # # ``` # Would result in `'not waldo'` # # @example Quoting a key with period # ```puppet # $x = [1, 2, { 'readme.md' => "This is a readme."}] # $x.get('2."readme.md"') # ``` # # @example Quoting a numeric string # ```puppet # $x = [1, 2, { '10' => "ten"}] # $x.get('2."0"') # ``` # # **Error Handling** - There are two types of common errors that can # be handled by giving the function a code block to execute. # (A third kind or error; when the navigation string has syntax errors # (for example an empty segment or unbalanced quotes) will always raise # an error). # # The given block will be given an instance of the `Error` data type, # and it has methods to extract `msg`, `issue_code`, `kind`, and # `details`. # # The `msg` will be a preformatted message describing the error. # This is the error message that would have surfaced if there was # no block to handle the error. # # The `kind` is the string `'SLICE_ERROR'` for both kinds of errors, # and the `issue_code` is either the string `'EXPECTED_INTEGER_INDEX'` # for an attempt to index into an array with a String, # or `'EXPECTED_COLLECTION'` for an attempt to index into something that # is not a Collection. # # The `details` is a Hash that for both issue codes contain the # entry `'walked_path'` which is an Array with each key in the # progression of the dig up to the place where the error occurred. # # For an `EXPECTED_INTEGER_INDEX`-issue the detail `'index_type'` is # set to the data type of the index value and for an # `'EXPECTED_COLLECTION'`-issue the detail `'value_type'` is set # to the type of the value. # # The logic in the error handling block can inspect the details, # and either call `fail()` with a custom error message or produce # the wanted value. # # If the block produces `undef` it will not be replaced with a # given default value. # # @example Ensure `undef` result on error # ```puppet # $x = 'blue' # $x.get('0.color', 'green') |$error| { undef } # result is undef # # $y = ['blue'] # $y.get('color', 'green') |$error| { undef } # result is undef # ``` # # @example Accessing information in the Error # ```puppet # $x = [1, 2, ['blue']] # $x.get('2.color') |$error| { # notice("Walked path is ${error.details['walked_path']}") # } # ``` # Would notice `Walked path is [2, color]` # # Also see: # * `getvar()` that takes the first segment to be the name of a variable # and then delegates to this function. # * `dig()` function which is similar but uses an # array of navigation values instead of a dot notation string. # # @since 6.0.0 # Puppet::Functions.create_function(:get, Puppet::Functions::InternalFunction) do dispatch :get_from_value do param 'Any', :value param 'String', :dotted_string optional_param 'Any', :default_value optional_block_param 'Callable[1,1]', :block end # Gets a result from given value and a navigation string # def get_from_value(value, navigation, default_value = nil, &block) return default_value if value.nil? return value if navigation.empty? # Note: split_key always processes the initial segment as a string even if it could be an integer. # This since it is designed for lookup keys. For a numeric first segment # like '0.1' the wanted result is `[0,1]`, not `["0", 1]`. The workaround here is to # prefix the navigation with `"x."` thus giving split_key a first segment that is a string. # The fake segment is then dropped. segments = split_key("x." + navigation) { |_err| _("Syntax error in dotted-navigation string") } segments.shift begin result = call_function('dig', value, *segments) result.nil? ? default_value : result rescue Puppet::ErrorWithData => e if block_given? yield(e.error_data) else raise e end end end # reuse the split_key parser used also by lookup include Puppet::Pops::Lookup::SubLookup end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/assert_type.rb
lib/puppet/functions/assert_type.rb
# frozen_string_literal: true # Returns the given value if it is of the given # [data type](https://puppet.com/docs/puppet/latest/lang_data.html), or # otherwise either raises an error or executes an optional two-parameter # [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html). # # The function takes two mandatory arguments, in this order: # # 1. The expected data type. # 2. A value to compare against the expected data type. # # @example Using `assert_type` # # ```puppet # $raw_username = 'Amy Berry' # # # Assert that $raw_username is a non-empty string and assign it to $valid_username. # $valid_username = assert_type(String[1], $raw_username) # # # $valid_username contains "Amy Berry". # # If $raw_username was an empty string or a different data type, the Puppet run would # # fail with an "Expected type does not match actual" error. # ``` # # You can use an optional lambda to provide enhanced feedback. The lambda takes two # mandatory parameters, in this order: # # 1. The expected data type as described in the function's first argument. # 2. The actual data type of the value. # # @example Using `assert_type` with a warning and default value # # ```puppet # $raw_username = 'Amy Berry' # # # Assert that $raw_username is a non-empty string and assign it to $valid_username. # # If it isn't, output a warning describing the problem and use a default value. # $valid_username = assert_type(String[1], $raw_username) |$expected, $actual| { # warning( "The username should be \'${expected}\', not \'${actual}\'. Using 'anonymous'." ) # 'anonymous' # } # # # $valid_username contains "Amy Berry". # # If $raw_username was an empty string, the Puppet run would set $valid_username to # # "anonymous" and output a warning: "The username should be 'String[1, default]', not # # 'String[0, 0]'. Using 'anonymous'." # ``` # # For more information about data types, see the # [documentation](https://puppet.com/docs/puppet/latest/lang_data.html). # # @since 4.0.0 # Puppet::Functions.create_function(:assert_type) do dispatch :assert_type do param 'Type', :type param 'Any', :value optional_block_param 'Callable[Type, Type]', :block end dispatch :assert_type_s do param 'String', :type_string param 'Any', :value optional_block_param 'Callable[Type, Type]', :block end # @param type [Type] the type the value must be an instance of # @param value [Object] the value to assert # def assert_type(type, value) unless Puppet::Pops::Types::TypeCalculator.instance?(type, value) inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value) if block_given? # Give the inferred type to allow richer comparison in the given block (if generalized # information is lost). # value = yield(type, inferred_type) else raise Puppet::Pops::Types::TypeAssertionError.new( Puppet::Pops::Types::TypeMismatchDescriber.singleton.describe_mismatch('assert_type():', type, inferred_type), type, inferred_type ) end end value end # @param type_string [String] the type the value must be an instance of given in String form # @param value [Object] the value to assert # def assert_type_s(type_string, value, &proc) t = Puppet::Pops::Types::TypeParser.singleton.parse(type_string) block_given? ? assert_type(t, value, &proc) : assert_type(t, value) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/next.rb
lib/puppet/functions/next.rb
# frozen_string_literal: true # Makes iteration continue with the next value, optionally with a given value for this iteration. # If a value is not given it defaults to `undef` # # @example Using the `next()` function # # ```puppet # $data = ['a','b','c'] # $data.each |Integer $index, String $value| { # if $index == 1 { # next() # } # notice ("${index} = ${value}") # } # ``` # # Would notice: # ``` # Notice: Scope(Class[main]): 0 = a # Notice: Scope(Class[main]): 2 = c # ``` # # @since 4.7.0 Puppet::Functions.create_function(:next) do dispatch :next_impl do optional_param 'Any', :value end def next_impl(value = nil) file, line = Puppet::Pops::PuppetStack.top_of_stack exc = Puppet::Pops::Evaluator::Next.new(value, file, line) raise exc end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/convert_to.rb
lib/puppet/functions/convert_to.rb
# frozen_string_literal: true # The `convert_to(value, type)` is a convenience function that does the same as `new(type, value)`. # The difference in the argument ordering allows it to be used in chained style for # improved readability "left to right". # # When the function is given a lambda, it is called with the converted value, and the function # returns what the lambda returns, otherwise the converted value. # # @example 'convert_to' instead of 'new' # # ```puppet # # The harder to read variant: # # Using new operator - that is "calling the type" with operator () # Hash(Array("abc").map |$i,$v| { [$i, $v] }) # # # The easier to read variant: # # using 'convert_to' # "abc".convert_to(Array).map |$i,$v| { [$i, $v] }.convert_to(Hash) # ``` # # @since 5.4.0 # Puppet::Functions.create_function(:convert_to) do dispatch :convert_to do param 'Any', :value param 'Type', :type optional_repeated_param 'Any', :args optional_block_param 'Callable[1,1]', :block end def convert_to(value, type, *args, &block) result = call_function('new', type, value, *args) block_given? ? yield(result) : result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/split.rb
lib/puppet/functions/split.rb
# frozen_string_literal: true # Splits a string into an array using a given pattern. # The pattern can be a string, regexp or regexp type. # # @example Splitting a String value # # ```puppet # $string = 'v1.v2:v3.v4' # $array_var1 = split($string, /:/) # $array_var2 = split($string, '[.]') # $array_var3 = split($string, Regexp['[.:]']) # # #`$array_var1` now holds the result `['v1.v2', 'v3.v4']`, # # while `$array_var2` holds `['v1', 'v2:v3', 'v4']`, and # # `$array_var3` holds `['v1', 'v2', 'v3', 'v4']`. # ``` # # Note that in the second example, we split on a literal string that contains # a regexp meta-character (`.`), which must be escaped. A simple # way to do that for a single character is to enclose it in square # brackets; a backslash will also escape a single character. # Puppet::Functions.create_function(:split) do dispatch :split_String do param 'String', :str param 'String', :pattern end dispatch :split_Regexp do param 'String', :str param 'Regexp', :pattern end dispatch :split_RegexpType do param 'String', :str param 'Type[Regexp]', :pattern end dispatch :split_String_sensitive do param 'Sensitive[String]', :sensitive param 'String', :pattern end dispatch :split_Regexp_sensitive do param 'Sensitive[String]', :sensitive param 'Regexp', :pattern end dispatch :split_RegexpType_sensitive do param 'Sensitive[String]', :sensitive param 'Type[Regexp]', :pattern end def split_String(str, pattern) str.split(Regexp.compile(pattern)) end def split_Regexp(str, pattern) str.split(pattern) end def split_RegexpType(str, pattern) str.split(pattern.regexp) end def split_String_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_String(sensitive.unwrap, pattern)) end def split_Regexp_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_Regexp(sensitive.unwrap, pattern)) end def split_RegexpType_sensitive(sensitive, pattern) Puppet::Pops::Types::PSensitiveType::Sensitive.new(split_RegexpType(sensitive.unwrap, pattern)) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/scanf.rb
lib/puppet/functions/scanf.rb
# frozen_string_literal: true # Scans a string and returns an array of one or more converted values based on the given format string. # See the documentation of Ruby's String#scanf method for details about the supported formats (which # are similar but not identical to the formats used in Puppet's `sprintf` function.) # # This function takes two mandatory arguments: the first is the string to convert, and the second is # the format string. The result of the scan is an array, with each successfully scanned and transformed value. # The scanning stops if a scan is unsuccessful, and the scanned result up to that point is returned. If there # was no successful scan, the result is an empty array. # # "42".scanf("%i") # # You can also optionally pass a lambda to scanf, to do additional validation or processing. # # # "42".scanf("%i") |$x| { # unless $x[0] =~ Integer { # fail "Expected a well formed integer value, got '$x[0]'" # } # $x[0] # } # # # # # # @since 4.0.0 # Puppet::Functions.create_function(:scanf) do require 'scanf' dispatch :scanf do param 'String', :data param 'String', :format optional_block_param end def scanf(data, format) result = data.scanf(format) if block_given? result = yield(result) end result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false