puppetlabs-stdlib-4.25.00040755005276200011600000000000013252003413012142 5ustar00puppetlabs-stdlib-4.25.0/CHANGELOG.md0100644005276200011600000010763113252003272014042 0ustar00# Change log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org). ## Supported Release 4.25.0 ### Summary This is quite a feature heavy release, it makes this module PDK-compliant for easier maintenance and includes a roll up of maintenance changes. #### Added - PDK conversion [MODULES-6332](https://tickets.puppetlabs.com/browse/MODULES-6332). - Update `join_keys_to_values` with an undef statement. - Type alias `Stdlib::Fqdn` matches paths on a fully qualified domain name. - Type alias `Stdlib::Host` matches a valid host, this can be a valid 'ipv4', 'ipv6' or 'fqdn'. - Type alias `Stdlib::Port` matches a valid TCP/UDP Port number. - Type alias `Stdlib::Filesource` matches paths valid values for the source parameter of the puppet file type. - Type alias `Stdlib::IP::Address` matches any IP address, including both IPv4 and IPv6 addresses, - Type alias `Stdlib::IP::Address::V4` matches any string consisting of a valid IPv4 address, this is extended by 'CIDR' and 'nosubnet'. - Type alias `Stdlib::IP::Address::V6` matches any string consisting of a valid IPv6 address, this is extended by 'Full', 'Alternate' and 'Compressed'. - Type alias `Stdlib::IP::Address::V6::Nosubnet`matches any string consisting of a valid IPv6 address with no subnet, this is extended by 'Full', 'Alternate' and 'Compressed'. - Type alias `Stdlib::Port` matches a valid TCP/UDP Port number this is then extended to 'Privileged' which are ports less than 1024 and 'Unprivileged' which are ports greater than 1024. ## Supported Release 4.24.0 ### Summary This release includes a roll up of minor changes and a new feature which provides the ability to skip undef values `to_json_pretty()`. We have also reverted a change that was previously made and resulted in breaking compatibility with Ruby 1.8.7. #### Added - Ability to skip undef values in `to_json_pretty()`. - Fix type3x function in stdlib ([MODULES-6216](https://tickets.puppet.com/browse/MODULES-6216)) #### Changed - Indentation for `sync.yml` was fixed. - Updated type alias tests and dropped superfluous wrapper classes - Revert to old ruby 1.X style of hash ([MODULES-6139](https://tickets.puppet.com/browse/MODULES-6139)) - `rubocop.yml` not managed by msync ([MODULES-6201](https://tickets.puppet.com/browse/MODULES-6201)) ## Supported Release 4.23.0 ### Summary This release is in order to implement Rubocop changes throughout the module. #### Added - Standard and translated readme's have been updated. - Rubocop has been implemented in the module and a wide variety of changes have been made to the code. - Modulesync changes have been merged into the code. #### Fixed - Minor fix to the readme. ## Supported Release 4.22.0 ### Summary This is a clean release in preparation of putting the module through the rubocop process. #### Added - Support has been added for Debian 9 - 'Stdlib::Mode type' has been added to the module. - A type for 'ensure' has been added to the service resources. - A new function 'sprintf_hash' has been added to allow the use of named references. #### Removed - Support has been removed for: RedHat 4, CentOS 4, OracleLinux 4, Scientific 4, SLES 10 SP4, Windows Server 2003, Windows Server 2003 R2 and Windows 8. #### Fixed - The 'ruby_spec.rb' test file has been altered s that it properly checks results. - Example syntax in 'file_line.rb' has been fixed. ## Supported Release 4.21.0 ### Summary This is a small feature release that includes a revamped, albeit backwards-compatible file_line type. #### Added - `replace_all_matches_not_matching_line` parameter in file_line - additional tests and documentation for file_line #### Removed - duplicate spec test for absolute_path #### Fixed - Unixpath type to allow "/" as valid path - file_line behavior that caused infinite appending of `line` to a file ([MODULES-5651](https://tickets.puppet.com/browse/MODULES-5651)) ## Supported Release 4.20.0 ### Summary This release adds new functions and updated README translations. #### Added - `to_json`, `to_json_pretty`, and `to_yaml` functions - new Japanese README translations #### Fixed - compatibility issue with older versions of Puppet and the `pw_hash` function ([MODULES-5546](https://tickets.puppet.com/browse/MODULES-5546)) #### Removed - support for EOL platform Debian 6 (Squeeze) ## Supported Release 4.19.0 ### Summary This release adds new functions and better documentation/fixes for existing functions with a noteworthy fix for file_line. #### Added - Add validate_domain_name function - Add the round function - Add type for MAC address - Add support for sensitive data type to pw_hash ([MODULES-4908](https://tickets.puppet.com/browse/MODULES-4908)) - Add new function, fact() (FACT-932) #### Fixed - Fixes for the file_line provider ([MODULES-5003](https://tickets.puppet.com/browse/MODULES-5003)) - Add documentation for email functions ([MODULES-5382](https://tickets.puppet.com/browse/MODULES-5382)) - unique function is deprecated for puppet version > 5. (FM-6239) - Fix headers in CHANGELOG.md so that headers render correctly - ensure_packages, converge ensure values 'present' and 'installed' #### Changed - Removes listed support for EOL Ubuntu versions ## Supported Release 4.18.0 ### Summary Small release that reverts the Puppet version requirement lower bound to again include Puppet 2.7+ and bumps the upper bound to now include Puppet 5. #### Fixed - Reverts lower bound of Puppet requirement to 2.7.20 ## Supported Release 4.17.1 ### Summary Small release to address a bug (PUP-7650). Also pushes the Puppet version compatibility to 4.7.0. #### Bugfixes - (MODULES-5095) Workaround for PUP-7650 - (FM-6197) Formatting fixes for file_line resource ## Supported Release 4.17.0 ### Summary This release adds support for internationalization. It also contains Japanese translations for the README, summary and description of the metadata.json and major cleanups in the README. Additional folders have been introduced called locales and readmes where translation files can be found. A number of features and bug fixes are also included in this release. It also adds a new function `glob()` for expanding file lists. Also works around an issue that appeared in puppet 4.6.0 involving types being declared multiple times. #### Features - Addition of POT file / folder structure for i18n. - Addition of Internationalized READMEs. - `glob()` function ### Fixed - Occasional duplicate type definitions when using `defined_with_params()` - `file_line` encoding issue on ruby 1.8 (unsupported) - Huge readme refresh ## Supported Release 4.16.0 ### Summary This release sees a massive update to all unit tests to test UTF8 characters. There are also multiple cleanups in preparation for internationalization. Alongside this, improvements to ipv6 support, a new length function compatible with Puppet 4, and an update to path types. Also contains multiple bug fixes around functionality and tests. #### Features - Addition of coverage in all unit tests for functions, data and resource types for UTF8 for i18n. - All strings within the readme and functions that are split over two lines have been combined in preparation for i18n parser/decorator. - Improvement on the ipv6 support for type - Improves regex to catch some valid (but lesser known) ipv6 strings, mostly those which are a mix of ipv6 strings and embedded ipv6 numbers. - Adds a new parameter `encoding` to allow non UTF-8 files to specify a file encoding. This prevents receiving the error message "invalid byte sequence in UTF-8" when special characters that are not UTF-8 encoded appear in the input stream, such as the copyright symbol. - Addition of the new length function. Returns the length of a given string, array or hash. To eventually replace the deprecated size() function as can handle the new type functionality introduced in Puppet 4. - Permit double slash in absolute/Unix path types. #### Bugfixes - Fix unsupported data type error with rspec-puppet master. - Now allows test module metadata.json to be read by Puppet. - Fix acceptance test failure "Hiera is not a class". - Removal of unsupported platforms and future parser setting in acceptance tests. - Regex for tuple checking has been loosened. - Ensure_packages function - Now only tries to apply the resource if not defined. - (MODULES-4528) Use versioncmp to check Puppet version for 4.10.x compat. - Adds comments to warn for UTF8 incompatibility of the functions that may not be compatible with UTF8 with Ruby < 2.4.0. ## Supported Release 4.15.0 ### Summary This release introduces multiple new functions, a new fact and the addition of Ubuntu Xenial support. Also includes a bugfix and documentation update. #### Features - Addition of puppet_server fact to return agents server. - Addition of a pry function. - Addition of tests for ensure_resources. - Addition of FQDN UUID generation function. - Addition of Ubuntu Xenial to OS Support. #### Bugfixes - Ensure_packages now works with Ruby < 2.0. - Updated the documentation of str2bool function. ## Supported Release 4.14.0 ### Summary Adds several new features and updates, especially around refining the deprecation and validate_legacy functions. Also includes a Gemfile update around an issue with parallel_tests dependancy for different versions of Ruby. #### Features - Deprecation function now uses puppet stacktrace if available. - join_key_to_values function now handles array values. If values are arrays, multiple keys are added for each element. - Updated Gemfile to deal with parallel_tests Ruby dependancy (MODULES-3983). - Updated/Fixed ipv4 regex validator (MODULES-3980). - Deprecation clarification added to README. #### Bugfixes - README typo fixes. - Use .dup to duplicate classes for modification (MODULES-3829). - Fixes spec failures that were caused by a change in the tested error message in validate_legacy_spec. - Broken link to validate_legacy docs fixed. - Updates deprecation tests to include future parser. ## Supported Release 4.13.1 ### Summary This bugfix release addresses the `undefined method 'optional_repeated_param'` error messages seen by users of puppet 3.7. It also improves the user experience around function deprecations by emitting one warning per function(-name) instead of only one deprecation overall. This allows users to identify all deprecated functions used in one agent run, with less back-and-forth. #### Bugfixes * Emit deprecations warnings for each function, instead of once per process. (MODULES-3961) * Use a universally available API for the v4 deprecation stubs of `is_*` and `validate_*`. (MODULES-3962) * Make `getvar()` compatible to ruby 1.8.7. (MODULES-3969) * Add v4 deprecation stubs for the `is_` counterparts of the deprecated functions to emit the deprecations warnings in all cases. ## Supported Release 4.13.0 ### Summary This version of stdlib deprecates a whole host of functions, and provides stepping stones to move to Puppet 4 type validations. Be sure to check out the new `deprecation()` and `validate_legacy()` functions to migrate off the deprecated v3-style data validations. Many thanks to all community contributors: bob, Dmitry Ilyin, Dominic Cleal, Joris, Joseph Yaworski, Loic Antoine-Gombeaud, Maksym Melnychok, Michiel Brandenburg, Nate Potter, Romain Tartière, Stephen Benjamin, and Steve Moore, as well as anyone contributing in the code review process and by submitting issues. Special thanks to [Voxpupuli's](https://voxpupuli.org/) Igor Galić for donating the puppet-tea types to kickstart this part of stdlib. #### Deprecations * `validate_absolute_path`, `validate_array`, `validate_bool`, `validate_hash`, `validate_integer`, `validate_ip_address`, `validate_ipv4_address`, `validate_ipv6_address`, `validate_numeric`, `validate_re`, `validate_slength`, `validate_string`, and their `is_` counter parts are now deprecated on Puppet 4. See the `validate_legacy()` description in the README for help on migrating away from those functions. * The `dig` function is provided by core puppet since 4.5.0 with slightly different calling convention. The stdlib version can still be accessed as `dig44` for now. #### Features * Add Puppet 4 data types for Unix, and Windows paths, and URLs. * Add `deprecation` function to warn users of functionality that will be removed soon. * Add `validate_legacy` function to help with migrating to Puppet 4 data types. * Add `any2bool` function, a combination of of `string2bool` and `num2bool`. * Add `delete_regex` function to delete array elements matching a regular expression. * Add `puppet_environmentpath` fact to expose the `environmentpath` setting. * Add `regexpescape` function to safely insert arbitrary strings into regular expressions. * Add `shell_escape`, `shell_join`, and `shell_split` functions for safer working with shell scripts.. * The `delete` function now also accepts regular expressions as search term. * The `loadyaml` function now accepts a default value, which is returned when there is an error loading the file. #### Bugfixes * Fix `file_line.match_for_absence` implementation and description to actually work. (MODULES-3590) * Fix `getparam` so that it can now also return `false`. (MODULES-3933) * Fix the fixture setup for testing and adjust `load_module_metadata` and `loadjson` tests. * Fix `defined_with_params` to handle `undef` correctly on all puppet versions. (PUP-6422, MODULES-3543) * Fix `file_line.path` validation to use puppet's built in `absolute_path?` matcher. #### Minor Improvements * README changes: improved descriptions of `deep_merge`, `delete`, `ensure_packages`, `file_line.after`, `range`, and `validate_numeric`. * The `getvar` function now returns nil in all situations where the variable is not found. * Update the `dig44` function with better `undef`, `nil`, and `false` handling. * Better wording on `str2bool` argument validation error message. ### Known issues * The `validate_legacy` function relies on internal APIs from Puppet 4.4.0 (PE 2016.1) onwards, and doesn't work on earlier versions. * Puppet 4.5.0 (PE 2016.2) has a number of improvements around data types - especially error handling - that make working with them much nicer. ## Supported Release 4.12.0 ### Summary This release provides several new functions, bugfixes, modulesync changes, and some documentation updates. #### Features - Adds `clamp`. This function keeps values within a specified range. - Adds `validate_x509_rsa_key_pair`. This function validates an x509 RSA certificate and key pair. - Adds `dig`. This function performs a deep lookup in nested hashes or arrays. - Extends the `base64` support to fit `rfc2045` and `rfc4648`. - Adds `is_ipv6_address` and `is_ipv4_address`. These functions validate the specified ipv4 or ipv6 addresses. - Adds `enclose_ipv6`. This function encloses IPv6 addresses in square brackets. - Adds `ensure_resources`. This function takes a list of resources and creates them if they do not exist. - Extends `suffix` to support applying a suffix to keys in a hash. - Apply modulesync changes. - Add validate_email_address function. #### Bugfixes - Fixes `fqdn_rand_string` tests, since Puppet 4.4.0 and later have a higher `fqdn_rand` ceiling. - (MODULES-3152) Adds a check to `package_provider` to prevent failures if Gem is not installed. - Fixes to README.md. - Fixes catch StandardError rather than the gratuitous Exception - Fixes file_line attribute validation. - Fixes concat with Hash arguments. ## Supported Release 4.11.0 ### Summary Provides a validate_absolute_paths and Debian 8 support. There is a fix to the is_package_provider fact and a test improvement. #### Features - Adds new parser called is_absolute_path - Supports Debian 8 #### Bugfixes - Allow package_provider fact to resolve on PE 3.x #### Improvements - ensures that the test passes independently of changes to rubygems for ensure_resource ## 2015-12-15 - Supported Release 4.10.0 ### Summary Includes the addition of several new functions and considerable improvements to the existing functions, tests and documentation. Includes some bug fixes which includes compatibility, test and fact issues. #### Features - Adds service_provider fact - Adds is_a() function - Adds package_provider fact - Adds validate_ip_address function - Adds seeded_rand function #### Bugfixes - Fix backwards compatibility from an improvement to the parseyaml function - Renaming of load_module_metadata test to include _spec.rb - Fix root_home fact on AIX 5.x, now '-c' rather than '-C' - Fixed Gemfile to work with ruby 1.8.7 #### Improvements - (MODULES-2462) Improvement of parseyaml function - Improvement of str2bool function - Improvement to readme - Improvement of intersection function - Improvement of validate_re function - Improved speed on Facter resolution of service_provider - empty function now handles numeric values - Package_provider now prevents deprecation warning about the allow_virtual parameter - load_module_metadata now succeeds on empty file - Check added to ensure puppetversion value is not nil - Improvement to bool2str to return a string of choice using boolean - Improvement to naming convention in validate_ipv4_address function ## Supported Release 4.9.1 ### Summary Small release for support of newer PE versions. This increments the version of PE in the metadata.json file. ## 2015-09-08 - Supported Release 4.9.0 ### Summary This release adds new features including the new functions dos2unix, unix2dos, try_get_value, convert_base as well as other features and improvements. #### Features - (MODULES-2370) allow `match` parameter to influence `ensure => absent` behavior - (MODULES-2410) Add new functions dos2unix and unix2dos - (MODULE-2456) Modify union to accept more than two arrays - Adds a convert_base function, which can convert numbers between bases - Add a new function "try_get_value" #### Bugfixes - n/a #### Improvements - (MODULES-2478) Support root_home fact on AIX through "lsuser" command - Acceptance test improvements - Unit test improvements - Readme improvements ## 2015-08-10 - Supported Release 4.8.0 ### Summary This release adds a function for reading metadata.json from any module, and expands file\_line's abilities. #### Features - New parameter `replace` on `file_line` - New function `load_module_metadata()` to load metadata.json and return the content as a hash. - Added hash support to `size()` #### Bugfixes - Fix various docs typos - Fix `file_line` resource on puppet < 3.3 ## 2015-06-22 - Supported Release 4.7.0 ### Summary Adds Solaris 12 support along with improved Puppet 4 support. There are significant test improvements, and some minor fixes. #### Features - Add support for Solaris 12 #### Bugfixes - Fix for AIO Puppet 4 - Fix time for ruby 1.8.7 - Specify rspec-puppet version - range() fix for typeerror and missing functionality - Fix pw_hash() on JRuby < 1.7.17 - fqdn_rand_string: fix argument error message - catch and rescue from looking up non-existent facts - Use puppet_install_helper, for Puppet 4 #### Improvements - Enforce support for Puppet 4 testing - fqdn_rotate/fqdn_rand_string acceptance tests and implementation - Simplify mac address regex - validate_integer, validate_numeric: explicitely reject hashes in arrays - Readme edits - Remove all the pops stuff for rspec-puppet - Sync via modulesync - Add validate_slength optional 3rd arg - Move tests directory to examples directory ## 2015-04-14 - Supported Release 4.6.0 ### Summary Adds functions and function argument abilities, and improves compatibility with the new puppet parser #### Features - MODULES-444: `concat()` can now take more than two arrays - `basename()` added to have Ruby File.basename functionality - `delete()` can now take an array of items to remove - `prefix()` can now take a hash - `upcase()` can now take a hash or array of upcaseable things - `validate_absolute_path()` can now take an array - `validate_cmd()` can now use % in the command to embed the validation file argument in the string - MODULES-1473: deprecate `type()` function in favor of `type3x()` - MODULES-1473: Add `type_of()` to give better type information on future parser - Deprecate `private()` for `assert_private()` due to future parser - Adds `ceiling()` to take the ceiling of a number - Adds `fqdn_rand_string()` to generate random string based on fqdn - Adds `pw_hash()` to generate password hashes - Adds `validate_integer()` - Adds `validate_numeric()` (like `validate_integer()` but also accepts floats) #### Bugfixes - Fix seeding of `fqdn_rotate()` - `ensure_resource()` is more verbose on debug mode - Stricter argument checking for `dirname()` - Fix `is_domain_name()` to better match RFC - Fix `uriescape()` when called with array - Fix `file_line` resource when using the `after` attribute with `match` ## 2015-01-14 - Supported Release 4.5.1 ### Summary This release changes the temporary facter_dot_d cache locations outside of the /tmp directory due to a possible security vunerability. CVE-2015-1029 #### Bugfixes - Facter_dot_d cache will now be stored in puppet libdir instead of tmp ## 2014-12-15 - Supported Release 4.5.0 ### Summary This release improves functionality of the member function and adds improved future parser support. #### Features - MODULES-1329: Update member() to allow the variable to be an array. - Sync .travis.yml, Gemfile, Rakefile, and CONTRIBUTING.md via modulesync #### Bugfixes - Fix range() to work with numeric ranges with the future parser - Accurately express SLES support in metadata.json (was missing 10SP4 and 12) - Don't require `line` to match the `match` parameter ## 2014-11-10 - Supported Release 4.4.0 ### Summary This release has an overhauled readme, new private manifest function, and fixes many future parser bugs. #### Features - All new shiny README - New `private()` function for making private manifests (yay!) #### Bugfixes - Code reuse in `bool2num()` and `zip()` - Fix many functions to handle `generate()` no longer returning a string on new puppets - `concat()` no longer modifies the first argument (whoops) - strict variable support for `getvar()`, `member()`, `values_at`, and `has_interface_with()` - `to_bytes()` handles PB and EB now - Fix `tempfile` ruby requirement for `validate_augeas()` and `validate_cmd()` - Fix `validate_cmd()` for windows - Correct `validate_string()` docs to reflect non-handling of `undef` - Fix `file_line` matching on older rubies ## 2014-07-15 - Supported Release 4.3.2 ### Summary This release merely updates metadata.json so the module can be uninstalled and upgraded via the puppet module command. ## 2014-07-14 - Supported Release 4.3.1 ### Summary This supported release updates the metadata.json to work around upgrade behavior of the PMT. #### Bugfixes - Synchronize metadata.json with PMT-generated metadata to pass checksums ## 2014-06-27 - Supported Release 4.3.0 ### Summary This release is the first supported release of the stdlib 4 series. It remains backwards-compatible with the stdlib 3 series. It adds two new functions, one bugfix, and many testing updates. #### Features - New `bool2str()` function - New `camelcase()` function #### Bugfixes - Fix `has_interface_with()` when interfaces fact is nil ## 2014-06-04 - Release 4.2.2 ### Summary This release adds PE3.3 support in the metadata and fixes a few tests. ## 2014-05-08 - Release - 4.2.1 ### Summary This release moves a stray symlink that can cause problems. ## 2014-05-08 - Release - 4.2.0 ### Summary This release adds many new functions and fixes, and continues to be backwards compatible with stdlib 3.x #### Features - New `base64()` function - New `deep_merge()` function - New `delete_undef_values()` function - New `delete_values()` function - New `difference()` function - New `intersection()` function - New `is_bool()` function - New `pick_default()` function - New `union()` function - New `validate_ipv4_address` function - New `validate_ipv6_address` function - Update `ensure_packages()` to take an option hash as a second parameter. - Update `range()` to take an optional third argument for range step - Update `validate_slength()` to take an optional third argument for minimum length - Update `file_line` resource to take `after` and `multiple` attributes #### Bugfixes - Correct `is_string`, `is_domain_name`, `is_array`, `is_float`, and `is_function_available` for parsing odd types such as bools and hashes. - Allow facts.d facts to contain `=` in the value - Fix `root_home` fact on darwin systems - Fix `concat()` to work with a second non-array argument - Fix `floor()` to work with integer strings - Fix `is_integer()` to return true if passed integer strings - Fix `is_numeric()` to return true if passed integer strings - Fix `merge()` to work with empty strings - Fix `pick()` to raise the correct error type - Fix `uriescape()` to use the default URI.escape list - Add/update unit & acceptance tests. ## 2014-03-04 - Supported Release - 3.2.1 ### Summary This is a supported release #### Bugfixes - Fixed `is_integer`/`is_float`/`is_numeric` for checking the value of arithmatic expressions. #### Known bugs * No known bugs --- ##### 2013-05-06 - Jeff McCune - 4.1.0 * (#20582) Restore facter\_dot\_d to stdlib for PE users (3b887c8) * (maint) Update Gemfile with GEM\_FACTER\_VERSION (f44d535) ##### 2013-05-06 - Alex Cline - 4.1.0 * Terser method of string to array conversion courtesy of ethooz. (d38bce0) ##### 2013-05-06 - Alex Cline 4.1.0 * Refactor ensure\_resource expectations (b33cc24) ##### 2013-05-06 - Alex Cline 4.1.0 * Changed str-to-array conversion and removed abbreviation. (de253db) ##### 2013-05-03 - Alex Cline 4.1.0 * (#20548) Allow an array of resource titles to be passed into the ensure\_resource function (e08734a) ##### 2013-05-02 - Raphaël Pinson - 4.1.0 * Add a dirname function (2ba9e47) ##### 2013-04-29 - Mark Smith-Guerrero - 4.1.0 * (maint) Fix a small typo in hash() description (928036a) ##### 2013-04-12 - Jeff McCune - 4.0.2 * Update user information in gemspec to make the intent of the Gem clear. ##### 2013-04-11 - Jeff McCune - 4.0.1 * Fix README function documentation (ab3e30c) ##### 2013-04-11 - Jeff McCune - 4.0.0 * stdlib 4.0 drops support with Puppet 2.7 * stdlib 4.0 preserves support with Puppet 3 ##### 2013-04-11 - Jeff McCune - 4.0.0 * Add ability to use puppet from git via bundler (9c5805f) ##### 2013-04-10 - Jeff McCune - 4.0.0 * (maint) Make stdlib usable as a Ruby GEM (e81a45e) ##### 2013-04-10 - Erik Dalén - 4.0.0 * Add a count function (f28550e) ##### 2013-03-31 - Amos Shapira - 4.0.0 * (#19998) Implement any2array (7a2fb80) ##### 2013-03-29 - Steve Huff - 4.0.0 * (19864) num2bool match fix (8d217f0) ##### 2013-03-20 - Erik Dalén - 4.0.0 * Allow comparisons of Numeric and number as String (ff5dd5d) ##### 2013-03-26 - Richard Soderberg - 4.0.0 * add suffix function to accompany the prefix function (88a93ac) ##### 2013-03-19 - Kristof Willaert - 4.0.0 * Add floor function implementation and unit tests (0527341) ##### 2012-04-03 - Eric Shamow - 4.0.0 * (#13610) Add is\_function\_available to stdlib (961dcab) ##### 2012-12-17 - Justin Lambert - 4.0.0 * str2bool should return a boolean if called with a boolean (5d5a4d4) ##### 2012-10-23 - Uwe Stuehler - 4.0.0 * Fix number of arguments check in flatten() (e80207b) ##### 2013-03-11 - Jeff McCune - 4.0.0 * Add contributing document (96e19d0) ##### 2013-03-04 - Raphaël Pinson - 4.0.0 * Add missing documentation for validate\_augeas and validate\_cmd to README.markdown (a1510a1) ##### 2013-02-14 - Joshua Hoblitt - 4.0.0 * (#19272) Add has\_element() function (95cf3fe) ##### 2013-02-07 - Raphaël Pinson - 4.0.0 * validate\_cmd(): Use Puppet::Util::Execution.execute when available (69248df) ##### 2012-12-06 - Raphaël Pinson - 4.0.0 * Add validate\_augeas function (3a97c23) ##### 2012-12-06 - Raphaël Pinson - 4.0.0 * Add validate\_cmd function (6902cc5) ##### 2013-01-14 - David Schmitt - 4.0.0 * Add geppetto project definition (b3fc0a3) ##### 2013-01-02 - Jaka Hudoklin - 4.0.0 * Add getparam function to get defined resource parameters (20e0e07) ##### 2013-01-05 - Jeff McCune - 4.0.0 * (maint) Add Travis CI Support (d082046) ##### 2012-12-04 - Jeff McCune - 4.0.0 * Clarify that stdlib 3 supports Puppet 3 (3a6085f) ##### 2012-11-30 - Erik Dalén - 4.0.0 * maint: style guideline fixes (7742e5f) ##### 2012-11-09 - James Fryman - 4.0.0 * puppet-lint cleanup (88acc52) ##### 2012-11-06 - Joe Julian - 4.0.0 * Add function, uriescape, to URI.escape strings. Redmine #17459 (fd52b8d) ##### 2012-09-18 - Chad Metcalf - 3.2.0 * Add an ensure\_packages function. (8a8c09e) ##### 2012-11-23 - Erik Dalén - 3.2.0 * (#17797) min() and max() functions (9954133) ##### 2012-05-23 - Peter Meier - 3.2.0 * (#14670) autorequire a file\_line resource's path (dfcee63) ##### 2012-11-19 - Joshua Harlan Lifton - 3.2.0 * Add join\_keys\_to\_values function (ee0f2b3) ##### 2012-11-17 - Joshua Harlan Lifton - 3.2.0 * Extend delete function for strings and hashes (7322e4d) ##### 2012-08-03 - Gary Larizza - 3.2.0 * Add the pick() function (ba6dd13) ##### 2012-03-20 - Wil Cooley - 3.2.0 * (#13974) Add predicate functions for interface facts (f819417) ##### 2012-11-06 - Joe Julian - 3.2.0 * Add function, uriescape, to URI.escape strings. Redmine #17459 (70f4a0e) ##### 2012-10-25 - Jeff McCune - 3.1.1 * (maint) Fix spec failures resulting from Facter API changes (97f836f) ##### 2012-10-23 - Matthaus Owens - 3.1.0 * Add PE facts to stdlib (cdf3b05) ##### 2012-08-16 - Jeff McCune - 3.0.1 * Fix accidental removal of facts\_dot\_d.rb in 3.0.0 release ##### 2012-08-16 - Jeff McCune - 3.0.0 * stdlib 3.0 drops support with Puppet 2.6 * stdlib 3.0 preserves support with Puppet 2.7 ##### 2012-08-07 - Dan Bode - 3.0.0 * Add function ensure\_resource and defined\_with\_params (ba789de) ##### 2012-07-10 - Hailee Kenney - 3.0.0 * (#2157) Remove facter\_dot\_d for compatibility with external facts (f92574f) ##### 2012-04-10 - Chris Price - 3.0.0 * (#13693) moving logic from local spec\_helper to puppetlabs\_spec\_helper (85f96df) ##### 2012-10-25 - Jeff McCune - 2.5.1 * (maint) Fix spec failures resulting from Facter API changes (97f836f) ##### 2012-10-23 - Matthaus Owens - 2.5.0 * Add PE facts to stdlib (cdf3b05) ##### 2012-08-15 - Dan Bode - 2.5.0 * Explicitly load functions used by ensure\_resource (9fc3063) ##### 2012-08-13 - Dan Bode - 2.5.0 * Add better docs about duplicate resource failures (97d327a) ##### 2012-08-13 - Dan Bode - 2.5.0 * Handle undef for parameter argument (4f8b133) ##### 2012-08-07 - Dan Bode - 2.5.0 * Add function ensure\_resource and defined\_with\_params (a0cb8cd) ##### 2012-08-20 - Jeff McCune - 2.5.0 * Disable tests that fail on 2.6.x due to #15912 (c81496e) ##### 2012-08-20 - Jeff McCune - 2.5.0 * (Maint) Fix mis-use of rvalue functions as statements (4492913) ##### 2012-08-20 - Jeff McCune - 2.5.0 * Add .rspec file to repo root (88789e8) ##### 2012-06-07 - Chris Price - 2.4.0 * Add support for a 'match' parameter to file\_line (a06c0d8) ##### 2012-08-07 - Erik Dalén - 2.4.0 * (#15872) Add to\_bytes function (247b69c) ##### 2012-07-19 - Jeff McCune - 2.4.0 * (Maint) use PuppetlabsSpec::PuppetInternals.scope (master) (deafe88) ##### 2012-07-10 - Hailee Kenney - 2.4.0 * (#2157) Make facts\_dot\_d compatible with external facts (5fb0ddc) ##### 2012-03-16 - Steve Traylen - 2.4.0 * (#13205) Rotate array/string randomley based on fqdn, fqdn\_rotate() (fef247b) ##### 2012-05-22 - Peter Meier - 2.3.3 * fix regression in #11017 properly (f0a62c7) ##### 2012-05-10 - Jeff McCune - 2.3.3 * Fix spec tests using the new spec\_helper (7d34333) ##### 2012-05-10 - Puppet Labs - 2.3.2 * Make file\_line default to ensure => present (1373e70) * Memoize file\_line spec instance variables (20aacc5) * Fix spec tests using the new spec\_helper (1ebfa5d) * (#13595) initialize\_everything\_for\_tests couples modules Puppet ver (3222f35) * (#13439) Fix MRI 1.9 issue with spec\_helper (15c5fd1) * (#13439) Fix test failures with Puppet 2.6.x (665610b) * (#13439) refactor spec helper for compatibility with both puppet 2.7 and master (82194ca) * (#13494) Specify the behavior of zero padded strings (61891bb) ##### 2012-03-29 Puppet Labs - 2.1.3 * (#11607) Add Rakefile to enable spec testing * (#12377) Avoid infinite loop when retrying require json ##### 2012-03-13 Puppet Labs - 2.3.1 * (#13091) Fix LoadError bug with puppet apply and puppet\_vardir fact ##### 2012-03-12 Puppet Labs - 2.3.0 * Add a large number of new Puppet functions * Backwards compatibility preserved with 2.2.x ##### 2011-12-30 Puppet Labs - 2.2.1 * Documentation only release for the Forge ##### 2011-12-30 Puppet Labs - 2.1.2 * Documentation only release for PE 2.0.x ##### 2011-11-08 Puppet Labs - 2.2.0 * #10285 - Refactor json to use pson instead. * Maint - Add watchr autotest script * Maint - Make rspec tests work with Puppet 2.6.4 * #9859 - Add root\_home fact and tests ##### 2011-08-18 Puppet Labs - 2.1.1 * Change facts.d paths to match Facter 2.0 paths. * /etc/facter/facts.d * /etc/puppetlabs/facter/facts.d ##### 2011-08-17 Puppet Labs - 2.1.0 * Add R.I. Pienaar's facts.d custom facter fact * facts defined in /etc/facts.d and /etc/puppetlabs/facts.d are automatically loaded now. ##### 2011-08-04 Puppet Labs - 2.0.0 * Rename whole\_line to file\_line * This is an API change and as such motivating a 2.0.0 release according to semver.org. ##### 2011-08-04 Puppet Labs - 1.1.0 * Rename append\_line to whole\_line * This is an API change and as such motivating a 1.1.0 release. ##### 2011-08-04 Puppet Labs - 1.0.0 * Initial stable release * Add validate\_array and validate\_string functions * Make merge() function work with Ruby 1.8.5 * Add hash merging function * Add has\_key function * Add loadyaml() function * Add append\_line native ##### 2011-06-21 Jeff McCune - 0.1.7 * Add validate\_hash() and getvar() functions ##### 2011-06-15 Jeff McCune - 0.1.6 * Add anchor resource type to provide containment for composite classes ##### 2011-06-03 Jeff McCune - 0.1.5 * Add validate\_bool() function to stdlib ##### 0.1.4 2011-05-26 Jeff McCune * Move most stages after main ##### 0.1.3 2011-05-25 Jeff McCune * Add validate\_re() function ##### 0.1.2 2011-05-24 Jeff McCune * Update to add annotated tag ##### 0.1.1 2011-05-24 Jeff McCune * Add stdlib::stages class with a standard set of stages puppetlabs-stdlib-4.25.0/CONTRIBUTING.md0100644005276200011600000002306013206047630014460 0ustar00# Contributing to Puppet modules So you want to contribute to a Puppet module: Great! Below are some instructions to get you started doing that very thing while setting expectations around code quality as well as a few tips for making the process as easy as possible. ### Table of Contents 1. [Getting Started](#getting-started) 1. [Commit Checklist](#commit-checklist) 1. [Submission](#submission) 1. [More about commits](#more-about-commits) 1. [Testing](#testing) - [Running Tests](#running-tests) - [Writing Tests](#writing-tests) 1. [Get Help](#get-help) ## Getting Started - Fork the module repository on GitHub and clone to your workspace - Make your changes! ## Commit Checklist ### The Basics - [x] my commit is a single logical unit of work - [x] I have checked for unnecessary whitespace with "git diff --check" - [x] my commit does not include commented out code or unneeded files ### The Content - [x] my commit includes tests for the bug I fixed or feature I added - [x] my commit includes appropriate documentation changes if it is introducing a new feature or changing existing functionality - [x] my code passes existing test suites ### The Commit Message - [x] the first line of my commit message includes: - [x] an issue number (if applicable), e.g. "(MODULES-xxxx) This is the first line" - [x] a short description (50 characters is the soft limit, excluding ticket number(s)) - [x] the body of my commit message: - [x] is meaningful - [x] uses the imperative, present tense: "change", not "changed" or "changes" - [x] includes motivation for the change, and contrasts its implementation with the previous behavior ## Submission ### Pre-requisites - Make sure you have a [GitHub account](https://github.com/join) - [Create a ticket](https://tickets.puppet.com/secure/CreateIssue!default.jspa), or [watch the ticket](https://tickets.puppet.com/browse/) you are patching for. ### Push and PR - Push your changes to your fork - [Open a Pull Request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/) against the repository in the puppetlabs organization ## More about commits 1. Make separate commits for logically separate changes. Please break your commits down into logically consistent units which include new or changed tests relevant to the rest of the change. The goal of doing this is to make the diff easier to read for whoever is reviewing your code. In general, the easier your diff is to read, the more likely someone will be happy to review it and get it into the code base. If you are going to refactor a piece of code, please do so as a separate commit from your feature or bug fix changes. We also really appreciate changes that include tests to make sure the bug is not re-introduced, and that the feature is not accidentally broken. Describe the technical detail of the change(s). If your description starts to get too long, that is a good sign that you probably need to split up your commit into more finely grained pieces. Commits which plainly describe the things which help reviewers check the patch and future developers understand the code are much more likely to be merged in with a minimum of bike-shedding or requested changes. Ideally, the commit message would include information, and be in a form suitable for inclusion in the release notes for the version of Puppet that includes them. Please also check that you are not introducing any trailing whitespace or other "whitespace errors". You can do this by running "git diff --check" on your changes before you commit. 2. Sending your patches To submit your changes via a GitHub pull request, we _highly_ recommend that you have them on a topic branch, instead of directly on "master". It makes things much easier to keep track of, especially if you decide to work on another thing before your first change is merged in. GitHub has some pretty good [general documentation](http://help.github.com/) on using their site. They also have documentation on [creating pull requests](https://help.github.com/articles/creating-a-pull-request-from-a-fork/). In general, after pushing your topic branch up to your repository on GitHub, you can switch to the branch in the GitHub UI and click "Pull Request" towards the top of the page in order to open a pull request. 3. Update the related JIRA issue. If there is a JIRA issue associated with the change you submitted, then you should update the ticket to include the location of your branch, along with any other commentary you may wish to make. # Testing ## Getting Started Our Puppet modules provide [`Gemfile`](./Gemfile)s, which can tell a Ruby package manager such as [bundler](http://bundler.io/) what Ruby packages, or Gems, are required to build, develop, and test this software. Please make sure you have [bundler installed](http://bundler.io/#getting-started) on your system, and then use it to install all dependencies needed for this project in the project root by running ```shell % bundle install --path .bundle/gems Fetching gem metadata from https://rubygems.org/........ Fetching gem metadata from https://rubygems.org/.. Using rake (10.1.0) Using builder (3.2.2) -- 8><-- many more --><8 -- Using rspec-system-puppet (2.2.0) Using serverspec (0.6.3) Using rspec-system-serverspec (1.0.0) Using bundler (1.3.5) Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed. ``` NOTE: some systems may require you to run this command with sudo. If you already have those gems installed, make sure they are up-to-date: ```shell % bundle update ``` ## Running Tests With all dependencies in place and up-to-date, run the tests: ### Unit Tests ```shell % bundle exec rake spec ``` This executes all the [rspec tests](http://rspec-puppet.com/) in the directories defined [here](https://github.com/puppetlabs/puppetlabs_spec_helper/blob/699d9fbca1d2489bff1736bb254bb7b7edb32c74/lib/puppetlabs_spec_helper/rake_tasks.rb#L17) and so on. rspec tests may have the same kind of dependencies as the module they are testing. Although the module defines these dependencies in its [metadata.json](./metadata.json), rspec tests define them in [.fixtures.yml](./fixtures.yml). ### Acceptance Tests Some Puppet modules also come with acceptance tests, which use [beaker][]. These tests spin up a virtual machine under [VirtualBox](https://www.virtualbox.org/), controlled with [Vagrant](http://www.vagrantup.com/), to simulate scripted test scenarios. In order to run these, you need both Virtualbox and Vagrant installed on your system. Run the tests by issuing the following command ```shell % bundle exec rake spec_clean % bundle exec rspec spec/acceptance ``` This will now download a pre-fabricated image configured in the [default node-set](./spec/acceptance/nodesets/default.yml), install Puppet, copy this module, and install its dependencies per [spec/spec_helper_acceptance.rb](./spec/spec_helper_acceptance.rb) and then run all the tests under [spec/acceptance](./spec/acceptance). ## Writing Tests ### Unit Tests When writing unit tests for Puppet, [rspec-puppet][] is your best friend. It provides tons of helper methods for testing your manifests against a catalog (e.g. contain_file, contain_package, with_params, etc). It would be ridiculous to try and top rspec-puppet's [documentation][rspec-puppet_docs] but here's a tiny sample: Sample manifest: ```puppet file { "a test file": ensure => present, path => "/etc/sample", } ``` Sample test: ```ruby it 'does a thing' do expect(subject).to contain_file("a test file").with({:path => "/etc/sample"}) end ``` ### Acceptance Tests Writing acceptance tests for Puppet involves [beaker][] and its cousin [beaker-rspec][]. A common pattern for acceptance tests is to create a test manifest, apply it twice to check for idempotency or errors, then run expectations. ```ruby it 'does an end-to-end thing' do pp = <<-EOF file { 'a test file': ensure => present, path => "/etc/sample", content => "test string", } apply_manifest(pp, :catch_failures => true) apply_manifest(pp, :catch_changes => true) end describe file("/etc/sample") do it { is_expected.to contain "test string" } end ``` # If you have commit access to the repository Even if you have commit access to the repository, you still need to go through the process above, and have someone else review and merge in your changes. The rule is that **all changes must be reviewed by a project developer that did not write the code to ensure that all changes go through a code review process.** The record of someone performing the merge is the record that they performed the code review. Again, this should be someone other than the author of the topic branch. # Get Help ### On the web * [Puppet help messageboard](http://puppet.com/community/get-help) * [Writing tests](https://docs.puppet.com/guides/module_guides/bgtm.html#step-three-module-testing) * [General GitHub documentation](http://help.github.com/) * [GitHub pull request documentation](http://help.github.com/send-pull-requests/) ### On chat * Slack (slack.puppet.com) #forge-modules, #puppet-dev, #windows, #voxpupuli * IRC (freenode) #puppet-dev, #voxpupuli [rspec-puppet]: http://rspec-puppet.com/ [rspec-puppet_docs]: http://rspec-puppet.com/documentation/ [beaker]: https://github.com/puppetlabs/beaker [beaker-rspec]: https://github.com/puppetlabs/beaker-rspec puppetlabs-stdlib-4.25.0/Gemfile0100644005276200011600000001350413252003272013517 0ustar00source ENV['GEM_SOURCE'] || 'https://rubygems.org' def location_for(place_or_version, fake_version = nil) if place_or_version =~ %r{\A(git[:@][^#]*)#(.*)} [fake_version, { git: Regexp.last_match(1), branch: Regexp.last_match(2), require: false }].compact elsif place_or_version =~ %r{\Afile:\/\/(.*)} ['>= 0', { path: File.expand_path(Regexp.last_match(1)), require: false }] else [place_or_version, { require: false }] end end def gem_type(place_or_version) if place_or_version =~ %r{\Agit[:@]} :git elsif !place_or_version.nil? && place_or_version.start_with?('file:') :file else :gem end end ruby_version_segments = Gem::Version.new(RUBY_VERSION.dup).segments minor_version = ruby_version_segments[0..1].join('.') group :development do gem "fast_gettext", '1.1.0', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.1.0') gem "fast_gettext", require: false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.1.0') gem "json_pure", '<= 2.0.1', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') gem "json", '= 1.8.1', require: false if Gem::Version.new(RUBY_VERSION.dup) == Gem::Version.new('2.1.9') gem "puppet-module-posix-default-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-posix-dev-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-win-default-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] gem "puppet-module-win-dev-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] gem "puppet-blacksmith", '~> 3.4', require: false end group :system_tests do gem "puppet-module-posix-system-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-win-system-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] gem "beaker", *location_for(ENV['BEAKER_VERSION'] || '~> 3.13') gem "beaker-abs", *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.1') gem "beaker-pe", require: false gem "beaker-hostgenerator" gem "beaker-rspec" end puppet_version = ENV['PUPPET_GEM_VERSION'] puppet_type = gem_type(puppet_version) facter_version = ENV['FACTER_GEM_VERSION'] hiera_version = ENV['HIERA_GEM_VERSION'] def puppet_older_than?(version) puppet_version = ENV['PUPPET_GEM_VERSION'] !puppet_version.nil? && Gem::Version.correct?(puppet_version) && Gem::Requirement.new("< #{version}").satisfied_by?(Gem::Version.new(puppet_version.dup)) end gems = {} gems['puppet'] = location_for(puppet_version) # If facter or hiera versions have been specified via the environment # variables, use those versions. If not, and if the puppet version is < 3.5.0, # use known good versions of both for puppet < 3.5.0. if facter_version gems['facter'] = location_for(facter_version) elsif puppet_type == :gem && puppet_older_than?('3.5.0') gems['facter'] = ['>= 1.6.11', '<= 1.7.5', require: false] end if hiera_version gems['hiera'] = location_for(ENV['HIERA_GEM_VERSION']) elsif puppet_type == :gem && puppet_older_than?('3.5.0') gems['hiera'] = ['>= 1.0.0', '<= 1.3.0', require: false] end if Gem.win_platform? && (puppet_type != :gem || puppet_older_than?('3.5.0')) # For Puppet gems < 3.5.0 (tested as far back as 3.0.0) on Windows if puppet_type == :gem gems['ffi'] = ['1.9.0', require: false] gems['minitar'] = ['0.5.4', require: false] gems['win32-eventlog'] = ['0.5.3', '<= 0.6.5', require: false] gems['win32-process'] = ['0.6.5', '<= 0.7.5', require: false] gems['win32-security'] = ['~> 0.1.2', '<= 0.2.5', require: false] gems['win32-service'] = ['0.7.2', '<= 0.8.8', require: false] else gems['ffi'] = ['~> 1.9.0', require: false] gems['minitar'] = ['~> 0.5.4', require: false] gems['win32-eventlog'] = ['~> 0.5', '<= 0.6.5', require: false] gems['win32-process'] = ['~> 0.6', '<= 0.7.5', require: false] gems['win32-security'] = ['~> 0.1', '<= 0.2.5', require: false] gems['win32-service'] = ['~> 0.7', '<= 0.8.8', require: false] end gems['win32-dir'] = ['~> 0.3', '<= 0.4.9', require: false] if RUBY_VERSION.start_with?('1.') gems['win32console'] = ['1.3.2', require: false] # sys-admin was removed in Puppet 3.7.0 and doesn't compile under Ruby 2.x gems['sys-admin'] = ['1.5.6', require: false] end # Puppet < 3.7.0 requires these. # Puppet >= 3.5.0 gem includes these as requirements. # The following versions are tested to work with 3.0.0 <= puppet < 3.7.0. gems['win32-api'] = ['1.4.8', require: false] gems['win32-taskscheduler'] = ['0.2.2', require: false] gems['windows-api'] = ['0.4.3', require: false] gems['windows-pr'] = ['1.2.3', require: false] elsif Gem.win_platform? # If we're using a Puppet gem on Windows which handles its own win32-xxx gem # dependencies (>= 3.5.0), set the maximum versions (see PUP-6445). gems['win32-dir'] = ['<= 0.4.9', require: false] gems['win32-eventlog'] = ['<= 0.6.5', require: false] gems['win32-process'] = ['<= 0.7.5', require: false] gems['win32-security'] = ['<= 0.2.5', require: false] gems['win32-service'] = ['<= 0.8.8', require: false] end gems.each do |gem_name, gem_params| gem gem_name, *gem_params end # Evaluate Gemfile.local and ~/.gemfile if they exist extra_gemfiles = [ "#{__FILE__}.local", File.join(Dir.home, '.gemfile'), ] extra_gemfiles.each do |gemfile| if File.file?(gemfile) && File.readable?(gemfile) eval(File.read(gemfile), binding) end end # vim: syntax=ruby puppetlabs-stdlib-4.25.0/LICENSE0100644005276200011600000002613613206047630013243 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. puppetlabs-stdlib-4.25.0/MAINTAINERS.md0100644005276200011600000000027613206047630014327 0ustar00## Maintenance Maintainers: - Puppet Forge Modules Team `forge-modules |at| puppet |dot| com` Tickets: https://tickets.puppet.com/browse/MODULES. Make sure to set component to `stdlib`. puppetlabs-stdlib-4.25.0/NOTICE0100644005276200011600000000127713206047630013141 0ustar00stdlib puppet module Copyright (C) 2011-2016 Puppet Labs, Inc. and some parts: Copyright (C) 2011 Krzysztof Wilczynski Puppet Labs can be contacted at: info@puppetlabs.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. puppetlabs-stdlib-4.25.0/README.md0100644005276200011600000024257213252003272013514 0ustar00# stdlib #### Table of Contents 1. [Module Description - What the module does and why it is useful](#module-description) 1. [Setup - The basics of getting started with stdlib](#setup) 1. [Usage - Configuration options and additional functionality](#usage) 1. [Reference - An under-the-hood peek at what the module is doing and how](#reference) 1. [Classes](#classes) 1. [Defined Types](#defined-types) 1. [Data Types](#data-types) 1. [Facts](#facts) 1. [Functions](#functions) 1. [Limitations - OS compatibility, etc.](#limitations) 1. [Development - Guide for contributing to the module](#development) 1. [Contributors](#contributors) ## Module Description This module provides a standard library of resources for Puppet modules. Puppet modules make heavy use of this standard library. The stdlib module adds the following resources to Puppet: * Stages * Facts * Functions * Defined types * Data types * Providers > *Note:* As of version 3.7, Puppet Enterprise no longer includes the stdlib module. If you're running Puppet Enterprise, you should install the most recent release of stdlib for compatibility with Puppet modules. ## Setup [Install](https://docs.puppet.com/puppet/latest/modules_installing.html) the stdlib module to add the functions, facts, and resources of this standard library to Puppet. If you are authoring a module that depends on stdlib, be sure to [specify dependencies](https://docs.puppet.com/puppet/latest/modules_metadata.html#specifying-dependencies) in your metadata.json. ## Usage Most of stdlib's features are automatically loaded by Puppet. To use standardized run stages in Puppet, declare this class in your manifest with `include stdlib`. When declared, stdlib declares all other classes in the module. The only other class currently included in the module is `stdlib::stages`. The `stdlib::stages` class declares various run stages for deploying infrastructure, language runtimes, and application layers. The high level stages are (in order): * setup * main * runtime * setup_infra * deploy_infra * setup_app * deploy_app * deploy Sample usage: ```puppet node default { include stdlib class { java: stage => 'runtime' } } ``` ## Reference * [Public classes](#public-classes) * [Private classes](#private-classes) * [Defined types](#defined-types) * [Data types](#data-types) * [Facts](#facts) * [Functions](#functions) ### Classes #### Public classes The `stdlib` class has no parameters. #### Private classes * `stdlib::stages`: Manages a standard set of run stages for Puppet. ### Defined types #### `file_line` Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet appends the line to the end of the file to ensure the desired state. Multiple resources can be declared to manage multiple lines in the same file. Example: ```puppet file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } ``` In the example above, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`. Match Example: ```puppet file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', } ``` In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and replaces it with the value in line. Match Example: ```puppet file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', append_on_no_match => false, } ``` In this code example, `match` looks for a line beginning with export followed by 'HTTP_PROXY' and replaces it with the value in line. If a match is not found, then no changes are made to the file. Examples of `ensure => absent`: This type has two behaviors when `ensure => absent` is set. The first is to set `match => ...` and `match_for_absence => true`. Match looks for a line beginning with 'export', followed by 'HTTP_PROXY', and then deletes it. If multiple lines match, an error is raised unless the `multiple => true` parameter is set. The `line => ...` parameter in this example would be accepted but ignored. For example: ```puppet file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } ``` The second way of using `ensure => absent` is to specify a `line => ...` and no match. When ensuring lines are absent, the default behavior is to remove all lines matching. This behavior can't be disabled. For example: ```puppet file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', } ``` Encoding example: ```puppet file_line { "XScreenSaver": ensure => present, path => '/root/XScreenSaver' line => "*lock: 10:00:00", match => '^*lock:', encoding => "iso-8859-1", } ``` Files with special characters that are not valid UTF-8 give the error message "Invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify it with the `encoding` attribute. **Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file. **Parameters** All parameters are optional, unless otherwise noted. ##### `after` Specifies the line after which Puppet adds any new lines using a regular expression. (Existing lines are added in place.) Values: String containing a regex. Default value: `undef`. ##### `encoding` Specifies the correct file encoding. Values: String specifying a valid Ruby character encoding. Default: 'UTF-8'. ##### `ensure`: Specifies whether the resource is present. Values: 'present', 'absent'. Default value: 'present'. ##### `line` **Required.** Sets the line to be added to the file located by the `path` parameter. Values: String. ##### `match` Specifies a regular expression to compare against existing lines in the file; if a match is found, it is replaced rather than adding a new line. Values: String containing a regex. Default value: `undef`. ##### `match_for_absence` Specifies whether a match should be applied when `ensure => absent`. If set to `true` and match is set, the line that matches is deleted. If set to `false` (the default), match is ignored when `ensure => absent` and the value of `line` is used instead. Ignored when `ensure => present`. Boolean. Default value: `false`. ##### `multiple` Specifies whether `match` and `after` can change multiple lines. If set to `false`, allows file_line to replace only one line and raises an error if more than one will be replaced. If set to `true`, allows file_line to replace one or more lines. Values: `true`, `false`. Default value: `false`. ##### `name` Specifies the name to use as the identity of the resource. If you want the resource namevar to differ from the supplied `title` of the resource, specify it with `name`. Values: String. Default value: The value of the title. ##### `path` **Required.** Specifies the file in which Puppet ensures the line specified by `line`. Value: String specifying an absolute path to the file. ##### `replace` Specifies whether the resource overwrites an existing line that matches the `match` parameter when `line` does not otherwise exist. If set to `false` and a line is found matching the `match` parameter, the line is not placed in the file. Boolean. Default value: `true`. ##### `replace_all_matches_not_matching_line` Replaces all lines matched by `match` parameter, even if `line` already exists in the file. Default value: `false`. ### Data types #### `Stdlib::Absolutepath` A strict absolute path type. Uses a variant of Unixpath and Windowspath types. Acceptable input examples: ```shell /var/log ``` ```shell /usr2/username/bin:/usr/local/bin:/usr/bin:. ``` ```shell C:\\WINDOWS\\System32 ``` Unacceptable input example: ```shell ../relative_path ``` #### `Stdlib::Ensure::Service` Matches acceptable ensure values for service resources. Acceptable input examples: ```shell stopped running ``` Unacceptable input example: ```shell true false ``` #### `Stdlib::Httpsurl` Matches HTTPS URLs. Acceptable input example: ```shell https://hello.com ``` Unacceptable input example: ```shell httds://notquiteright.org` ``` #### `Stdlib::Httpurl` Matches both HTTPS and HTTP URLs. Acceptable input example: ```shell https://hello.com http://hello.com ``` Unacceptable input example: ```shell httds://notquiteright.org ``` #### `Stdlib::MAC` Matches MAC addresses defined in [RFC5342](https://tools.ietf.org/html/rfc5342). #### `Stdlib::Unixpath` Matches paths on Unix operating systems. Acceptable input example: ```shell /usr2/username/bin:/usr/local/bin:/usr/bin: /var/tmp ``` Unacceptable input example: ```shell C:/whatever ``` #### `Stdlib::Filemode` Matches valid four digit modes in octal format. Acceptable input examples: ```shell 0644 ``` ```shell 1777 ``` Unacceptable input examples: ```shell 644 ``` ```shell 0999 ``` #### `Stdlib::Windowspath` Matches paths on Windows operating systems. Acceptable input example: ```shell C:\\WINDOWS\\System32 C:\\ \\\\host\\windows ``` Valid values: A windows filepath. #### `Stdlib::Filesource` Matches paths valid values for the source parameter of the puppet file type. Acceptable input example: ```shell http://example.com https://example.com file:///hello/bla ``` Valid values: A filepath. #### `Stdlib::Fqdn` Matches paths on fully qualified domain name. Acceptable input example: ```shell localhost example.com www.example.com ``` Valid values: Domain name of a server. #### `Stdlib::Host` Matches a valid host which could be a valid ipv4, ipv6 or fqdn. Acceptable input example: ```shell localhost www.example.com 192.0.2.1 ``` Valid values: An IP address or domain name. #### `Stdlib::Port` Matches a valid TCP/UDP Port number. Acceptable input examples: ```shell 80 443 65000 ``` Valid values: An Integer. #### `Stdlib::Port::Privileged` Matches a valid TCP/UDP Privileged port i.e. < 1024. Acceptable input examples: ```shell 80 443 1023 ``` Valid values: A number less than 1024. #### `Stdlib::Port::Unprivileged` Matches a valid TCP/UDP Privileged port i.e. >= 1024. Acceptable input examples: ```shell 1024 1337 65000 ``` Valid values: A number more than or equal to 1024. #### `Stdlib::Base32` Matches paths a valid base32 string. Acceptable input example: ```shell ASDASDDASD3453453 asdasddasd3453453= ASDASDDASD3453453== ``` Valid values: A base32 string. #### `Stdlib::Base64` Matches paths a valid base64 string. Acceptable input example: ```shell asdasdASDSADA342386832/746+= asdasdASDSADA34238683274/6+ asdasdASDSADA3423868327/46+== ``` Valid values: A base64 string. #### `Stdlib::Ipv4` Matches on valid IPv4 addresses. Acceptable input example: ```shell 0.0.0.0 192.0.2.1 127.0.0.1 ``` Valid values: An IPv4 address. #### `Stdlib::Ipv6` Matches on valid IPv6 addresses. Acceptable input example: ```shell 2001:0db8:85a3:0000:0000:8a2e:0370:7334 2001:db8:: 2001:db8::80 ``` Valid values: An IPv6 address. #### `Stdlib::Ip_address` Matches on valid IPv4 or IPv6 addresses. Acceptable input example: ```shell 0.0.0.0 127.0.0.1 fe80:0000:0000:0000:0204:61ff:fe9d:f156 ``` Valid values: An IP address. #### `Stdlib::IP::Address` Matches any IP address, including both IPv4 and IPv6 addresses. It will match them either with or without an address prefix as used in CIDR format IPv4 addresses. Examples: ``` '127.0.0.1' =~ Stdlib::IP::Address # true '10.1.240.4/24' =~ Stdlib::IP::Address # true '52.10.10.141' =~ Stdlib::IP::Address # true '192.168.1' =~ Stdlib::IP::Address # false 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address # true 'FF01:0:0:0:0:0:0:101' =~ Stdlib::IP::Address # true ``` #### `Stdlib::IP::Address::V4` Match any string consisting of an IPv4 address in the quad-dotted decimal format, with or without a CIDR prefix. It will not match any abbreviated form (for example, 192.168.1) because these are poorly documented and inconsistently supported. Examples: ``` '127.0.0.1' =~ Stdlib::IP::Address::V4 # true '10.1.240.4/24' =~ Stdlib::IP::Address::V4 # true '192.168.1' =~ Stdlib::IP::Address::V4 # false 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address::V4 # false '12AB::CD30:192.168.0.1' =~ Stdlib::IP::Address::V4 # false ``` Valid values: An IPv4 address. #### `Stdlib::IP::Address::V6` Match any string consistenting of an IPv6 address in any of the documented formats in RFC 2373, with or without an address prefix. Examples: ``` '127.0.0.1' =~ Stdlib::IP::Address::V6 # false '10.1.240.4/24' =~ Stdlib::IP::Address::V6 # false 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address::V6 # true 'FF01:0:0:0:0:0:0:101' =~ Stdlib::IP::Address::V6 # true 'FF01::101' =~ Stdlib::IP::Address::V6 # true ``` Valid values: An IPv6 address. #### `Stdlib::IP::Address::Nosubnet` Match the same things as the `Stdlib::IP::Address` alias, except it will not match an address that includes an address prefix (for example, it will match '192.168.0.6' but not '192.168.0.6/24'). Valid values: An IP address with no subnet. #### `Stdlib::IP::Address::V4::CIDR` Match an IPv4 address in the CIDR format. It will only match if the address contains an address prefix (for example, it will match '192.168.0.6/24' but not '192.168.0.6'). Valid values: An IPv4 address with a CIDR provided eg: '192.186.8.101/105'. This will match anything inclusive of '192.186.8.101' to '192.168.8.105'. #### `Stdlib::IP::Address::V4::Nosubnet` Match an IPv4 address only if the address does not contain an address prefix (for example, it will match '192.168.0.6' but not '192.168.0.6/24'). Valid values: An IPv4 address with no subnet. #### `Stdlib::IP::Address::V6::Full` Match an IPv6 address formatted in the "preferred form" as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt), with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). #### `Stdlib::IP::Address::V6::Alternate` Match an IPv6 address formatted in the "alternative form" allowing for representing the last two 16-bit pieces of the address with a quad-dotted decimal, as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will match addresses with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). #### `Stdlib::IP::Address::V6::Compressed` Match an IPv6 address which may contain `::` used to compress zeros as documented in section 2.2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will match addresses with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). #### `Stdlib::IP::Address::V6::Nosubnet` Alias to allow `Stdlib::IP::Address::V6::Nosubnet::Full`, `Stdlib::IP::Address::V6::Nosubnet::Alternate` and `Stdlib::IP::Address::V6::Nosubnet::Compressed`. #### `Stdlib::IP::Address::V6::Nosubnet::Full` Match an IPv6 address formatted in the "preferred form" as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will not match addresses with address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). #### `Stdlib::IP::Address::V6::Nosubnet::Alternate` Match an IPv6 address formatted in the "alternative form" allowing for representing the last two 16-bit pieces of the address with a quad-dotted decimal, as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will only match addresses without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). #### `Stdlib::IP::Address::V6::Nosubnet::Compressed` Match an IPv6 address which may contain `::` used to compress zeros as documented in section 2.2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will only match addresses without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). ### Facts #### `package_provider` Returns the default provider Puppet uses to manage packages on this system. #### `is_pe` Returns whether Puppet Enterprise is installed. Does not report anything on platforms newer than PE 3.x. #### `pe_version` Returns the version of Puppet Enterprise installed. Does not report anything on platforms newer than PE 3.x. #### `pe_major_version` Returns the major version Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x. #### `pe_minor_version` Returns the minor version of Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x. #### `pe_patch_version` Returns the patch version of Puppet Enterprise that is installed. #### `puppet_vardir` Returns the value of the Puppet vardir setting for the node running Puppet or Puppet agent. #### `puppet_environmentpath` Returns the value of the Puppet environment path settings for the node running Puppet or Puppet agent. #### `puppet_server` Returns the Puppet agent's `server` value, which is the hostname of the Puppet master with which the agent should communicate. #### `root_home` Determines the root home directory. Determines the root home directory, which depends on your operating system. Generally this is '/root'. #### `service_provider` Returns the default provider Puppet uses to manage services on this system ### Functions #### `abs` Returns the absolute value of a number. For example, '-34.56' becomes '34.56'. Argument: A single argument of either an integer or float value. *Type*: rvalue. #### `any2array` Converts any object to an array containing that object. Converts empty argument lists are to empty arrays. Hashes are converted to arrays of alternating keys and values. Arrays are not touched. *Type*: rvalue. #### `any2bool` Converts any object to a Boolean: * Strings such as 'Y', 'y', '1', 'T', 't', 'TRUE', 'yes', 'true' return `true`. * Strings such as '0', 'F', 'f', 'N', 'n', 'FALSE', 'no', 'false' return `false`. * Booleans return their original value. * A number (or a string representation of a number) greater than 0 returns `true`, otherwise `false`. * An undef value returns `false`. * Anything else returns `true`. *Type*: rvalue. #### `assert_private` Sets the current class or definition as private. Calling the class or defined type from outside the current module fails. For example, `assert_private()` called in class `foo::bar` outputs the following message if class is called from outside module `foo`: `Class foo::bar is private.` To specify the error message you want to use: ```puppet assert_private("You're not supposed to do that!") ``` *Type*: statement. #### `base64` Converts a string to and from base64 encoding. Requires an `action` ('encode', 'decode') and either a plain or base64-encoded `string`, and an optional `method` ('default', 'strict', 'urlsafe'). For backward compatibility, `method` is set as `default` if not specified. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. **Examples:** ```puppet base64('encode', 'hello') base64('encode', 'hello', 'default') # return: "aGVsbG8=\n" base64('encode', 'hello', 'strict') # return: "aGVsbG8=" base64('decode', 'aGVsbG8=') base64('decode', 'aGVsbG8=\n') base64('decode', 'aGVsbG8=', 'default') base64('decode', 'aGVsbG8=\n', 'default') base64('decode', 'aGVsbG8=', 'strict') # return: "hello" base64('encode', 'https://puppetlabs.com', 'urlsafe') # return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==" base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe') # return: "https://puppetlabs.com" ``` *Type*: rvalue. #### `basename` Returns the `basename` of a path. An optional argument strips the extension. For example: * ('/path/to/a/file.ext') returns 'file.ext' * ('relative/path/file.ext') returns 'file.ext' * ('/path/to/a/file.ext', '.ext') returns 'file' *Type*: rvalue. #### `bool2num` Converts a Boolean to a number. Converts values: * `false`, 'f', '0', 'n', and 'no' to 0. * `true`, 't', '1', 'y', and 'yes' to 1. Argument: a single Boolean or string as an input. *Type*: rvalue. #### `bool2str` Converts a Boolean to a string using optionally supplied arguments. The optional second and third arguments represent what true and false are converted to respectively. If only one argument is given, it is converted from a Boolean to a string containing `true` or `false`. *Examples:* ```puppet bool2str(true) => `true` bool2str(true, 'yes', 'no') => 'yes' bool2str(false, 't', 'f') => 'f' ``` Arguments: Boolean. *Type*: rvalue. #### `camelcase` Converts the case of a string or all strings in an array to CamelCase (mixed case). Arguments: Either an array or string. Returns the same type of argument as it received, but in CamelCase form. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. *Type*: rvalue. #### `capitalize` Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string. Arguments: either a single string or an array as an input. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `ceiling` Returns the smallest integer greater than or equal to the argument. Arguments: A single numeric value. *Type*: rvalue. #### `chomp` Removes the record separator from the end of a string or an array of strings; for example, 'hello\n' becomes 'hello'. Arguments: a single string or array. *Type*: rvalue. #### `chop` 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. To only remove record separators, use the `chomp` function. Arguments: A string or an array of strings as input. *Type*: rvalue. #### `clamp` Keeps value within the range [Min, X, Max] by sort based on integer value (parameter order doesn't matter). Strings are converted and compared numerically. Arrays of values are flattened into a list for further handling. For example: * `clamp('24', [575, 187])` returns 187. * `clamp(16, 88, 661)` returns 88. * `clamp([4, 3, '99'])` returns 4. Arguments: strings, arrays, or numerics. *Type*: rvalue. #### `concat` Appends the contents of multiple arrays onto the first array given. For example: * `concat(['1','2','3'],'4')` returns ['1','2','3','4']. * `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7']. *Type*: rvalue. #### `convert_base` Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example: * `convert_base(5, 2)` results in: '101' * `convert_base('254', '16')` results in: 'fe' #### `count` If called with only an array, counts the number of elements that are **not** nil or `undef`. If called with a second argument, counts the number of elements in an array that matches the second argument. *Type*: rvalue. #### `deep_merge` Recursively merges two or more hashes together and returns the resulting hash. ```puppet $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) ``` The resulting hash is equivalent to: ```puppet $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } ``` If there is a duplicate key that is a hash, they are recursively merged. If there is a duplicate key that is not a hash, the key in the rightmost hash takes precedence. *Type*: rvalue. #### `defined_with_params` Takes a resource reference and an optional hash of attributes. Returns `true` if a resource with the specified attributes has already been added to the catalog. Returns `false` otherwise. ```puppet user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } ``` *Type*: rvalue. #### `delete` Deletes all instances of a given element from an array, substring from a string, or key from a hash. For example: * `delete(['a','b','c','b'], 'b')` returns ['a','c']. * `delete('abracadabra', 'bra')` returns 'acada'. * `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}. * `delete(['ab', 'b'], 'b')` returns ['ab']. *Type*: rvalue. #### `delete_at` Deletes a determined indexed value from an array. For example: `delete_at(['a','b','c'], 1)` returns ['a','c']. *Type*: rvalue. #### `delete_regex` Deletes all instances of a given element from an array or hash that match a provided regular expression. A string is treated as a one-item array. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. For example * `delete_regex(['a','b','c','b'], 'b')` returns ['a','c']. * `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}. * `delete_regex(['abf', 'ab', 'ac'], '^ab.*')` returns ['ac']. * `delete_regex(['ab', 'b'], 'b')` returns ['ab']. *Type*: rvalue. #### `delete_values` Deletes all instances of a given value from a hash. For example: * `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')` returns {'a'=>'A','c'=>'C','B'=>'D'} *Type*: rvalue. #### `delete_undef_values` Deletes all instances of the `undef` value from an array or hash. For example: * `$hash = delete_undef_values({a=>'A', b=>'', c=>`undef`, d => false})` returns {a => 'A', b => '', d => false}. *Type*: rvalue. #### `deprecation` Prints deprecation warnings and logs a warning once for a given key: ```puppet deprecation(key, message) ``` Arguments: * A string specifying the key: To keep the number of messages low during the lifetime of a Puppet process, only one message per key is logged. * A string specifying the message: the text to be logged. *Type*: Statement. **Settings that affect `deprecation`** Other settings in Puppet affect the stdlib `deprecation` function: * [`disable_warnings`](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings) * [`max_deprecations`](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations) * [`strict`](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict): * `error`: Fails immediately with the deprecation message * `off`: Output emits no messages. * `warning`: Logs all warnings. This is the default setting. * The environment variable `STDLIB_LOG_DEPRECATIONS` Specifies whether or not to log deprecation warnings. This is especially useful for automated tests to avoid flooding your logs before you are ready to migrate. This variable is Boolean, with the following effects: * `true`: Functions log a warning. * `false`: No warnings are logged. * No value set: Puppet 4 emits warnings, but Puppet 3 does not. #### `difference` Returns the difference between two arrays. The returned array is a copy of the original array, removing any items that also appear in the second array. For example: * `difference(["a","b","c"],["b","c","d"])` returns ["a"]. *Type*: rvalue. #### `dig` > DEPRECATED: This function has been replaced with a built-in [`dig`](https://docs.puppet.com/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version. Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path. In addition to the required path argument, the function accepts the default argument. It is returned if the path is not correct, if no value was found, or if any other error has occurred. ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` 1. **$data** The data structure we are working with. 2. **['a', 'b', 2]** The path array. 3. **'not_found'** The default value. It is returned if nothing is found. Default value: `undef`. *Type*: rvalue. #### `dig44` Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path. In addition to the required path argument, the function accepts the default argument. It is returned if the path is incorrect, if no value was found, or if any other error has occurred. ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig44($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig44($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` *Type*: rvalue. 1. **$data** The data structure we are working with. 2. **['a', 'b', 2]** The path array. 3. **'not_found'** The default value. It will be returned if nothing is found. (optional, defaults to `undef`) #### `dirname` Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'. *Type*: rvalue. #### `dos2unix` Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template. ```puppet file { $config_file: ensure => file, content => dos2unix(template('my_module/settings.conf.erb')), } ``` See also [unix2dos](#unix2dos). *Type*: rvalue. #### `downcase` Converts the case of a string or of all strings in an array to lowercase. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. *Type*: rvalue. #### `empty` Returns `true` if the argument is an array or hash that contains no elements, or an empty string. Returns `false` when the argument is a numerical value. *Type*: rvalue. #### `enclose_ipv6` Takes an array of IP addresses and encloses the ipv6 addresses with square brackets. *Type*: rvalue. #### `ensure_packages` Takes a list of packages in an array or hash and installs them only if they don't already exist. Optionally takes a hash as a second parameter to be passed as the third argument to the `ensure_resource()` or `ensure_resources()` function. *Type*: statement. For an array: ```puppet ensure_packages(['ksh','openssl'], {'ensure' => 'present'}) ``` For a hash: ```puppet ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'}) ``` #### `ensure_resource` Takes a resource type, title, and a hash of attributes that describe the resource(s). ``` user { 'dan': ensure => present, } ``` This example only creates the resource if it does not already exist: `ensure_resource('user', 'dan', {'ensure' => 'present' })` If the resource already exists, but does not match the specified parameters, this function attempts to recreate the resource, leading to a duplicate resource definition error. An array of resources can also be passed in, and each will be created with the type and parameters specified if it doesn't already exist. `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})` *Type*: statement. #### `ensure_resources` Creates resource declarations from a hash, but doesn't conflict with resources that are already declared. Specify a resource type and title and a hash of attributes that describe the resource(s). ```puppet user { 'dan': gid => 'mygroup', ensure => present, } ensure_resources($user) ``` Pass in a hash of resources. Any listed resources that don't already exist will be created with the type and parameters specified: ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) From Hiera backend: ```yaml userlist: dan: gid: 'mygroup' uid: '600' alex: gid: 'mygroup' ``` ```puppet ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) ``` #### `fact` Return the value of a given fact. Supports the use of dot-notation for referring to structured facts. If a fact requested does not exist, returns Undef. Example usage: ```puppet fact('kernel') fact('osfamily') fact('os.architecture') ``` Array indexing: ```puppet $first_processor = fact('processors.models.0') $second_processor = fact('processors.models.1') ``` Fact containing a "." in the fact name: ```puppet fact('vmware."VRA.version"') ``` #### `flatten` Flattens deeply nested arrays and returns a single flat array as a result. For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c']. *Type*: rvalue. #### `floor` Returns the largest integer less than or equal to the argument. Arguments: A single numeric value. *Type*: rvalue. #### `fqdn_rand_string` Generates a random alphanumeric string, combining the `$fqdn` fact and an optional seed for repeatable randomness. Optionally, you can specify a character set for the function (defaults to alphanumeric). *Usage:* ```puppet fqdn_rand_string(LENGTH, [CHARSET], [SEED]) ``` *Examples:* ```puppet fqdn_rand_string(10) fqdn_rand_string(10, 'ABCDEF!@#$%^') fqdn_rand_string(10, '', 'custom seed') ``` Arguments: * An integer, specifying the length of the resulting string. * Optionally, a string specifying the character set. * Optionally, a string specifying the seed for repeatable randomness. *Type*: rvalue. #### `fqdn_rotate` Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness. *Usage:* ```puppet fqdn_rotate(VALUE, [SEED]) ``` *Examples:* ```puppet fqdn_rotate(['a', 'b', 'c', 'd']) fqdn_rotate('abcd') fqdn_rotate([1, 2, 3], 'custom seed') ``` *Type*: rvalue. #### `fqdn_uuid` Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace: * fqdn_uuid('puppetlabs.com') returns '9c70320f-6815-5fc5-ab0f-debe68bf764c' * fqdn_uuid('google.com') returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8' *Type*: rvalue. #### `get_module_path` Returns the absolute path of the specified module for the current environment. ```puppet $module_path = get_module_path('stdlib') ``` *Type*: rvalue. #### `getparam` Returns the value of a resource's parameter. Arguments: A resource reference and the name of the parameter. For example, the following returns 'param_value': ```puppet define example_resource($param) { } example_resource { "example_resource_instance": param => "param_value" } getparam(Example_resource["example_resource_instance"], "param") ``` *Type*: rvalue. #### `getvar` Looks up a variable in a remote namespace. For example: ```puppet $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo ``` This is useful if the namespace itself is stored in a string: ```puppet $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar ``` *Type*: rvalue. #### `glob` Returns an array of strings of paths matching path patterns. Arguments: A string or an array of strings specifying path patterns. ```puppet $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf']) ``` *Type*: rvalue. #### `grep` Searches through an array and returns any elements that match the provided regular expression. For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd']. *Type*: rvalue. #### `has_interface_with` Returns a Boolean based on kind and value: * macaddress * netmask * ipaddress * network *Examples:* ```puppet has_interface_with("macaddress", "x:x:x:x:x:x") has_interface_with("ipaddress", "127.0.0.1") => true ``` If no kind is given, then the presence of the interface is checked: ```puppet has_interface_with("lo") => true ``` *Type*: rvalue. #### `has_ip_address` Returns `true` if the client has the requested IP address on some interface. This function iterates through the `interfaces` fact and checks the `ipaddress_IFACE` facts, performing a simple string comparison. Arguments: A string specifying an IP address. *Type*: rvalue. #### `has_ip_network` Returns `true` if the client has an IP address within the requested network. This function iterates through the `interfaces` fact and checks the `network_IFACE` facts, performing a simple string comparision. Arguments: A string specifying an IP address. *Type*: rvalue. #### `has_key` Determines if a hash has a certain key value. *Example*: ``` $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } ``` *Type*: rvalue. #### `hash` Converts an array into a hash. For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}. *Type*: rvalue. #### `intersection` Returns an array an intersection of two. For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"]. *Type*: rvalue. #### `is_a` Boolean check to determine whether a variable is of a given data type. This is equivalent to the `=~` type checks. This function is available only in Puppet 4, or in Puppet 3 with the "future" parser. ``` foo = 3 $bar = [1,2,3] $baz = 'A string!' if $foo.is_a(Integer) { notify { 'foo!': } } if $bar.is_a(Array) { notify { 'bar!': } } if $baz.is_a(String) { notify { 'baz!': } } ``` * See the [the Puppet type system](https://docs.puppetlabs.com/latest/type.html#about-resource-types) for more information about types. * See the [`assert_type()`](https://docs.puppetlabs.com/latest/function.html#asserttype) function for flexible ways to assert the type of a value. #### `is_absolute_path` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the given path is absolute. *Type*: rvalue. #### `is_array` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is an array. *Type*: rvalue. #### `is_bool` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is a Boolean. *Type*: rvalue. #### `is_domain_name` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the string passed to this function is a syntactically correct domain name. *Type*: rvalue. #### `is_email_address` Returns true if the string passed to this function is a valid email address. *Type*: rvalue. #### `is_float` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is a float. *Type*: rvalue. #### `is_function_available` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Accepts a string as an argument and determines whether the Puppet runtime has access to a function by that name. It returns `true` if the function exists, `false` if not. *Type*: rvalue. #### `is_hash` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is a hash. *Type*: rvalue. #### `is_integer` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable returned to this string is an integer. *Type*: rvalue. #### `is_ip_address` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the string passed to this function is a valid IP address. *Type*: rvalue. #### `is_ipv6_address` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the string passed to this function is a valid IPv6 address. *Type*: rvalue. #### `is_ipv4_address` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the string passed to this function is a valid IPv4 address. *Type*: rvalue. #### `is_mac_address` Returns `true` if the string passed to this function is a valid MAC address. *Type*: rvalue. #### `is_numeric` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is a number. *Type*: rvalue. #### `is_string` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Returns `true` if the variable passed to this function is a string. *Type*: rvalue. #### `join` Joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c". *Type*: rvalue. #### `join_keys_to_values` Joins each key of a hash to that key's corresponding value with a separator, returning the result as strings. If a value is an array, the key is prefixed to each element. The return value is a flattened array. For example, `join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")` results in ["a is 1","b is 2","b is 3"]. *Type*: rvalue. #### `keys` Returns the keys of a hash as an array. *Type*: rvalue. #### `length` Returns the length of a given string, array or hash. Replaces the deprecated `size()` function. *Type*: rvalue. #### `loadyaml` Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type. For example: ```puppet $myhash = loadyaml('/etc/puppet/data/myhash.yaml') ``` The second parameter is returned if the file was not found or could not be parsed. For example: ```puppet $myhash = loadyaml('no-file.yaml', {'default'=>'value'}) ``` *Type*: rvalue. #### `loadjson` Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type. For example: ```puppet $myhash = loadjson('/etc/puppet/data/myhash.json') ``` The second parameter is returned if the file was not found or could not be parsed. For example: ```puppet $myhash = loadjson('no-file.json', {'default'=>'value'}) ``` *Type*: rvalue. #### `load_module_metadata` Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules. ```puppet $metadata = load_module_metadata('archive') notify { $metadata['author']: } ``` When a module's metadata file is absent, the catalog compilation fails. To avoid this failure: ``` $metadata = load_module_metadata('mysql', true) if empty($metadata) { notify { "This module does not have a metadata.json file.": } } ``` *Type*: rvalue. #### `lstrip` Strips spaces to the left of a string. *Type*: rvalue. #### `max` Returns the highest value of all arguments. Requires at least one argument. Arguments: A numeric or a string representing a number. *Type*: rvalue. #### `member` This function determines if a variable is a member of an array. The variable can be a string, an array, or a fixnum. For example, `member(['a','b'], 'b')` and `member(['a','b','c'], ['b','c'])` return `true`, while `member(['a','b'], 'c')` and `member(['a','b','c'], ['c','d'])` return `false`. *Note*: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them. *Type*: rvalue. #### `merge` Merges two or more hashes together and returns the resulting hash. *Example*: ```puppet $hash1 = {'one' => 1, 'two' => 2} $hash2 = {'two' => 'dos', 'three' => 'tres'} $merged_hash = merge($hash1, $hash2) # The resulting hash is equivalent to: # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} ``` When there is a duplicate key, the key in the rightmost hash takes precedence. *Type*: rvalue. #### `min` Returns the lowest value of all arguments. Requires at least one argument. Arguments: A numeric or a string representing a number. *Type*: rvalue. #### `num2bool` Converts a number or a string representation of a number into a true Boolean. Zero or anything non-numeric becomes `false`. Numbers greater than 0 become `true`. *Type*: rvalue. #### `parsejson` Converts a string of JSON into the correct Puppet structure (as a hash, array, string, integer, or a combination of such). Arguments: * The JSON string to convert, as a first argument. * Optionally, the result to return if conversion fails, as a second error. *Type*: rvalue. #### `parseyaml` Converts a string of YAML into the correct Puppet structure. Arguments: * The YAML string to convert, as a first argument. * Optionally, the result to return if conversion fails, as a second error. *Type*: rvalue. #### `pick` From a list of values, returns the first value that is not undefined or an empty string. Takes any number of arguments, and raises an error if all values are undefined or empty. ```puppet $real_jenkins_version = pick($::jenkins_version, '1.449') ``` *Type*: rvalue. #### `pick_default` Returns the first value in a list of values. Unlike the `pick()` function, `pick_default()` does not fail if all arguments are empty. This allows it to use an empty value as default. *Type*: rvalue. #### `prefix` Applies a prefix to all elements in an array, or to the keys in a hash. For example: * `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc']. * `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}. *Type*: rvalue. #### `pry` Invokes a pry debugging session in the current scope object. Useful for debugging manifest code at specific points during a compilation. Should be used only when running `puppet apply` or running a Puppet master in the foreground. Requires the `pry` gem to be installed in Puppet's rubygems. *Examples:* ```puppet pry() ``` In a pry session, useful commands include: * Run `catalog` to see the contents currently compiling catalog. * Run `cd catalog` and `ls` to see catalog methods and instance variables. * Run `@resource_table` to see the current catalog resource table. #### `pw_hash` Hashes a password using the crypt function. Provides a hash usable on most POSIX systems. The first argument to this function is the password to hash. If it is `undef` or an empty string, this function returns `undef`. The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are: |Hash type |Specifier| |---------------------|---------| |MD5 |1 | |SHA-256 |5 | |SHA-512 (recommended)|6 | The third argument to this function is the salt to use. This function uses the Puppet master's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `range` Extrapolates a range as an array when given in the form of '(start, stop)'. For example, `range("0", "9")` returns [0,1,2,3,4,5,6,7,8,9]. Zero-padded strings are converted to integers automatically, so `range("00", "09")` returns [0,1,2,3,4,5,6,7,8,9]. Non-integer strings are accepted: * `range("a", "c")` returns ["a","b","c"]. * `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"]. You must explicitly include trailing zeros, or the underlying Ruby function fails. Passing a third argument causes the generated range to step by that interval. For example: * `range("0", "9", "2")` returns ["0","2","4","6","8"]. *Type*: rvalue. #### `regexpescape` Regexp escape a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue. #### `reject` Searches through an array and rejects all elements that match the provided regular expression. For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc']. *Type*: rvalue. #### `reverse` Reverses the order of a string or array. #### `round` Rounds a number to the nearest integer *Type*: rvalue. #### `rstrip` Strips spaces to the right of the string. *Type*: rvalue. #### `seeded_rand` Takes an integer max value and a string seed value and returns a repeatable random integer smaller than max. Similar to `fqdn_rand`, but does not add node specific data to the seed. *Type*: rvalue. #### `shell_escape` Escapes a string so that it can be safely used in a Bourne shell command line. Note that the resulting string should be used unquoted and is not intended for use in either double or single quotes. This function behaves the same as Ruby's `Shellwords.shellescape()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape). For example: ```puppet shell_escape('foo b"ar') => 'foo\ b\"ar' ``` *Type*: rvalue. #### `shell_join` Builds a command line string from a given array of strings. Each array item is escaped for Bourne shell. All items are then joined together, with a single space in between. This function behaves the same as Ruby's `Shellwords.shelljoin()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin). For example: ```puppet shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z' ``` *Type*: rvalue. #### `shell_split` Splits a string into an array of tokens. This function behaves the same as Ruby's `Shellwords.shellsplit()` function; see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit). *Example:* ```puppet shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z'] ``` *Type*: rvalue. #### `shuffle` Randomizes the order of a string or array elements. *Type*: rvalue. #### `size` Returns the number of elements in a string, an array or a hash. This function will be deprecated in a future release. For Puppet 4, use the `length` function. *Type*: rvalue. #### `sprintf_hash` Performs printf-style formatting with named references of text. The first parameter is a format string describing how to format the rest of the parameters in the hash. See Ruby documentation for [`Kernel::sprintf`](https://ruby-doc.org/core-2.4.2/Kernel.html#method-i-sprintf) for details about this function. For example: ```puppet $output = sprintf_hash('String: %s / number converted to binary: %b', { 'foo' => 'a string', 'number' => 5 }) # $output = 'String: a string / number converted to binary: 101' ``` *Type*: rvalue #### `sort` Sorts strings and arrays lexically. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `squeeze` Replaces consecutive repeats (such as 'aaaa') in a string with a single character. Returns a new string. *Type*: rvalue. #### `str2bool` Converts certain strings to a Boolean. This attempts to convert strings that contain the values '1', 'true', 't', 'y', or 'yes' to `true`. Strings that contain values '0', 'false', 'f', 'n', or 'no', or that are an empty string or undefined are converted to `false`. Any other value causes an error. These checks are case insensitive. *Type*: rvalue. #### `str2saltedsha512` Converts a string to a salted-SHA512 password hash, used for OS X versions 10.7 or greater. Returns a hex version of a salted-SHA512 password hash, which can be inserted into Puppet manifests as a valid password attribute. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `strftime` Returns formatted time. For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date. Arguments: A string specifying the time in `strftime` format. See the Ruby [strftime](https://ruby-doc.org/core-2.1.9/Time.html#method-i-strftime) documentation for details. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. *Format:* * `%a`: The abbreviated weekday name ('Sun') * `%A`: The full weekday name ('Sunday') * `%b`: The abbreviated month name ('Jan') * `%B`: The full month name ('January') * `%c`: The preferred local date and time representation * `%C`: Century (20 in 2009) * `%d`: Day of the month (01..31) * `%D`: Date (%m/%d/%y) * `%e`: Day of the month, blank-padded ( 1..31) * `%F`: Equivalent to %Y-%m-%d (the ISO 8601 date format) * `%h`: Equivalent to %b * `%H`: Hour of the day, 24-hour clock (00..23) * `%I`: Hour of the day, 12-hour clock (01..12) * `%j`: Day of the year (001..366) * `%k`: Hour, 24-hour clock, blank-padded ( 0..23) * `%l`: Hour, 12-hour clock, blank-padded ( 0..12) * `%L`: Millisecond of the second (000..999) * `%m`: Month of the year (01..12) * `%M`: Minute of the hour (00..59) * `%n`: Newline (\n) * `%N`: Fractional seconds digits, default is 9 digits (nanosecond) * `%3N`: Millisecond (3 digits) * `%6N`: Microsecond (6 digits) * `%9N`: Nanosecond (9 digits) * `%p`: Meridian indicator ('AM' or 'PM') * `%P`: Meridian indicator ('am' or 'pm') * `%r`: Time, 12-hour (same as %I:%M:%S %p) * `%R`: Time, 24-hour (%H:%M) * `%s`: Number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC. * `%S`: Second of the minute (00..60) * `%t`: Tab character ( ) * `%T`: Time, 24-hour (%H:%M:%S) * `%u`: Day of the week as a decimal, Monday being 1. (1..7) * `%U`: Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) * `%v`: VMS date (%e-%b-%Y) * `%V`: Week number of year according to ISO 8601 (01..53) * `%W`: Week number of the current year, starting with the first Monday as the first day of the first week (00..53) * `%w`: Day of the week (Sunday is 0, 0..6) * `%x`: Preferred representation for the date alone, no time * `%X`: Preferred representation for the time alone, no date * `%y`: Year without a century (00..99) * `%Y`: Year with century * `%z`: Time zone as hour offset from UTC (for example +0900) * `%Z`: Time zone name * `%%`: Literal '%' character #### `strip` Removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa". *Type*: rvalue. #### `suffix` Applies a suffix to all elements in an array or to all keys in a hash. For example: * `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']. * `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}. *Type*: rvalue. #### `swapcase` Swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd". *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `time` Returns the current Unix epoch time as an integer. For example, `time()` returns something like '1311972653'. *Type*: rvalue. #### `to_bytes` Converts the argument into bytes. For example, "4 kB" becomes "4096". Arguments: A single string. *Type*: rvalue. #### `to_json` Converts input into a JSON String. For example, `{ "key" => "value" }` becomes `{"key":"value"}`. *Type*: rvalue. #### `to_json_pretty` Converts input into a pretty JSON String. For example, `{ "key" => "value" }` becomes `{\n \"key\": \"value\"\n}`. *Type*: rvalue. #### `to_yaml` Converts input into a YAML String. For example, `{ "key" => "value" }` becomes `"---\nkey: value\n"`. *Type*: rvalue. #### `try_get_value` **DEPRECATED:** replaced by `dig()`. Retrieves a value within multiple layers of hashes and arrays. Arguments: * A string containing a path, as the first argument. Provide this argument as a string of hash keys or array indexes starting with zero and separated by the path separator character (default "/"). This function goes through the structure by each path component and tries to return the value at the end of the path. * A default argument as a second argument. This argument is returned if the path is not correct, if no value was found, or if any other error has occurred. * The path separator character as a last argument. ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = try_get_value($data, 'a/b/2') # $value = 'b3' # with all possible options $value = try_get_value($data, 'a/b/2', 'not_found', '/') # $value = 'b3' # using the default value $value = try_get_value($data, 'a/b/c/d', 'not_found') # $value = 'not_found' # using custom separator $value = try_get_value($data, 'a|b', [], '|') # $value = ['b1','b2','b3'] ``` 1. **$data** The data structure we are working with. 2. **'a/b/2'** The path string. 3. **'not_found'** The default value. It will be returned if nothing is found. (optional, defaults to *`undef`*) 4. **'/'** The path separator character. (optional, defaults to *'/'*) *Type*: rvalue. #### `type3x` **Deprecated**. This function will be removed in a future release. Returns a string description of the type of a given value. The type can be a string, array, hash, float, integer, or Boolean. For Puppet 4, use the new type system instead. Arguments: * string * array * hash * float * integer * Boolean *Type*: rvalue. #### `type_of` This function is provided for backwards compatibility, but the built-in [type() function](https://docs.puppet.com/puppet/latest/reference/function.html#type) provided by Puppet is preferred. Returns the literal type of a given value. Requires Puppet 4. Useful for comparison of types with `<=` such as in `if type_of($some_value) <= Array[String] { ... }` (which is equivalent to `if $some_value =~ Array[String] { ... }`). *Type*: rvalue. #### `union` Returns a union of two or more arrays, without duplicates. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"]. *Type*: rvalue. #### `unique` Removes duplicates from strings and arrays. For example, `unique("aabbcc")` returns 'abc', and `unique(["a","a","b","b","c","c"])` returns ["a","b","c"]. *Type*: rvalue. #### `unix2dos` Returns the DOS version of a given string. Useful when using a File resource with a cross-platform template. *Type*: rvalue. ```puppet file { $config_file: ensure => file, content => unix2dos(template('my_module/settings.conf.erb')), } ``` See also [dos2unix](#dos2unix). #### `upcase` Converts an object, array, or hash of objects to uppercase. Objects to be converted must respond to upcase. For example, `upcase('abcd')` returns 'ABCD'. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `uriescape` URLEncodes a string or array of strings. Arguments: Either a single string or an array of strings. *Type*: rvalue. *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. #### `validate_absolute_path` Validates that a given string represents an absolute path in the filesystem. Works for Windows and Unix style paths. The following values pass: ```puppet $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' validate_absolute_path($my_path) $my_path2 = '/var/lib/puppet' validate_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet'] validate_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet','/usr/share/puppet'] validate_absolute_path($my_path4) ``` The following values fail, causing compilation to terminate: ```puppet validate_absolute_path(true) validate_absolute_path('../var/lib/puppet') validate_absolute_path('var/lib/puppet') validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = `undef` validate_absolute_path($undefined) ``` *Type*: statement. #### `validate_array` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that all passed values are array data structures. Terminates catalog compilation if any value fails this check. The following values pass: ```puppet $my_array = [ 'one', 'two' ] validate_array($my_array) ``` The following values fail, causing compilation to terminate: ```puppet validate_array(true) validate_array('some_string') $undefined = `undef` validate_array($undefined) ``` *Type*: statement. #### `validate_augeas` Validates a string using an Augeas lens. Arguments: * The string to test, as the first argument. * The name of the Augeas lens to use, as the second argument. * Optionally, a list of paths which should **not** be found in the file, as a third argument. * Optionally, an error message to raise and show to the user, as a fourth argument. If Augeas fails to parse the string with the lens, the compilation terminates with a parse error. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. For example, to make sure your $passwdcontent never contains user `foo`, include the third argument: ```puppet validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) ``` To raise and display an error message, include the fourth argument: ```puppet validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') ``` *Type*: statement. #### `validate_bool` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that all passed values are either `true` or `false`. Terminates catalog compilation if any value fails this check. The following values pass: ```puppet $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) ``` The following values fail, causing compilation to terminate: ```puppet $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) ``` *Type*: statement. #### `validate_cmd` Validates a string with an external command. Arguments: * The string to test, as the first argument. * The path to a test command, as the second argument. This argument takes a % as a placeholder for the file path (if no % placeholder is given, defaults to the end of the command). If the command is launched against a tempfile containing the passed string, or returns a non-null value, compilation will terminate with a parse error. * Optionally, an error message to raise and show to the user, as a third argument. ```puppet # Defaults to end of path validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') ``` ```puppet # % as file location validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') ``` *Type*: statement. #### `validate_domain_name` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validate that all values passed are syntactically correct domain names. Aborts catalog compilation if any value fails this check. The following values pass: ~~~ $my_domain_name = 'server.domain.tld' validate_domain_name($my_domain_name) validate_domain_name('domain.tld', 'puppet.com', $my_domain_name) ~~~ The following values fail, causing compilation to abort: ~~~ validate_domain_name(1) validate_domain_name(true) validate_domain_name('invalid domain') validate_domain_name('-foo.example.com') validate_domain_name('www.example.2com') ~~~ *Type*: statement. #### `validate_email_address` Validate that all values passed are valid email addresses. Fail compilation if any value fails this check. The following values will pass: ~~~ $my_email = "waldo@gmail.com" validate_email_address($my_email) validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email) ~~~ The following values will fail, causing compilation to abort: ~~~ $some_array = [ 'bad_email@/d/efdf.com' ] validate_email_address($some_array) ~~~ *Type*: statement. #### `validate_hash` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that all passed values are hash data structures. Terminates catalog compilation if any value fails this check. The following values will pass: ```puppet $my_hash = { 'one' => 'two' } validate_hash($my_hash) ``` The following values will fail, causing compilation to terminate: ```puppet validate_hash(true) validate_hash('some_string') $undefined = `undef` validate_hash($undefined) ``` *Type*: statement. #### `validate_integer` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates an integer or an array of integers. Terminates catalog compilation if any of the checks fail. Arguments: * An integer or an array of integers, as the first argument. * Optionally, a maximum, as the second argument. (All elements of) the first argument must be equal to or less than this maximum. * Optionally, a minimum, as the third argument. (All elements of) the first argument must be equal to or greater than than this maximum. This function fails if the first argument is not an integer or array of integers, or if the second or third arguments are not convertable to an integer. However, if (and only if) a minimum is given, the second argument may be an empty string or `undef`, which serves as a placeholder to ensure the minimum check. The following values pass: ```puppet validate_integer(1) validate_integer(1, 2) validate_integer(1, 1) validate_integer(1, 2, 0) validate_integer(2, 2, 2) validate_integer(2, '', 0) validate_integer(2, `undef`, 0) $foo = `undef` validate_integer(2, $foo, 0) validate_integer([1,2,3,4,5], 6) validate_integer([1,2,3,4,5], 6, 0) ``` * Plus all of the above, but any combination of values passed as strings ('1' or "1"). * Plus all of the above, but with (correct) combinations of negative integer values. The following values fail, causing compilation to terminate: ```puppet validate_integer(true) validate_integer(false) validate_integer(7.0) validate_integer({ 1 => 2 }) $foo = `undef` validate_integer($foo) validate_integer($foobaridontexist) validate_integer(1, 0) validate_integer(1, true) validate_integer(1, '') validate_integer(1, `undef`) validate_integer(1, , 0) validate_integer(1, 2, 3) validate_integer(1, 3, 2) validate_integer(1, 3, true) ``` * Plus all of the above, but any combination of values passed as strings (`false` or "false"). * Plus all of the above, but with incorrect combinations of negative integer values. * Plus all of the above, but with non-integer items in arrays or maximum / minimum argument. *Type*: statement. #### `validate_ip_address` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that the argument is an IP address, regardless of whether it is an IPv4 or an IPv6 address. It also validates IP address with netmask. Arguments: A string specifying an IP address. The following values will pass: ```puppet validate_ip_address('0.0.0.0') validate_ip_address('8.8.8.8') validate_ip_address('127.0.0.1') validate_ip_address('194.232.104.150') validate_ip_address('3ffe:0505:0002::') validate_ip_address('::1/64') validate_ip_address('fe80::a00:27ff:fe94:44d6/64') validate_ip_address('8.8.8.8/32') ``` The following values will fail, causing compilation to terminate: ```puppet validate_ip_address(1) validate_ip_address(true) validate_ip_address(0.0.0.256) validate_ip_address('::1', {}) validate_ip_address('0.0.0.0.0') validate_ip_address('3.3.3') validate_ip_address('23.43.9.22/64') validate_ip_address('260.2.32.43') ``` #### `validate_legacy` Validates a value against both a specified type and a deprecated validation function. Silently passes if both pass, errors if only one validation passes, and fails if both validations return false. Arguments: * The type to check the value against, * The full name of the previous validation function, * The value to be checked, * An unspecified number of arguments needed for the previous validation function. Example: ```puppet validate_legacy('Optional[String]', 'validate_re', 'Value to be validated', ["."]) ``` This function supports updating modules from Puppet 3-style argument validation (using the stdlib `validate_*` functions) to Puppet 4 data types, without breaking functionality for those depending on Puppet 3-style validation. > Note: This function is compatible only with Puppet 4.4.0 (PE 2016.1) and later. ##### For module users If you are running Puppet 4, the `validate_legacy` function can help you find and resolve deprecated Puppet 3 `validate_*` functions. These functions are deprecated as of stdlib version 4.13 and will be removed in a future version of stdlib. Puppet 4 allows improved defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Data types avoid some of the problems with Puppet 3's `validate_*` functions, which were sometimes inconsistent. For example, [validate_numeric](#validate_numeric) unintentionally allowed not only numbers, but also arrays of numbers or strings that looked like numbers. If you run Puppet 4 and use modules with deprecated `validate_*` functions, you might encounter deprecation messages. The `validate_legacy` function makes these differences visible and makes it easier to move to the clearer Puppet 4 syntax. The deprecation messages you get can vary, depending on the modules and data that you use. These deprecation messages appear by default only in Puppet 4: * `Notice: Accepting previously invalid value for target type ''`: This message is informational only. You're using values that are allowed by the new type, but would have been invalid by the old validation function. * `Warning: This method is deprecated, please use the stdlib validate_legacy function`: The module has not yet upgraded to `validate_legacy`. Use the [deprecation](#deprecation) options to silence warnings for now, or submit a fix with the module's developer. See the information [for module developers](#for-module-developers) below for how to fix the issue. * `Warning: validate_legacy() expected value, got _`: Your code passes a value that was accepted by the Puppet 3-style validation, but will not be accepted by the next version of the module. Most often, you can fix this by removing quotes from numbers or booleans. * `Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, validate_legacy() expected value, got `: Your code passes a value that is not acceptable to either the new or the old style validation. ##### For module developers The `validate_legacy` function helps you move from Puppet 3 style validation to Puppet 4 validation without breaking functionality your module's users depend on. Moving to Puppet 4 type validation allows much better defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Many of Puppet 3's `validate_*` functions have surprising holes in their validation. For example, [validate_numeric](#validate_numeric) allows not only numbers, but also arrays of numbers or strings that look like numbers, without giving you any control over the specifics. For each parameter of your classes and defined types, choose a new Puppet 4 data type to use. In most cases, the new data type allows a different set of values than the original `validate_*` function. The situation then looks like this: | | `validate_` pass | `validate_` fail | | ------------ | ---------------- | ---------------- | | matches type | pass | pass, notice | | fails type | pass, deprecated | fail | The code after the validation still has to handle all possible values for now, but users of your code can change their manifests to pass only values that match the new type. For each `validate_*` function in stdlib, there is a matching `Stdlib::Compat::*` type that allows the appropriate set of values. See the documentation in the `types/` directory in the stdlib source code for caveats. For example, given a class that should accept only numbers, like this: ```puppet class example($value) { validate_numeric($value) ``` the resulting validation code looks like this: ```puppet class example( Variant[Stdlib::Compat::Numeric, Numeric] $value ) { validate_legacy(Numeric, 'validate_numeric', $value) ``` Here, the type of `$value` is defined as `Variant[Stdlib::Compat::Numeric, Numeric]`, which allows any `Numeric` (the new type), as well as all values previously accepted by `validate_numeric` (through `Stdlib::Compat::Numeric`). The call to `validate_legacy` takes care of triggering the correct log or fail message for you. It requires the new type, the previous validation function name, and all arguments to that function. If your module still supported Puppet 3, this is a breaking change. Update your `metadata.json` requirements section to indicate that your module no longer supports Puppet 3, and bump the major version of your module. With this change, all existing tests for your module should still pass. Create additional tests for the new possible values. As a breaking change, this is also a good time to call [`deprecation`](#deprecation) for any parameters you want to get rid of, or to add additional constraints on your parameters. After releasing this version, you can release another breaking change release where you remove all compat types and all calls to `validate_legacy`. At that time, you can also go through your code and remove any leftovers dealing with the previously possible values. Always note such changes in your CHANGELOG and README. #### `validate_numeric` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates a numeric value, or an array or string of numeric values. Terminates catalog compilation if any of the checks fail. Arguments: * A numeric value, or an array or string of numeric values. * Optionally, a maximum value. (All elements of) the first argument has to be less or equal to this max. * Optionally, a minimum value. (All elements of) the first argument has to be greater or equal to this min. This function fails if the first argument is not a numeric (Integer or Float) or an array or string of numerics, or if the second and third arguments are not convertable to a numeric. If, and only if, a minimum is given, the second argument can be an empty string or `undef`, which serves as a placeholder to ensure the minimum check. For passing and failing usage, see [`validate_integer`](#validate-integer). The same values pass and fail, except that `validate_numeric` also allows floating point values. *Type*: statement. #### `validate_re` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Performs simple validation of a string against one or more regular expressions. Arguments: * The string to test, as the first argument. If this argument is not a string, compilation terminates. Use quotes to force stringification. * A stringified regular expression (without the // delimiters) or an array of regular expressions, as the second argument. * Optionally, the error message raised and shown to the user, as a third argument. If none of the regular expressions in the second argument match the string passed in the first argument, compilation terminates with a parse error. The following strings validate against the regular expressions: ```puppet validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) ``` The following string fails to validate, causing compilation to terminate: ```puppet validate_re('one', [ '^two', '^three' ]) ``` To set the error message: ```puppet validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') ``` To force stringification, use quotes: ``` validate_re("${::operatingsystemmajrelease}", '^[57]$') ``` *Type*: statement. #### `validate_slength` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that a string (or an array of strings) is less than or equal to a specified length Arguments: * A string or an array of strings, as a first argument. * A numeric value for maximum length, as a second argument. * Optionally, a numeric value for minimum length, as a third argument. The following values pass: ```puppet validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) validate_slength(["discombobulate","moo"],17,3) ``` The following values fail: ```puppet validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) validate_slength(["discombobulate","moo"],17,10) ``` *Type*: statement. #### `validate_string` **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check. The following values pass: ```puppet $my_string = "one two" validate_string($my_string, 'three') ``` The following values fail, causing compilation to terminate: ```puppet validate_string(true) validate_string([ 'some', 'array' ]) ``` *Note:* validate_string(`undef`) will not fail in this version of the functions API. Instead, use: ``` if $var == `undef` { fail('...') } ``` *Type*: statement. #### `validate_x509_rsa_key_pair` Validates a PEM-formatted X.509 certificate and private key using OpenSSL. Verifies that the certificate's signature was created from the supplied key. Fails catalog compilation if any value fails this check. Arguments: * An X.509 certificate as the first argument. * An RSA private key, as the second argument. ```puppet validate_x509_rsa_key_pair($cert, $key) ``` *Type*: statement. #### `values` Returns the values of a given hash. For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3]. *Type*: rvalue. #### `values_at` Finds values inside an array based on location. Arguments: * The array you want to analyze, as the first argument. * Any combination of the following values, as the second argument: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above For example: * `values_at(['a','b','c'], 2)` returns ['c']. * `values_at(['a','b','c'], ["0-1"])` returns ['a','b']. * `values_at(['a','b','c','d','e'], [0, "2-3"])` returns ['a','c','d']. *Type*: rvalue. #### `zip` Takes one element from first array given and merges corresponding elements from second array given. This generates a sequence of n-element arrays, where *n* is one more than the count of arguments. For example, `zip(['1','2','3'],['4','5','6'])` results in ["1", "4"], ["2", "5"], ["3", "6"]. *Type*: rvalue. ## Limitations As of Puppet Enterprise 3.7, the stdlib module is no longer included in PE. PE users should install the most recent release of stdlib for compatibility with Puppet modules. ### Version Compatibility Versions | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x | :---------------|:-----:|:---:|:---:|:----: **stdlib 2.x** | **yes** | **yes** | no | no **stdlib 3.x** | no | **yes** | **yes** | no **stdlib 4.x** | no | **yes** | **yes** | no **stdlib 4.6+** | no | **yes** | **yes** | **yes** **stdlib 5.x** | no | no | **yes** | **yes** **stdlib 5.x**: When released, stdlib 5.x will drop support for Puppet 2.7.x. Please see [this discussion](https://github.com/puppetlabs/puppetlabs-stdlib/pull/176#issuecomment-30251414). ## Development Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide](https://docs.puppetlabs.com/forge/contributing.html). To report or research a bug with any part of this module, please go to [http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES). ## Contributors The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors). puppetlabs-stdlib-4.25.0/README_DEVELOPER.markdown0100644005276200011600000000254113066754712016350 0ustar00Puppet Specific Facts ===================== Facter is meant to stand alone and apart from Puppet. However, Facter often runs inside Puppet and all custom facts included in the stdlib module will almost always be evaluated in the context of Puppet and Facter working together. Still, we don't want to write custom facts that blow up in the users face if Puppet is not loaded in memory. This is often the case if the user runs `facter` without also supplying the `--puppet` flag. Ah! But Jeff, the custom fact won't be in the `$LOAD_PATH` unless the user supplies `--facter`! You might say... Not (always) true I say! If the user happens to have a CWD of `/stdlib/lib` then the facts will automatically be evaluated and blow up. In any event, it's pretty easy to write a fact that has no value if Puppet is not loaded. Simply do it like this: Facter.add(:node_vardir) do setcode do # This will be nil if Puppet is not available. Facter::Util::PuppetSettings.with_puppet do Puppet[:vardir] end end end The `Facter::Util::PuppetSettings.with_puppet` method accepts a block and yields to it only if the Puppet library is loaded. If the Puppet library is not loaded, then the method silently returns `nil` which Facter interprets as an undefined fact value. The net effect is that the fact won't be set. puppetlabs-stdlib-4.25.0/README_SPECS.markdown0100644005276200011600000000043013206047630015661 0ustar00NOTE ==== This project's specs depend on puppet core, and thus they require the `puppetlabs_spec_helper` project. For more information please see the README in that project, which can be found here: [puppetlabs spec helper](https://github.com/puppetlabs/puppetlabs_spec_helper) puppetlabs-stdlib-4.25.0/RELEASE_PROCESS.markdown0100644005276200011600000000174313206047630016255 0ustar00# Contributing to this module # * Work in a topic branch * Submit a github pull request * Address any comments / feeback * Merge into master using --no-ff # Releasing this module # * This module adheres to http://semver.org/ * Look for API breaking changes using git diff vX.Y.Z..master * If no API breaking changes, the minor version may be bumped. * If there are API breaking changes, the major version must be bumped. * If there are only small minor changes, the patch version may be bumped. * Update the CHANGELOG * Update the Modulefile * Commit these changes with a message along the lines of "Update CHANGELOG and Modulefile for release" * Create an annotated tag with git tag -a vX.Y.Z -m 'version X.Y.Z' (NOTE the leading v as per semver.org) * Push the tag with git push origin --tags * Build a new package with puppet-module or the rake build task if it exists * Publish the new package to the forge * Bonus points for an announcement to puppet-users. puppetlabs-stdlib-4.25.0/Rakefile0100644005276200011600000000024713252003272013671 0ustar00require 'puppetlabs_spec_helper/rake_tasks' require 'puppet-syntax/tasks/puppet-syntax' require 'puppet_blacksmith/rake_tasks' require 'puppet-lint/tasks/puppet-lint' puppetlabs-stdlib-4.25.0/appveyor.yml0100644005276200011600000000240013252003272014605 0ustar00version: 1.1.x.{build} skip_commits: message: /^\(?doc\)?.*/ clone_depth: 10 init: - SET - 'mkdir C:\ProgramData\PuppetLabs\code && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\facter && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\hiera && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\puppet\var && exit 0' environment: matrix: - RUBY_VERSION: 24-x64 CHECK: syntax lint - RUBY_VERSION: 24-x64 CHECK: metadata_lint - RUBY_VERSION: 24-x64 CHECK: rubocop - PUPPET_GEM_VERSION: ~> 4.0 RUBY_VERSION: 21 CHECK: spec - PUPPET_GEM_VERSION: ~> 4.0 RUBY_VERSION: 21-x64 CHECK: spec - PUPPET_GEM_VERSION: ~> 5.0 RUBY_VERSION: 24 CHECK: spec - PUPPET_GEM_VERSION: ~> 5.0 RUBY_VERSION: 24-x64 CHECK: spec matrix: fast_finish: true install: - set PATH=C:\Ruby%RUBY_VERSION%\bin;%PATH% - bundle install --jobs 4 --retry 2 --without system_tests - type Gemfile.lock build: off test_script: - bundle exec puppet -V - ruby -v - gem -v - bundle -v - bundle exec rake %CHECK% notifications: - provider: Email to: - nobody@nowhere.com on_build_success: false on_build_failure: false on_build_status_changed: false puppetlabs-stdlib-4.25.0/checksums.json0100644005276200011600000012377013252003413015110 0ustar00{ "CHANGELOG.md": "aabe0b7bd9b188f3dceeae9709ea25b6", "CONTRIBUTING.md": "4d17f3c942e7c93d1577cc4438a231e4", "Gemfile": "47f2bb73e730d42a921e7bca4449f5aa", "LICENSE": "3b83ef96387f14655fc854ddc3c6bd57", "MAINTAINERS.md": "b40ec4f2c16145af6f723c2c34bb2ff9", "NOTICE": "b2e552587e5969886fdd60481e8b0351", "README.md": "722e9a82d5389f8cd5b95f930cfeae2e", "README_DEVELOPER.markdown": "220a8b28521b5c5d2ea87c4ddb511165", "README_SPECS.markdown": "82bb4c6abbb711f40778b162ec0070c1", "RELEASE_PROCESS.markdown": "94b92bc99ac4106ba1a74d5c04e520f9", "Rakefile": "892f5f56e24ac668b998bb74fb18035e", "appveyor.yml": "105dce352be3244a497e667f6b0403c7", "examples/file_line.pp": "d8126b139dd1dce21ff26910d1c5a245", "examples/has_interface_with.pp": "d69d520cf3ff4d0b495480afaca359ef", "examples/has_ip_address.pp": "32f42575e49aa66f0f2398a70ae2a9f4", "examples/has_ip_network.pp": "bfb8db068c58d77c4dd7ae9697536537", "examples/init.pp": "b52fd907330ddbd9c3e070cf39f7b317", "lib/facter/facter_dot_d.rb": "9f65108ecd7b8c5ce9c90ab4cd9d45be", "lib/facter/package_provider.rb": "12d57e65f9b90c13e7808c347fbdc0b0", "lib/facter/pe_version.rb": "245bb8ea121e8a55e1a38668cc480530", "lib/facter/puppet_settings.rb": "d86bacf2b962a4744b701868cda31729", "lib/facter/root_home.rb": "b384092f0470b9e2177edaf546de2ec1", "lib/facter/service_provider.rb": "66cc42526eae631e306b397391f1f01c", "lib/facter/util/puppet_settings.rb": "f69007bcc02031cd772fa7f2dffa3c0c", "lib/puppet/functions/deprecation.rb": "705115a036e0235840db59cf9f4c17fe", "lib/puppet/functions/fact.rb": "5879006198f1f4106acfe13422087d56", "lib/puppet/functions/is_a.rb": "5a61d6a34ef45d7a5490455f334ef48a", "lib/puppet/functions/is_absolute_path.rb": "0806756fc12b1fc752d1b54e81b15832", "lib/puppet/functions/is_array.rb": "4d5c8d6af4e481ebb42f73b6504685c8", "lib/puppet/functions/is_bool.rb": "9ae803c605c5ed057508c6501ef1a47f", "lib/puppet/functions/is_float.rb": "ebe18dc0096233fcd555423761fc29f2", "lib/puppet/functions/is_ip_address.rb": "ab9a1c6172db59cc15023f220853e2f2", "lib/puppet/functions/is_ipv4_address.rb": "dec325b5911ce409b16c643697a13822", "lib/puppet/functions/is_ipv6_address.rb": "f4864fee72c42bd3e40914768fb10f8e", "lib/puppet/functions/is_numeric.rb": "970d785070eaa02bcac3e0589a8d5e7f", "lib/puppet/functions/is_string.rb": "5aa459896fda1782f74752a1d324f048", "lib/puppet/functions/length.rb": "3f6b0510bfe134241e4529d3f1a5318d", "lib/puppet/functions/sprintf_hash.rb": "50fc7c6e57c098b7e6a594e1fd0d9904", "lib/puppet/functions/to_json.rb": "bb6893a3e9eb6c48064c5a3c0bd4a41a", "lib/puppet/functions/to_json_pretty.rb": "61ff20121b4c09987eadf3242b6231cf", "lib/puppet/functions/to_yaml.rb": "0358dfd97b9a051e15046c6842b327be", "lib/puppet/functions/type_of.rb": "4ee9c082047c08b8b1a82bc0bef8fd78", "lib/puppet/functions/validate_absolute_path.rb": "556b0e3de450f03d724747d7d3825309", "lib/puppet/functions/validate_array.rb": "efe329c6c8f65fce1ae2560fa5751530", "lib/puppet/functions/validate_bool.rb": "5516a0f2efb48eeb4460fc713c6f9521", "lib/puppet/functions/validate_hash.rb": "ce99bea6e1ee4da1a67b53b3ce06ce96", "lib/puppet/functions/validate_integer.rb": "c028b299f194c221002ba442077e9209", "lib/puppet/functions/validate_ip_address.rb": "278f3e0ea96b4b31e7b85c13887079b6", "lib/puppet/functions/validate_ipv4_address.rb": "bd015492af1f3c4bef7ac780ae1c7e61", "lib/puppet/functions/validate_ipv6_address.rb": "5144a327b6850ed5b7fb26fa37113353", "lib/puppet/functions/validate_legacy.rb": "789bdef436873b6fcc8205c6d2270e43", "lib/puppet/functions/validate_numeric.rb": "2bd2733f44749e0e56940ceaf5d8e2f8", "lib/puppet/functions/validate_re.rb": "12c3412a7383b1d258dba5d4307e9464", "lib/puppet/functions/validate_slength.rb": "1fc441736085bd0b5c7862f5dc9f839a", "lib/puppet/functions/validate_string.rb": "c0fe867d3b5f8fbcaa3641f0f393a669", "lib/puppet/parser/functions/abs.rb": "176df45128a7b89c9ec6a6c6918d8c30", "lib/puppet/parser/functions/any2array.rb": "60cdb0bdfabff0115e74eda31c5c869b", "lib/puppet/parser/functions/any2bool.rb": "4bafd2903a5e7992b4a8af476f05f46a", "lib/puppet/parser/functions/assert_private.rb": "c61884d43ebdb5ee5a5aa1507165084a", "lib/puppet/parser/functions/base64.rb": "6216cc60b71949724e21b0be4dbac316", "lib/puppet/parser/functions/basename.rb": "6b0dc955024352c8007d175f900dba36", "lib/puppet/parser/functions/bool2num.rb": "bfeeac22e909c76dc5a0d55441f39a27", "lib/puppet/parser/functions/bool2str.rb": "e9e1c441e3b3c51b8b0734d12e9a63a5", "lib/puppet/parser/functions/camelcase.rb": "13f3125b1bcb6ce7794385aea6cbc4c0", "lib/puppet/parser/functions/capitalize.rb": "0a039c4bcd3a73dab80b389332457f0d", "lib/puppet/parser/functions/ceiling.rb": "c4af0da229909c00b2adda7bdd3f0d93", "lib/puppet/parser/functions/chomp.rb": "ebb5eb5e2020ec84c00477777f29b6bc", "lib/puppet/parser/functions/chop.rb": "6a7d4154b326e84e478eb4a17aa55e74", "lib/puppet/parser/functions/clamp.rb": "eeaed011946f4dec98870815e7c1657c", "lib/puppet/parser/functions/concat.rb": "02a6ba0560a005b5f92aec096ce26e09", "lib/puppet/parser/functions/convert_base.rb": "438da17946864b835e38155b8f72a184", "lib/puppet/parser/functions/count.rb": "0241b1bd0bc8de6426b7d077a54f56fe", "lib/puppet/parser/functions/deep_merge.rb": "fae771cff4fc1d6c639bea1672e05c9c", "lib/puppet/parser/functions/defined_with_params.rb": "0e2a92b10efb6c502df6a52f35cf7983", "lib/puppet/parser/functions/delete.rb": "ec0bb949e24d1b9ca6c749af0ab18de9", "lib/puppet/parser/functions/delete_at.rb": "4a6bde67835592dafa48bca7bb8af939", "lib/puppet/parser/functions/delete_regex.rb": "ee86f13f796e61e41c62ee91f8349735", "lib/puppet/parser/functions/delete_undef_values.rb": "247a52c41dc02375b50ac3c1791f4c09", "lib/puppet/parser/functions/delete_values.rb": "0a979383ac73e1bf82278e0eb104842c", "lib/puppet/parser/functions/deprecation.rb": "9f935fec2f9f0d01394292eb6f21bd7d", "lib/puppet/parser/functions/difference.rb": "e3d3006b7f50fc0fad1616ec53f21614", "lib/puppet/parser/functions/dig.rb": "d315de1659a037430fea9623bff323a6", "lib/puppet/parser/functions/dig44.rb": "2317ddee7dbda385e2f964655fe6ad88", "lib/puppet/parser/functions/dirname.rb": "240597e264df02effa454cf9cb8bb9e7", "lib/puppet/parser/functions/dos2unix.rb": "ab2f9f280c616be55f58903948e226a2", "lib/puppet/parser/functions/downcase.rb": "3e6b908548607a55ee426e8be16fb46c", "lib/puppet/parser/functions/empty.rb": "f9dcb1b4cb0abb671294d5283e673ee5", "lib/puppet/parser/functions/enclose_ipv6.rb": "89c728eb11f71ed9390664bad9732328", "lib/puppet/parser/functions/ensure_packages.rb": "a0b4bdc14613d4b8c396b4e02a1aa33d", "lib/puppet/parser/functions/ensure_resource.rb": "2915c77baa0d45531912613dd1cac902", "lib/puppet/parser/functions/ensure_resources.rb": "805d56e894c9dcca2595464fa87a7c56", "lib/puppet/parser/functions/flatten.rb": "54fd2d9d7bc7cd4f9889554da6094dd8", "lib/puppet/parser/functions/floor.rb": "f0a70977110525dc4aa6b109db9ff9e4", "lib/puppet/parser/functions/fqdn_rand_string.rb": "731365381b6a28a196e108329e16c6c2", "lib/puppet/parser/functions/fqdn_rotate.rb": "3925369078084f98f9b527d25cc9e4d2", "lib/puppet/parser/functions/fqdn_uuid.rb": "adbd60dbcc561c8586567a6e58abec82", "lib/puppet/parser/functions/get_module_path.rb": "e141ce049d4ace6d12b50d6b171b029c", "lib/puppet/parser/functions/getparam.rb": "84c7358b24f0a5e45c1ad523c196817e", "lib/puppet/parser/functions/getvar.rb": "835e6b79e209a541e125cdaddefb3396", "lib/puppet/parser/functions/glob.rb": "f8177554be6da357b0822edaa7eb8d14", "lib/puppet/parser/functions/grep.rb": "b2e7e32188a1cb4f1dafa375ba9b8b14", "lib/puppet/parser/functions/has_interface_with.rb": "422015811c5b7c0656b83eaea3b8fdcc", "lib/puppet/parser/functions/has_ip_address.rb": "fc76c9a87145560f58a4ae9a6d9df444", "lib/puppet/parser/functions/has_ip_network.rb": "b1bb1868e6fef95f8ae840d420ab0816", "lib/puppet/parser/functions/has_key.rb": "572f8a648c74c0b774718991a88adc56", "lib/puppet/parser/functions/hash.rb": "5730e6a297b9064c12d3484a2ae31010", "lib/puppet/parser/functions/intersection.rb": "6436444eb8585ee71cfd5bd1e0802026", "lib/puppet/parser/functions/is_absolute_path.rb": "268600b66670a29690be009d45013d42", "lib/puppet/parser/functions/is_array.rb": "0e425e55c8ce9cc5e327d53d114391ba", "lib/puppet/parser/functions/is_bool.rb": "4e021a5143c2c98b31344acceda5fbe2", "lib/puppet/parser/functions/is_domain_name.rb": "1abf04d1d57de6f7f630045c0efe5e4c", "lib/puppet/parser/functions/is_email_address.rb": "d11c644fa1bd73f8e1d36c4f9e67272e", "lib/puppet/parser/functions/is_float.rb": "b95a00f15242e3f26a5cf129db7d31e5", "lib/puppet/parser/functions/is_function_available.rb": "3bb60da5789493da017f84d48ac46f08", "lib/puppet/parser/functions/is_hash.rb": "3f74a7e9b6e47b834c4ad58939c27eab", "lib/puppet/parser/functions/is_integer.rb": "e3480725fccac1c7eba28162dc62393d", "lib/puppet/parser/functions/is_ip_address.rb": "3616dacf58febcd4944945d3c2647efe", "lib/puppet/parser/functions/is_ipv4_address.rb": "7930d25d23d92f0e5cb81f93315cea16", "lib/puppet/parser/functions/is_ipv6_address.rb": "c206564af3a738e504afca2284497d3c", "lib/puppet/parser/functions/is_mac_address.rb": "b75e440d5594b879b70cf034fc52cd51", "lib/puppet/parser/functions/is_numeric.rb": "4bd1a47192ce4040810819789fbf3147", "lib/puppet/parser/functions/is_string.rb": "cf06fecd6147bea77d406a189b649f81", "lib/puppet/parser/functions/join.rb": "aed0b418cc216d86f3beaa5f2302279b", "lib/puppet/parser/functions/join_keys_to_values.rb": "5ad99136e59a68064c24dd2933727c57", "lib/puppet/parser/functions/keys.rb": "d65816215c6c7736bcfe393e7d9d3bf4", "lib/puppet/parser/functions/load_module_metadata.rb": "4972bafc84e5b7ce4a00cbee21aece18", "lib/puppet/parser/functions/loadjson.rb": "b6e43c28dee4a74a7312af41393d09de", "lib/puppet/parser/functions/loadyaml.rb": "9066804fd56894210d4d064aab9df406", "lib/puppet/parser/functions/lstrip.rb": "de231169f63d922b72b754521488bca5", "lib/puppet/parser/functions/max.rb": "3406e6e1da36ed126ca7a359dbbcbb23", "lib/puppet/parser/functions/member.rb": "4f8639d96fbd17cd194224794dd9f279", "lib/puppet/parser/functions/merge.rb": "e867f9f9340d7bf5b85141d2f7ec2392", "lib/puppet/parser/functions/min.rb": "6243d16650b1787f017f587b5be276f3", "lib/puppet/parser/functions/num2bool.rb": "35f42a4339b34d0b1efc6a6c3b2d3b69", "lib/puppet/parser/functions/parsejson.rb": "fee0dc33cd6e18b0d9a5fe8befb66cd2", "lib/puppet/parser/functions/parseyaml.rb": "f4b67d011970c1799bc6fb36a3caf1f2", "lib/puppet/parser/functions/pick.rb": "4a4ba9288a233a4bcdbdc59ecac80be0", "lib/puppet/parser/functions/pick_default.rb": "6b0ccac1913a85e540a3de20c6a88096", "lib/puppet/parser/functions/prefix.rb": "3d268ec646255199ade4b01b719a59ed", "lib/puppet/parser/functions/private.rb": "a1f44a1c32da00aa14f474f4f303be87", "lib/puppet/parser/functions/pry.rb": "970544bf6308b7b6902b936063a45109", "lib/puppet/parser/functions/pw_hash.rb": "07fea662493e5b2ffcf37dbb4c4e74b9", "lib/puppet/parser/functions/range.rb": "60d786031129d4a495a67468d4b5219d", "lib/puppet/parser/functions/regexpescape.rb": "d7d22f987d616f2b5ec9d967f1528f53", "lib/puppet/parser/functions/reject.rb": "31f5f65be6f710d6856ffce75c432271", "lib/puppet/parser/functions/reverse.rb": "3f96ffed2afe4987da5039de2d56f38b", "lib/puppet/parser/functions/round.rb": "287db8b83f3bc6652eb042682f8be698", "lib/puppet/parser/functions/rstrip.rb": "5042d02e81ac59068d87a2b54c784cce", "lib/puppet/parser/functions/seeded_rand.rb": "4f45ef0723411ff8281aaf093f0fabc2", "lib/puppet/parser/functions/shell_escape.rb": "6e51793b8483eb6bfc4be98b438fd47e", "lib/puppet/parser/functions/shell_join.rb": "4fbe23ff73932f65db696f106517887e", "lib/puppet/parser/functions/shell_split.rb": "cb851119ee167ccb12930c53e94333cc", "lib/puppet/parser/functions/shuffle.rb": "6b16497151e961fbdb6e00ec70d6bbe9", "lib/puppet/parser/functions/size.rb": "05cbf180420e3a3e2e5aa5be157c6951", "lib/puppet/parser/functions/sort.rb": "20fa47c2ccde4b37626e8d3995503f02", "lib/puppet/parser/functions/squeeze.rb": "e42e1d5ec9a23443d14ff07512fd695f", "lib/puppet/parser/functions/str2bool.rb": "b82d971cc305a19b26089cc4fd566eb0", "lib/puppet/parser/functions/str2saltedsha512.rb": "d4443e8985b4ce6f6e925c6f46d8456c", "lib/puppet/parser/functions/strftime.rb": "62b13548cc3b28b1609b7b4bd966f666", "lib/puppet/parser/functions/strip.rb": "ec030431f8ec17e285f18a6f60b7f269", "lib/puppet/parser/functions/suffix.rb": "4eff1920b75829e32fb2c2ee4aab8a24", "lib/puppet/parser/functions/swapcase.rb": "d1a53787b35ae9a5a643c49f4e0975a8", "lib/puppet/parser/functions/time.rb": "cd31abf40b4e4e22b9de8b6b27ec1a50", "lib/puppet/parser/functions/to_bytes.rb": "55a65ad70ea78983e7c1d6d565094c1f", "lib/puppet/parser/functions/try_get_value.rb": "b039b960b07a21b935baf6c78fb94612", "lib/puppet/parser/functions/type.rb": "857348edb913cdc4f25b2169994984cf", "lib/puppet/parser/functions/type3x.rb": "22c902213365c39919625d1a33d5abff", "lib/puppet/parser/functions/union.rb": "690e5c15a1e7b95ab4b90ee18eb48f81", "lib/puppet/parser/functions/unique.rb": "e448da2c183c0e19bd6e64bc423a749f", "lib/puppet/parser/functions/unix2dos.rb": "0aa6e66d1c47ca0bb417e248b01f6f1b", "lib/puppet/parser/functions/upcase.rb": "b0ed0e1ada21b9d73a00043146254335", "lib/puppet/parser/functions/uriescape.rb": "f2facfe201658a65a7e81199cdd1bef7", "lib/puppet/parser/functions/validate_absolute_path.rb": "892faf0e74b99b11190ec7fc4b78a893", "lib/puppet/parser/functions/validate_array.rb": "9518be91bab77e56be711d1498d119b9", "lib/puppet/parser/functions/validate_augeas.rb": "c5bbf1bc42b7ea024e48ab12b46f55e9", "lib/puppet/parser/functions/validate_bool.rb": "bea67f1a0f5fc23ee8b632000cfa63db", "lib/puppet/parser/functions/validate_cmd.rb": "dbb22e68eca3f6be63fb49b465b1d611", "lib/puppet/parser/functions/validate_domain_name.rb": "04f4b1d0be9a8a12d278f0b044f78427", "lib/puppet/parser/functions/validate_email_address.rb": "6dc01f14c43fdff19106a2388d01b51a", "lib/puppet/parser/functions/validate_hash.rb": "80f7cfb430818e1497d3b12769d8f9c4", "lib/puppet/parser/functions/validate_integer.rb": "edb176a717c4af6cd50d2d26e4da149d", "lib/puppet/parser/functions/validate_ip_address.rb": "55d0f019803d687bf95bcc64e8751ba5", "lib/puppet/parser/functions/validate_ipv4_address.rb": "94843b876cc92414b29223f7ac3cc3b6", "lib/puppet/parser/functions/validate_ipv6_address.rb": "6c10396f466f64a6f897d1be4291dd4a", "lib/puppet/parser/functions/validate_numeric.rb": "092cce5ed9d3a73319c48cdf9a2a822e", "lib/puppet/parser/functions/validate_re.rb": "df6a2cc342dad63d008ef257fde9038a", "lib/puppet/parser/functions/validate_slength.rb": "b20959e080f36bf320eacb472d125741", "lib/puppet/parser/functions/validate_string.rb": "0239e1697134605a6385ff8c9bdc066b", "lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb": "b16e5ebaeb497e1639c7bf78d61c2b45", "lib/puppet/parser/functions/values.rb": "94ac0ce49d09256677f6adddd40be129", "lib/puppet/parser/functions/values_at.rb": "72d780badb5f600dbd6b9ca3271ee12f", "lib/puppet/parser/functions/zip.rb": "aef1ee868716d07b01e605ae6c4741cc", "lib/puppet/provider/file_line/ruby.rb": "06dd4b2bd0037fcdc8382fcd4214dda3", "lib/puppet/type/anchor.rb": "95867e600863019b08990277c4254cac", "lib/puppet/type/file_line.rb": "208655541a332e54e2d9abac0e328d33", "locales/config.yaml": "d3795b3334faf13674a5d1e3759064ac", "locales/ja/puppetlabs-stdlib.po": "805e5d893d2025ad57da8ec0614a6753", "locales/puppetlabs-stdlib.pot": "23c892ac0683aef4b09aabe0037750ae", "manifests/init.pp": "9560a09f657d7eebbfdb920cefcc1d4f", "manifests/stages.pp": "72eb4fa624474faf23b39e57cf1590bd", "metadata.json": "4b4534918f365e7a921357b2e0706528", "readmes/README_ja_JP.md": "978d15a5afefe82cf56b26147f642989", "spec/acceptance/abs_spec.rb": "7715ab973d77565334ef04d2945e840f", "spec/acceptance/anchor_spec.rb": "96b18124a8bd485928ef49ac82072789", "spec/acceptance/any2array_spec.rb": "afb6dcad76b0147b9759b7bc5b9f81a2", "spec/acceptance/base64_spec.rb": "4f2a739188800f899e1153240e75a867", "spec/acceptance/bool2num_spec.rb": "325d2956a04ab77a3b936707c7cba83c", "spec/acceptance/build_csv.rb": "c02546e9be4117ba6590c40fb535b626", "spec/acceptance/capitalize_spec.rb": "1d5bb25195997de3d52576d85b565e65", "spec/acceptance/ceiling_spec.rb": "dcdfb99eec26c3cfd9764683cfbcd681", "spec/acceptance/chomp_spec.rb": "414bd567e479d78ca79fddcc08597b5f", "spec/acceptance/chop_spec.rb": "ec26d4021b7dc6dadb7e052541e53531", "spec/acceptance/clamp_spec.rb": "38ef1cd4a69c626b47a36f445399a18c", "spec/acceptance/concat_spec.rb": "1e4b3759c686f93c1c50bc32f68a2970", "spec/acceptance/count_spec.rb": "af83c60aaa37eecacbdc92edc541f510", "spec/acceptance/deep_merge_spec.rb": "de55a20ccadfa53047e7cd6853790869", "spec/acceptance/defined_with_params_spec.rb": "b7b26e78d4f651a062c0a44fb72ecbc3", "spec/acceptance/delete_at_spec.rb": "0a823f7136e0d9b181498b79fb577db7", "spec/acceptance/delete_spec.rb": "fa99091339feb1b41517badb42183c43", "spec/acceptance/delete_undef_values_spec.rb": "4cd0e584fb380dd167d27d333a46f98a", "spec/acceptance/delete_values_spec.rb": "390bf022a32894538789719d3cb5dd5d", "spec/acceptance/deprecation_spec.rb": "8456adcd9b7233b958568c7642f7546d", "spec/acceptance/difference_spec.rb": "4cbc7c5d29085c1b53502071ff9a642a", "spec/acceptance/dirname_spec.rb": "3124953534921949cfae133c62a8854f", "spec/acceptance/downcase_spec.rb": "0dae28c3855010c935f5fc15750f58c9", "spec/acceptance/empty_spec.rb": "69209a5a5c03e79a8b8239fdb7564a7e", "spec/acceptance/ensure_resource_spec.rb": "421d87e0564a96d7121e9f650fc298db", "spec/acceptance/flatten_spec.rb": "5604874984383bbff39ac0c8971f3085", "spec/acceptance/floor_spec.rb": "c0bf8a724133dc729736624ac8014a04", "spec/acceptance/fqdn_rand_string_spec.rb": "6e3a47910c3a30965f92e5192167996b", "spec/acceptance/fqdn_rotate_spec.rb": "90526d4da86b4b8dfe5a7c7414a68bed", "spec/acceptance/get_module_path_spec.rb": "1f28f79d01e62aea27ac188f8685448c", "spec/acceptance/getparam_spec.rb": "85b8f5d43ba5fdf7463d05ecd2be98cf", "spec/acceptance/getvar_spec.rb": "30389707dfe05f7e880d0081da6b199f", "spec/acceptance/grep_spec.rb": "cc7455b6462216739d68fe60b1f2182c", "spec/acceptance/has_interface_with_spec.rb": "7949fda36ab1f09ef0dba0df3e652321", "spec/acceptance/has_ip_address_spec.rb": "a0f023a6c279118e267fd1617d7f826c", "spec/acceptance/has_ip_network_spec.rb": "d0a903209ac89e4a1676c401e3578ecf", "spec/acceptance/has_key_spec.rb": "15d06fdd3b90dafae4e525119defdffb", "spec/acceptance/hash_spec.rb": "80df2664feec477338de01971244abe8", "spec/acceptance/intersection_spec.rb": "3669973a6867125a6dfe3c62291a9b26", "spec/acceptance/is_a_spec.rb": "dfe4a69e2d0169058c8471176daf9475", "spec/acceptance/is_array_spec.rb": "178f20209b2a9b0fff5a4b19f6d357ab", "spec/acceptance/is_bool_spec.rb": "c7899b8418827895c7741821afb9ed1c", "spec/acceptance/is_domain_name_spec.rb": "65f16ae06c86a84087d3bf0d12e13822", "spec/acceptance/is_float_spec.rb": "150c8eded212136c2ebdaf3fe1da58bd", "spec/acceptance/is_function_available_spec.rb": "787968e4fde88096bed7196da743b7f5", "spec/acceptance/is_hash_spec.rb": "109a16c5d1b179c22e16083896dd909f", "spec/acceptance/is_integer_spec.rb": "eeac793b6b324be56320e3aa2d522591", "spec/acceptance/is_ip_address_spec.rb": "5a9a283c107b721222745b3319846699", "spec/acceptance/is_ipv4_address_spec.rb": "b35350b402102c9a56f4cab2e7f9d637", "spec/acceptance/is_ipv6_address_spec.rb": "815e46cffa09b5b4fbd2577f521c4112", "spec/acceptance/is_mac_address_spec.rb": "af6eaf2f1b7d4738b9b319c0e21518bd", "spec/acceptance/is_numeric_spec.rb": "862ccf7794114c9e6be8aa8579459390", "spec/acceptance/is_string_spec.rb": "cf17a7f85d478a85486a1d51cf1ff43b", "spec/acceptance/join_keys_to_values_spec.rb": "952b1972871245c3b81d161eddaf0cf5", "spec/acceptance/join_spec.rb": "d8452c8e04ba96a76e1c01d7d4bca381", "spec/acceptance/keys_spec.rb": "05c9441840cf17600969494befa1c754", "spec/acceptance/loadjson_spec.rb": "caf988a38ca39e9ab689f5bdd7682d12", "spec/acceptance/loadyaml_spec.rb": "1a03b0173e01136dac2122250d91aea8", "spec/acceptance/lstrip_spec.rb": "3cd5ce22a5169c8ffcdb15c80686d07d", "spec/acceptance/max_spec.rb": "a45ed58678d647c3b4ec584f35a19678", "spec/acceptance/member_spec.rb": "e84805576685a43f99ae0394138250b7", "spec/acceptance/merge_spec.rb": "ea5d379011e4b26ed759218b655fb3ae", "spec/acceptance/min_spec.rb": "633c9b4f1efa045c03e98f989b61248c", "spec/acceptance/nodesets/centos-7-x64.yml": "a713f3abd3657f0ae2878829badd23cd", "spec/acceptance/nodesets/debian-8-x64.yml": "d2d2977900989f30086ad251a14a1f39", "spec/acceptance/nodesets/default.yml": "b42da5a1ea0c964567ba7495574b8808", "spec/acceptance/nodesets/docker/centos-7.yml": "8a3892807bdd62306ae4774f41ba11ae", "spec/acceptance/nodesets/docker/debian-8.yml": "ac8e871d1068c96de5e85a89daaec6df", "spec/acceptance/nodesets/docker/ubuntu-14.04.yml": "dc42ee922a96908d85b8f0f08203ce58", "spec/acceptance/num2bool_spec.rb": "0fa9912f43d7ae039a02ef2f6a85a7f5", "spec/acceptance/parsejson_spec.rb": "73b31b7f5c700008368a7c6fc499c3e0", "spec/acceptance/parseyaml_spec.rb": "058551a9e7929e4b96304ea4724d62c5", "spec/acceptance/pick_default_spec.rb": "c2f8d2212bc20d14ee4f54255697f346", "spec/acceptance/pick_spec.rb": "121e85041360bda45177199e0e65d9ab", "spec/acceptance/prefix_spec.rb": "512eb6b6225f915492a48959e53ee488", "spec/acceptance/pw_hash_spec.rb": "68c310a38bfc8e21eacfd13d6ec4dfb6", "spec/acceptance/range_spec.rb": "67c4b14ed153c2a3157395935d3f6d86", "spec/acceptance/reject_spec.rb": "ac159911f45bd26a36da598053f19047", "spec/acceptance/reverse_spec.rb": "57369ac237603436732d5562c5bcfe7a", "spec/acceptance/rstrip_spec.rb": "1f3bf4ee8f7dcf8aa6a5386d21552848", "spec/acceptance/shuffle_spec.rb": "323ac9f08ef167e216185ab57e507f59", "spec/acceptance/size_spec.rb": "a670710119c133a7bb5722e4811693c3", "spec/acceptance/sort_spec.rb": "525a8cfa1379d5819745de0757f45c2b", "spec/acceptance/squeeze_spec.rb": "7a8285c918172ed071310c1ec817f4b3", "spec/acceptance/str2bool_spec.rb": "15279972cc4e6f681659943075158c2e", "spec/acceptance/str2saltedsha512_spec.rb": "d427fe7a14b24e8eee0aac5488d6689f", "spec/acceptance/strftime_spec.rb": "9418b364f7cecd2ff24ab48b3f157380", "spec/acceptance/strip_spec.rb": "a6fdae3794f65342f2f579c29adcabb7", "spec/acceptance/suffix_spec.rb": "651b6b42c78b59cf0d2b2b7acca22aa0", "spec/acceptance/swapcase_spec.rb": "b6522090043b47dfe79006a61763d3fa", "spec/acceptance/time_spec.rb": "a9358f62424190c8680da83f2037effb", "spec/acceptance/to_bytes_spec.rb": "f90cbc4cf797d5558e39e297b6046ecc", "spec/acceptance/try_get_value_spec.rb": "bc69f3a81ad499d71ea65a6735d23940", "spec/acceptance/type3x_spec.rb": "81eb5098ee98bbd333d146a3cecf1f22", "spec/acceptance/type_spec.rb": "7f660b97f5c5658e549d66e5308d9891", "spec/acceptance/union_spec.rb": "5b95b33a9351e3cab302e906ecea1b03", "spec/acceptance/unique_spec.rb": "ed10916d862bcc03df3cf353da23f565", "spec/acceptance/upcase_spec.rb": "3f52c03ed89f281941de741752c61be0", "spec/acceptance/uriescape_spec.rb": "3f797d8a5ef4c90199c657607e27247e", "spec/acceptance/validate_absolute_path_spec.rb": "de2d5ac508650c3d5a496b8aa2426ff0", "spec/acceptance/validate_array_spec.rb": "ccbd0333b4dfaefea4e5b29dadf6f7b9", "spec/acceptance/validate_augeas_spec.rb": "0fb53ec581b4994cd953de04ac917c14", "spec/acceptance/validate_bool_spec.rb": "4de809a02a2b855c2e450d9d0cd79947", "spec/acceptance/validate_cmd_spec.rb": "6874d4d569892a81f191748b5a11798a", "spec/acceptance/validate_hash_spec.rb": "68fa9c3d3e2c45235cdbcc719c624daf", "spec/acceptance/validate_ipv4_address_spec.rb": "735189c0b33e895be86c1926cbfd70e6", "spec/acceptance/validate_ipv6_address_spec.rb": "84fa3d17099679a7598f376555eb4bb8", "spec/acceptance/validate_re_spec.rb": "3f547e59f3ebbed788346085546fa12e", "spec/acceptance/validate_slength_spec.rb": "95651bebb658dc4d7e17d17089c9f7a3", "spec/acceptance/validate_string_spec.rb": "ec58a1c5212d20aba9a85e7ffa0785f2", "spec/acceptance/values_at_spec.rb": "d904736b35cc719ec29718c63af2b7e8", "spec/acceptance/values_spec.rb": "9585e4a67209246be263511050f3b4b6", "spec/acceptance/zip_spec.rb": "6d7bddd5f15bc22cb252033b80590d68", "spec/fixtures/dscacheutil/root": "e1a7622f55f3d1be258c9a5b16b474be", "spec/fixtures/lsuser/root": "2ed657fa157372a81634539bb1a56be8", "spec/fixtures/test/manifests/base32.pp": "2662eb916f3830689f40decfe8fddae8", "spec/fixtures/test/manifests/base64.pp": "935f9c1b4ac741c58b7abd49d3cfb794", "spec/fixtures/test/manifests/deftype.pp": "1f2e86fa39604fdfde8fd20b9ae92813", "spec/fixtures/test/manifests/ensure_resources.pp": "898c473ba5641313294827f4b4845bd6", "spec/functions/abs_spec.rb": "eb9982a88e173ed84926afbbda41452e", "spec/functions/any2array_spec.rb": "3ada6ddbda41b8681ba4b924ce81d422", "spec/functions/any2bool_spec.rb": "903aacf741bdf4f7049cd4ee1d34d673", "spec/functions/assert_private_spec.rb": "c4f0ced23534a74d6478fbd7477003e7", "spec/functions/base64_spec.rb": "5083c40b825f86863cc2950d97d3807b", "spec/functions/basename_spec.rb": "beeae06a6fc449d44352031e4a61e900", "spec/functions/bool2num_spec.rb": "bb82d4eed099e97c5af545cdce3445d6", "spec/functions/bool2str_spec.rb": "286b56a5bab37d4849e10b7f0f9630ed", "spec/functions/camelcase_spec.rb": "1d9ae972915a1c45c8093eda7ea8a1fe", "spec/functions/capitalize_spec.rb": "8d7ed6e2c3a338b17a09e6c891c1215c", "spec/functions/ceiling_spec.rb": "dbda35bf0b2aaffb87ba533454004569", "spec/functions/chomp_spec.rb": "5883602173019b8237aed1624bd40170", "spec/functions/chop_spec.rb": "3e293af75bdc7f72655eadcd9920c95f", "spec/functions/clamp_spec.rb": "8094bc19ff0fe82dfd0a072b654bf318", "spec/functions/concat_spec.rb": "d103f894bdb4a2054b17cb0185a033a1", "spec/functions/convert_base_spec.rb": "534bd90106b2c58f736b897974c5a10a", "spec/functions/count_spec.rb": "55a6ead532b31f2ccfcc7fb7126e34d7", "spec/functions/deep_merge_spec.rb": "134d802b7d39e6523e3a622d2718ec12", "spec/functions/defined_with_params_spec.rb": "b24e3fd629b4d52f1abd1b13f715a9a7", "spec/functions/delete_at_spec.rb": "2a373b50759ef60b3abc569bca50537c", "spec/functions/delete_regex_spec.rb": "5b6cf5e6d94da0d00fd612f4558fc426", "spec/functions/delete_spec.rb": "0cee161af26c8dc4165bf0cfea09ce85", "spec/functions/delete_undef_values_spec.rb": "00ca6e3d2c838b6b12263268c698e0ce", "spec/functions/delete_values_spec.rb": "41003ea949782329513763df34861264", "spec/functions/deprecation_spec.rb": "58094a18d86c44c6caf4cf29863880aa", "spec/functions/difference_spec.rb": "bb86ac651f85148184a04248e21b3073", "spec/functions/dig44_spec.rb": "1d8a681607f745e41499ce87d6ef00f0", "spec/functions/dig_spec.rb": "74f65f4c4f237d9bc122abf5fd862b6b", "spec/functions/dirname_spec.rb": "39b1fbb7cfd05881e21beaf81b667ec4", "spec/functions/dos2unix_spec.rb": "f7f10a39d4d4d42bef7a1bc99d97ea1c", "spec/functions/downcase_spec.rb": "2a5970a27352ebee3bae7b28bb4edacb", "spec/functions/empty_spec.rb": "056560850a13bb017871a1cd953db62d", "spec/functions/ensure_packages_spec.rb": "c19f725196a6aee508c25c9c0e1468f4", "spec/functions/ensure_resource_spec.rb": "de9dc96ceefe684e7c785f385136b44a", "spec/functions/ensure_resources_spec.rb": "d8e93e55de05ddb1fce5c242ab21b0a7", "spec/functions/flatten_spec.rb": "c9446276e2d7c973a6a07ad64e49562f", "spec/functions/floor_spec.rb": "68fdcf9ab8596a83ee00b83e52b2889b", "spec/functions/fqdn_rand_string_spec.rb": "136cf6e77e02b42d79c0e5766779d5d4", "spec/functions/fqdn_rotate_spec.rb": "792ada483512e4d60a3937fd1c8f788f", "spec/functions/fqdn_uuid_spec.rb": "60526a453f556867b369496ca1215a86", "spec/functions/get_module_path_spec.rb": "7c3aa0236a71a77e12698ef7988bec38", "spec/functions/getparam_spec.rb": "807694642f3ebdfafca4c8f0eca4c062", "spec/functions/getvar_spec.rb": "327fc59ca02525d9a6d266957461c32f", "spec/functions/glob_spec.rb": "537139a45aa1acfb605aa0cb6b598b73", "spec/functions/grep_spec.rb": "c79409710df9272306ac1211668dd85f", "spec/functions/has_interface_with_spec.rb": "d484da75727170eb3ff22bbc71394fd1", "spec/functions/has_ip_address_spec.rb": "811d63a9c87a1de43a18d07c8ee5a796", "spec/functions/has_ip_network_spec.rb": "9ec0c0c607a60d2dde3a66fc969e4478", "spec/functions/has_key_spec.rb": "d4d97da7d35a794e72d1bbc5e0a4838f", "spec/functions/hash_spec.rb": "cd394a2a67891c1b8d8666d71ee8ede2", "spec/functions/intersection_spec.rb": "be5f4ab66e9f8567b93c368acb5dbf7c", "spec/functions/is_a_spec.rb": "e657f393cc3572883aa2ab872840f4bf", "spec/functions/is_array_spec.rb": "aa5f9f75714c267f1ea0463412f24285", "spec/functions/is_bool_spec.rb": "46ed9e2d70f68db12799918d88d2d804", "spec/functions/is_domain_name_spec.rb": "0e2cf9c9410827484ee3652591757faf", "spec/functions/is_email_address_spec.rb": "f3e60f28e9d66d7707a434a8edc79900", "spec/functions/is_float_spec.rb": "a89f4bbc747ce7117c6899d8e5e75e83", "spec/functions/is_function_available_spec.rb": "0f46d970fca74c87dbcbbaa588b6dc37", "spec/functions/is_hash_spec.rb": "cec4b5638ea3f871350a055cee98ea11", "spec/functions/is_integer_spec.rb": "aa78c5487a22744feccc74ad1ad7f211", "spec/functions/is_ip_address_spec.rb": "c175629e894671b57ed97f76d7ee495c", "spec/functions/is_ipv4_address_spec.rb": "c10a82ce2b0987cba45916f442759d8c", "spec/functions/is_ipv6_address_spec.rb": "f33842262d74f6fa6ac459f980938ecf", "spec/functions/is_mac_address_spec.rb": "80b7d3346f1b4b487f5f88257fe33bc4", "spec/functions/is_numeric_spec.rb": "e3e3c3541c794d74ae1775ca5996e47d", "spec/functions/is_string_spec.rb": "1b1fd9c63def53fcb519a04952057aa0", "spec/functions/join_keys_to_values_spec.rb": "5b8d4704d1e3aee0a8b9738d1324f7f3", "spec/functions/join_spec.rb": "3e5aeaa1d43d94b7ee91333128ee85cc", "spec/functions/keys_spec.rb": "72de4563373767837422c5ce2f4c1d0b", "spec/functions/length_spec.rb": "2aeb769d6c523476eeb4f338aeb32b71", "spec/functions/load_module_metadata_spec.rb": "fcd21ec96196921526179de3fa5de95d", "spec/functions/loadjson_spec.rb": "4d24fcd02c823ea02eb56e96b223038e", "spec/functions/loadyaml_spec.rb": "b85e7f0425df94bb3356db2e52530d79", "spec/functions/lstrip_spec.rb": "7a6e82653fe4087615bb29e4d8818008", "spec/functions/max_spec.rb": "e12bc75395d63b5c15c830291d2f8afe", "spec/functions/member_spec.rb": "43c3c315d44b793a0da3ed80820d386f", "spec/functions/merge_spec.rb": "48761dac5afc99bd381f76f88927cdb0", "spec/functions/min_spec.rb": "44df74b50984cc4efedca7ac9adeef91", "spec/functions/num2bool_spec.rb": "fe3c3dbec9787622850175db510fe4f0", "spec/functions/parsejson_spec.rb": "2f626614bba7f123fc0704878cad731a", "spec/functions/parseyaml_spec.rb": "1e41204590f35d1cc127efcbdaa8321f", "spec/functions/pick_default_spec.rb": "9c8337fb7dd83df40d01c5977d62b4a7", "spec/functions/pick_spec.rb": "856384e60757e1d94ca3aef161be3d0a", "spec/functions/prefix_spec.rb": "a4d28e657d42a42e06f7bcaf1bba1c08", "spec/functions/private_spec.rb": "689c5821596afd859de6312e8ffb1fea", "spec/functions/pw_hash_spec.rb": "d9bdce271d38ce6ec1d8258e807a7c67", "spec/functions/range_spec.rb": "9d38e84765c4fbd8351211741b493b01", "spec/functions/regexpescape_spec.rb": "80a497405be58e82e849cfb3784dbfd1", "spec/functions/reject_spec.rb": "24c6e7597e73bcef62637cf90d994db9", "spec/functions/reverse_spec.rb": "19829abf65a041a74097cfeb8f9e821a", "spec/functions/round_spec.rb": "62862ca723b0e2406e1ab278b4b8a7a8", "spec/functions/rstrip_spec.rb": "240792c366063a1cf82c51615d3f4316", "spec/functions/seeded_rand_spec.rb": "9ff38a91d988c51ef70149bb902e3a83", "spec/functions/shell_escape_spec.rb": "513534e47818ce650b343985febedf9e", "spec/functions/shell_join_spec.rb": "e47a7b81d864933fa3ed8b03f189019e", "spec/functions/shell_split_spec.rb": "ea446ddf08763b98ca794d4aaf9878ee", "spec/functions/shuffle_spec.rb": "f0415952345da7d4464512728f35e52f", "spec/functions/size_spec.rb": "d3aa74419efba6ec5c4b50ccbd45bf88", "spec/functions/sort_spec.rb": "ae131f00aa9ce2a576243f997e0f12b2", "spec/functions/sprintf_hash_spec.rb": "1b014e8c0a44b935ec0c045e275ad6b3", "spec/functions/squeeze_spec.rb": "3d01142c11d5e7e7e841c23e9a37e458", "spec/functions/str2bool_spec.rb": "d099ca74f02ac231f699e59d7a41bafb", "spec/functions/str2saltedsha512_spec.rb": "815dfb2f7c65f81769c117129e45bf85", "spec/functions/strftime_spec.rb": "e4ff0163ab707966186d7941b0e5f18d", "spec/functions/strip_spec.rb": "c439a03137befdff8dd0ef483bf1ef2c", "spec/functions/suffix_spec.rb": "dac301a98ed47f85c62293ca968066ff", "spec/functions/swapcase_spec.rb": "53e01155bd14271641dc954b02bc06e6", "spec/functions/time_spec.rb": "eaf3f48601278bb250659b05022a2a44", "spec/functions/to_bytes_spec.rb": "dbc093a1a72429a0a67e784ecabc100a", "spec/functions/to_json_pretty_spec.rb": "318892fb8ae3fba91ea3a3f41d563c54", "spec/functions/to_json_spec.rb": "e4fbcd70fb3e0b6890337b6eec51f1f0", "spec/functions/to_yaml_spec.rb": "b151fd564e9f7e8b35b69c6ae46948e1", "spec/functions/try_get_value_spec.rb": "53ab2e553ae441821ad02be3c952a34a", "spec/functions/type3x_spec.rb": "cd85e50dda33d32fb90f08eafb29efd7", "spec/functions/type_of_spec.rb": "ecfeb9d47e54f5aae421f7855853d47a", "spec/functions/type_spec.rb": "3a7a71aed638cacfc3d22573cf66ced6", "spec/functions/union_spec.rb": "237517b051eddffd7afc020eeb53c7a1", "spec/functions/unique_spec.rb": "27af15518c2bc4f6dc3009d563d25144", "spec/functions/unix2dos_spec.rb": "77e6d0e7c703576924981038472c8e4e", "spec/functions/upcase_spec.rb": "3eb2544373f1c474b334dd9b37ae4818", "spec/functions/uriescape_spec.rb": "b88f0575ba928b4f60635de6db77299c", "spec/functions/validate_absolute_path_spec.rb": "09470e989ed56866d380e1fb1e2d81f2", "spec/functions/validate_array_spec.rb": "814b2e7f39ed83d5ff0b822c32462a47", "spec/functions/validate_augeas_spec.rb": "4bf035ec4548a00d42f73643374d6f58", "spec/functions/validate_bool_spec.rb": "0c486955f041d86356d41f86ea0c6bd4", "spec/functions/validate_cmd_spec.rb": "179e570e9aec94c5dcaf337a6b431d20", "spec/functions/validate_domain_name_spec.rb": "611f3b301003d11a6a55e293dc3a8e5c", "spec/functions/validate_email_address_spec.rb": "8bac32b793f1e4264ae32df975d4d893", "spec/functions/validate_hash_spec.rb": "09e78289eac14bdc3389620a4dfc3c8d", "spec/functions/validate_integer_spec.rb": "a82914e1813c10b0ffa432ccf44ef781", "spec/functions/validate_ip_address_spec.rb": "fe5c58a23295a00c55637ee3dcb6470f", "spec/functions/validate_ipv4_address_spec.rb": "b8b6ff3ab6dc9360635f6b3a4d2aaaec", "spec/functions/validate_ipv6_address_spec.rb": "1ebc18a929b989eb4591260a75edb5de", "spec/functions/validate_legacy_spec.rb": "2d93df10c72ec5dde1e6618c02e78d40", "spec/functions/validate_numeric_spec.rb": "ace0a1f0d69c78ced85a02900e6d0f73", "spec/functions/validate_re_spec.rb": "19e0f2589d5a48559efa61cfe308ef1b", "spec/functions/validate_slength_spec.rb": "d0e2b4c6ca7050a39f02c1a3005dcb5f", "spec/functions/validate_string_spec.rb": "7591075ba74d9d69145497ff0ba040ff", "spec/functions/validate_x509_rsa_key_pair_spec.rb": "5d3260fcd331122fc3fb056fe8da5acf", "spec/functions/values_at_spec.rb": "a434a3361626dfcab7adfc92a5a1ea4e", "spec/functions/values_spec.rb": "c57de9582664ead57c5bd7ea2e10120a", "spec/functions/zip_spec.rb": "163a0f62553252a8ef8adc9fc44a3568", "spec/monkey_patches/alias_should_to_must.rb": "f600592b4735dc33b31b32a2feb16e2d", "spec/monkey_patches/publicize_methods.rb": "87e62e90546d9f4de8ea11985bc9b8b4", "spec/spec_helper.rb": "46139e5e37020afbb7e1a5af9346e02d", "spec/spec_helper_acceptance.rb": "0467e585d269c0909286c3ced0f9c936", "spec/spec_helper_local.rb": "5644c5ce611a9e131cf37106e2a8b841", "spec/support/shared_data.rb": "dfe4cbdbe2833d670a89bcdf3163839b", "spec/type_aliases/absolute_path_spec.rb": "5bdfe834183c06b06a406ac4c8a20622", "spec/type_aliases/array_spec.rb": "5a7a5be96ccb1347a5a806ef436064e6", "spec/type_aliases/base32_spec.rb": "3d4394fb10e0cc58f5ed6b11a00cdffc", "spec/type_aliases/base64_spec.rb": "383aa3be600b38a3a7de1e488056262e", "spec/type_aliases/bool_spec.rb": "798d1fb0b43cdc7c560ba8b61fb742e6", "spec/type_aliases/compat__ip_address.rb": "7ee3a1f901e33a5a72632cd390629450", "spec/type_aliases/compat__ipv4_spec.rb": "d091b3dcd1fc3a30fe080d9b53a69014", "spec/type_aliases/compat__ipv6_spec.rb": "08005590462f404047995ec86a80e85c", "spec/type_aliases/filemode_spec.rb": "81b7a8687b9bcf1ddaf5667d95498f19", "spec/type_aliases/filesource_spec.rb": "4b72052c22274c568849c2138b6b44ab", "spec/type_aliases/float_spec.rb": "e566885fdf22399a54450022bfbfd31a", "spec/type_aliases/fqdn_spec.rb": "cc343ee15ae50af90a2a6faa41864111", "spec/type_aliases/hash_spec.rb": "1b8c49a76db8b5ef44f0f0a8e56c5eb3", "spec/type_aliases/host_spec.rb": "418b672c12248267e3aa810b8e9a3832", "spec/type_aliases/httpsurl_spec.rb": "a0aff170decf6659dd5d253f06459ae0", "spec/type_aliases/httpurl_spec.rb": "64e610fd2369f9579d72879ea80634f9", "spec/type_aliases/integer_spec.rb": "8f66ae64602543d65e4b784527bf1463", "spec/type_aliases/ip_address.rb": "064acb87912cb36c8fc0a1f3b5441eef", "spec/type_aliases/ip_address_nosubnet_spec.rb": "9d196b9b9522a91ac2bc3a67ccd02d5f", "spec/type_aliases/ip_address_spec.rb": "ae9c24b0ee7d77b967b93ffb13fb67bb", "spec/type_aliases/ip_address_v4_nosubnet_spec.rb": "c30a31b7bcb92eed728be5fef7b45724", "spec/type_aliases/ip_address_v4_spec.rb": "0aacb3967d4ca3a7f8bc3a17e93f141f", "spec/type_aliases/ip_address_v6_alternative_spec.rb": "17da75c696f406ffbd4829a13828fcc5", "spec/type_aliases/ip_address_v6_compressed_spec.rb": "508f6e102bbc3c7af4bd24df5e640f40", "spec/type_aliases/ip_address_v6_full_spec.rb": "35ff79b1855e77ffff7c38599cfafaa2", "spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb": "020fc117a134398818910b41a76094aa", "spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb": "f97969e6cdae00e5a1ffbbd71ba7e08e", "spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb": "c5fad1a8e5fee0cfac3ee9f1b5083804", "spec/type_aliases/ip_address_v6_spec.rb": "74a4c54bf8fffc4ebc3e33c12b085640", "spec/type_aliases/ipv4_spec.rb": "7bb8f191690fb67806be4c8349872a3e", "spec/type_aliases/ipv6_spec.rb": "8343f83b863e73348969d0f790a6fb6b", "spec/type_aliases/numeric_spec.rb": "06ae28964dfad6ca60ac59468c33104b", "spec/type_aliases/port__privileged_spec.rb": "531e8567e3251548324088e1cdac29d6", "spec/type_aliases/port__unprivileged_spec.rb": "ec5aa19f8bfb62307617c0e9b002475d", "spec/type_aliases/port_spec.rb": "6fff6e2cfc7b91e49b6dd169629f8a53", "spec/type_aliases/string_spec.rb": "458ac453f5870066824b6a11ec49f9ae", "spec/type_aliases/unixpath_spec.rb": "015ad5050bcbe3b9b633e13525412e48", "spec/type_aliases/windowspath_spec.rb": "946275f885194c3f2fde07b66aa46f4a", "spec/unit/facter/facter_dot_d_spec.rb": "5819f8f97ea8f3211e28227b3271ad53", "spec/unit/facter/package_provider_spec.rb": "540249c2017840d6e2734a794c04cf7b", "spec/unit/facter/pe_version_spec.rb": "fb8e7c13a12d391b3d811c5302c9af1f", "spec/unit/facter/root_home_spec.rb": "11a86d91c351d57ac745b209c0442638", "spec/unit/facter/service_provider_spec.rb": "5a43493034d23c39854768056c3bb1b2", "spec/unit/facter/util/puppet_settings_spec.rb": "6aa4f5900c1a3e222a525c6bf49dabfe", "spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb": "444b7b0ede4b79a6a7ebddf3fc9fdd5f", "spec/unit/puppet/parser/functions/is_absolute_path_spec.rb": "258f55b8c9563bad0aaa9e98df4d6fc6", "spec/unit/puppet/provider/file_line/ruby_spec.rb": "edc07d6d00266f2cd38a3063fc353f2c", "spec/unit/puppet/provider/file_line/ruby_spec_alter.rb": "d698b231920f0bd276bff2fd7c519b3d", "spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb": "a37b003841a30386ef4b11aba52b54f8", "spec/unit/puppet/type/anchor_spec.rb": "e9370e22ce9d724e39fb00fe6c1198f5", "spec/unit/puppet/type/file_line_spec.rb": "92c3ac78210f730fc2135e012ded86bb", "types/absolutepath.pp": "3ae6f48dd95835df87c5dacea13c88d2", "types/base32.pp": "c1e7d9939641c49af90b07043a52112e", "types/base64.pp": "6e61a5c608ab2147fdf295f97b1052c9", "types/compat/absolute_path.pp": "c500d00e471fa7684abce8c67e2a0a3e", "types/compat/array.pp": "43c41022dd743d55c8e9e82ce3ed741c", "types/compat/bool.pp": "6e0cd7b2a7e1b9efaa0e273937211e58", "types/compat/float.pp": "fd134a0e0e1abd420cec2107780a7afa", "types/compat/hash.pp": "3535d98f0f3eaec44d443190f258e9ba", "types/compat/integer.pp": "d73ad743def0a4e754cbf2e82d5c6b5d", "types/compat/ip_address.pp": "d42c7435de30a469a71b69c45d642da7", "types/compat/ipv4.pp": "962713ea8483c01f2188f87fac1fefa8", "types/compat/ipv6.pp": "bc2c5d46bb49c5180c70c64a8a9ee6ea", "types/compat/numeric.pp": "b9543932cda152dfc2cb7fb554a307f7", "types/compat/re.pp": "70b05d4697e61f9af0c212ba063f395d", "types/compat/string.pp": "b9a179664c85e121aa0277021627d126", "types/ensure/service.pp": "efa28f903420bb9555910c27a9b810e8", "types/filemode.pp": "1776107a2f48cb22131e61f4aaf93750", "types/filesource.pp": "ca652b33c6848e2a6231279fe7cc58d0", "types/fqdn.pp": "f6fb6bf625dab3bd0ab63a1ff7983fb8", "types/host.pp": "69260768a909759bdc31aeaae58d449e", "types/httpsurl.pp": "108225d0273e17d541b239882287ed15", "types/httpurl.pp": "4ba64825b11af75997c59b5acf07c62d", "types/ip/address/nosubnet.pp": "e7c5a338634dfd0eea60cf36092f3fd8", "types/ip/address/v4/cidr.pp": "2f6f69e74d16f08f3e80e2ca3f3dd413", "types/ip/address/v4/nosubnet.pp": "9590ebd639bc47fd25288d32dee5405d", "types/ip/address/v4.pp": "18165fd02c81c08dff234f83d50662a0", "types/ip/address/v6/alternative.pp": "9e82ba1516dc28cab9707066780ca512", "types/ip/address/v6/compressed.pp": "f4d8102d586347ba093a2793271460c5", "types/ip/address/v6/full.pp": "0492b9081ca01bfff8a3d3f07df5c41c", "types/ip/address/v6/nosubnet/alternative.pp": "b9a6cd5a4c2a2e8013022fd4cfd11a3e", "types/ip/address/v6/nosubnet/compressed.pp": "ca2f53bcc3f659d994a6e0d3fe17861e", "types/ip/address/v6/nosubnet/full.pp": "5fa0bb70ed3e72ac52738ba182f22c1c", "types/ip/address/v6/nosubnet.pp": "612651452cd225ade84fe31750d02903", "types/ip/address/v6.pp": "1f3c0aa34dbc083d26f135246c8576eb", "types/ip/address.pp": "9929a758afc9469acbcff0c2050bb0ab", "types/ip_address.pp": "fdede88de3e8322ed265baf0a0e4229e", "types/ipv4.pp": "495e86194de9d4e3c17a0abc195bec91", "types/ipv6.pp": "bec72ad7b5e56ab34b93c61b2e1871a9", "types/mac.pp": "b6b9a7148111578052bdb34e7ef0ce19", "types/port/privileged.pp": "c4ce776dd07a3c8dd3379db8cd49e32a", "types/port/unprivileged.pp": "85359128fa9261fe8bf58c8525574404", "types/port.pp": "b1edd08c4eff860b3ea8bd84cd48ba81", "types/unixpath.pp": "b64a48701e7adfda45d31fd80bee4ad0", "types/windowspath.pp": "4c1eda331ecb43de98c29ed22d0ad448" }puppetlabs-stdlib-4.25.0/examples0040755005276200011600000000000013252003413013760 5ustar00puppetlabs-stdlib-4.25.0/examples/file_line.pp0100644005276200011600000000030113206047630016325 0ustar00# This is a simple smoke test # of the file_line resource type. file { '/tmp/dansfile': ensure => file, } -> file_line { 'dans_line': line => 'dan is awesome', path => '/tmp/dansfile', } puppetlabs-stdlib-4.25.0/examples/has_interface_with.pp0100644005276200011600000000136313206047630020236 0ustar00include ::stdlib info('has_interface_with(\'lo\'):', has_interface_with('lo')) info('has_interface_with(\'loX\'):', has_interface_with('loX')) info('has_interface_with(\'ipaddress\', \'127.0.0.1\'):', has_interface_with('ipaddress', '127.0.0.1')) info('has_interface_with(\'ipaddress\', \'127.0.0.100\'):', has_interface_with('ipaddress', '127.0.0.100')) info('has_interface_with(\'network\', \'127.0.0.0\'):', has_interface_with('network', '127.0.0.0')) info('has_interface_with(\'network\', \'128.0.0.0\'):', has_interface_with('network', '128.0.0.0')) info('has_interface_with(\'netmask\', \'255.0.0.0\'):', has_interface_with('netmask', '255.0.0.0')) info('has_interface_with(\'netmask\', \'256.0.0.0\'):', has_interface_with('netmask', '256.0.0.0')) puppetlabs-stdlib-4.25.0/examples/has_ip_address.pp0100644005276200011600000000024113206047630017352 0ustar00include ::stdlib info('has_ip_address(\'192.168.1.256\'):', has_ip_address('192.168.1.256')) info('has_ip_address(\'127.0.0.1\'):', has_ip_address('127.0.0.1')) puppetlabs-stdlib-4.25.0/examples/has_ip_network.pp0100644005276200011600000000023113206047630017415 0ustar00include ::stdlib info('has_ip_network(\'127.0.0.0\'):', has_ip_network('127.0.0.0')) info('has_ip_network(\'128.0.0.0\'):', has_ip_network('128.0.0.0')) puppetlabs-stdlib-4.25.0/examples/init.pp0100644005276200011600000000002113206047630015341 0ustar00include ::stdlib puppetlabs-stdlib-4.25.0/lib0040755005276200011600000000000013252003413012710 5ustar00puppetlabs-stdlib-4.25.0/lib/facter0040755005276200011600000000000013252003413014154 5ustar00puppetlabs-stdlib-4.25.0/lib/facter/facter_dot_d.rb0100644005276200011600000001141513252003272017177 0ustar00# A Facter plugin that loads facts from /etc/facter/facts.d # and /etc/puppetlabs/facter/facts.d. # # Facts can be in the form of JSON, YAML or Text files # and any executable that returns key=value pairs. # # In the case of scripts you can also create a file that # contains a cache TTL. For foo.sh store the ttl as just # a number in foo.sh.ttl # # The cache is stored in $libdir/facts_dot_d.cache as a mode # 600 file and will have the end result of not calling your # fact scripts more often than is needed class Facter::Util::DotD require 'yaml' def initialize(dir = '/etc/facts.d', cache_file = File.join(Puppet[:libdir], 'facts_dot_d.cache')) @dir = dir @cache_file = cache_file @cache = nil @types = { '.txt' => :txt, '.json' => :json, '.yaml' => :yaml } end def entries Dir.entries(@dir).reject { |f| f =~ %r{^\.|\.ttl$} }.sort.map { |f| File.join(@dir, f) } rescue [] end def fact_type(file) extension = File.extname(file) type = @types[extension] || :unknown type = :script if type == :unknown && File.executable?(file) type end def txt_parser(file) File.readlines(file).each do |line| next unless line =~ %r{^([^=]+)=(.+)$} var = Regexp.last_match(1) val = Regexp.last_match(2) Facter.add(var) do setcode { val } end end rescue StandardError => e Facter.warn("Failed to handle #{file} as text facts: #{e.class}: #{e}") end def json_parser(file) begin require 'json' rescue LoadError retry if require 'rubygems' raise end JSON.parse(File.read(file)).each_pair do |f, v| Facter.add(f) do setcode { v } end end rescue StandardError => e Facter.warn("Failed to handle #{file} as json facts: #{e.class}: #{e}") end def yaml_parser(file) require 'yaml' YAML.load_file(file).each_pair do |f, v| Facter.add(f) do setcode { v } end end rescue StandardError => e Facter.warn("Failed to handle #{file} as yaml facts: #{e.class}: #{e}") end def script_parser(file) result = cache_lookup(file) ttl = cache_time(file) if result Facter.debug("Using cached data for #{file}") else result = Facter::Util::Resolution.exec(file) if ttl > 0 Facter.debug("Updating cache for #{file}") cache_store(file, result) cache_save! end end result.split("\n").each do |line| next unless line =~ %r{^(.+)=(.+)$} var = Regexp.last_match(1) val = Regexp.last_match(2) Facter.add(var) do setcode { val } end end rescue StandardError => e Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}") Facter.debug(e.backtrace.join("\n\t")) end def cache_save! cache = load_cache File.open(@cache_file, 'w', 0o600) { |f| f.write(YAML.dump(cache)) } rescue # rubocop:disable Lint/HandleExceptions end def cache_store(file, data) load_cache @cache[file] = { :data => data, :stored => Time.now.to_i } rescue # rubocop:disable Lint/HandleExceptions end def cache_lookup(file) cache = load_cache return nil if cache.empty? ttl = cache_time(file) return nil unless cache[file] now = Time.now.to_i return cache[file][:data] if ttl == -1 return cache[file][:data] if (now - cache[file][:stored]) <= ttl return nil rescue return nil end def cache_time(file) meta = file + '.ttl' return File.read(meta).chomp.to_i rescue return 0 end def load_cache @cache ||= if File.exist?(@cache_file) YAML.load_file(@cache_file) else {} end return @cache rescue @cache = {} return @cache end def create entries.each do |fact| type = fact_type(fact) parser = "#{type}_parser" next unless respond_to?("#{type}_parser") Facter.debug("Parsing #{fact} using #{parser}") send(parser, fact) end end end mdata = Facter.version.match(%r{(\d+)\.(\d+)\.(\d+)}) if mdata (major, minor, _patch) = mdata.captures.map { |v| v.to_i } if major < 2 # Facter 1.7 introduced external facts support directly unless major == 1 && minor > 6 Facter::Util::DotD.new('/etc/facter/facts.d').create Facter::Util::DotD.new('/etc/puppetlabs/facter/facts.d').create # Windows has a different configuration directory that defaults to a vendor # specific sub directory of the %COMMON_APPDATA% directory. if Dir.const_defined? 'COMMON_APPDATA' # rubocop:disable Metrics/BlockNesting : Any attempt to alter this breaks it windows_facts_dot_d = File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'facter', 'facts.d') Facter::Util::DotD.new(windows_facts_dot_d).create end end end end puppetlabs-stdlib-4.25.0/lib/facter/package_provider.rb0100644005276200011600000000117613212471613020076 0ustar00# Fact: package_provider # # Purpose: Returns the default provider Puppet will choose to manage packages # on this system # # Resolution: Instantiates a dummy package resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/package' Facter.add(:package_provider) do setcode do if defined? Gem && Gem::Version.new(Facter.value(:puppetversion).split(' ')[0]) >= Gem::Version.new('3.6') Puppet::Type.type(:package).newpackage(:name => 'dummy', :allow_virtual => 'true')[:provider].to_s else Puppet::Type.type(:package).newpackage(:name => 'dummy')[:provider].to_s end end end puppetlabs-stdlib-4.25.0/lib/facter/pe_version.rb0100644005276200011600000000242113212471613016734 0ustar00# Fact: is_pe, pe_version, pe_major_version, pe_minor_version, pe_patch_version # # Purpose: Return various facts about the PE state of the system # # Resolution: Uses a regex match against puppetversion to determine whether the # machine has Puppet Enterprise installed, and what version (overall, major, # minor, patch) is installed. # # Caveats: # Facter.add('pe_version') do setcode do puppet_ver = Facter.value('puppetversion') if !puppet_ver.nil? pe_ver = puppet_ver.match(%r{Puppet Enterprise (\d+\.\d+\.\d+)}) pe_ver[1] if pe_ver else nil end end end Facter.add('is_pe') do setcode do if Facter.value(:pe_version).to_s.empty? false else true end end end Facter.add('pe_major_version') do confine :is_pe => true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[0] end end end Facter.add('pe_minor_version') do confine :is_pe => true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[1] end end end Facter.add('pe_patch_version') do confine :is_pe => true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[2] end end end puppetlabs-stdlib-4.25.0/lib/facter/puppet_settings.rb0100644005276200011600000000241213206047630020021 0ustar00# These facter facts return the value of the Puppet vardir and environment path # settings for the node running puppet or puppet agent. The intent is to # enable Puppet modules to automatically have insight into a place where they # can place variable data, or for modules running on the puppet master to know # where environments are stored. # # The values should be directly usable in a File resource path attribute. # begin require 'facter/util/puppet_settings' rescue LoadError => e # puppet apply does not add module lib directories to the $LOAD_PATH (See # #4248). It should (in the future) but for the time being we need to be # defensive which is what this rescue block is doing. rb_file = File.join(File.dirname(__FILE__), 'util', 'puppet_settings.rb') load rb_file if File.exist?(rb_file) || raise(e) end # These will be nil if Puppet is not available. Facter.add(:puppet_vardir) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:vardir] end end end Facter.add(:puppet_environmentpath) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:environmentpath] end end end Facter.add(:puppet_server) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:server] end end end puppetlabs-stdlib-4.25.0/lib/facter/root_home.rb0100644005276200011600000000223113212471613016555 0ustar00# A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. module Facter::Util::RootHome class << self def returnt_root_home root_ent = Facter::Util::Resolution.exec('getent passwd root') # The home directory is the sixth element in the passwd entry # If the platform doesn't have getent, root_ent will be nil and we should # return it straight away. root_ent && root_ent.split(':')[5] end end end Facter.add(:root_home) do setcode { Facter::Util::RootHome.returnt_root_home } end Facter.add(:root_home) do confine :kernel => :darwin setcode do str = Facter::Util::Resolution.exec('dscacheutil -q user -a name root') hash = {} str.split("\n").each do |pair| key, value = pair.split(%r{:}) hash[key] = value end hash['dir'].strip end end Facter.add(:root_home) do confine :kernel => :aix root_home = nil setcode do str = Facter::Util::Resolution.exec('lsuser -c -a home root') str && str.split("\n").each do |line| next if line =~ %r{^#} root_home = line.split(%r{:})[1] end root_home end end puppetlabs-stdlib-4.25.0/lib/facter/service_provider.rb0100644005276200011600000000062313212471613020137 0ustar00# Fact: service_provider # # Purpose: Returns the default provider Puppet will choose to manage services # on this system # # Resolution: Instantiates a dummy service resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/service' Facter.add(:service_provider) do setcode do Puppet::Type.type(:service).newservice(:name => 'dummy')[:provider].to_s end end puppetlabs-stdlib-4.25.0/lib/facter/util0040755005276200011600000000000013252003413015131 5ustar00puppetlabs-stdlib-4.25.0/lib/facter/util/puppet_settings.rb0100644005276200011600000000113413206047630020776 0ustar00# A method to evaluate a Facter code block if puppet is loaded. module Facter::Util::PuppetSettings # This method is intended to provide a convenient way to evaluate a # Facter code block only if Puppet is loaded. This is to account for the # situation where the fact happens to be in the load path, but Puppet is # not loaded for whatever reason. Perhaps the user is simply running # facter without the --puppet flag and they happen to be working in a lib # directory of a module. def self.with_puppet Module.const_get('Puppet') rescue NameError nil else yield end end puppetlabs-stdlib-4.25.0/lib/puppet0040755005276200011600000000000013252003413014225 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/functions0040755005276200011600000000000013252003413016235 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/functions/deprecation.rb0100644005276200011600000000233113206047630021142 0ustar00# Function to print deprecation warnings, Logs a warning once for a given key. The uniqueness key - can appear once. # The msg is the message text including any positional information that is formatted by the user/caller of the method. # It is affected by the puppet setting 'strict', which can be set to :error (outputs as an error message), # :off (no message / error is displayed) and :warning (default, outputs a warning) *Type*: String, String. # Puppet::Functions.create_function(:deprecation) do dispatch :deprecation do param 'String', :key param 'String', :message end def deprecation(key, message) if defined? Puppet::Pops::PuppetStack.stacktrace stacktrace = Puppet::Pops::PuppetStack.stacktrace() file = stacktrace[0] line = stacktrace[1] message = "#{message} at #{file}:#{line}" end # depending on configuration setting of strict case Puppet.settings[:strict] when :off # rubocop:disable Lint/EmptyWhen : Is required to prevent false errors # do nothing when :error raise("deprecation. #{key}. #{message}") else unless ENV['STDLIB_LOG_DEPRECATIONS'] == 'false' Puppet.deprecation_warning(message, key) end end end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/fact.rb0100644005276200011600000000305213206047630017563 0ustar00# Digs into the facts hash using dot-notation # # Example usage: # # fact('osfamily') # fact('os.architecture') # # Array indexing: # # fact('mountpoints."/dev".options.1') # # Fact containing a "." in the name: # # fact('vmware."VRA.version"') # Puppet::Functions.create_function(:fact) do dispatch :fact do param 'String', :fact_name end def to_dot_syntax(array_path) array_path.map { |string| string.include?('.') ? %("#{string}") : string }.join('.') end def fact(fact_name) facts = closure_scope['facts'] # Transform the dot-notation string into an array of paths to walk. Make # sure to correctly extract double-quoted values containing dots as single # elements in the path. path = fact_name.scan(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first } walked_path = [] path.reduce(facts) do |d, k| return nil if d.nil? || k.nil? if d.is_a?(Array) begin result = d[Integer(k)] rescue ArgumentError => e # rubocop:disable Lint/UselessAssignment : Causes errors if assigment is removed. Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'") result = nil end elsif d.is_a?(Hash) result = d[k] else Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is not a collection; cannot walk to '#{k}'") result = nil end walked_path << k result end end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_a.rb0100644005276200011600000000206213206047630017561 0ustar00# Boolean check to determine whether a variable is of a given data type. This is equivalent to the `=~` type checks. # # @example how to check a data type # # check a data type # foo = 3 # $bar = [1,2,3] # $baz = 'A string!' # # if $foo.is_a(Integer) { # notify { 'foo!': } # } # if $bar.is_a(Array) { # notify { 'bar!': } # } # if $baz.is_a(String) { # notify { 'baz!': } # } # # See the documentation for "The Puppet Type System" for more information about types. # See the `assert_type()` function for flexible ways to assert the type of a value. # Puppet::Functions.create_function(:is_a) do dispatch :is_a do param 'Any', :value param 'Type', :type end def is_a(value, type) # rubocop:disable Style/PredicateName : Used in to many other places to rename at this time, attempting to refactor caused Rubocop to crash. # See puppet's lib/puppet/pops/evaluator/evaluator_impl.rb eval_MatchExpression Puppet::Pops::Types::TypeCalculator.instance?(type, value) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_absolute_path.rb0100644005276200011600000000153313206047630022175 0ustar00Puppet::Functions.create_function(:is_absolute_path) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_absolute_path', 'This method is deprecated, please use match expressions with Stdlib::Compat::Absolute_Path instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_absolute_path', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_array.rb0100644005276200011600000000147313206047630020464 0ustar00Puppet::Functions.create_function(:is_array) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_array', 'This method is deprecated, please use match expressions with Stdlib::Compat::Array instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_array', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_bool.rb0100644005276200011600000000146713206047630020304 0ustar00Puppet::Functions.create_function(:is_bool) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_bool', 'This method is deprecated, please use match expressions with Stdlib::Compat::Bool instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_bool', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_float.rb0100644005276200011600000000147313206047630020453 0ustar00Puppet::Functions.create_function(:is_float) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_float', 'This method is deprecated, please use match expressions with Stdlib::Compat::Float instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_float', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_ip_address.rb0100644005276200011600000000151713206047630021462 0ustar00Puppet::Functions.create_function(:is_ip_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_ip_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ip_address instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_ip_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_ipv4_address.rb0100644005276200011600000000151713206047630021734 0ustar00Puppet::Functions.create_function(:is_ipv4_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_ipv4_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ipv4 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_ipv4_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_ipv6_address.rb0100644005276200011600000000151713206047630021736 0ustar00Puppet::Functions.create_function(:is_ipv6_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_ipv4_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ipv6 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_ipv6_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_numeric.rb0100644005276200011600000000150313206047630021002 0ustar00Puppet::Functions.create_function(:is_numeric) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_numeric', 'This method is deprecated, please use match expressions with Stdlib::Compat::Numeric instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_numeric', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/is_string.rb0100644005276200011600000000147713206047630020660 0ustar00Puppet::Functions.create_function(:is_string) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'is_string', 'This method is deprecated, please use match expressions with Stdlib::Compat::String instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') scope.send('function_is_string', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/length.rb0100644005276200011600000000076213206047630020134 0ustar00# A function to eventually replace the old size() function for stdlib - The original size function did not handle Puppets new type capabilities, so this function is a Puppet 4 compatible solution. Puppet::Functions.create_function(:length) do dispatch :length do param 'Variant[String,Array,Hash]', :value end def length(value) if value.is_a?(String) result = value.length elsif value.is_a?(Array) || value.is_a?(Hash) result = value.size end result end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/sprintf_hash.rb0100644005276200011600000000211613206047630021336 0ustar00# Uses sprintf with named references. # # The first parameter is format string describing how the rest of the parameters in the hash # should be formatted. See the documentation for the `Kernel::sprintf` function in Ruby for # all the details. # # In the given argument hash with parameters, all keys are converted to symbols so they work # with the `sprintf` function. # # @example Format a string and number # $output = sprintf_hash('String: %s / number converted to binary: %b', # { 'foo' => 'a string', 'number' => 5 }) # # $output = 'String: a string / number converted to binary: 101' # Puppet::Functions.create_function(:sprintf_hash) do # @param format The format to use. # @param arguments Hash with parameters. # @return The formatted string. dispatch :sprintf_hash do param 'String', :format param 'Hash', :arguments # Disabled for now. This gives issues on puppet 4.7.1. # return_type 'String' end def sprintf_hash(format, arguments) Kernel.sprintf(format, Hash[arguments.map { |(k, v)| [k.to_sym, v] }]) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/to_json.rb0100644005276200011600000000056413206047630020326 0ustar00# Take a data structure and output it as JSON # # @example how to output JSON # # output json to a file # file { '/tmp/my.json': # ensure => file, # content => to_json($myhash), # } # # require 'json' Puppet::Functions.create_function(:to_json) do dispatch :to_json do param 'Any', :data end def to_json(data) data.to_json end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/to_json_pretty.rb0100644005276200011600000000177713212471613021743 0ustar00# Take a data structure and output it as pretty JSON # # @example how to output pretty JSON # # output pretty json to a file # file { '/tmp/my.json': # ensure => file, # content => to_json_pretty($myhash), # } # # @example how to output pretty JSON skipping over keys with undef values # # output pretty JSON to a file skipping over undef values # file { '/tmp/my.json': # ensure => file, # content => to_json_pretty({ # param_one => 'value', # param_two => undef, # }), # } # require 'json' Puppet::Functions.create_function(:to_json_pretty) do dispatch :to_json_pretty do param 'Variant[Hash, Array]', :data optional_param 'Boolean', :skip_undef end def to_json_pretty(data, skip_undef = false) if skip_undef if data.is_a? Array data = data.reject { |value| value.nil? } elsif data.is_a? Hash data = data.reject { |_, value| value.nil? } end end JSON.pretty_generate(data) << "\n" end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/to_yaml.rb0100644005276200011600000000056413206047630020317 0ustar00# Take a data structure and output it as YAML # # @example how to output YAML # # output yaml to a file # file { '/tmp/my.yaml': # ensure => file, # content => to_yaml($myhash), # } # # require 'yaml' Puppet::Functions.create_function(:to_yaml) do dispatch :to_yaml do param 'Any', :data end def to_yaml(data) data.to_yaml end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/type_of.rb0100644005276200011600000000167213206047630020321 0ustar00# Returns the type when passed a value. # # @example how to compare values' types # # compare the types of two values # if type_of($first_value) != type_of($second_value) { fail("first_value and second_value are different types") } # @example how to compare against an abstract type # unless type_of($first_value) <= Numeric { fail("first_value must be Numeric") } # unless type_of{$first_value) <= Collection[1] { fail("first_value must be an Array or Hash, and contain at least one element") } # # See the documentation for "The Puppet Type System" for more information about types. # See the `assert_type()` function for flexible ways to assert the type of a value. # # The built-in type() function in puppet is generally preferred over this function # this function is provided for backwards compatibility. Puppet::Functions.create_function(:type_of) do def type_of(value) Puppet::Pops::Types::TypeCalculator.infer_set(value) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_absolute_path.rb0100644005276200011600000000155213206047630023354 0ustar00Puppet::Functions.create_function(:validate_absolute_path) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_absolute_path', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_Path. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_absolute_path', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_array.rb0100644005276200011600000000151213206047630021634 0ustar00Puppet::Functions.create_function(:validate_array) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_array', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_array', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_bool.rb0100644005276200011600000000150613206047630021454 0ustar00Puppet::Functions.create_function(:validate_bool) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_bool', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_bool', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_hash.rb0100644005276200011600000000150613206047630021444 0ustar00Puppet::Functions.create_function(:validate_hash) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_hash', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_hash', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_integer.rb0100644005276200011600000000152213206047630022154 0ustar00Puppet::Functions.create_function(:validate_integer) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_integer', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_integer', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_ip_address.rb0100644005276200011600000000153613206047630022641 0ustar00Puppet::Functions.create_function(:validate_ip_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_ip_address', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_Address. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_ip_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_ipv4_address.rb0100644005276200011600000000154613206047630023114 0ustar00Puppet::Functions.create_function(:validate_ipv4_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_ipv4_address', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4_Address. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_ipv4_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_ipv6_address.rb0100644005276200011600000000154613206047630023116 0ustar00Puppet::Functions.create_function(:validate_ipv6_address) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_ipv6_address', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6_address. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_ipv6_address', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_legacy.rb0100644005276200011600000000425713206047630021773 0ustar00Puppet::Functions.create_function(:validate_legacy) do # The function checks a value against both the target_type (new) and the previous_validation function (old). dispatch :validate_legacy do param 'Any', :scope param 'Type', :target_type param 'String', :function_name param 'Any', :value repeated_param 'Any', :args end dispatch :validate_legacy_s do param 'Any', :scope param 'String', :type_string param 'String', :function_name param 'Any', :value repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def validate_legacy_s(scope, type_string, *args) t = Puppet::Pops::Types::TypeParser.new.parse(type_string, scope) validate_legacy(scope, t, *args) end def validate_legacy(scope, target_type, function_name, value, *prev_args) if assert_type(target_type, value) if previous_validation(scope, function_name, value, *prev_args) # Silently passes else Puppet.notice("Accepting previously invalid value for target type '#{target_type}'") end else inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value) error_msg = Puppet::Pops::Types::TypeMismatchDescriber.new.describe_mismatch("validate_legacy(#{function_name})", target_type, inferred_type) if previous_validation(scope, function_name, value, *prev_args) call_function('deprecation', 'validate_legacy', error_msg) else call_function('fail', error_msg) end end end def previous_validation(scope, function_name, value, *prev_args) # Call the previous validation function and catch any errors. Return true if no errors are thrown. scope.send("function_#{function_name}".to_s, [value, *prev_args]) true rescue Puppet::ParseError false end def assert_type(type, value) Puppet::Pops::Types::TypeCalculator.instance?(type, value) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_numeric.rb0100644005276200011600000000152213206047630022161 0ustar00Puppet::Functions.create_function(:validate_numeric) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_numeric', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_numeric', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_re.rb0100644005276200011600000000146513206047630021133 0ustar00Puppet::Functions.create_function(:validate_re) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_re', 'This method is deprecated, please use the stdlib validate_legacy function, with Pattern[]. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_re', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_slength.rb0100644005276200011600000000150313206047630022162 0ustar00Puppet::Functions.create_function(:validate_slength) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_slength', 'This method is deprecated, please use the stdlib validate_legacy function, with String[]. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_slength', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/functions/validate_string.rb0100644005276200011600000000151613206047630022030 0ustar00Puppet::Functions.create_function(:validate_string) do dispatch :deprecation_gen do param 'Any', :scope repeated_param 'Any', :args end # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def deprecation_gen(scope, *args) call_function('deprecation', 'validate_string', 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.') scope.send('function_validate_string', args) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser0040755005276200011600000000000013252003413015521 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions0040755005276200011600000000000013252003413017531 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/abs.rb0100644005276200011600000000157013212471613020711 0ustar00# # abs.rb # module Puppet::Parser::Functions newfunction(:abs, :type => :rvalue, :doc => <<-DOC Returns the absolute value of a number, for example -34.56 becomes 34.56. Takes a single integer and float value as an argument. DOC ) do |arguments| raise(Puppet::ParseError, "abs(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] # Numbers in Puppet are often string-encoded which is troublesome ... if value.is_a?(String) if value =~ %r{^-?(?:\d+)(?:\.\d+){1}$} value = value.to_f elsif value =~ %r{^-?\d+$} value = value.to_i else raise(Puppet::ParseError, 'abs(): Requires float or integer to work with') end end # We have numeric value to handle ... result = value.abs return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/any2array.rb0100644005276200011600000000133613212471613022054 0ustar00# # any2array.rb # module Puppet::Parser::Functions newfunction(:any2array, :type => :rvalue, :doc => <<-DOC This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. DOC ) do |arguments| if arguments.empty? return [] end return arguments unless arguments.length == 1 return arguments[0] if arguments[0].is_a?(Array) if arguments[0].is_a?(Hash) result = [] arguments[0].each do |key, value| result << key << value end return result end return arguments end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/any2bool.rb0100644005276200011600000000276213252003272021671 0ustar00# # any2bool.rb # module Puppet::Parser::Functions newfunction(:any2bool, :type => :rvalue, :doc => <<-DOC This converts 'anything' to a boolean. In practise it does the following: * Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true * Strings such as 0,F,f,N,n,FALSE,no,'false' will return false * Booleans will just return their original value * Number (or a string representation of a number) > 0 will return true, otherwise false * undef will return false * Anything else will return true DOC ) do |arguments| raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? # If argument is already Boolean, return it if !!arguments[0] == arguments[0] # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean return arguments[0] end arg = arguments[0] if arg.nil? return false end if arg == :undef return false end valid_float = begin !!Float(arg) # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean rescue false end if arg.is_a?(Numeric) return function_num2bool([arguments[0]]) end if arg.is_a?(String) return function_num2bool([arguments[0]]) if valid_float return function_str2bool([arguments[0]]) end return true end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/assert_private.rb0100644005276200011600000000155313212471613023200 0ustar00# # assert_private.rb # module Puppet::Parser::Functions newfunction(:assert_private, :doc => <<-DOC Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. DOC ) do |args| raise(Puppet::ParseError, "assert_private(): Wrong number of arguments given (#{args.size}}) for 0 or 1)") if args.size > 1 scope = self if scope.lookupvar('module_name') != scope.lookupvar('caller_module_name') message = nil if args[0] && args[0].is_a?(String) message = args[0] else manifest_name = scope.source.name manifest_type = scope.source.type message = (manifest_type.to_s == 'hostclass') ? 'Class' : 'Definition' message += " #{manifest_name} is private" end raise(Puppet::ParseError, message) end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/base64.rb0100644005276200011600000000415213212471613021227 0ustar00# Please note: This function is an implementation of a Ruby class 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. module Puppet::Parser::Functions newfunction(:base64, :type => :rvalue, :doc => <<-'DOC') do |args| Base64 encode or decode a string based on the command and the string submitted Usage: $encodestring = base64('encode', 'thestring') $decodestring = base64('decode', 'dGhlc3RyaW5n') # explicitly define encode/decode method: default, strict, urlsafe $method = 'default' $encodestring = base64('encode', 'thestring', $method) $decodestring = base64('decode', 'dGhlc3RyaW5n', $method) DOC require 'base64' raise Puppet::ParseError, "base64(): Wrong number of arguments (#{args.length}; must be >= 2)" unless args.length >= 2 actions = %w[encode decode] unless actions.include?(args[0]) raise Puppet::ParseError, "base64(): the first argument must be one of 'encode' or 'decode'" end unless args[1].is_a?(String) raise Puppet::ParseError, 'base64(): the second argument must be a string to base64' end method = %w[default strict urlsafe] chosen_method = if args.length <= 2 'default' else args[2] end unless method.include?(chosen_method) raise Puppet::ParseError, "base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'" end case args[0] when 'encode' case chosen_method when 'default' result = Base64.encode64(args[1]) when 'strict' result = Base64.strict_encode64(args[1]) when 'urlsafe' result = Base64.urlsafe_encode64(args[1]) end when 'decode' case chosen_method when 'default' result = Base64.decode64(args[1]) when 'strict' result = Base64.strict_decode64(args[1]) when 'urlsafe' result = Base64.urlsafe_decode64(args[1]) end end return result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/basename.rb0100644005276200011600000000150113212471613021711 0ustar00# # basename.rb # module Puppet::Parser::Functions newfunction(:basename, :type => :rvalue, :doc => <<-DOC Strips directory (and optional suffix) from a filename DOC ) do |arguments| raise(Puppet::ParseError, 'basename(): No arguments given') if arguments.empty? raise(Puppet::ParseError, "basename(): Too many arguments given (#{arguments.size})") if arguments.size > 2 raise(Puppet::ParseError, 'basename(): Requires string as first argument') unless arguments[0].is_a?(String) rv = File.basename(arguments[0]) if arguments.size == 1 if arguments.size == 2 raise(Puppet::ParseError, 'basename(): Requires string as second argument') unless arguments[1].is_a?(String) rv = File.basename(arguments[0], arguments[1]) end return rv end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/bool2num.rb0100644005276200011600000000116213212471613021676 0ustar00# # bool2num.rb # module Puppet::Parser::Functions newfunction(:bool2num, :type => :rvalue, :doc => <<-DOC Converts a boolean to a number. Converts the values: false, f, 0, n, and no to 0 true, t, 1, y, and yes to 1 Requires a single boolean or string as an input. DOC ) do |arguments| raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = function_str2bool([arguments[0]]) # We have real boolean values as well ... result = value ? 1 : 0 return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/bool2str.rb0100644005276200011600000000255013212471613021711 0ustar00# # bool2str.rb # module Puppet::Parser::Functions newfunction(:bool2str, :type => :rvalue, :doc => <<-DOC Converts a boolean to a string using optionally supplied arguments. The optional second and third arguments represent what true and false will be converted to respectively. If only one argument is given, it will be converted from a boolean to a string containing 'true' or 'false'. *Examples:* bool2str(true) => 'true' bool2str(true, 'yes', 'no') => 'yes' bool2str(false, 't', 'f') => 'f' Requires a single boolean as an input. DOC ) do |arguments| unless arguments.size == 1 || arguments.size == 3 raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)") end value = arguments[0] true_string = arguments[1] || 'true' false_string = arguments[2] || 'false' klass = value.class # We can have either true or false, and nothing else unless [FalseClass, TrueClass].include?(klass) raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with') end unless [true_string, false_string].all? { |x| x.is_a?(String) } raise(Puppet::ParseError, 'bool2str(): Requires strings to convert to') end return value ? true_string : false_string end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/camelcase.rb0100644005276200011600000000217713212471613022065 0ustar00# # camelcase.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:camelcase, :type => :rvalue, :doc => <<-DOC Converts the case of a string or all strings in an array to camel case. DOC ) do |arguments| raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'camelcase(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.split('_').map { |e| e.capitalize }.join : i } else value.split('_').map { |e| e.capitalize }.join end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/capitalize.rb0100644005276200011600000000212313212471613022264 0ustar00# # capitalize.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:capitalize, :type => :rvalue, :doc => <<-DOC Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. DOC ) do |arguments| raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'capitalize(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.capitalize : i } else value.capitalize end return result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/ceiling.rb0100644005276200011600000000137313212471613021557 0ustar00# # ceiling.rb # module Puppet::Parser::Functions newfunction(:ceiling, :type => :rvalue, :doc => <<-DOC Returns the smallest integer greater or equal to the argument. Takes a single numeric value as an argument. DOC ) do |arguments| raise(Puppet::ParseError, "ceiling(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 begin arg = Float(arguments[0]) rescue TypeError, ArgumentError => _e raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arguments[0]} for Numeric)") end raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.ceil end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/chomp.rb0100644005276200011600000000162613212471613021254 0ustar00# # chomp.rb # module Puppet::Parser::Functions newfunction(:chomp, :type => :rvalue, :doc => <<-DOC Removes the record separator from the end of a string or an array of strings, for example `hello\n` becomes `hello`. Requires a single string or array as an input. DOC ) do |arguments| raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'chomp(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.chomp : i } else value.chomp end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/chop.rb0100644005276200011600000000205513212471613021074 0ustar00# # chop.rb # module Puppet::Parser::Functions newfunction(:chop, :type => :rvalue, :doc => <<-DOC 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. Requires a string or array of strings as input. DOC ) do |arguments| raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'chop(): Requires either an array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.chop : i } else value.chop end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/clamp.rb0100644005276200011600000000137713212471613021245 0ustar00# # clamp.rb # module Puppet::Parser::Functions newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-DOC Clamps value to a range. DOC ) do |args| args.flatten! raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3 # check values out args.each do |value| case [value.class] when [String] raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ %r{^\d+$} when [Hash] raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})") end end # convert to numeric each element # then sort them and get a middle value args.map { |n| n.to_i }.sort[1] end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/concat.rb0100644005276200011600000000155313212471613021414 0ustar00# # concat.rb # module Puppet::Parser::Functions newfunction(:concat, :type => :rvalue, :doc => <<-DOC Appends the contents of multiple arrays into array 1. *Example:* concat(['1','2','3'],['4','5','6'],['7','8','9']) Would result in: ['1','2','3','4','5','6','7','8','9'] DOC ) do |arguments| # Check that more than 2 arguments have been given ... raise(Puppet::ParseError, "concat(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 a = arguments[0] # Check that the first parameter is an array unless a.is_a?(Array) raise(Puppet::ParseError, 'concat(): Requires array to work with') end result = a arguments.shift arguments.each do |x| result += (x.is_a?(Array) ? x : [x]) end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/convert_base.rb0100644005276200011600000000270413212471613022616 0ustar00# # convert_base.rb # module Puppet::Parser::Functions newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'DOC') do |args| Converts a given integer or base 10 string representing an integer to a specified base, as a string. Usage: $binary_repr = convert_base(5, 2) # $binary_repr is now set to "101" $hex_repr = convert_base("254", "16") # $hex_repr is now set to "fe" DOC raise Puppet::ParseError, 'convert_base(): First argument must be either a string or an integer' unless args[0].is_a?(Integer) || args[0].is_a?(String) raise Puppet::ParseError, 'convert_base(): Second argument must be either a string or an integer' unless args[1].is_a?(Integer) || args[1].is_a?(String) if args[0].is_a?(String) raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[0] =~ %r{^[0-9]+$} end if args[1].is_a?(String) raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[1] =~ %r{^[0-9]+$} end number_to_convert = args[0] new_base = args[1] number_to_convert = number_to_convert.to_i new_base = new_base.to_i raise Puppet::ParseError, 'convert_base(): base must be at least 2 and must not be greater than 36' unless new_base >= 2 && new_base <= 36 return number_to_convert.to_s(new_base) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/count.rb0100644005276200011600000000124413212471613021272 0ustar00# # count.rb # module Puppet::Parser::Functions newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC Takes an array as first argument and an optional second argument. Count the number of elements in array that matches second argument. If called with only an array it counts the number of elements that are not nil/undef. DOC ) do |args| if args.size > 2 raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.") end collection, item = args if item collection.count item else collection.count { |obj| !obj.nil? && obj != :undef && obj != '' } end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/deep_merge.rb0100644005276200011600000000303713212471613022240 0ustar00# # deep_merge.rb # module Puppet::Parser::Functions newfunction(:deep_merge, :type => :rvalue, :doc => <<-'DOC') do |args| Recursively merges two or more hashes together and returns the resulting hash. For example: $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) # The resulting hash is equivalent to: # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } When there is a duplicate key that is a hash, they are recursively merged. When there is a duplicate key that is not a hash, the key in the rightmost hash will "win." DOC if args.length < 2 raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)" end deep_merge = proc do |hash1, hash2| hash1.merge(hash2) do |_key, old_value, new_value| if old_value.is_a?(Hash) && new_value.is_a?(Hash) deep_merge.call(old_value, new_value) else new_value end end end result = {} args.each do |arg| next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef # If the argument was not a hash, skip it. unless arg.is_a?(Hash) raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments" end result = deep_merge.call(result, arg) end return(result) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/defined_with_params.rb0100644005276200011600000000367313212471613024146 0ustar00# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:defined_with_params, :type => :rvalue, :doc => <<-'DOC' Takes a resource reference and an optional hash of attributes. Returns true if a resource with the specified attributes has already been added to the catalog, and false otherwise. user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } DOC ) do |vals| reference, params = vals raise(ArgumentError, 'Must specify a reference') unless reference if !params || params == '' params = {} end ret = false if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 # Workaround for PE-20308 if reference.is_a?(String) type_name, title = Puppet::Resource.type_and_title(reference, nil) type = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type_or_class(find_global_scope, type_name.downcase) elsif reference.is_a?(Puppet::Resource) type = reference.resource_type title = reference.title else raise(ArgumentError, "Reference is not understood: '#{reference.class}'") end # end workaround else type = reference.to_s title = nil end resource = findresource(type, title) if resource matches = params.map do |key, value| # eql? avoids bugs caused by monkeypatching in puppet resource_is_undef = resource[key].eql?(:undef) || resource[key].nil? value_is_undef = value.eql?(:undef) || value.nil? (resource_is_undef && value_is_undef) || (resource[key] == value) end ret = params.empty? || !matches.include?(false) end Puppet.debug("Resource #{reference} was not determined to be defined") ret end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/delete.rb0100644005276200011600000000213613212471613021405 0ustar00# # delete.rb # module Puppet::Parser::Functions newfunction(:delete, :type => :rvalue, :doc => <<-DOC Deletes all instances of a given element from an array, substring from a string, or key from a hash. *Examples:* delete(['a','b','c','b'], 'b') Would return: ['a','c'] delete({'a'=>1,'b'=>2,'c'=>3}, 'b') Would return: {'a'=>1,'c'=>3} delete({'a'=>1,'b'=>2,'c'=>3}, ['b','c']) Would return: {'a'=>1} delete('abracadabra', 'bra') Would return: 'acada' DOC ) do |arguments| raise(Puppet::ParseError, "delete(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2 collection = arguments[0].dup Array(arguments[1]).each do |item| case collection when Array, Hash collection.delete item when String collection.gsub! item, '' else raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.") end end collection end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/delete_at.rb0100644005276200011600000000220413212471613022065 0ustar00# # delete_at.rb # module Puppet::Parser::Functions newfunction(:delete_at, :type => :rvalue, :doc => <<-DOC Deletes a determined indexed value from an array. *Examples:* delete_at(['a','b','c'], 1) Would return: ['a','c'] DOC ) do |arguments| raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'delete_at(): Requires array to work with') end index = arguments[1] if index.is_a?(String) && !index.match(%r{^\d+$}) raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index') end result = array.clone # Numbers in Puppet are often string-encoded which is troublesome ... index = index.to_i if index > result.size - 1 # First element is at index 0 is it not? raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given') end result.delete_at(index) # We ignore the element that got deleted ... return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/delete_regex.rb0100644005276200011600000000271713212471613022604 0ustar00# # delete_regex.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:delete_regex, :type => :rvalue, :doc => <<-DOC deletes all instances of a given element that match a regular expression from an array or key from a hash. Multiple regular expressions are assumed to be matched as an OR. *Examples:* delete_regex(['a','b','c','b'], 'b') Would return: ['a','c'] delete_regex(['a','b','c','b'], ['b', 'c']) Would return: ['a'] delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b') Would return: {'a'=>1,'c'=>3} delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$') Would return: {'b'=>2,'c'=>3} DOC ) do |arguments| raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2 collection = arguments[0].dup Array(arguments[1]).each do |item| case collection when Array, Hash, String collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) } else raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.") end end collection end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/delete_undef_values.rb0100644005276200011600000000171513212471613024147 0ustar00# # delete_undef_values.rb # module Puppet::Parser::Functions newfunction(:delete_undef_values, :type => :rvalue, :doc => <<-DOC Returns a copy of input hash or array with all undefs deleted. *Examples:* $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) Would return: {a => 'A', b => '', d => false} $array = delete_undef_values(['A','',undef,false]) Would return: ['A','',false] DOC ) do |args| raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.empty? unless args[0].is_a?(Array) || args[0].is_a?(Hash) raise(Puppet::ParseError, "delete_undef_values(): expected an array or hash, got #{args[0]} type #{args[0].class} ") end result = args[0].dup if result.is_a?(Hash) result.delete_if { |_key, val| val.equal? :undef } elsif result.is_a?(Array) result.delete :undef end result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/delete_values.rb0100644005276200011600000000132113212471613022757 0ustar00# # delete_values.rb # module Puppet::Parser::Functions newfunction(:delete_values, :type => :rvalue, :doc => <<-DOC Deletes all instances of a given value from a hash. *Examples:* delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') Would return: {'a'=>'A','c'=>'C','B'=>'D'} DOC ) do |arguments| raise(Puppet::ParseError, "delete_values(): Wrong number of arguments given (#{arguments.size} of 2)") if arguments.size != 2 hash, item = arguments unless hash.is_a?(Hash) raise(TypeError, "delete_values(): First argument must be a Hash. Given an argument of class #{hash.class}.") end hash.dup.delete_if { |_key, val| item == val } end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/deprecation.rb0100644005276200011600000000122513212471613022436 0ustar00# # deprecation.rb # module Puppet::Parser::Functions newfunction(:deprecation, :doc => <<-DOC Function to print deprecation warnings (this is the 3.X version of it), The uniqueness key - can appear once. The msg is the message text including any positional information that is formatted by the user/caller of the method.). DOC ) do |arguments| raise(Puppet::ParseError, "deprecation: Wrong number of arguments given (#{arguments.size} for 2)") unless arguments.size == 2 key = arguments[0] message = arguments[1] if ENV['STDLIB_LOG_DEPRECATIONS'] == 'true' warning("deprecation. #{key}. #{message}") end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/difference.rb0100644005276200011600000000152013212471613022231 0ustar00# # difference.rb # module Puppet::Parser::Functions newfunction(:difference, :type => :rvalue, :doc => <<-DOC This function returns the difference between two arrays. The returned array is a copy of the original array, removing any items that also appear in the second array. *Examples:* difference(["a","b","c"],["b","c","d"]) Would return: ["a"] DOC ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "difference(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, 'difference(): Requires 2 arrays') end result = first - second return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/dig.rb0100644005276200011600000000112213212471613020700 0ustar00# # dig.rb # module Puppet::Parser::Functions newfunction(:dig, :type => :rvalue, :doc => <<-DOC DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version. DOC ) do |arguments| warning('dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.') unless Puppet::Parser::Functions.autoloader.loaded?(:dig44) Puppet::Parser::Functions.autoloader.load(:dig44) end function_dig44(arguments) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/dig44.rb0100644005276200011600000000370013252003272021050 0ustar00# # dig44.rb # module Puppet::Parser::Functions newfunction( :dig44, :type => :rvalue, :arity => -2, :doc => <<-DOC DEPRECATED: This function has been replaced in puppet 4.5.0. Looks up into a complex structure of arrays and hashes and returns a value or the default value if nothing was found. Key can contain slashes to describe path components. The function will go down the structure and try to extract the required value. $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig44($data, ['a', 'b', '2'], 'not_found') => $value = 'b3' a -> first hash key b -> second hash key 2 -> array index starting with 0 not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. In addition to the required "key" argument, the function accepts a default argument. It will be returned if no value was found or a path component is missing. And the fourth argument can set a variable path separator. DOC ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2 data, path, default = *arguments raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") unless data.is_a?(Hash) || data.is_a?(Array) raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") unless path.is_a? Array value = path.reduce(data) do |structure, key| break unless structure.is_a?(Hash) || structure.is_a?(Array) if structure.is_a? Array begin key = Integer key rescue break end end break if structure[key].nil? || structure[key] == :undef structure[key] end value.nil? ? default : value end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/dirname.rb0100644005276200011600000000112713212471613021561 0ustar00# # dirname.rb # module Puppet::Parser::Functions newfunction(:dirname, :type => :rvalue, :doc => <<-DOC Returns the dirname of a path. DOC ) do |arguments| if arguments.empty? raise(Puppet::ParseError, 'dirname(): No arguments given') end if arguments.size > 1 raise(Puppet::ParseError, "dirname(): Too many arguments given (#{arguments.size})") end unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dirname(): Requires string as argument') end return File.dirname(arguments[0]) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/dos2unix.rb0100644005276200011600000000070613212471613021717 0ustar00# Custom Puppet function to convert dos to unix format module Puppet::Parser::Functions newfunction(:dos2unix, :type => :rvalue, :arity => 1, :doc => <<-DOC Returns the Unix version of the given string. Takes a single string argument. DOC ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dos2unix(): Requires string as argument') end arguments[0].gsub(%r{\r\n}, "\n") end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/downcase.rb0100644005276200011600000000205513212471613021746 0ustar00# # downcase.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:downcase, :type => :rvalue, :doc => <<-DOC Converts the case of a string or all strings in an array to lower case. DOC ) do |arguments| raise(Puppet::ParseError, "downcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'downcase(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.downcase : i } else value.downcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/empty.rb0100644005276200011600000000122613212471613021300 0ustar00# # empty.rb # module Puppet::Parser::Functions newfunction(:empty, :type => :rvalue, :doc => <<-DOC Returns true if the variable is empty. DOC ) do |arguments| raise(Puppet::ParseError, "empty(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(String) || value.is_a?(Numeric) raise(Puppet::ParseError, 'empty(): Requires either array, hash, string or integer to work with') end return false if value.is_a?(Numeric) result = value.empty? return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/enclose_ipv6.rb0100644005276200011600000000223113212471613022533 0ustar00# # enclose_ipv6.rb # module Puppet::Parser::Functions newfunction(:enclose_ipv6, :type => :rvalue, :doc => <<-DOC Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. DOC ) do |arguments| require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if arguments.size != 1 raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments given #{arguments.size} for 1") end unless arguments[0].is_a?(String) || arguments[0].is_a?(Array) raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type given #{arguments[0].class} expected String or Array") end input = [arguments[0]].flatten.compact result = [] input.each do |val| unless val == '*' begin ip = IPAddr.new(val) rescue *rescuable_exceptions raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument given #{val} is not an ip address.") end val = "[#{ip}]" if ip.ipv6? end result << val end return result.uniq end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/ensure_packages.rb0100644005276200011600000000341413212471613023302 0ustar00# # ensure_packages.rb # module Puppet::Parser::Functions newfunction(:ensure_packages, :type => :statement, :doc => <<-DOC Takes a list of packages and only installs them if they don't already exist. It optionally takes a hash as a second parameter that will be passed as the third argument to the ensure_resource() function. DOC ) do |arguments| raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments given (#{arguments.size} for 1 or 2)") if arguments.size > 2 || arguments.empty? raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') if arguments.size == 2 && !arguments[1].is_a?(Hash) if arguments[0].is_a?(Hash) if arguments[1] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resources) function_ensure_resources(['package', arguments[0].dup, defaults]) else packages = Array(arguments[0]) if arguments[1] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resource) packages.each do |package_name| raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.empty? unless findresource("Package[#{package_name}]") function_ensure_resource(['package', package_name, defaults]) end end end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/ensure_resource.rb0100644005276200011600000000324713212471613023357 0ustar00# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resource, :type => :statement, :doc => <<-'DOC' Takes a resource type, title, and a list of attributes that describe a resource. user { 'dan': ensure => present, } This example only creates the resource if it does not already exist: ensure_resource('user', 'dan', {'ensure' => 'present' }) If the resource already exists but does not match the specified parameters, this function will attempt to recreate the resource leading to a duplicate resource definition error. An array of resources can also be passed in and each will be created with the type and parameters specified if it doesn't already exist. ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} items = [title].flatten items.each do |item| Puppet::Parser::Functions.function(:defined_with_params) if function_defined_with_params(["#{type}[#{item}]", params]) Puppet.debug("Resource #{type}[#{item}] with params #{params} not created because it already exists") else Puppet.debug("Create new resource #{type}[#{item}] with params #{params}") Puppet::Parser::Functions.function(:create_resources) function_create_resources([type.capitalize, { item => params }]) end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/ensure_resources.rb0100644005276200011600000000315713212471613023542 0ustar00require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resources, :type => :statement, :doc => <<-'DOC' Takes a resource type, title (only hash), and a list of attributes that describe a resource. user { 'dan': gid => 'mygroup', ensure => present, } An hash of resources should be passed in and each will be created with the type and parameters specified if it doesn't already exist. ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) From Hiera Backend: userlist: dan: gid: 'mygroup' uid: '600' alex: gid: 'mygroup' Call: ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} raise(Puppet::ParseError, 'ensure_resources(): Requires second argument to be a Hash') unless title.is_a?(Hash) resource_hash = title.dup resources = resource_hash.keys Puppet::Parser::Functions.function(:ensure_resource) resources.each do |resource_name| params_merged = if resource_hash[resource_name] params.merge(resource_hash[resource_name]) else params end function_ensure_resource([type, resource_name, params_merged]) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/flatten.rb0100644005276200011600000000125113212471613021575 0ustar00# # flatten.rb # module Puppet::Parser::Functions newfunction(:flatten, :type => :rvalue, :doc => <<-DOC This function flattens any deeply nested arrays and returns a single flat array as a result. *Examples:* flatten(['a', ['b', ['c']]]) Would return: ['a','b','c'] DOC ) do |arguments| raise(Puppet::ParseError, "flatten(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'flatten(): Requires array to work with') end result = array.flatten return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/floor.rb0100644005276200011600000000135513212471613021266 0ustar00# # floor.rb # module Puppet::Parser::Functions newfunction(:floor, :type => :rvalue, :doc => <<-DOC Returns the largest integer less or equal to the argument. Takes a single numeric value as an argument. DOC ) do |arguments| raise(Puppet::ParseError, "floor(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 begin arg = Float(arguments[0]) rescue TypeError, ArgumentError => _e raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arguments[0]} for Numeric)") end raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.floor end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/fqdn_rand_string.rb0100644005276200011600000000326613212471613023472 0ustar00Puppet::Parser::Functions.newfunction( :fqdn_rand_string, :arity => -2, :type => :rvalue, :doc => "Usage: `fqdn_rand_string(LENGTH, [CHARSET], [SEED])`. LENGTH is required and must be a positive integer. CHARSET is optional and may be `undef` or a string. SEED is optional and may be any number or string. Generates a random string LENGTH characters long using the character set provided by CHARSET, combining the `$fqdn` fact and the value of SEED for repeatable randomness. (That is, each node will get a different random string from this function, but a given node's result will be the same every time unless its hostname changes.) Adding a SEED can be useful if you need more than one unrelated string. CHARSET will default to alphanumeric if `undef` or an empty string.", ) do |args| raise(ArgumentError, 'fqdn_rand_string(): wrong number of arguments (0 for 1)') if args.empty? Puppet::Parser::Functions.function('is_integer') raise(ArgumentError, 'fqdn_rand_string(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 raise(ArgumentError, 'fqdn_rand_string(): second argument must be undef or a string') unless args[1].nil? || args[1].is_a?(String) Puppet::Parser::Functions.function('fqdn_rand') length = args.shift.to_i charset = args.shift.to_s.chars.to_a charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty? rand_string = '' for current in 1..length # rubocop:disable Style/For : An each loop would not work correctly in this circumstance rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i] end rand_string end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/fqdn_rotate.rb0100644005276200011600000000346513212471613022457 0ustar00# # fqdn_rotate.rb # Puppet::Parser::Functions.newfunction( :fqdn_rotate, :type => :rvalue, :doc => "Usage: `fqdn_rotate(VALUE, [SEED])`. VALUE is required and must be an array or a string. SEED is optional and may be any number or string. Rotates VALUE a random number of times, combining the `$fqdn` fact and the value of SEED for repeatable randomness. (That is, each node will get a different random rotation from this function, but a given node's result will be the same every time unless its hostname changes.) Adding a SEED can be useful if you need more than one unrelated rotation.", ) do |args| raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.empty? value = args.shift require 'digest/md5' unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to rotate ... return result if result.size <= 1 # We turn any string value into an array to be able to rotate ... result = string ? result.split('') : result elements = result.size seed = Digest::MD5.hexdigest([lookupvar('::fqdn'), args].join(':')).hex # deterministic_rand() was added in Puppet 3.2.0; reimplement if necessary if Puppet::Util.respond_to?(:deterministic_rand) offset = Puppet::Util.deterministic_rand(seed, elements).to_i else return offset = Random.new(seed).rand(elements) if defined?(Random) == 'constant' && Random.class == Class old_seed = srand(seed) offset = rand(elements) srand(old_seed) end offset.times do result.push result.shift end result = string ? result.join : result return result end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/fqdn_uuid.rb0100644005276200011600000000467113212471613022127 0ustar00require 'digest/sha1' # # fqdn_uuid.rb # module Puppet::Parser::Functions newfunction(:fqdn_uuid, :type => :rvalue, :doc => <<-DOC) do |args| Creates a UUID based on a given string, assumed to be the FQDN For example, to generate a UUID based on the FQDN of a system: Usage: $uuid = fqdn_uuid($::fqdn) The generated UUID will be the same for the given hostname The resulting UUID is returned on the form: 1d839dea-5e10-5243-88eb-e66815bd7d5c (u.e. without any curly braces.) The generated UUID is a version 5 UUID with the V5 DNS namespace: 6ba7b810-9dad-11d1-80b4-00c04fd430c8 This only supports a the V5 SHA-1 hash, using the DNS namespace. Please consult http://www.ietf.org/rfc/rfc4122.txt for the details on UUID generation and example implementation. No verification is present at the moment as whether the domain name given is in fact a correct fully-qualified domain name. Therefore any arbitrary string and/or alpha-numeric value can subside for a domain name. DOC raise(ArgumentError, 'fqdn_uuid: No arguments given') if args.empty? raise(ArgumentError, "fqdn_uuid: Too many arguments given (#{args.length})") unless args.length == 1 fqdn = args[0] # Code lovingly taken from # https://github.com/puppetlabs/marionette-collective/blob/master/lib/mcollective/ssl.rb # This is the UUID version 5 type DNS name space which is as follows: # # 6ba7b810-9dad-11d1-80b4-00c04fd430c8 # uuid_name_space_dns = [0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8].map { |b| b.chr }.join sha1 = Digest::SHA1.new sha1.update(uuid_name_space_dns) sha1.update(fqdn) # first 16 bytes.. bytes = sha1.digest[0, 16].bytes.to_a # version 5 adjustments bytes[6] &= 0x0f bytes[6] |= 0x50 # variant is DCE 1.1 bytes[8] &= 0x3f bytes[8] |= 0x80 bytes = [4, 2, 2, 2, 6].map do |i| bytes.slice!(0, i).pack('C*').unpack('H*') end bytes.join('-') end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/get_module_path.rb0100644005276200011600000000120413212471613023276 0ustar00# # get_module_path.rb # module Puppet::Parser::Functions newfunction(:get_module_path, :type => :rvalue, :doc => <<-DOC Returns the absolute path of the specified module for the current environment. Example: $module_path = get_module_path('stdlib') DOC ) do |args| raise(Puppet::ParseError, 'get_module_path(): Wrong number of arguments, expects one') unless args.size == 1 module_path = Puppet::Module.find(args[0], compiler.environment.to_s) raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") unless module_path module_path.path end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/getparam.rb0100644005276200011600000000202513212471613021740 0ustar00# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:getparam, :type => :rvalue, :doc => <<-'DOC' Takes a resource reference and name of the parameter and returns value of resource's parameter. *Examples:* define example_resource($param) { } example_resource { "example_resource_instance": param => "param_value" } getparam(Example_resource["example_resource_instance"], "param") Would return: param_value DOC ) do |vals| reference, param = vals raise(ArgumentError, 'Must specify a reference') unless reference raise(ArgumentError, 'Must specify name of a parameter') unless param && param.instance_of?(String) return '' if param.empty? resource = findresource(reference.to_s) if resource return resource[param] unless resource[param].nil? end return '' end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/getvar.rb0100644005276200011600000000171413212471613021434 0ustar00# # getvar.rb # module Puppet::Parser::Functions newfunction(:getvar, :type => :rvalue, :doc => <<-'DOC') do |args| Lookup a variable in a remote namespace. For example: $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo This is useful if the namespace itself is stored in a string: $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar DOC unless args.length == 1 raise Puppet::ParseError, "getvar(): wrong number of arguments (#{args.length}; must be 1)" end begin result = nil catch(:undefined_variable) do result = lookupvar((args[0]).to_s) end # avoid relying on incosistent behaviour around ruby return values from catch result rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/glob.rb0100644005276200011600000000117213212471613021065 0ustar00# # glob.rb # module Puppet::Parser::Functions newfunction(:glob, :type => :rvalue, :doc => <<-'DOC' Returns an Array of file entries of a directory or an Array of directories. Uses same patterns as Dir#glob DOC ) do |arguments| unless arguments.size == 1 raise(Puppet::ParseError, 'glob(): Wrong number of arguments given ' \ "(#{arguments.size} for 1)") end pattern = arguments[0] unless pattern.is_a?(String) || pattern.is_a?(Array) raise(Puppet::ParseError, 'glob(): Requires either array or string ' \ 'to work') end Dir.glob(pattern) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/grep.rb0100644005276200011600000000115713212471613021102 0ustar00# # grep.rb # module Puppet::Parser::Functions newfunction(:grep, :type => :rvalue, :doc => <<-DOC This function searches through an array and returns any elements that match the provided regular expression. *Examples:* grep(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['aaa','aaaddd'] DOC ) do |arguments| if arguments.size != 2 raise(Puppet::ParseError, "grep(): Wrong number of arguments given #{arguments.size} for 2") end a = arguments[0] pattern = Regexp.new(arguments[1]) a.grep(pattern) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/has_interface_with.rb0100644005276200011600000000372713212471613024000 0ustar00# # has_interface_with # module Puppet::Parser::Functions newfunction(:has_interface_with, :type => :rvalue, :doc => <<-DOC Returns boolean based on kind and value: * macaddress * netmask * ipaddress * network has_interface_with("macaddress", "x:x:x:x:x:x") has_interface_with("ipaddress", "127.0.0.1") => true etc. If no "kind" is given, then the presence of the interface is checked: has_interface_with("lo") => true DOC ) do |args| raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments given (#{args.size} for 1 or 2)") if args.empty? || args.size > 2 interfaces = lookupvar('interfaces') # If we do not have any interfaces, then there are no requested attributes return false if interfaces == :undefined || interfaces.nil? interfaces = interfaces.split(',') if args.size == 1 return interfaces.member?(args[0]) end kind, value = args # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 factval = nil begin catch :undefined_variable do factval = lookupvar(kind) end rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end if factval == value return true end result = false interfaces.each do |iface| iface.downcase! factval = nil begin # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 catch :undefined_variable do factval = lookupvar("#{kind}_#{iface}") end rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end if value == factval result = true break end end result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/has_ip_address.rb0100644005276200011600000000133013212471613023106 0ustar00# # has_ip_address # module Puppet::Parser::Functions newfunction(:has_ip_address, :type => :rvalue, :doc => <<-DOC Returns true if the client has the requested IP address on some interface. This function iterates through the 'interfaces' fact and checks the 'ipaddress_IFACE' facts, performing a simple string comparison. DOC ) do |args| raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['ipaddress', args[0]]) end end # vim:sts=2 sw=2 puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/has_ip_network.rb0100644005276200011600000000132513212471613023156 0ustar00# # has_ip_network # module Puppet::Parser::Functions newfunction(:has_ip_network, :type => :rvalue, :doc => <<-DOC Returns true if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. DOC ) do |args| raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['network', args[0]]) end end # vim:sts=2 sw=2 puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/has_key.rb0100644005276200011600000000141513212471613021565 0ustar00# # has_key.rb # module Puppet::Parser::Functions newfunction(:has_key, :type => :rvalue, :doc => <<-'DOC') do |args| Determine if a hash has a certain key value. Example: $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } DOC unless args.length == 2 raise Puppet::ParseError, "has_key(): wrong number of arguments (#{args.length}; must be 2)" end unless args[0].is_a?(Hash) raise Puppet::ParseError, "has_key(): expects the first argument to be a hash, got #{args[0].inspect} which is of type #{args[0].class}" end args[0].key?(args[1]) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/hash.rb0100644005276200011600000000154013212471613021064 0ustar00# # hash.rb # module Puppet::Parser::Functions newfunction(:hash, :type => :rvalue, :doc => <<-DOC This function converts an array into a hash. *Examples:* hash(['a',1,'b',2,'c',3]) Would return: {'a'=>1,'b'=>2,'c'=>3} DOC ) do |arguments| raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'hash(): Requires array to work with') end result = {} begin # This is to make it compatible with older version of Ruby ... array = array.flatten result = Hash[*array] rescue StandardError raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/intersection.rb0100644005276200011600000000150713212471613022652 0ustar00# # intersection.rb # module Puppet::Parser::Functions newfunction(:intersection, :type => :rvalue, :doc => <<-DOC This function returns an array of the intersection of two. *Examples:* intersection(["a","b","c"],["b","c","d"]) # returns ["b","c"] intersection(["a","b","c"],[1,2,3,4]) # returns [] (true, when evaluated as a Boolean) DOC ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "intersection(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, 'intersection(): Requires 2 arrays') end result = first & second return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_absolute_path.rb0100644005276200011600000000447113212471613023474 0ustar00# # is_absolute_path.rb # module Puppet::Parser::Functions newfunction(:is_absolute_path, :type => :rvalue, :arity => 1, :doc => <<-'DOC') do |args| Returns boolean true if the string represents an absolute path in the filesystem. This function works for windows and unix style paths. The following values will return true: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' is_absolute_path($my_path) $my_path2 = '/var/lib/puppet' is_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet'] is_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet'] is_absolute_path($my_path4) The following values will return false: is_absolute_path(true) is_absolute_path('../var/lib/puppet') is_absolute_path('var/lib/puppet') $undefined = undef is_absolute_path($undefined) DOC function_deprecation([:is_absolute_path, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_path. There is further documentation for validate_legacy function in the README.']) require 'puppet/util' path = args[0] # This logic was borrowed from # [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb) # Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise. if Puppet::Util.respond_to?(:absolute_path?) value = (Puppet::Util.absolute_path?(path, :posix) || Puppet::Util.absolute_path?(path, :windows)) else # This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? # Determine in a platform-specific way whether a path is absolute. This # defaults to the local platform if none is specified. # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' name = '[^\\\\/]+' regexes = { :windows => %r{^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))}i, :posix => %r{^/}, } value = !!(path =~ regexes[:posix]) || !!(path =~ regexes[:windows]) # rubocop:disable Style/DoubleNegation : No alternative known end value end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_array.rb0100644005276200011600000000124213212471613021751 0ustar00# # is_array.rb # module Puppet::Parser::Functions newfunction(:is_array, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is an array. DOC ) do |arguments| function_deprecation([:is_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] result = type.is_a?(Array) return result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_bool.rb0100644005276200011600000000127613212471613021575 0ustar00# # is_bool.rb # module Puppet::Parser::Functions newfunction(:is_bool, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is a boolean. DOC ) do |arguments| function_deprecation([:is_bool, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(TrueClass) || type.is_a?(FalseClass) return result end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_domain_name.rb0100644005276200011600000000264513212471613023112 0ustar00# # is_domain_name.rb # module Puppet::Parser::Functions newfunction(:is_domain_name, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a syntactically correct domain name. DOC ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow string types return false unless arguments[0].is_a?(String) domain = arguments[0].dup # Limits (rfc1035, 3.1) domain_max_length = 255 label_min_length = 1 label_max_length = 63 # Allow ".", it is the top level domain return true if domain == '.' # Remove the final dot, if present. domain.chomp!('.') # Check the whole domain return false if domain.empty? return false if domain.length > domain_max_length # The top level domain must be alphabetic if there are multiple labels. # See rfc1123, 2.1 return false if domain.include?('.') && !%r{\.[A-Za-z]+$}.match(domain) # Check each label in the domain labels = domain.split('.') vlabels = labels.each do |label| break if label.length < label_min_length break if label.length > label_max_length break if label[-1..-1] == '-' break if label[0..0] == '-' break unless %r{^[a-z\d-]+$}i =~ label end return vlabels == labels end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_email_address.rb0100644005276200011600000000126313212471613023432 0ustar00# # is_email_address.rb # module Puppet::Parser::Functions newfunction(:is_email_address, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a valid email address. DOC ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_email_address(): Wrong number of arguments given #{arguments.size} for 1") end # Taken from http://emailregex.com/ (simpler regex) valid_email_regex = %r{\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z} return (arguments[0] =~ valid_email_regex) == 0 # rubocop:disable Style/NumericPredicate : Changing to '.zero?' breaks the code end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_float.rb0100644005276200011600000000153313212471613021743 0ustar00# # is_float.rb # module Puppet::Parser::Functions newfunction(:is_float, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is a float. DOC ) do |arguments| function_deprecation([:is_float, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Float. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_float(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Only allow Numeric or String types return false unless value.is_a?(Numeric) || value.is_a?(String) return false if value != value.to_f.to_s && !value.is_a?(Float) return true end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_function_available.rb0100644005276200011600000000136513212471613024466 0ustar00# # is_function_available.rb # module Puppet::Parser::Functions newfunction(:is_function_available, :type => :rvalue, :doc => <<-DOC This function accepts a string as an argument, determines whether the Puppet runtime has access to a function by that name. It returns a true if the function exists, false if not. DOC ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow String types return false unless arguments[0].is_a?(String) function = Puppet::Parser::Functions.function(arguments[0].to_sym) function.is_a?(String) && !function.empty? end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_hash.rb0100644005276200011600000000070313212471613021557 0ustar00# # is_hash.rb # module Puppet::Parser::Functions newfunction(:is_hash, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is a hash. DOC ) do |arguments| raise(Puppet::ParseError, "is_hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(Hash) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_integer.rb0100644005276200011600000000277013212471613022277 0ustar00# # is_integer.rb # module Puppet::Parser::Functions newfunction(:is_integer, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is an Integer or a decimal (base 10) integer in String form. The string may start with a '-' (minus). A value of '0' is allowed, but a leading '0' digit may not be followed by other digits as this indicates that the value is octal (base 8). If given any other argument `false` is returned. DOC ) do |arguments| function_deprecation([:is_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_integer(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow numbers prefixed with multiple # 0's # # TODO these parameter should be a constant but I'm not sure # if there is no risk to declare it inside of the module # Puppet::Parser::Functions # Integer numbers like # -1234568981273 # 47291 numeric = %r{^-?(?:(?:[1-9]\d*)|0)$} return true if value.is_a?(Integer) || (value.is_a?(String) && value.match(numeric)) return false end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_ip_address.rb0100644005276200011600000000152413212471613022753 0ustar00# # is_ip_address.rb # module Puppet::Parser::Functions newfunction(:is_ip_address, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a valid IP address. DOC ) do |arguments| require 'ipaddr' function_deprecation([:is_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return true if ip.ipv4? || ip.ipv6? return false end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_ipv4_address.rb0100644005276200011600000000146413212471613023230 0ustar00# # is_ipv4_address.rb # module Puppet::Parser::Functions newfunction(:is_ipv4_address, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a valid IPv4 address. DOC ) do |arguments| require 'ipaddr' function_deprecation([:is_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv4? end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_ipv6_address.rb0100644005276200011600000000146413212471613023232 0ustar00# # is_ipv6_address.rb # module Puppet::Parser::Functions newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a valid IPv6 address. DOC ) do |arguments| function_deprecation([:is_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' if arguments.size != 1 raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv6? end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_mac_address.rb0100644005276200011600000000102013212471613023072 0ustar00# # is_mac_address.rb # module Puppet::Parser::Functions newfunction(:is_mac_address, :type => :rvalue, :doc => <<-DOC Returns true if the string passed to this function is a valid mac address. DOC ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments given #{arguments.size} for 1") end mac = arguments[0] return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i =~ mac return false end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_numeric.rb0100644005276200011600000000436513212471613022306 0ustar00# # is_numeric.rb # module Puppet::Parser::Functions newfunction(:is_numeric, :type => :rvalue, :doc => <<-DOC Returns true if the given argument is a Numeric (Integer or Float), or a String containing either a valid integer in decimal base 10 form, or a valid floating point string representation. The function recognizes only decimal (base 10) integers and float but not integers in hex (base 16) or octal (base 8) form. The string representation may start with a '-' (minus). If a decimal '.' is used, it must be followed by at least one digit. Valid examples: 77435 10e-12 -8475 0.2343 -23.561e3 DOC ) do |arguments| function_deprecation([:is_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) if arguments.size != 1 raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow invalid octal numbers or # numbers prefixed with multiple 0's (except in hex numbers) # # TODO these parameters should be constants but I'm not sure # if there is no risk to declare them inside of the module # Puppet::Parser::Functions # TODO: decide if this should be used # HEX numbers like # 0xaa230F # 0X1234009C # 0x0012 # -12FcD # numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} # TODO: decide if this should be used # OCTAL numbers like # 01234567 # -045372 # numeric_oct = %r{^-?0[1-7][0-7]*$} # Integer/Float numbers like # -0.1234568981273 # 47291 # 42.12345e-12 numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$} if value.is_a?(Numeric) || (value.is_a?(String) && value.match(numeric) # or # value.match(numeric_hex) or # value.match(numeric_oct) ) return true else return false end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/is_string.rb0100644005276200011600000000156713212471613022153 0ustar00# # is_string.rb # module Puppet::Parser::Functions newfunction(:is_string, :type => :rvalue, :doc => <<-DOC Returns true if the variable passed to this function is a string. DOC ) do |arguments| function_deprecation([:is_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_string(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] # when called through the v4 API shim, undef gets translated to nil result = type.is_a?(String) || type.nil? if result && (type == type.to_f.to_s || type == type.to_i.to_s) return false end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/join.rb0100644005276200011600000000162013212471613021077 0ustar00# # join.rb # module Puppet::Parser::Functions newfunction(:join, :type => :rvalue, :doc => <<-DOC This function joins an array into a string using a separator. *Examples:* join(['a','b','c'], ",") Would result in: "a,b,c" DOC ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'join(): Requires array to work with') end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a?(String) raise(Puppet::ParseError, 'join(): Requires string to work with') end end result = suffix ? array.join(suffix) : array.join return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/join_keys_to_values.rb0100644005276200011600000000307413252003272024214 0ustar00# # join.rb # module Puppet::Parser::Functions newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-DOC This function joins each key of a hash to that key's corresponding value with a separator. Keys are cast to strings. If values are arrays, multiple keys are added for each element. The return value is an array in which each element is one joined key/value pair. *Examples:* join_keys_to_values({'a'=>1,'b'=>2}, " is ") Would result in: ["a is 1","b is 2"] join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") Would result in: ["a is 1","b is 2","b is 3"] DOC ) do |arguments| # Validate the number of arguments. if arguments.size != 2 raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.") end # Validate the first argument. hash = arguments[0] unless hash.is_a?(Hash) raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.") end # Validate the second argument. separator = arguments[1] unless separator.is_a?(String) raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.") end # Join the keys to their values. hash.map { |k, v| if v.is_a?(Array) v.map { |va| String(k) + separator + String(va) } elsif String(v) == 'undef' String(k) else String(k) + separator + String(v) end }.flatten end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/keys.rb0100644005276200011600000000100313212471613021106 0ustar00# # keys.rb # module Puppet::Parser::Functions newfunction(:keys, :type => :rvalue, :doc => <<-DOC Returns the keys of a hash as an array. DOC ) do |arguments| raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'keys(): Requires hash to work with') end result = hash.keys return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/load_module_metadata.rb0100644005276200011600000000163613212471613024273 0ustar00# # load_module_metadata.rb # module Puppet::Parser::Functions newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-DOC This function loads the metadata of a given module. DOC ) do |args| raise(Puppet::ParseError, 'load_module_metadata(): Wrong number of arguments, expects one or two') unless [1, 2].include?(args.size) mod = args[0] allow_empty_metadata = args[1] module_path = function_get_module_path([mod]) metadata_json = File.join(module_path, 'metadata.json') metadata_exists = File.exists?(metadata_json) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code if metadata_exists metadata = PSON.load(File.read(metadata_json)) else metadata = {} raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}") unless allow_empty_metadata end return metadata end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/loadjson.rb0100644005276200011600000000201713212471613021752 0ustar00# # loadjson.rb # module Puppet::Parser::Functions newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| Load a JSON file containing an array, string, or hash, and return the data in the corresponding native data type. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. For example: $myhash = loadjson('/etc/puppet/data/myhash.json') $myhash = loadjson('no-file.json', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 if File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code begin content = File.read(args[0]) PSON.load(content) || args[1] rescue StandardError => e raise e unless args[1] args[1] end else warning("Can't load '#{args[0]}' File does not exist!") args[1] end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/loadyaml.rb0100644005276200011600000000200213212471613021735 0ustar00# # loadyaml.rb # module Puppet::Parser::Functions newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. For example: $myhash = loadyaml('/etc/puppet/data/myhash.yaml') $myhash = loadyaml('no-file.yaml', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'yaml' if File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code begin YAML.load_file(args[0]) || args[1] rescue StandardError => e raise e unless args[1] args[1] end else warning("Can't load '#{args[0]}' File does not exist!") args[1] end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/lstrip.rb0100644005276200011600000000143713212471613021463 0ustar00# # lstrip.rb # module Puppet::Parser::Functions newfunction(:lstrip, :type => :rvalue, :doc => <<-DOC Strips leading spaces to the left of a string. DOC ) do |arguments| raise(Puppet::ParseError, "lstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'lstrip(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.lstrip : i } else value.lstrip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/max.rb0100644005276200011600000000117313212471613020730 0ustar00# # max.rb # module Puppet::Parser::Functions newfunction(:max, :type => :rvalue, :doc => <<-DOC Returns the highest value of all arguments. Requires at least one argument. DOC ) do |args| raise(Puppet::ParseError, 'max(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.max do |a, b| if a.to_s =~ %r{\A-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/member.rb0100644005276200011600000000300713212471613021410 0ustar00# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... # TODO(Krzysztof Wilczynski): Support for strings and hashes too ... # # member.rb # module Puppet::Parser::Functions newfunction(:member, :type => :rvalue, :doc => <<-DOC This function determines if a variable is a member of an array. The variable can be a string, fixnum, or array. *Examples:* member(['a','b'], 'b') Would return: true member(['a', 'b', 'c'], ['a', 'b']) would return: true member(['a','b'], 'c') Would return: false member(['a', 'b', 'c'], ['d', 'b']) would return: false DOC ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'member(): Requires array to work with') end unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array) raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array') end item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer) [arguments[1]] else arguments[1] end raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty? result = (item - array).empty? return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/merge.rb0100644005276200011600000000217613212471613021246 0ustar00# # merge.rb # module Puppet::Parser::Functions newfunction(:merge, :type => :rvalue, :doc => <<-'DOC') do |args| Merges two or more hashes together and returns the resulting hash. For example: $hash1 = {'one' => 1, 'two', => 2} $hash2 = {'two' => 'dos', 'three', => 'tres'} $merged_hash = merge($hash1, $hash2) # The resulting hash is equivalent to: # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} When there is a duplicate key, the key in the rightmost hash will "win." DOC if args.length < 2 raise Puppet::ParseError, "merge(): wrong number of arguments (#{args.length}; must be at least 2)" end # The hash we accumulate into accumulator = {} # Merge into the accumulator hash args.each do |arg| next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef unless arg.is_a?(Hash) raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments" end accumulator.merge!(arg) end # Return the fully merged hash accumulator end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/min.rb0100644005276200011600000000117313212471613020726 0ustar00# # min.rb # module Puppet::Parser::Functions newfunction(:min, :type => :rvalue, :doc => <<-DOC Returns the lowest value of all arguments. Requires at least one argument. DOC ) do |args| raise(Puppet::ParseError, 'min(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.min do |a, b| if a.to_s =~ %r{\A^-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/num2bool.rb0100644005276200011600000000223213212471613021675 0ustar00# # num2bool.rb # module Puppet::Parser::Functions newfunction(:num2bool, :type => :rvalue, :doc => <<-DOC This function converts a number or a string representation of a number into a true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 become true. DOC ) do |arguments| raise(Puppet::ParseError, "num2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 number = arguments[0] case number when Numeric # rubocop:disable Lint/EmptyWhen : Required for the module to work # Yay, it's a number when String begin number = Float(number) rescue ArgumentError => ex raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}") end else begin number = number.to_s rescue NoMethodError => ex raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}") end end # Truncate Floats number = number.to_i # Return true for any positive number and false otherwise return number > 0 end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/parsejson.rb0100644005276200011600000000126113212471613022145 0ustar00# # parsejson.rb # module Puppet::Parser::Functions newfunction(:parsejson, :type => :rvalue, :doc => <<-DOC This function accepts JSON as a string and converts it into the correct Puppet structure. The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 begin PSON.load(arguments[0]) || arguments[1] rescue StandardError => e raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/parseyaml.rb0100644005276200011600000000201113212471613022130 0ustar00# # parseyaml.rb # module Puppet::Parser::Functions newfunction(:parseyaml, :type => :rvalue, :doc => <<-DOC This function accepts YAML as a string and converts it into the correct Puppet structure. The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 require 'yaml' begin YAML.load(arguments[0]) || arguments[1] # rubocop:disable Security/YAMLLoad : using YAML.safe_load causes the code to break # in ruby 1.9.3 Psych::SyntaxError is a RuntimeException # this still needs to catch that and work also on rubies that # do not have Psych available. rescue StandardError, Psych::SyntaxError => e # rubocop:disable Lint/ShadowedException : See above raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/pick.rb0100644005276200011600000000212013212471613021062 0ustar00# # pick.rb # module Puppet::Parser::Functions newfunction(:pick, :type => :rvalue, :doc => <<-DOC This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string (two things in Puppet that will return a boolean false value). Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: $real_jenkins_version = pick($::jenkins_version, '1.449') The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. DOC ) do |args| args = args.compact args.delete(:undef) args.delete(:undefined) args.delete('') raise Puppet::ParseError, 'pick(): must receive at least one non empty value' if args[0].to_s.empty? return args[0] end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/pick_default.rb0100644005276200011600000000254113212471613022575 0ustar00# # pick_default.rb # module Puppet::Parser::Functions newfunction(:pick_default, :type => :rvalue, :doc => <<-DOC This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string (two things in Puppet that will return a boolean false value). If no value is found, it will return the last argument. Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: $real_jenkins_version = pick_default($::jenkins_version, '1.449') The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. Note that, contrary to the pick() function, the pick_default does not fail if all arguments are empty. This allows pick_default to use an empty value as default. DOC ) do |args| raise 'Must receive at least one argument.' if args.empty? default = args.last args = args[0..-2].compact args.delete(:undef) args.delete(:undefined) args.delete('') args << default return args[0] end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/prefix.rb0100644005276200011600000000260113212471613021435 0ustar00# # prefix.rb # module Puppet::Parser::Functions newfunction(:prefix, :type => :rvalue, :doc => <<-DOC This function applies a prefix to all elements in an array or a hash. *Examples:* prefix(['a','b','c'], 'p') Will return: ['pa','pb','pc'] DOC ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end prefix = arguments[1] if arguments[1] if prefix unless prefix.is_a?(String) raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}" end end result = if enumerable.is_a?(Array) # Turn everything into string same as join would do ... enumerable.map do |i| i = i.to_s prefix ? prefix + i : i end else Hash[enumerable.map do |k, v| k = k.to_s [prefix ? prefix + k : k, v] end] end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/private.rb0100644005276200011600000000137513212471613021621 0ustar00# # private.rb # module Puppet::Parser::Functions newfunction(:private, :doc => <<-'DOC' DEPRECATED: Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. DOC ) do |args| warning("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : Cannot shorten this line unless Puppet::Parser::Functions.autoloader.loaded?(:assert_private) Puppet::Parser::Functions.autoloader.load(:assert_private) end function_assert_private([(args[0] unless args.empty?)]) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/pry.rb0100644005276200011600000000161613212471613020757 0ustar00# # pry.rb # module Puppet::Parser::Functions newfunction(:pry, :type => :statement, :doc => <<-DOC This function invokes a pry debugging session in the current scope object. This is useful for debugging manifest code at specific points during a compilation. *Examples:* pry() DOC ) do |arguments| begin require 'pry' rescue LoadError raise(Puppet::Error, "pry(): Requires the 'pry' rubygem to use, but it was not found") end # ## Run `catalog` to see the contents currently compiling catalog ## Run `cd catalog` and `ls` to see catalog methods and instance variables ## Run `@resource_table` to see the current catalog resource table # if $stdout.isatty binding.pry # rubocop:disable Lint/Debugger else Puppet.warning 'pry(): cowardly refusing to start the debugger on a daemonized master' end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/pw_hash.rb0100644005276200011600000000534413212471613021600 0ustar00# Please note: This function is an implementation of a Ruby class 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. Puppet::Parser::Functions.newfunction( :pw_hash, :type => :rvalue, :arity => 3, :doc => "Hashes a password using the crypt function. Provides a hash usable on most POSIX systems. The first argument to this function is the password to hash. If it is undef or an empty string, this function returns undef. The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are: |Hash type |Specifier| |---------------------|---------| |MD5 |1 | |SHA-256 |5 | |SHA-512 (recommended)|6 | The third argument to this function is the salt to use. Note: this uses the Puppet Master's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function.", ) do |args| raise ArgumentError, "pw_hash(): wrong number of arguments (#{args.size} for 3)" if args.size != 3 args.map! do |arg| if (defined? Puppet::Pops::Types::PSensitiveType::Sensitive) && (arg.is_a? Puppet::Pops::Types::PSensitiveType::Sensitive) arg.unwrap else arg end end raise ArgumentError, 'pw_hash(): first argument must be a string' unless args[0].is_a?(String) || args[0].nil? raise ArgumentError, 'pw_hash(): second argument must be a string' unless args[1].is_a? String hashes = { 'md5' => '1', 'sha-256' => '5', 'sha-512' => '6' } hash_type = hashes[args[1].downcase] raise ArgumentError, "pw_hash(): #{args[1]} is not a valid hash type" if hash_type.nil? raise ArgumentError, 'pw_hash(): third argument must be a string' unless args[2].is_a? String raise ArgumentError, 'pw_hash(): third argument must not be empty' if args[2].empty? raise ArgumentError, 'pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]' unless args[2] =~ %r{\A[a-zA-Z0-9./]+\z} password = args[0] return nil if password.nil? || password.empty? salt = "$#{hash_type}$#{args[2]}" # handle weak implementations of String#crypt if 'test'.crypt('$1$1') != '$1$1$Bp8CU9Oujr9SSEw53WV6G.' # JRuby < 1.7.17 # MS Windows and other systems that don't support enhanced salts raise Puppet::ParseError, 'system does not support enhanced salts' unless RUBY_PLATFORM == 'java' # puppetserver bundles Apache Commons Codec org.apache.commons.codec.digest.Crypt.crypt(password.to_java_bytes, salt) else password.crypt(salt) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/range.rb0100644005276200011600000000415513212471613021242 0ustar00# # range.rb # # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... module Puppet::Parser::Functions newfunction(:range, :type => :rvalue, :doc => <<-DOC When given range in the form of (start, stop) it will extrapolate a range as an array. *Examples:* range("0", "9") Will return: [0,1,2,3,4,5,6,7,8,9] range("00", "09") Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to integers automatically) range("a", "c") Will return: ["a","b","c"] range("host01", "host10") Will return: ["host01", "host02", ..., "host09", "host10"] NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail. Passing a third argument will cause the generated range to step by that interval, e.g. range("0", "9", "2") Will return: [0,2,4,6,8] DOC ) do |arguments| raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.empty? if arguments.size > 1 start = arguments[0] stop = arguments[1] step = arguments[2].nil? ? 1 : arguments[2].to_i.abs type = '..' # Use the simplest type of Range available in Ruby else # arguments.size == 1 value = arguments[0] m = value.match(%r{^(\w+)(\.\.\.?|\-)(\w+)$}) if m start = m[1] stop = m[3] type = m[2] step = 1 elsif value =~ %r{^.+$} raise(Puppet::ParseError, "range(): Unable to compute range from the value: #{value}") else raise(Puppet::ParseError, "range(): Unknown range format: #{value}") end end # If we were given an integer, ensure we work with one if start.to_s =~ %r{^\d+$} start = start.to_i stop = stop.to_i else start = start.to_s stop = stop.to_s end range = case type when %r{^(..|-)$} then (start..stop) when '...' then (start...stop) # Exclusive of last element end result = range.step(step).to_a return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/regexpescape.rb0100644005276200011600000000165413252003272022616 0ustar00# # regexpescape.rb # module Puppet::Parser::Functions newfunction(:regexpescape, :type => :rvalue, :doc => <<-DOC Regexp escape a string or array of strings. Requires either a single string or an array as an input. DOC ) do |arguments| # rubocop:disable Layout/ClosingParenthesisIndentation raise(Puppet::ParseError, "regexpescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'regexpescape(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? Regexp.escape(i) : i } else Regexp.escape(value) end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/reject.rb0100644005276200011600000000114613212471613021417 0ustar00# # reject.rb # module Puppet::Parser::Functions newfunction(:reject, :type => :rvalue, :doc => <<-DOC) do |args| This function searches through an array and rejects all elements that match the provided regular expression. *Examples:* reject(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['bbb','ccc'] DOC if args.size != 2 raise Puppet::ParseError, "reject(): Wrong number of arguments given #{args.size} for 2" end ary = args[0] pattern = Regexp.new(args[1]) ary.reject { |e| e =~ pattern } end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/reverse.rb0100644005276200011600000000110013212471613021604 0ustar00# # reverse.rb # module Puppet::Parser::Functions newfunction(:reverse, :type => :rvalue, :doc => <<-DOC Reverses the order of a string or array. DOC ) do |arguments| raise(Puppet::ParseError, "reverse(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'reverse(): Requires either array or string to work with') end result = value.reverse return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/round.rb0100644005276200011600000000113213212471613021265 0ustar00# # round.rb # module Puppet::Parser::Functions newfunction(:round, :type => :rvalue, :doc => <<-DOC Rounds a number to the nearest integer *Examples:* round(2.9) returns: 3 round(2.4) returns: 2 DOC ) do |args| raise Puppet::ParseError, "round(): Wrong number of arguments given #{args.size} for 1" if args.size != 1 raise Puppet::ParseError, "round(): Expected a Numeric, got #{args[0].class}" unless args[0].is_a? Numeric value = args[0] if value >= 0 Integer(value + 0.5) else Integer(value - 0.5) end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/rstrip.rb0100644005276200011600000000131513212471613021464 0ustar00# # rstrip.rb # module Puppet::Parser::Functions newfunction(:rstrip, :type => :rvalue, :doc => <<-DOC Strips leading spaces to the right of the string. DOC ) do |arguments| raise(Puppet::ParseError, "rstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'rstrip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.rstrip : i } else value.rstrip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/seeded_rand.rb0100644005276200011600000000147513212471613022405 0ustar00# # seeded_rand.rb # Puppet::Parser::Functions.newfunction( :seeded_rand, :arity => 2, :type => :rvalue, :doc => <<-DOC Usage: `seeded_rand(MAX, SEED)`. MAX must be a positive integer; SEED is any string. Generates a random whole number greater than or equal to 0 and less than MAX, using the value of SEED for repeatable randomness. If SEED starts with "$fqdn:", this is behaves the same as `fqdn_rand`. DOC ) do |args| require 'digest/md5' raise(ArgumentError, 'seeded_rand(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 raise(ArgumentError, 'seeded_rand(): second argument must be a string') unless args[1].is_a? String max = args[0].to_i seed = Digest::MD5.hexdigest(args[1]).hex Puppet::Util.deterministic_rand(seed, max) end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/shell_escape.rb0100644005276200011600000000143213212471613022570 0ustar00require 'shellwords' # # shell_escape.rb # module Puppet::Parser::Functions newfunction(:shell_escape, :type => :rvalue, :doc => <<-DOC Escapes a string so that it can be safely used in a Bourne shell command line. Note that the resulting string should be used unquoted and is not intended for use in double quotes nor in single quotes. This function behaves the same as ruby's Shellwords.shellescape() function. DOC ) do |arguments| raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 # explicit conversion to string is required for ruby 1.9 string = arguments[0].to_s result = Shellwords.shellescape(string) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/shell_join.rb0100644005276200011600000000160113212471613022265 0ustar00 require 'shellwords' # # shell_join.rb # module Puppet::Parser::Functions newfunction(:shell_join, :type => :rvalue, :doc => <<-DOC Builds a command line string from the given array of strings. Each array item is escaped for Bourne shell. All items are then joined together, with a single space in between. This function behaves the same as ruby's Shellwords.shelljoin() function DOC ) do |arguments| raise(Puppet::ParseError, "shell_join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] raise Puppet::ParseError, "First argument is not an Array: #{array.inspect}" unless array.is_a?(Array) # explicit conversion to string is required for ruby 1.9 array = array.map { |item| item.to_s } result = Shellwords.shelljoin(array) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/shell_split.rb0100644005276200011600000000112413212471613022461 0ustar00require 'shellwords' # # shell_split.rb # module Puppet::Parser::Functions newfunction(:shell_split, :type => :rvalue, :doc => <<-DOC Splits a string into an array of tokens in the same way the Bourne shell does. This function behaves the same as ruby's Shellwords.shellsplit() function DOC ) do |arguments| raise(Puppet::ParseError, "shell_split(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 string = arguments[0].to_s result = Shellwords.shellsplit(string) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/shuffle.rb0100644005276200011600000000211213212471613021571 0ustar00# # shuffle.rb # module Puppet::Parser::Functions newfunction(:shuffle, :type => :rvalue, :doc => <<-DOC Randomizes the order of a string or array elements. DOC ) do |arguments| raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to shuffle ... return result if result.size <= 1 # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result elements = result.size # Simple implementation of Fisher–Yates in-place shuffle ... elements.times do |i| j = rand(elements - i) + i result[j], result[i] = result[i], result[j] end result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/size.rb0100644005276200011600000000233413212471613021115 0ustar00# # size.rb # module Puppet::Parser::Functions newfunction(:size, :type => :rvalue, :doc => <<-DOC Returns the number of elements in a string, an array or a hash DOC ) do |arguments| raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? item = arguments[0] function_deprecation([:size, 'This method is going to be deprecated, please use the stdlib length function.']) if item.is_a?(String) begin # # Check whether your item is a numeric value or not ... # This will take care about positive and/or negative numbers # for both integer and floating-point values ... # # Please note that Puppet has no notion of hexadecimal # nor octal numbers for its DSL at this point in time ... # Float(item) raise(Puppet::ParseError, 'size(): Requires either string, array or hash to work with') rescue ArgumentError result = item.size end elsif item.is_a?(Array) || item.is_a?(Hash) result = item.size else raise(Puppet::ParseError, 'size(): Unknown type given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/sort.rb0100644005276200011600000000133113212471613021126 0ustar00# # sort.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:sort, :type => :rvalue, :doc => <<-DOC Sorts strings and arrays lexically. DOC ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "sort(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] if value.is_a?(Array) value.sort elsif value.is_a?(String) value.split('').sort.join('') end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/squeeze.rb0100644005276200011600000000136713212471613021631 0ustar00# # squeeze.rb # module Puppet::Parser::Functions newfunction(:squeeze, :type => :rvalue, :doc => <<-DOC Returns a new string where runs of the same character that occur in this set are replaced by a single character. DOC ) do |arguments| if (arguments.size != 2) && (arguments.size != 1) raise(Puppet::ParseError, "squeeze(): Wrong number of arguments given #{arguments.size} for 2 or 1") end item = arguments[0] squeezeval = arguments[1] if item.is_a?(Array) if squeezeval item.map { |i| i.squeeze(squeezeval) } else item.map { |i| i.squeeze } end elsif squeezeval item.squeeze(squeezeval) else item.squeeze end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/str2bool.rb0100644005276200011600000000266213212471613021715 0ustar00# # str2bool.rb # module Puppet::Parser::Functions newfunction(:str2bool, :type => :rvalue, :doc => <<-DOC This converts a string to a boolean. This attempt to convert strings that contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things like: 0, F,f, N,n, false, FALSE, no to 'false'. DOC ) do |arguments| raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? string = arguments[0] # If string is already Boolean, return it if !!string == string # rubocop:disable Style/DoubleNegation : No viable alternative return string end unless string.is_a?(String) raise(Puppet::ParseError, 'str2bool(): Requires string to work with') end # We consider all the yes, no, y, n and so on too ... result = case string # # This is how undef looks like in Puppet ... # We yield false in this case. # when %r{^$}, '' then false # Empty string will be false ... when %r{^(1|t|y|true|yes)$}i then true when %r{^(0|f|n|false|no)$}i then false when %r{^(undef|undefined)$} then false # This is not likely to happen ... else raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/str2saltedsha512.rb0100644005276200011600000000235113212471613023155 0ustar00# # str2saltedsha512.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:str2saltedsha512, :type => :rvalue, :doc => <<-DOC This converts a string to a salted-SHA512 password hash (which is used for OS X versions >= 10.7). Given any simple string, you will get a hex version of a salted-SHA512 password hash that can be inserted into your Puppet manifests as a valid password attribute. DOC ) do |arguments| require 'digest/sha2' raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments passed (#{arguments.size} but we require 1)") if arguments.size != 1 password = arguments[0] unless password.is_a?(String) raise(Puppet::ParseError, "str2saltedsha512(): Requires a String argument, you passed: #{password.class}") end seedint = rand(2**31 - 1) seedstring = Array(seedint).pack('L') saltedpass = Digest::SHA512.digest(seedstring + password) (seedstring + saltedpass).unpack('H*')[0] end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/strftime.rb0100644005276200011600000000727113212471613022005 0ustar00# # strftime.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:strftime, :type => :rvalue, :doc => <<-DOC This function returns formatted time. *Examples:* To return the time since epoch: strftime("%s") To return the date: strftime("%Y-%m-%d") *Format meaning:* %a - The abbreviated weekday name (``Sun'') %A - The full weekday name (``Sunday'') %b - The abbreviated month name (``Jan'') %B - The full month name (``January'') %c - The preferred local date and time representation %C - Century (20 in 2009) %d - Day of the month (01..31) %D - Date (%m/%d/%y) %e - Day of the month, blank-padded ( 1..31) %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) %h - Equivalent to %b %H - Hour of the day, 24-hour clock (00..23) %I - Hour of the day, 12-hour clock (01..12) %j - Day of the year (001..366) %k - hour, 24-hour clock, blank-padded ( 0..23) %l - hour, 12-hour clock, blank-padded ( 0..12) %L - Millisecond of the second (000..999) %m - Month of the year (01..12) %M - Minute of the hour (00..59) %n - Newline (\n) %N - Fractional seconds digits, default is 9 digits (nanosecond) %3N millisecond (3 digits) %6N microsecond (6 digits) %9N nanosecond (9 digits) %p - Meridian indicator (``AM'' or ``PM'') %P - Meridian indicator (``am'' or ``pm'') %r - time, 12-hour (same as %I:%M:%S %p) %R - time, 24-hour (%H:%M) %s - Number of seconds since 1970-01-01 00:00:00 UTC. %S - Second of the minute (00..60) %t - Tab character (\t) %T - time, 24-hour (%H:%M:%S) %u - Day of the week as a decimal, Monday being 1. (1..7) %U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) %v - VMS date (%e-%b-%Y) %V - Week number of year according to ISO 8601 (01..53) %W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53) %w - Day of the week (Sunday is 0, 0..6) %x - Preferred representation for the date alone, no time %X - Preferred representation for the time alone, no date %y - Year without a century (00..99) %Y - Year with century %z - Time zone as hour offset from UTC (e.g. +0900) %Z - Time zone name %% - Literal ``%'' character DOC ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "strftime(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? format = arguments[0] raise(Puppet::ParseError, 'strftime(): You must provide format for evaluation') if format.empty? # The Time Zone argument is optional ... time_zone = arguments[1] if arguments[1] time = Time.new # There is probably a better way to handle Time Zone ... if time_zone && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone time = local_time.localtime ENV['TZ'] = original_zone end result = time.strftime(format) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/strip.rb0100644005276200011600000000151513212471613021304 0ustar00# # strip.rb # module Puppet::Parser::Functions newfunction(:strip, :type => :rvalue, :doc => <<-DOC This function removes leading and trailing whitespace from a string or from every string inside an array. *Examples:* strip(" aaa ") Would result in: "aaa" DOC ) do |arguments| raise(Puppet::ParseError, "strip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'strip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.strip : i } else value.strip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/suffix.rb0100644005276200011600000000262413212471613021451 0ustar00# # suffix.rb # module Puppet::Parser::Functions newfunction(:suffix, :type => :rvalue, :doc => <<-DOC This function applies a suffix to all elements in an array, or to the keys in a hash. *Examples:* suffix(['a','b','c'], 'p') Will return: ['ap','bp','cp'] DOC ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "suffix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "suffix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a? String raise Puppet::ParseError, "suffix(): expected second argument to be a String, got #{suffix.inspect}" end end result = if enumerable.is_a?(Array) # Turn everything into string same as join would do ... enumerable.map do |i| i = i.to_s suffix ? i + suffix : i end else Hash[enumerable.map do |k, v| k = k.to_s [suffix ? k + suffix : k, v] end] end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/swapcase.rb0100644005276200011600000000214613212471613021752 0ustar00# # swapcase.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:swapcase, :type => :rvalue, :doc => <<-DOC This function will swap the existing case of a string. *Examples:* swapcase("aBcD") Would result in: "AbCd" DOC ) do |arguments| raise(Puppet::ParseError, "swapcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'swapcase(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? i.swapcase : i } else value.swapcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/time.rb0100644005276200011600000000211113212471613021072 0ustar00# # time.rb # module Puppet::Parser::Functions newfunction(:time, :type => :rvalue, :doc => <<-DOC This function will return the current time since epoch as an integer. *Examples:* time() Will return something like: 1311972653 DOC ) do |arguments| # The Time Zone argument is optional ... time_zone = arguments[0] if arguments[0] if !arguments.empty? && (arguments.size != 1) raise(Puppet::ParseError, "time(): Wrong number of arguments given #{arguments.size} for 0 or 1") end time = Time.new # There is probably a better way to handle Time Zone ... if time_zone && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone result = local_time.localtime.strftime('%s') ENV['TZ'] = original_zone else result = time.localtime.strftime('%s') end # Calling Time#to_i on a receiver changes it. Trust me I am the Doctor. result = result.to_i return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/to_bytes.rb0100644005276200011600000000213613212471613021773 0ustar00# # to_bytes.rb # module Puppet::Parser::Functions newfunction(:to_bytes, :type => :rvalue, :doc => <<-DOC Converts the argument into bytes, for example 4 kB becomes 4096. Takes a single string value as an argument. These conversions reflect a layperson's understanding of 1 MB = 1024 KB, when in fact 1 MB = 1000 KB, and 1 MiB = 1024 KiB. DOC ) do |arguments| raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] return arg if arg.is_a? Numeric value, prefix = *%r{([0-9.e+-]*)\s*([^bB]?)}.match(arg)[1, 2] value = value.to_f case prefix when '' then return value.to_i when 'k' then return (value * (1 << 10)).to_i when 'M' then return (value * (1 << 20)).to_i when 'G' then return (value * (1 << 30)).to_i when 'T' then return (value * (1 << 40)).to_i when 'P' then return (value * (1 << 50)).to_i when 'E' then return (value * (1 << 60)).to_i else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/try_get_value.rb0100644005276200011600000000321113212471613023007 0ustar00# # try_get_value.rb # module Puppet::Parser::Functions newfunction( :try_get_value, :type => :rvalue, :arity => -2, :doc => <<-DOC DEPRECATED: this function is deprecated, please use dig() instead. Looks up into a complex structure of arrays and hashes and returns a value or the default value if nothing was found. Key can contain slashes to describe path components. The function will go down the structure and try to extract the required value. $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = try_get_value($data, 'a/b/2', 'not_found', '/') => $value = 'b3' a -> first hash key b -> second hash key 2 -> array index starting with 0 not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. / -> (optional) path delimiter. Defaults to '/'. In addition to the required "key" argument, "try_get_value" accepts default argument. It will be returned if no value was found or a path component is missing. And the fourth argument can set a variable path separator. DOC ) do |args| warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.') data = args[0] path = args[1] || '' default = args[2] if !(data.is_a?(Hash) || data.is_a?(Array)) || path == '' return default || data end separator = args[3] || '/' path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key } function_dig([data, path, default]) end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/type.rb0100644005276200011600000000142513212471613021124 0ustar00# # type.rb # module Puppet::Parser::Functions newfunction(:type, :type => :rvalue, :doc => <<-DOC DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system. DOC ) do |args| warning("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : Cannot reduce line length unless Puppet::Parser::Functions.autoloader.loaded?(:type3x) Puppet::Parser::Functions.autoloader.load(:type3x) end function_type3x(args) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/type3x.rb0100644005276200011600000000240313212471613021374 0ustar00# # type3x.rb # module Puppet::Parser::Functions newfunction(:type3x, :type => :rvalue, :doc => <<-DOC DEPRECATED: This function will be removed when puppet 3 support is dropped; please migrate to the new parser's typing system. Returns the type when passed a value. Type can be one of: * string * array * hash * float * integer * boolean DOC ) do |args| raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") unless args.size == 1 value = args[0] klass = value.class unless [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) # rubocop:disable Lint/UnifiedInteger raise(Puppet::ParseError, 'type3x(): Unknown type') end klass = klass.to_s # Ugly ... # We note that Integer is the parent to Bignum and Fixnum ... result = case klass when %r{^(?:Big|Fix)num$} then 'integer' when %r{^(?:True|False)Class$} then 'boolean' else klass end if result == 'String' if value == value.to_i.to_s result = 'Integer' elsif value == value.to_f.to_s result = 'Float' end end return result.downcase end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/union.rb0100644005276200011600000000126113212471613021271 0ustar00# # union.rb # module Puppet::Parser::Functions newfunction(:union, :type => :rvalue, :doc => <<-DOC This function returns a union of two or more arrays. *Examples:* union(["a","b","c"],["b","c","d"]) Would return: ["a","b","c","d"] DOC ) do |arguments| # Check that 2 or more arguments have been given ... raise(Puppet::ParseError, "union(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 arguments.each do |argument| raise(Puppet::ParseError, 'union(): Every parameter must be an array') unless argument.is_a?(Array) end arguments.reduce(:|) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/unique.rb0100644005276200011600000000245613212471613021456 0ustar00# # unique.rb # module Puppet::Parser::Functions newfunction(:unique, :type => :rvalue, :doc => <<-DOC This function will remove duplicates from strings and arrays. *Examples:* unique("aabbcc") Will return: abc You can also use this with arrays: unique(["a","a","b","b","c","c"]) This returns: ["a","b","c"] DOC ) do |arguments| if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 function_deprecation([:unique, 'This method is deprecated, please use the core puppet unique function. There is further documentation for the function in the release notes of Puppet 5.0.']) end raise(Puppet::ParseError, "unique(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'unique(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result result = result.uniq # Remove duplicates ... result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/unix2dos.rb0100644005276200011600000000071013212471613021712 0ustar00# Custom Puppet function to convert unix to dos format module Puppet::Parser::Functions newfunction(:unix2dos, :type => :rvalue, :arity => 1, :doc => <<-DOC Returns the DOS version of the given string. Takes a single string argument. DOC ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'unix2dos(): Requires string as argument') end arguments[0].gsub(%r{\r*\n}, "\r\n") end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/upcase.rb0100644005276200011600000000237413212471613021427 0ustar00# # upcase.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:upcase, :type => :rvalue, :doc => <<-DOC Converts a string or an array of strings to uppercase. *Examples:* upcase("abcd") Will return: ABCD DOC ) do |arguments| raise(Puppet::ParseError, "upcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.respond_to?(:upcase) raise(Puppet::ParseError, 'upcase(): Requires an array, hash or object that responds to upcase in order to work') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.map { |i| function_upcase([i]) } elsif value.is_a?(Hash) result = {} value.each_pair do |k, v| result[function_upcase([k])] = function_upcase([v]) end else result = value.upcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/uriescape.rb0100644005276200011600000000214513252003272022117 0ustar00require 'uri' # # uriescape.rb # Please note: This function is an implementation of a Ruby class 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. # module Puppet::Parser::Functions newfunction(:uriescape, :type => :rvalue, :doc => <<-DOC Urlencodes a string or array of strings. Requires either a single string or an array as an input. DOC ) do |arguments| raise(Puppet::ParseError, "uriescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'uriescape(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? URI.escape(i) : i } else URI.escape(value) end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_absolute_path.rb0100644005276200011600000000352413212471613024650 0ustar00# # validate_absolute_path.rb # module Puppet::Parser::Functions newfunction(:validate_absolute_path, :doc => <<-'DOC') do |args| Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. The following values will pass: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' validate_absolute_path($my_path) $my_path2 = '/var/lib/puppet' validate_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet'] validate_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet','/usr/share/puppet'] validate_absolute_path($my_path4) The following values will fail, causing compilation to abort: validate_absolute_path(true) validate_absolute_path('../var/lib/puppet') validate_absolute_path('var/lib/puppet') validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = undef validate_absolute_path($undefined) DOC require 'puppet/util' if args.empty? raise Puppet::ParseError, "validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # put arg to candidate var to be able to replace it candidates = arg # if arg is just a string with a path to test, convert it to an array # to avoid test code duplication unless arg.is_a?(Array) candidates = Array.new(1, arg) end # iterate over all paths within the candidates array candidates.each do |path| unless function_is_absolute_path([path]) raise Puppet::ParseError, "#{path.inspect} is not an absolute path." end end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_array.rb0100644005276200011600000000212013212471613023123 0ustar00# # validate_array.rb # module Puppet::Parser::Functions newfunction(:validate_array, :doc => <<-'DOC') do |args| Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_array = [ 'one', 'two' ] validate_array($my_array) The following values will fail, causing compilation to abort: validate_array(true) validate_array('some_string') $undefined = undef validate_array($undefined) DOC function_deprecation([:validate_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_array(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Array) raise Puppet::ParseError, "#{arg.inspect} is not an Array. It looks to be a #{arg.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_augeas.rb0100644005276200011600000000534613212471613023267 0ustar00require 'tempfile' # # validate_augaes.rb # module Puppet::Parser::Functions newfunction(:validate_augeas, :doc => <<-'DOC') do |args| Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. For example, if you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) Or if you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') DOC unless Puppet.features.augeas? raise Puppet::ParseError, 'validate_augeas(): this function requires the augeas feature. See http://docs.puppetlabs.com/guides/augeas.html#pre-requisites for how to activate it.' end if (args.length < 2) || (args.length > 4) raise Puppet::ParseError, "validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)" end msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" require 'augeas' aug = Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) begin content = args[0] # Test content in a temporary file tmpfile = Tempfile.new('validate_augeas') begin tmpfile.write(content) ensure tmpfile.close end # Check for syntax lens = args[1] aug.transform( :lens => lens, :name => 'Validate_augeas', :incl => tmpfile.path, ) aug.load! unless aug.match("/augeas/files#{tmpfile.path}//error").empty? error = aug.get("/augeas/files#{tmpfile.path}//error/message") msg += " with error: #{error}" raise Puppet::ParseError, msg end # Launch unit tests tests = args[2] || [] aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" raise Puppet::ParseError, msg unless aug.match(t).empty? end ensure aug.close tmpfile.unlink end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_bool.rb0100644005276200011600000000161213212471613022745 0ustar00# # validate_bool.rb # module Puppet::Parser::Functions newfunction(:validate_bool, :doc => <<-'DOC') do |args| Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. The following values will pass: $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) The following values will fail, causing compilation to abort: $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) DOC if args.empty? raise Puppet::ParseError, "validate_bool(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless function_is_bool([arg]) raise Puppet::ParseError, "#{arg.inspect} is not a boolean. It looks to be a #{arg.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_cmd.rb0100644005276200011600000000435513212471613022564 0ustar00require 'puppet/util/execution' require 'tempfile' # # validate_cmd.rb # module Puppet::Parser::Functions newfunction(:validate_cmd, :doc => <<-'DOC') do |args| Perform validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a % as a placeholder for the file path (will default to the end). If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: Example: # Defaults to end of path validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') # % as file location validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') DOC if (args.length < 2) || (args.length > 3) raise Puppet::ParseError, "validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)" end msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}" content = args[0] checkscript = args[1] # Test content in a temporary file tmpfile = Tempfile.new('validate_cmd') begin tmpfile.write(content) tmpfile.close check_with_correct_location = if checkscript =~ %r{\s%(\s|$)} checkscript.gsub(%r{%}, tmpfile.path) else "#{checkscript} #{tmpfile.path}" end if Puppet::Util::Execution.respond_to?('execute') Puppet::Util::Execution.execute(check_with_correct_location) else Puppet::Util.execute(check_with_correct_location) end rescue Puppet::ExecutionFailure => detail msg += "\n#{detail}" raise Puppet::ParseError, msg rescue StandardError => detail msg += "\n#{detail.class.name} #{detail}" raise Puppet::ParseError, msg ensure tmpfile.unlink end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_domain_name.rb0100644005276200011600000000252413212471613024264 0ustar00# # validate_domain_name.rb # module Puppet::Parser::Functions newfunction(:validate_domain_name, :doc => <<-DOC Validate that all values passed are syntactically correct domain names. Fail compilation if any value fails this check. The following values will pass: $my_domain_name = 'server.domain.tld' validate_domain_name($my_domain_name) validate_domain_name('domain.tld', 'puppet.com', $my_domain_name) The following values will fail, causing compilation to abort: validate_domain_name(1) validate_domain_name(true) validate_domain_name('invalid domain') validate_domain_name('-foo.example.com') validate_domain_name('www.example.2com') DOC ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_domain_name(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" unless function_is_domain_name([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_email_address.rb0100644005276200011600000000223413212471613024607 0ustar00# # validate_email_address.rb # module Puppet::Parser::Functions newfunction(:validate_email_address, :doc => <<-DOC Validate that all values passed are valid email addresses. Fail compilation if any value fails this check. The following values will pass: $my_email = "waldo@gmail.com" validate_email_address($my_email) validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email) The following values will fail, causing compilation to abort: $some_array = [ 'bad_email@/d/efdf.com' ] validate_email_address($some_array) DOC ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_email_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" unless function_is_email_address([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_hash.rb0100644005276200011600000000212713212471613022737 0ustar00# # validate_hash.rb # module Puppet::Parser::Functions newfunction(:validate_hash, :doc => <<-'DOC') do |args| Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_hash = { 'one' => 'two' } validate_hash($my_hash) The following values will fail, causing compilation to abort: validate_hash(true) validate_hash('some_string') $undefined = undef validate_hash($undefined) DOC function_deprecation([:validate_hash, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_hash(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Hash) raise Puppet::ParseError, "#{arg.inspect} is not a Hash. It looks to be a #{arg.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_integer.rb0100644005276200011600000001235613212471613023456 0ustar00# # validate_interger.rb # module Puppet::Parser::Functions newfunction(:validate_integer, :doc => <<-'DOC') do |args| Validate that the first argument is an integer (or an array of integers). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not an integer or array of integers, and if arg 2 and arg 3 are not convertable to an integer. The following values will pass: validate_integer(1) validate_integer(1, 2) validate_integer(1, 1) validate_integer(1, 2, 0) validate_integer(2, 2, 2) validate_integer(2, '', 0) validate_integer(2, undef, 0) $foo = undef validate_integer(2, $foo, 0) validate_integer([1,2,3,4,5], 6) validate_integer([1,2,3,4,5], 6, 0) Plus all of the above, but any combination of values passed as strings ('1' or "1"). Plus all of the above, but with (correct) combinations of negative integer values. The following values will not: validate_integer(true) validate_integer(false) validate_integer(7.0) validate_integer({ 1 => 2 }) $foo = undef validate_integer($foo) validate_integer($foobaridontexist) validate_integer(1, 0) validate_integer(1, true) validate_integer(1, '') validate_integer(1, undef) validate_integer(1, , 0) validate_integer(1, 2, 3) validate_integer(1, 3, 2) validate_integer(1, 3, true) Plus all of the above, but any combination of values passed as strings ('false' or "false"). Plus all of the above, but with incorrect combinations of negative integer values. Plus all of the above, but with non-integer items in arrays or maximum / minimum argument. DOC function_deprecation([:validate_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters raise Puppet::ParseError, "validate_integer(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args # check maximum parameter if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set if args.length > 2 && max == '' max = nil else begin max = Integer(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected second argument to be unset or an Integer, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Integer(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected third argument to be unset or an Integer, got #{min}:#{min.class}" end else min = nil end # ensure that min < max if min && max && min > max raise Puppet::ParseError, "validate_integer(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function validator = ->(num) do # check input < max if max && num > max raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) if min && num < min raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Integer(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected element at array position #{pos} to be an Integer, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Integer(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_ip_address.rb0100644005276200011600000000337213212471613024134 0ustar00# # validate_ip_address.rb # module Puppet::Parser::Functions newfunction(:validate_ip_address, :doc => <<-DOC Validate that all values passed are valid IP addresses, regardless they are IPv4 or IPv6 Fail compilation if any value fails this check. The following values will pass: $my_ip = "1.2.3.4" validate_ip_address($my_ip) validate_ip_address("8.8.8.8", "172.16.0.1", $my_ip) $my_ip = "3ffe:505:2" validate_ip_address(1) validate_ip_address($my_ip) validate_ip_address("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ip_address($some_array) DOC ) do |args| require 'ipaddr' rescuable_exceptions = [ArgumentError] function_deprecation([:validate_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv4? || IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_ipv4_address.rb0100644005276200011600000000307313212471613024404 0ustar00# # validate_ipv4_address.rb # module Puppet::Parser::Functions newfunction(:validate_ipv4_address, :doc => <<-DOC Validate that all values passed are valid IPv4 addresses. Fail compilation if any value fails this check. The following values will pass: $my_ip = "1.2.3.4" validate_ipv4_address($my_ip) validate_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ipv4_address($some_array) DOC ) do |args| function_deprecation([:validate_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv4? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_ipv6_address.rb0100644005276200011600000000312113212471613024400 0ustar00# # validate_ipv7_address.rb # module Puppet::Parser::Functions newfunction(:validate_ipv6_address, :doc => <<-DOC Validate that all values passed are valid IPv6 addresses. Fail compilation if any value fails this check. The following values will pass: $my_ip = "3ffe:505:2" validate_ipv6_address(1) validate_ipv6_address($my_ip) validate_bool("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ true, false, "garbage string", "1.2.3.4" ] validate_ipv6_address($some_array) DOC ) do |args| function_deprecation([:validate_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_numeric.rb0100644005276200011600000001011413212471613023451 0ustar00# # validate_numeric.rb # module Puppet::Parser::Functions newfunction(:validate_numeric, :doc => <<-'DOC') do |args| Validate that the first argument is a numeric value (or an array of numeric values). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not a numeric (Integer or Float) or array of numerics, and if arg 2 and arg 3 are not convertable to a numeric. For passing and failing usage, see `validate_integer()`. It is all the same for validate_numeric, yet now floating point values are allowed, too. DOC function_deprecation([:validate_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters raise Puppet::ParseError, "validate_numeric(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args # check maximum parameter if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set if args.length > 2 && max == '' max = nil else begin max = Float(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected second argument to be unset or a Numeric, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Float(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected third argument to be unset or a Numeric, got #{min}:#{min.class}" end else min = nil end # ensure that min < max if min && max && min > max raise Puppet::ParseError, "validate_numeric(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function validator = ->(num) do # check input < max if max && num > max raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) if min && num < min raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Float(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected element at array position #{pos} to be a Numeric, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be a Numeric or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Float(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected first argument to be a Numeric or Array, got #{input.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_re.rb0100644005276200011600000000413513212471613022423 0ustar00# # validate.rb # module Puppet::Parser::Functions newfunction(:validate_re, :doc => <<-'DOC') do |args| Perform simple validation of a string against one or more regular expressions. The first argument of this function should be a string to test, and the second argument should be a stringified regular expression (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. The following strings will validate against the regular expressions: validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) The following strings will fail to validate, causing compilation to abort: validate_re('one', [ '^two', '^three' ]) A helpful error message can be returned like this: validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') Note: Compilation will also abort, if the first argument is not a String. Always use quotes to force stringification: validate_re("${::operatingsystemmajrelease}", '^[57]$') DOC function_deprecation([:validate_re, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Re. There is further documentation for validate_legacy function in the README.']) if (args.length < 2) || (args.length > 3) raise Puppet::ParseError, "validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)" end raise Puppet::ParseError, "validate_re(): input needs to be a String, not a #{args[0].class}" unless args[0].is_a? String msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" # We're using a flattened array here because we can't call String#any? in # Ruby 1.9 like we can in Ruby 1.8 raise Puppet::ParseError, msg unless [args[1]].flatten.any? do |re_str| args[0] =~ Regexp.compile(re_str) end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_slength.rb0100644005276200011600000000537413212471613023467 0ustar00# # validate_slength.rb # module Puppet::Parser::Functions newfunction(:validate_slength, :doc => <<-'DOC') do |args| Validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. An optional third parameter can be given the minimum length. It fails if the first argument is not a string or array of strings, and if arg 2 and arg 3 are not convertable to a number. The following values will pass: validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) validate_slength(["discombobulate","moo"],17,3) The following valueis will not: validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) validate_slength(["discombobulate","moo"],17,10) DOC function_deprecation([:validate_slength, 'This method is deprecated, please use the stdlib validate_legacy function, with String[]. There is further documentation for validate_legacy function in the README.']) raise Puppet::ParseError, "validate_slength(): Wrong number of arguments (#{args.length}; must be 2 or 3)" unless args.length == 2 || args.length == 3 input, max_length, min_length = *args begin max_length = Integer(max_length) raise ArgumentError if max_length <= 0 rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected second argument to be a positive Numeric, got #{max_length}:#{max_length.class}" end if min_length begin min_length = Integer(min_length) raise ArgumentError if min_length < 0 rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected third argument to be unset or a positive Numeric, got #{min_length}:#{min_length.class}" end else min_length = 0 end raise Puppet::ParseError, 'validate_slength(): Expected second argument to be equal to or larger than third argument' unless max_length >= min_length validator = ->(str) do unless str.length <= max_length && str.length >= min_length raise Puppet::ParseError, "validate_slength(): Expected length of #{input.inspect} to be between #{min_length} and #{max_length}, was #{input.length}" end end case input when String validator.call(input) when Array input.each_with_index do |arg, pos| raise Puppet::ParseError, "validate_slength(): Expected element at array position #{pos} to be a String, got #{arg.class}" unless arg.is_a? String validator.call(arg) end else raise Puppet::ParseError, "validate_slength(): Expected first argument to be a String or Array, got #{input.class}" end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_string.rb0100644005276200011600000000253013212471613023320 0ustar00# # validate_String.rb # module Puppet::Parser::Functions newfunction(:validate_string, :doc => <<-'DOC') do |args| Validate that all passed values are string data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_string = "one two" validate_string($my_string, 'three') The following values will fail, causing compilation to abort: validate_string(true) validate_string([ 'some', 'array' ]) Note: validate_string(undef) will not fail in this version of the functions API (incl. current and future parser). Instead, use: if $var == undef { fail('...') } DOC function_deprecation([:validate_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) if args.empty? raise Puppet::ParseError, "validate_string(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # when called through the v4 API shim, undef gets translated to nil unless arg.is_a?(String) || arg.nil? raise Puppet::ParseError, "#{arg.inspect} is not a string. It looks to be a #{arg.class}" end end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb0100644005276200011600000000242413212471613025251 0ustar00# # validate_x509_rsa_key_pair.rb # module Puppet::Parser::Functions newfunction(:validate_x509_rsa_key_pair, :doc => <<-DOC Validates a PEM-formatted X.509 certificate and RSA private key using OpenSSL. Verifies that the certficate's signature was created from the supplied key. Fail compilation if any value fails this check. validate_x509_rsa_key_pair($cert, $key) DOC ) do |args| require 'openssl' NUM_ARGS = 2 unless defined? NUM_ARGS unless args.length == NUM_ARGS raise Puppet::ParseError, "validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end end begin cert = OpenSSL::X509::Certificate.new(args[0]) rescue OpenSSL::X509::CertificateError => e raise Puppet::ParseError, "Not a valid x509 certificate: #{e}" end begin key = OpenSSL::PKey::RSA.new(args[1]) rescue OpenSSL::PKey::RSAError => e raise Puppet::ParseError, "Not a valid RSA key: #{e}" end unless cert.verify(key) raise Puppet::ParseError, 'Certificate signature does not match supplied key' end end end puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/values.rb0100644005276200011600000000133313212471613021440 0ustar00# # values.rb # module Puppet::Parser::Functions newfunction(:values, :type => :rvalue, :doc => <<-DOC When given a hash this function will return the values of that hash. *Examples:* $hash = { 'a' => 1, 'b' => 2, 'c' => 3, } values($hash) This example would return: [1,2,3] DOC ) do |arguments| raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'values(): Requires hash to work with') end result = hash.values return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/values_at.rb0100644005276200011600000000512613212471613022130 0ustar00# # values_at.rb # module Puppet::Parser::Functions newfunction(:values_at, :type => :rvalue, :doc => <<-DOC Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above *Examples*: values_at(['a','b','c'], 2) Would return ['c']. values_at(['a','b','c'], ["0-1"]) Would return ['a','b']. values_at(['a','b','c','d','e'], [0, "2-3"]) Would return ['a','c','d']. DOC ) do |arguments| raise(Puppet::ParseError, "values_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments.shift unless array.is_a?(Array) raise(Puppet::ParseError, 'values_at(): Requires array to work with') end indices = [arguments.shift].flatten # Get them all ... Pokemon ... if !indices || indices.empty? raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect') end indices_list = [] indices.each do |i| i = i.to_s m = i.match(%r{^(\d+)(\.\.\.?|\-)(\d+)$}) if m start = m[1].to_i stop = m[3].to_i type = m[2] raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index') if start > stop raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size') if stop > array.size - 1 # First element is at index 0 is it not? range = case type when %r{^(\.\.|\-)$} then (start..stop) when %r{^(\.\.\.)$} then (start...stop) # Exclusive of last element ... end range.each { |i| indices_list << i.to_i } # rubocop:disable Lint/ShadowingOuterLocalVariable : Value is meant to be shadowed else # Only positive numbers allowed in this case ... unless i =~ %r{^\d+$} raise(Puppet::ParseError, 'values_at(): Unknown format of given index') end # In Puppet numbers are often string-encoded ... i = i.to_i if i > array.size - 1 # Same story. First element is at index 0 ... raise(Puppet::ParseError, 'values_at(): Given index exceeds array size') end indices_list << i end end # We remove nil values as they make no sense in Puppet DSL ... result = indices_list.map { |i| array[i] }.compact return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/parser/functions/zip.rb0100644005276200011600000000175413212471613020752 0ustar00# # zip.rb # module Puppet::Parser::Functions newfunction(:zip, :type => :rvalue, :doc => <<-DOC Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. *Example:* zip(['1','2','3'],['4','5','6']) Would result in: ["1", "4"], ["2", "5"], ["3", "6"] DOC ) do |arguments| # Technically we support three arguments but only first is mandatory ... raise(Puppet::ParseError, "zip(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 a = arguments[0] b = arguments[1] unless a.is_a?(Array) && b.is_a?(Array) raise(Puppet::ParseError, 'zip(): Requires array to work with') end flatten = function_str2bool([arguments[2]]) if arguments[2] result = a.zip(b) result = flatten ? result.flatten : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.25.0/lib/puppet/provider0040755005276200011600000000000013252003413016057 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/provider/file_line0040755005276200011600000000000013252003413020005 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/provider/file_line/ruby.rb0100644005276200011600000001153113212471613021377 0ustar00Puppet::Type.type(:file_line).provide(:ruby) do def exists? found = false lines_count = 0 lines.each do |line| found = line.chomp == resource[:line] if found lines_count += 1 end end return found = lines_count > 0 if resource[:match].nil? match_count = count_matches(new_match_regex) found = if resource[:ensure] == :present if match_count.zero? if lines_count.zero? && resource[:append_on_no_match].to_s == 'false' true # lies, but gets the job done elsif lines_count.zero? && resource[:append_on_no_match].to_s != 'false' false else true end elsif resource[:replace_all_matches_not_matching_line].to_s == 'true' false # maybe lies, but knows there's still work to do elsif lines_count.zero? resource[:replace].to_s == 'false' else true end elsif match_count.zero? if lines_count.zero? false else true end elsif lines_count.zero? resource[:match_for_absence].to_s == 'true' else true end end def create return if resource[:replace].to_s != 'true' && count_matches(new_match_regex) > 0 if resource[:match] handle_create_with_match elsif resource[:after] handle_create_with_after else handle_append_line end end def destroy if resource[:match_for_absence].to_s == 'true' && resource[:match] handle_destroy_with_match else handle_destroy_line end end private def lines # If this type is ever used with very large files, we should # write this in a different way, using a temp # file; for now assuming that this type is only used on # small-ish config files that can fit into memory without # too much trouble. @lines ||= File.readlines(resource[:path], :encoding => resource[:encoding]) rescue TypeError => _e # Ruby 1.8 doesn't support open_args @lines ||= File.readlines(resource[:path]) end def new_after_regex resource[:after] ? Regexp.new(resource[:after]) : nil end def new_match_regex resource[:match] ? Regexp.new(resource[:match]) : nil end def count_matches(regex) lines.select { |line| if resource[:replace_all_matches_not_matching_line].to_s == 'true' line.match(regex) unless line.chomp == resource[:line] else line.match(regex) end }.size end def handle_create_with_match after_regex = new_after_regex match_regex = new_match_regex match_count = count_matches(new_match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(match_regex.match(line) ? resource[:line] : line) next unless match_count.zero? && after_regex if after_regex.match(line) fh.puts(resource[:line]) match_count += 1 # Increment match_count to indicate that the new line has been inserted. end end if match_count.zero? fh.puts(resource[:line]) end end end def handle_create_with_after after_regex = new_after_regex after_count = count_matches(after_regex) if after_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "#{after_count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(line) if after_regex.match(line) fh.puts(resource[:line]) end end if after_count.zero? fh.puts(resource[:line]) end end end def handle_destroy_with_match match_regex = new_match_regex match_count = count_matches(match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end local_lines = lines File.open(resource[:path], 'w') do |fh| fh.write(local_lines.reject { |line| match_regex.match(line) }.join('')) end end def handle_destroy_line local_lines = lines File.open(resource[:path], 'w') do |fh| fh.write(local_lines.reject { |line| line.chomp == resource[:line] }.join('')) end end def handle_append_line local_lines = lines File.open(resource[:path], 'w') do |fh| local_lines.each do |line| fh.puts(line) end fh.puts(resource[:line]) end end end puppetlabs-stdlib-4.25.0/lib/puppet/type0040755005276200011600000000000013252003413015206 5ustar00puppetlabs-stdlib-4.25.0/lib/puppet/type/anchor.rb0100644005276200011600000000325213212471613017072 0ustar00Puppet::Type.newtype(:anchor) do desc <<-'DESCRIPTION' A simple resource type intended to be used as an anchor in a composite class. In Puppet 2.6, when a class declares another class, the resources in the interior class are not contained by the exterior class. This interacts badly with the pattern of composing complex modules from smaller classes, as it makes it impossible for end users to specify order relationships between the exterior class and other modules. The anchor type lets you work around this. By sandwiching any interior classes between two no-op resources that _are_ contained by the exterior class, you can ensure that all resources in the module are contained. class ntp { # These classes will have the correct order relationship with each # other. However, without anchors, they won't have any order # relationship to Class['ntp']. class { 'ntp::package': } -> class { 'ntp::config': } -> class { 'ntp::service': } # These two resources "anchor" the composed classes within the ntp # class. anchor { 'ntp::begin': } -> Class['ntp::package'] Class['ntp::service'] -> anchor { 'ntp::end': } } This allows the end user of the ntp module to establish require and before relationships with Class['ntp']: class { 'ntp': } -> class { 'mcollective': } class { 'mcollective': } -> class { 'ntp': } DESCRIPTION newparam :name do desc 'The name of the anchor resource.' end def refresh # We don't do anything with them, but we need this to # show that we are "refresh aware" and not break the # chain of propagation. end end puppetlabs-stdlib-4.25.0/lib/puppet/type/file_line.rb0100644005276200011600000001541113212471613017546 0ustar00Puppet::Type.newtype(:file_line) do desc <<-DOC Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will append the line to the end of the file to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. Example: file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } In this example, Puppet will ensure both of the specified lines are contained in the file /etc/sudoers. Match Example: file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', } In this code example match will look for a line beginning with export followed by HTTP_PROXY and replace it with the value in line. Examples With `ensure => absent`: This type has two behaviors when `ensure => absent` is set. One possibility is to set `match => ...` and `match_for_absence => true`, as in the following example: file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } In this code example match will look for a line beginning with export followed by HTTP_PROXY and delete it. If multiple lines match, an error will be raised unless the `multiple => true` parameter is set. Note that the `line => ...` parameter would be accepted BUT IGNORED in the above example. The second way of using `ensure => absent` is to specify a `line => ...`, and no match: file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', } Note that when ensuring lines are absent this way, the default behavior this time is to always remove all lines matching, and this behavior can't be disabled. Encoding example: file_line { "XScreenSaver": ensure => present, path => '/root/XScreenSaver', line => "*lock: 10:00:00", match => '^*lock:', encoding => "iso-8859-1", } Files with special characters that are not valid UTF-8 will give the error message "invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify the correct encoding using the encoding attribute, the value of which needs to be a valid Ruby character encoding. **Autorequires:** If Puppet is managing the file that will contain the line being managed, the file_line resource will autorequire that file. DOC ensurable do defaultvalues defaultto :present end newparam(:name, :namevar => true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:match) do desc 'An optional ruby regular expression to run against existing lines in the file.' \ ' If a match is found, we replace that line rather than adding a new line.' \ ' A regex comparison is performed against the line value and if it does not' \ ' match an exception will be raised.' end newparam(:match_for_absence) do desc 'An optional value to determine if match should be applied when ensure => absent.' \ ' If set to true and match is set, the line that matches match will be deleted.' \ ' If set to false (the default), match is ignored when ensure => absent.' \ ' When `ensure => present`, match_for_absence is ignored.' newvalues(true, false) defaultto false end newparam(:multiple) do desc 'An optional value to determine if match can change multiple lines.' \ ' If set to false, an exception will be raised if more than one line matches' newvalues(true, false) end newparam(:after) do desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)' \ ' This is also takes a regex.' end # The line property never changes; the type only ever performs a create() or # destroy(). line is a property in order to allow it to correctly handle # Sensitive type values. Because it is a property which will never change, # it should never be considered out of sync. newproperty(:line) do desc 'The line to be appended to the file or used to replace matches found by the match attribute.' def retrieve @resource[:line] end end newparam(:path) do desc 'The file Puppet will ensure contains the line specified by the line parameter.' validate do |value| unless Puppet::Util.absolute_path?(value) raise Puppet::Error, "File paths must be fully qualified, not '#{value}'" end end end newparam(:replace) do desc 'If true, replace line that matches. If false, do not write line if a match is found' newvalues(true, false) defaultto true end newparam(:replace_all_matches_not_matching_line) do desc 'Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file.' newvalues(true, false) defaultto false end newparam(:encoding) do desc 'For files that are not UTF-8 encoded, specify encoding such as iso-8859-1' defaultto 'UTF-8' end newparam(:append_on_no_match) do desc 'If true, append line if match is not found. If false, do not append line if a match is not found' newvalues(true, false) defaultto true end # Autorequire the file resource if it's being managed autorequire(:file) do self[:path] end validate do if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:multiple].to_s == 'false' raise(Puppet::Error, 'multiple must be true when replace_all_matches_not_matching_line is true') end if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:replace].to_s == 'false' raise(Puppet::Error, 'replace must be true when replace_all_matches_not_matching_line is true') end unless self[:line] unless (self[:ensure].to_s == 'absent') && (self[:match_for_absence].to_s == 'true') && self[:match] raise(Puppet::Error, 'line is a required attribute') end end unless self[:path] raise(Puppet::Error, 'path is a required attribute') end end end puppetlabs-stdlib-4.25.0/locales0040755005276200011600000000000013252003413013564 5ustar00puppetlabs-stdlib-4.25.0/locales/config.yaml0100644005276200011600000000204413206047630016001 0ustar00--- # This is the project-specific configuration file for setting up # fast_gettext for your project. gettext: # This is used for the name of the .pot and .po files; they will be # called .pot? project_name: puppetlabs-stdlib # This is used in comments in the .pot and .po files to indicate what # project the files belong to and should bea little more desctiptive than # package_name: puppetlabs-stdlib # The locale that the default messages in the .pot file are in default_locale: en # The email used for sending bug reports. bugs_address: docs@puppet.com # The holder of the copyright. copyright_holder: Puppet, Inc. # This determines which comments in code should be eligible for translation. # Any comments that start with this string will be externalized. (Leave # empty to include all.) comments_tag: TRANSLATOR # Patterns for +Dir.glob+ used to find all files that might contain # translatable content, relative to the project root directory source_files: - './lib/**/*.rb' puppetlabs-stdlib-4.25.0/locales/ja0040755005276200011600000000000013252003413014156 5ustar00puppetlabs-stdlib-4.25.0/locales/ja/puppetlabs-stdlib.po0100644005276200011600000000150113206047630020235 0ustar00# #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-03-21 14:19+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: 梅田智世 , 2017\n" "Language-Team: Japanese (Japan) (https://www.transifex.com/puppet/teams/29089/ja_JP/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ja_JP\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Translate Toolkit 2.0.0\n" #. metadata.json #: .summary msgid "Standard library of resources for Puppet modules." msgstr "Puppet モジュールのリソースの標準ライブラリ" #. metadata.json #: .description msgid "Standard Library for Puppet Modules" msgstr "Puppet モジュールの標準ライブラリ" puppetlabs-stdlib-4.25.0/locales/puppetlabs-stdlib.pot0100644005276200011600000000113013206047630020025 0ustar00#, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-03-21 14:19+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Translate Toolkit 2.0.0\n" #. metadata.json #: .summary msgid "Standard library of resources for Puppet modules." msgstr "" #. metadata.json #: .description msgid "Standard Library for Puppet Modules" msgstr "" puppetlabs-stdlib-4.25.0/manifests0040755005276200011600000000000013252003413014133 5ustar00puppetlabs-stdlib-4.25.0/manifests/init.pp0100644005276200011600000000061613206047630015526 0ustar00# Class: stdlib # # This module manages stdlib. Most of stdlib's features are automatically # loaded by Puppet, but this class should be declared in order to use the # standardized run stages. # # Parameters: none # # Actions: # # Declares all other classes in the stdlib module. Currently, this consists # of stdlib::stages. # # Requires: nothing # class stdlib { include ::stdlib::stages } puppetlabs-stdlib-4.25.0/manifests/stages.pp0100644005276200011600000000153513206047630016052 0ustar00# Class: stdlib::stages # # This class manages a standard set of run stages for Puppet. It is managed by # the stdlib class, and should not be declared independently. # # The high level stages are (in order): # # * setup # * main # * runtime # * setup_infra # * deploy_infra # * setup_app # * deploy_app # * deploy # # Parameters: none # # Actions: # # Declares various run-stages for deploying infrastructure, # language runtimes, and application layers. # # Requires: nothing # # Sample Usage: # # node default { # include ::stdlib # class { java: stage => 'runtime' } # } # class stdlib::stages { stage { 'setup': before => Stage['main'] } stage { 'runtime': require => Stage['main'] } -> stage { 'setup_infra': } -> stage { 'deploy_infra': } -> stage { 'setup_app': } -> stage { 'deploy_app': } -> stage { 'deploy': } } puppetlabs-stdlib-4.25.0/metadata.json0100644005276200011600000000415713252003413014700 0ustar00{ "name": "puppetlabs-stdlib", "version": "4.25.0", "author": "puppetlabs", "summary": "Standard library of resources for Puppet modules.", "license": "Apache-2.0", "source": "https://github.com/puppetlabs/puppetlabs-stdlib", "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", "issues_url": "https://tickets.puppetlabs.com/browse/MODULES", "dependencies": [ ], "data_provider": null, "operatingsystem_support": [ { "operatingsystem": "RedHat", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "CentOS", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "OracleLinux", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "Scientific", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "SLES", "operatingsystemrelease": [ "11 SP1", "12" ] }, { "operatingsystem": "Debian", "operatingsystemrelease": [ "7", "8", "9" ] }, { "operatingsystem": "Ubuntu", "operatingsystemrelease": [ "14.04", "16.04" ] }, { "operatingsystem": "Solaris", "operatingsystemrelease": [ "10", "11" ] }, { "operatingsystem": "Windows", "operatingsystemrelease": [ "Server 2008", "Server 2008 R2", "Server 2012", "Server 2012 R2", "Server 2016", "7", "8", "10" ] }, { "operatingsystem": "AIX", "operatingsystemrelease": [ "5.3", "6.1", "7.1" ] } ], "requirements": [ { "name": "puppet", "version_requirement": ">=2.7.20 < 6.0.0" } ], "description": "Standard Library for Puppet Modules", "pdk-version": "1.4.1", "template-url": "file:///opt/puppetlabs/pdk/share/cache/pdk-templates.git", "template-ref": "1.4.1-0-g52adbbb" } puppetlabs-stdlib-4.25.0/readmes0040755005276200011600000000000013252003413013562 5ustar00puppetlabs-stdlib-4.25.0/readmes/README_ja_JP.md0100644005276200011600000026703413206047630016204 0ustar00# stdlib #### 目次 1. [モジュールの説明 - モジュールの機能とその有益性](#モジュールの説明) 1. [セットアップ - stdlib導入の基本](#セットアップ) 1. [使用 - 設定オプションと追加機能](#使用方法) 1. [リファレンス - モジュールの機能と動作について](#参考) 1. [クラス](#クラス) 1. [定義タイプ](#定義タイプ) 1. [データタイプ](#データタイプ) 1. [Facts](#facts) 1. [関数](#関数) 1. [制約 - OS互換性など](#制約) 1. [開発 - モジュール貢献についてのガイド](#開発) 1. [コントリビュータ](#コントリビュータ) ## モジュールの説明 このモジュールでは、Puppetモジュールリソースの標準ライブラリを提供しています。Puppetモジュールでは、この標準ライブラリを広く使用しています。stdlibモジュールは、以下のリソースをPuppetに追加します。 * ステージ * Facts * 関数 * 定義タイプ * データタイプ * プロバイダ > *注:* バージョン3.7のPuppet Enterpriseには、stdlibモジュールが含まれていません。Puppet Enterpriseを使用している場合は、Puppetと互換性のあるstdlibの最新リリースをインストールする必要があります。 ## セットアップ stdlibモジュールを[インストール](https://docs.puppet.com/puppet/latest/modules_installing.html)し、この標準ライブラリの関数、Facts、リソースをPuppetに追加します。 stdlibに依存するモジュールを記述する場合は、必ずmetadata.jsonで[依存関係を特定](https://docs.puppet.com/puppet/latest/modules_metadata.html#specifying-dependencies)してください。 ## 使用方法 stdlibのほとんどの機能は、Puppetに自動的にロードされます。Puppetで標準化されたランステージを使用するには、`include stdlib`を用いてマニフェスト内でこのクラスを宣言してください。 宣言すると、stdlibがモジュール内の他のすべてのクラスを宣言します。現在モジュールに含まれている他のクラスは、`stdlib::stages`のみです。 `stdlib::stages`クラスは、インフラストラクチャ、言語ランタイム、アプリケーションレイヤの配備に関する各種のランステージを宣言します。ハイレベルステージは、以下のとおりです(順番どおり)。 * setup * main * runtime * setup_infra * deploy_infra * setup_app * deploy_app * deploy 使用例: ```puppet node default { include stdlib class { java: stage => 'runtime' } } ``` ## リファレンス * [パブリッククラス](#パブリッククラス) * [プライベートクラス](#プライベートクラス) * [定義タイプ](#定義タイプ) * [データタイプ](#データタイプ) * [Facts](#facts) * [関数](#関数) ### クラス #### パブリッククラス `stdlib`クラスにはパラメータはありません。 #### プライベートクラス * `stdlib::stages`: Puppetのランステージの標準セットを管理します。 ### 定義タイプ #### `file_line` 任意の行がファイル内に確実に含まれるようにします。最初と最後の空白を含め、行全体をマッチさせます。その行が与えられたファイルに含まれない場合は、Puppetがファイルの最後にその行を追加し、望ましい状態を確保します。1つのファイル内で複数のリソースを宣言し、複数の行を管理することが可能です。 例: ```puppet file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } ``` 上の例では、指定された両方の行が、ファイル `/etc/sudoers`に確実に含まれます。 マッチ例: ```puppet file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', } ``` 上の例では、`match`により、'export'で始まり'HTTP_PROXY'と続く行が探され、その行が行内の値に置き換えられます。 マッチ例: ```puppet file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', append_on_no_match => false, } ``` このコードの例では、`match`によってexportで始まり'HTTP_PROXY'が続く行が検索され、その行が行内の値に置き換えられます。マッチするものが見つからない場合、ファイルは変更されません。 `ensure => absent`の例: `ensure => absent`を設定する場合に、このタイプの動作には2通りがあります。 1つは`match => ...`と`match_for_absence => true`の設定です。`match`により、'export'で始まり'HTTP_PROXY'と続く行が探され、その行が削除されます。複数の行がマッチし、`multiple => true`パラメータが設定されていない場合は、エラーが生じます。 この例で`line => ...`パラメータは承認されますが無視されます。 例: ```puppet file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } ``` `ensure => absent`を設定する場合のもう1つの動作は、`line => ...`の指定と一致なしです。行が存在しないことを確認した場合のデフォルトの動作では、マッチするすべての行を削除します。この動作を無効にすることはできません。 例: ```puppet file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', } ``` エンコード例: ```puppet file_line { "XScreenSaver": ensure => present, path => '/root/XScreenSaver' line => "*lock: 10:00:00", match => '^*lock:', encoding => "iso-8859-1", } ``` ファイルにUTF-8に対応しない特殊文字が用いられていると、「Invalid byte sequence in UTF-8」(UTF-8で無効なバイト列)というエラーメッセージが表示されます。この場合は、ファイルエンコーディングを決定し、`encoding`属性で指定してください。 **Autorequire:** Puppetが管理しているファイルに、管理対象となる行が含まれている場合は、`file_line`リソースと当該ファイルの暗黙的な依存関係が設定されます。 **パラメータ** パラメータは、別途説明がない限り、すべてオプションです。 ##### `after` このパラメータで指定された行の後に、Puppetが正規表現を用いて新規の行を追加します(既存の行が規定の位置に追加されます)。 値: 正規表現を含む文字列 デフォルト値: `undef` ##### `encoding` 適正なファイルエンコードを指定します。 値: 有効なRuby文字エンコードを指定する文字列 デフォルト: 'UTF-8' ##### `ensure`: リソースが存在するかどうかを指定します。 値: 'present'、'absent' デフォルト値: 'present' ##### `line` **必須** `path`パラメータにより位置を示されたファイルに追加する行を設定します。 値: 文字列 ##### `match` ファイル内の既存の行と比較する正規表現を指定します。マッチが見つかった場合、新規の行を追加する代わりに、置き換えられます。 値: 正規表現を含む文字列 デフォルト値: `undef` ##### `match_for_absence` `ensure => absent`の場合にマッチを適用するかどうかを指定します。`true`に設定してマッチを設定すると、マッチする行が削除されます。`false`に設定すると(デフォルト)、`ensure => absent`の場合にマッチが無視され、代わりに`line`の値が使用されます。`ensure => present`になっている場合は、このパラメータは無視されます。 ブーリアン デフォルト値: `false` ##### `multiple` `match`および`after`により複数の行を変更できるかどうかを指定します。`false`に設定すると、file_lineは1つの行のみ置き換えることができますが、複数の行を置き換えようとするとエラーが発生します。`true`に設定すると、file_lineは1つまたは複数の行を置き換えることができます。 値: `true`、`false` デフォルト値: `false` ##### `name` リソースの名称として使用する名前を指定します。リソースのnamevarをリソースの規定の`title`と異なるものにしたい場合は、`name`で名前を指定します。 値: 文字列 デフォルト値: タイトルの値 ##### `path` **必須** `line`で指定された行を確保するファイルを指定します。 値: 当該ファイルの絶対パスを指定する文字列 ##### `replace` `match`パラメータとマッチする既存の行をリソースで上書きするかどうかを指定します。`false`に設定すると、`match`パラメータにマッチする行が見つかった場合、その行はファイルに配置されません。 `false`に設定すると、`match`パラメータにマッチする行が見つかった場合、その行はファイルに配置されません。 ブーリアン デフォルト値: `true` ##### `replace_all_matches_not_matching_line` `line`がファイルにすでに存在する場合でも、`match`パラメータに一致するすべての行が置き換えられます。 デフォルト値: `false` ### データタイプ #### `Stdlib::Absolutepath` 厳密な絶対パスタイプ。UnixpathタイプおよびWindowspathタイプの異形を使用します。 使用可能なインプット例: ```shell /var/log ``` ```shell /usr2/username/bin:/usr/local/bin:/usr/bin:. ``` ```shell C:\\WINDOWS\\System32 ``` 使用不可能なインプット例: ```shell ../relative_path ``` #### `Stdlib::Ensure::Service` サービスリソースの使用可能なensure値と一致します。 使用可能なインプット例: ```shell 停止済み 実行中 ``` 使用不可能なインプット例: ```shell true false ``` #### `Stdlib::Httpsurl` HTTPS URLに一致します。 使用可能なインプット例: ```shell https://hello.com ``` 使用不可能なインプット例: ```shell httds://notquiteright.org` ``` #### `Stdlib::Httpurl` HTTPSおよびHTTP URLの両方に一致します。 使用可能なインプット例: ```shell https://hello.com http://hello.com ``` 使用不可能なインプット例: ```shell httds://notquiteright.org ``` #### `Stdlib::MAC` [RFC5342](https://tools.ietf.org/html/rfc5342)で定義されるMACアドレスに一致します。 #### `Stdlib::Unixpath` Unixオペレーティングシステムのパスに一致します。 使用可能なインプット例: ```shell /usr2/username/bin:/usr/local/bin:/usr/bin: /var/tmp ``` 使用不可能なインプット例: ```shell C:/whatever ``` #### `Stdlib::Filemode` 8進数で有効な4桁モードと一致します。 使用可能なインプット例: ```shell 0644 ``` ```shell 1777 ``` 使用不可能なインプット例: ```shell 644 ``` ```shell 0999 ``` #### `Stdlib::Windowspath` Windowsオペレーティングシステムのパスに一致します。 使用可能なインプット例: ```shell C:\\WINDOWS\\System32 C:\\ \\\\host\\windows ``` 使用不可能なインプット例: ```shell /usr2/username/bin:/usr/local/bin:/usr/bin:. ``` ### Facts #### `package_provider` Puppetがこのシステムのパッケージ管理に使用するデフォルトのプロバイダを返します。 #### `is_pe` Puppet Enterpriseがインストールされているかどうかを返します。PE 3.x以降のプラットフォームでは何も報告されません。 #### `pe_version` インストールされているPuppet Enterpriseのバージョンを返します。PE 3.x以降のプラットフォームでは何も報告されません。 #### `pe_major_version` インストールされているPuppet Enterpriseのメジャーバージョンを返します。PE 3.x以降のプラットフォームでは何も報告されません。 #### `pe_minor_version` インストールされているPuppet Enterpriseのマイナーバージョンを返します。PE 3.x以降のプラットフォームでは何も報告されません。 #### `pe_patch_version` インストールされているPuppet Enterpriseのパッチバージョンを返します。 #### `puppet_vardir` PuppetまたはPuppet agentが稼働しているノードについて設定されたPuppet vardirの値を返します。 #### `puppet_environmentpath` PuppetまたはPuppet agentが稼働しているノードについて設定されたPuppet環境の値を返します。 #### `puppet_server` Puppet agentの`server`値を返します。この値は、agentが通信するPuppet masterのホストネームです。 #### `root_home` ルートのホームディレクトリを決定します。 ルートのホームディレクトリを決定します。これは、オペレーティングシステムによって異なります。通常は'/root'です。 #### `service_provider` Puppetがこのシステムのサービス管理に使用するデフォルトのプロバイダを返します。 ### 関数 #### `abs` 数字の絶対値を返します。たとえば、'-34.56'は'34.56'になります。 引数: 整数値または浮動小数点値のいずれかの単一の引数。 *タイプ*: 右辺値 #### `any2array` 任意のオブジェクトを、そのオブジェクトを含む配列に変換します。空の引数リストは空の配列に変換されます。ハッシュは、キーと値が交互になった配列に変換されます。配列は変換されません。 *タイプ*: 右辺値 #### `any2bool` 任意のオブジェクトをブーリアンに変換します。 * 'Y'、'y'、'1'、'T'、't'、'TRUE'、'yes'、'true'といった文字列は`true`を返します。 * '0'、'F'、'f'、'N'、'n'、'FALSE'、'no'、'false'といった文字列は`false`を返します。 * ブーリアンは元の値を返します。 * 0よりも大きい数字(または数字の文字列表現)は`true`を返します。それ以外は`false`を返します。 * undef値は`false`を返します。 * それ以外はすべて`true`を返します。 *タイプ*: 右辺値 #### `assert_private` 現在のクラスまたは定義をプライベートとして設定します。現在のモジュール外のクラスまたは定義タイプを呼び出すことはできません。 たとえば、クラス`foo::bar`で`assert_private()`がコールされると、クラスがモジュール`foo`の外から呼び出された場合、次のメッセージがアウトプットされます:`Class foo::bar is private`。 使用したいエラーメッセージを指定する方法: ```puppet assert_private("You're not supposed to do that!") ``` *タイプ*: ステートメント #### `base64` 文字列とbase64エンコードを相互に変換します。`action` ('encode'、'decode')とプレーンまたは base64でエンコードした`string`、およびオプションで`method` ('default'、'strict'、'urlsafe')が必要です。 下位互換性を得るには、`method`を`default`に設定します(指定されていない場合)。 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 **例:** ```puppet base64('encode', 'hello') base64('encode', 'hello', 'default') # リターン: "aGVsbG8=\n" base64('encode', 'hello', 'strict') # リターン: "aGVsbG8=" base64('decode', 'aGVsbG8=') base64('decode', 'aGVsbG8=\n') base64('decode', 'aGVsbG8=', 'default') base64('decode', 'aGVsbG8=\n', 'default') base64('decode', 'aGVsbG8=', 'strict') # リターン: "hello" base64('encode', 'https://puppetlabs.com', 'urlsafe') # リターン: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==" base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe') # リターン: "https://puppetlabs.com" ``` *タイプ*: 右辺値 #### `basename` パスの`basename`を返します。オプションの引数で拡張子が外れます。例: * ('/path/to/a/file.ext')は'file.ext'を返します。 * ('relative/path/file.ext')は'file.ext'を返します。 * ('/path/to/a/file.ext', '.ext')は'file'を返します。 *タイプ*: 右辺値 #### `bool2num` ブーリアンを数字に変換します。以下の値を変換します。 * `false`、'f'、'0'、'n'、'no'を0に変換します。 * `true`、't'、'1'、'y'、'yes'を1に変換します。 引数: インプットとして、単一のブーリアンまたは文字列。 *タイプ*: 右辺値 #### `bool2str` オプションで提供される引数を用いて、ブーリアンを文字列に変換します。オプションの第2および第3の引数は、trueおよびfalseがそれぞれ何に変換されるかを表しています。与えられた引数が1つだけの場合は、ブーリアンから`true`または`false`を含む文字列に変換されます。 *例:* ```puppet bool2str(true) => `true` bool2str(true, 'yes', 'no') => 'yes' bool2str(false, 't', 'f') => 'f' ``` 引数: ブーリアン。 *タイプ*: 右辺値 #### `camelcase` 配列内の1つの文字列またはすべての文字列の大文字と小文字の別をCamelCase(大小文字混在)に変換します。 引数: 配列または文字列のいずれか。受け取ったものと同じタイプの引数を返しますが、CamelCaseの形式で返します。 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 *タイプ*: 右辺値 #### `capitalize` 文字列または複数文字列の配列の最初の文字を大文字にし、各文字列の残りの文字を小文字にします。 引数: インプットとして、単一文字列または配列。*タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `ceiling` 引数以上の最小整数を返します。 引数: 単一の数値。 *タイプ*: 右辺値 #### `chomp` 文字列または複数文字列の配列の最後から、レコード分離文字を削除します。たとえば、'hello\n'は'hello'になります。 引数: 単一の文字または配列。 *タイプ*: 右辺値 #### `chop` 最後の文字を削除した新しい文字列を返します。文字列が'\r\n'で終わる場合は、両方の文字が削除されます。`chop`を空文字列に適用すると、空文字列が返されます。レコード分離文字のみを削除する場合は、`chomp`関数を使用してください。 引数: インプットとして、文字列または複数文字列の配列。 *タイプ*: 右辺値 #### `clamp` 整数値に基づく分類により、当該領域[Min、X、Max]内で値を維持します(パラメータの順序は関係ありません)。文字列が変換され、数字として比較されます。値の配列は、さらなる処理が可能なリストに平坦化されます。例: * `clamp('24', [575, 187])`は187を返します。 * `clamp(16, 88, 661)`は88を返します。 * `clamp([4, 3, '99'])`は4を返します。 引数: 文字列、配列、数字。 *タイプ*: 右辺値 #### `concat` 複数配列のコンテンツを、与えられた最初の配列に追加します。例: * `concat(['1','2','3'],'4')`は['1','2','3','4']を返します。 * `concat(['1','2','3'],'4',['5','6','7'])`は['1','2','3','4','5','6','7']を返します。 *タイプ*: 右辺値 #### `convert_base` 与えられた整数または整数を表す10進数文字列を、指定した基数の文字列に変換します。例: * `convert_base(5, 2)`は'101'になります。 * `convert_base('254', '16')`は'fe'になります。 #### `count` 配列のみで呼び出した場合は、空または`undef`**ではない**要素の数をカウントします。第2の引数を用いて呼び出した場合は、第2の引数にマッチする配列内の要素の数をカウントします。 *タイプ*: 右辺値 #### `deep_merge` 2つ以上のハッシュを再帰的に統合し、その結果得られたハッシュを返します。 ```puppet $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) ``` 得られるハッシュは、以下に相当します。 ```puppet $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } ``` ハッシュである重複キーが存在する場合は、そうした重複キーが再帰的に統合されます。ハッシュではない重複キーが存在する場合は、最右のハッシュのキーが上位になります。 *タイプ*: 右辺値 #### `defined_with_params` 属性のリソースリファレンスとオプションでハッシュを取得します。特定の属性を持つリソースがすでにカタログに追加されている場合は`true`を返します。そうでない場合は`false`を返します。 ```puppet user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } ``` *タイプ*: 右辺値 #### `delete` 配列から任意の要素のインスタンスを、文字列からサブストリングを、またはハッシュからキーをすべて削除します。 例: * `delete(['a','b','c','b'], 'b')`は['a','c']を返します。 * `delete('abracadabra', 'bra')`は'acada'を返します。 * `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])`は{'a'=> 1}を返します。 * `delete(['ab', 'b'], 'b')`は['ab']を返します。 *タイプ*: 右辺値 #### `delete_at` 決められたインデックス付き値を配列から削除します。 例: `delete_at(['a','b','c'], 1)`は['a','c']を返します。 *タイプ*: 右辺値 #### `delete_regex` 提示された正規表現にマッチする任意の要素のインスタンスを、配列またはハッシュからすべて削除します。文字列は1アイテム配列として処理されます。 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 例 * `delete_regex(['a','b','c','b'], 'b')`は['a','c']を返します。 * `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])`は{'a'=> 1}を返します。 * `delete_regex(['abf', 'ab', 'ac'], '^ab.*')`は['ac']を返します。 * `delete_regex(['ab', 'b'], 'b')`は['ab']を返します。 *タイプ*: 右辺値 #### `delete_values` 任意の値のインスタンスをハッシュからすべて削除します。 例: * `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')`は{'a'=>'A','c'=>'C','B'=>'D'}を返します。 *タイプ*: 右辺値 #### `delete_undef_values` `undef`値のインスタンスをアレイまたはハッシュからすべて削除します。 例: * `$hash = delete_undef_values({a=>'A', b=>'', c=>`undef`, d => false})`は{a => 'A', b => '', d => false}を返します。 *タイプ*: 右辺値 #### `deprecation` 非推奨警告をプリントし、任意のキーについて警告を一度記録します: ```puppet deprecation(key, message) ``` 引数: * キーを指定する文字列: Puppetプロセスの継続期間中にメッセージの数を少なく抑えるために、1つのキーにつき1つのメッセージのみを記録します。 * メッセージを指定する文字列: 記録されるテキスト。 *タイプ*: ステートメント **`deprecation`に影響を与える設定** Puppetの他の設定は、stdlibの`deprecation`関数に影響を与えます。 * [`disable_warnings`](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings) * [`max_deprecations`](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations) * [`strict`](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict): * `error`: 非推奨メッセージにより、ただちに機能しなくなります。 * `off`: メッセージがアウトプットされません。 * `warning`: すべての警告を記録します。これがデフォルト設定です。 * 環境変数`STDLIB_LOG_DEPRECATIONS` 非推奨警告を記録するかどうかを指定します。これは特に、自動テストの際、移行の準備ができる前にログに情報が氾濫するのを避けるうえで役立ちます。 この変数はブーリアンで、以下の効果があります: * `true`: 警告を記録します。 * `false`: 警告は記録されません。 * 値を設定しない場合: Puppet 4は警告を出しますが、Puppet 3は出しません。 #### `difference` 2つの配列の間の差異を返します。返される配列はオリジナル配列のコピーで、第2の配列にも見られるアイテムがあれば、それが取り除かれます。 例: * `difference(["a","b","c"],["b","c","d"])`は["a"]を返します。 *タイプ*: 右辺値 #### `dig` > 非推奨: この関数は、Puppet 4.5.0で、内蔵の[`dig`](https://docs.puppet.com/puppet/latest/function.html#dig)関数に置き換えられました。下位互換性を得るには、[`dig44()`](#dig44)を使用するか、新しいバージョンを使用してください。 パスを含むキー配列を通じて、複数レイヤーのハッシュおよびアレイ内の値を探します。この関数は各パスコンポーネントにより構造内を移動し、パスの最後で値を返すよう試みます。 この関数では、必要とされるパス引数に加え、デフォルトの引数を使用できます。パスが正しくない場合や、値が見つからない場合、その他のエラーが生じた場合は、デフォルトの引数を返します。 ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig($data, ['a', 'b', 2]) # $value = 'b3' # 可能なすべてのオプションを使用 $value = dig($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # デフォルト値を使用 $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` 1. **$data** 取り扱うデータ構造。 2. **['a', 'b', 2]** パス配列。 3. **'not_found'** デフォルト値。何も見つからない場合に返されます。 デフォルト値: `undef` *タイプ*: 右辺値 #### `dig44` パスを含むキー配列を通じて、複数レイヤーのハッシュおよびアレイ内の値を探します。この関数は各パスコンポーネントにより構造内を移動し、パスの最後で値を返すよう試みます。 この関数では、必要とされるパス引数に加え、デフォルトの引数を使用できます。パスが正しくない場合や、値が見つからない場合、その他のエラーが生じた場合は、デフォルトの引数を返します。 ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig44($data, ['a', 'b', 2]) # $value = 'b3' # 可能なすべてのオプションを使用 $value = dig44($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # デフォルト値を使用 $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` *タイプ*: 右辺値 1. **$data** 取り扱うデータ構造。 2. **['a', 'b', 2]** パス配列。 3. **'not_found'** デフォルト値。何も見つからない場合に返されます。 (オプション、デフォルトは`undef`) #### `dirname` パスの`dirname`を返します。たとえば、`dirname('/path/to/a/file.ext')`は'/path/to/a'を返します。 *タイプ*: 右辺値 #### `dos2unix` 与えられた文字列のUnixバージョンを返します。クロスプラットフォームテンプレートでファイルリソースを使用する場合に非常に役立ちます。 ```puppet file { $config_file: ensure => file, content => dos2unix(template('my_module/settings.conf.erb')), } ``` [unix2dos](#unix2dos)も参照してください。 *タイプ*: 右辺値 #### `downcase` 配列内の1つの文字列またはすべての文字列の大文字と小文字の別を、小文字に変換します。 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 *タイプ*: 右辺値 #### `empty` 引数が要素を含まない配列かハッシュ、または空文字列である場合に、`true`を返します。引数が数値の場合に`false`を返します。 *タイプ*: 右辺値 #### `enclose_ipv6` IPアドレスの配列を取得し、ipv6アドレスを大括弧でくくります。 *タイプ*: 右辺値 #### `ensure_packages` 配列またはハッシュ内のパッケージのリストを取得し、すでに存在しない場合にのみ、それらをインストールします。オプションで、ハッシュを第2のパラメータとして取得し、第3の引数として`ensure_resource()`または `ensure_resources()`関数に渡します。 *タイプ*: ステートメント 配列の場合: ```puppet ensure_packages(['ksh','openssl'], {'ensure' => 'present'}) ``` ハッシュの場合: ```puppet ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'}) ``` #### `ensure_resource` リソースタイプ、タイトル、リソースを記述する属性のハッシュを取得します。 ``` user { 'dan': ensure => present, } ``` この例では、すでに存在しない場合にのみリソースが作成されます: `ensure_resource('user', 'dan', {'ensure' => 'present' })` リソースがすでに存在しているものの、指定されたパラメータとマッチしない場合は、リソースの再作成が試みられ、重複リソース定義エラーにつながります。 リソースの配列を提示することも可能です。それぞれのリソースは、すでに存在しない場合に、指定のタイプおよびパラメータにより作成されます。 `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})` *タイプ*: ステートメント #### `ensure_resources` ハッシュからリソース宣言を作成しますが、すでに宣言されているリソースとは対立しません。 リソースタイプ、タイトル、リソースを記述する属性のハッシュを指定します。 ```puppet user { 'dan': gid => 'mygroup', ensure => present, } ensure_resources($user) ``` リソースのハッシュを提示します。リストにあるリソースは、すでに存在しない場合に、指定のタイプおよびパラメータにより作成されます。 ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) Hieraバックエンドから: ```yaml userlist: dan: gid: 'mygroup' uid: '600' alex: gid: 'mygroup' ``` ```puppet ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) ``` #### `fact` 指定されたfactの値を返します。構造化されたfactを参照する場合にドット表記を使用することができます。指定されたfactが存在しない場合は、Undefを返します。 使用例: ```puppet fact('kernel') fact('osfamily') fact('os.architecture') ``` 配列のインデックス: ```puppet $first_processor = fact('processors.models.0') $second_processor = fact('processors.models.1') ``` 名前に「.」を含むfact: ```puppet fact('vmware."VRA.version"') ``` #### `flatten` ネストの深いアレイを平坦化し、結果として単一のフラット配列を返します。 たとえば、`flatten(['a', ['b', ['c']]])`は['a','b','c']を返します。 *タイプ*: 右辺値 #### `floor` 引数以下の最大整数を返します。 引数: 単一の数値。 *タイプ*: 右辺値 #### `fqdn_rand_string` ランダムな英数字文字列を生成します。`$fqdn` factとオプションのシードを組み合わせると、反復的な無作為抽出が可能です。オプションで、この関数に使用する文字セットを指定することもできます(デフォルトは英数字)。 *使用例:* ```puppet fqdn_rand_string(LENGTH, [CHARSET], [SEED]) ``` *例:* ```puppet fqdn_rand_string(10) fqdn_rand_string(10, 'ABCDEF!@#$%^') fqdn_rand_string(10, '', 'custom seed') ``` 引数: * 整数、得られる文字列の長さを指定。 * オプションで、文字セットを指定する文字列。 * オプションで、反復的な無作為抽出を可能にするシードを指定する文字列。 *タイプ*: 右辺値 #### `fqdn_rotate` 配列と文字列をランダムな回数で回転させます。`$fqdn` factとオプションのシードを組み合わせると、反復的な無作為抽出が可能です。 *使用例:* ```puppet fqdn_rotate(VALUE, [SEED]) ``` *例:* ```puppet fqdn_rotate(['a', 'b', 'c', 'd']) fqdn_rotate('abcd') fqdn_rotate([1, 2, 3], 'custom seed') ``` *タイプ*: 右辺値 #### `fqdn_uuid` DNSネームスペースのFQDN文字列をもとに、[RFC 4122](https://tools.ietf.org/html/rfc4122)有効バージョン5 UUIDを返します: * fqdn_uuid('puppetlabs.com')は'9c70320f-6815-5fc5-ab0f-debe68bf764c'を返します。 * fqdn_uuid('google.com')は'64ee70a4-8cc1-5d25-abf2-dea6c79a09c8'を返します。 *タイプ*: 右辺値 #### `get_module_path` 現在の環境について、指定されたモジュールの絶対パスを返します。 ```puppet $module_path = get_module_path('stdlib') ``` *タイプ*: 右辺値 #### `getparam` リソースのパラメータの値を返します。 引数: リソースリファレンスおよびパラメータの名前。 たとえば、以下の場合は'param_value'を返します: ```puppet define example_resource($param) { } example_resource { "example_resource_instance": param => "param_value" } getparam(Example_resource["example_resource_instance"], "param") ``` *タイプ*: 右辺値 #### `getvar` リモートネームスペースの変数を調べます。 例: ```puppet $foo = getvar('site::data::foo') # $foo = $site::data::fooに相当 ``` この関数は、ネームスペースそのものが文字列に保存されている場合に役立ちます: ```puppet $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # $bar = $site::data::barに相当 ``` *タイプ*: 右辺値 #### `glob` パスパターンに一致するパスの文字列配列を返します。 引数: パスパターンを指定する文字列または文字列配列。 ```puppet $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf']) ``` *タイプ*: 右辺値 #### `grep` 配列内を検索し、提示された正規表現に一致する要素を返します。 たとえば、`grep(['aaa','bbb','ccc','aaaddd'], 'aaa')`は['aaa','aaaddd']を返します。 *タイプ*: 右辺値 #### `has_interface_with` 種類および値に基づきブーリアンを返します: * macaddress * netmask * ipaddress * network *例:* ```puppet has_interface_with("macaddress", "x:x:x:x:x:x") has_interface_with("ipaddress", "127.0.0.1") => true ``` 種類が提示されていない場合は、インターフェースの有無が確認されます: ```puppet has_interface_with("lo") => true ``` *タイプ*: 右辺値 #### `has_ip_address` 一部のインターフェース上で、リクエストされたIPアドレスがクライアントに存在する場合は`true`を返します。この関数は`interfaces` factで反復され、`ipaddress_IFACE` factsをチェックし、簡単な文字列比較を実行します。 引数: IPアドレスを指定する文字列。 *タイプ*: 右辺値 #### `has_ip_network` リクエストされたネットワーク内でIPアドレスがクライアントに存在する場合は`true`を返します。この関数は`interfaces` factで反復され、 `network_IFACE` factsをチェックし、簡単な文字列比較を実行します。 引数: IPアドレスを指定する文字列。 *タイプ*: 右辺値 #### `has_key` ハッシュに特定のキー値があるかどうかを判定します。 *例*: ``` $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } ``` *タイプ*: 右辺値 #### `hash` 配列をハッシュに変換します。 たとえば、`hash(['a',1,'b',2,'c',3])`は{'a'=>1,'b'=>2,'c'=>3}を返します。 *タイプ*: 右辺値 #### `intersection` 2つの共通部分の配列を返します。 たとえば、`intersection(["a","b","c"],["b","c","d"])`は["b","c"]を返します。 *タイプ*: 右辺値 #### `is_a` ブーリアンチェックにより、変数が任意のデータタイプのものかどうかを判定します。これは`=~`タイプチェックに相当します。この関数はPuppet 4と、"future"パーサーを備えたPuppet 3でのみ使用できます。 ``` foo = 3 $bar = [1,2,3] $baz = 'A string!' if $foo.is_a(Integer) { notify { 'foo!': } } if $bar.is_a(Array) { notify { 'bar!': } } if $baz.is_a(String) { notify { 'baz!': } } ``` * タイプに関する詳細は、[Puppetタイプシステム](https://docs.puppetlabs.com/latest/type.html#about-resource-types)を参照してください。 * 値のタイプを特定する各種の方法については、[`assert_type()`](https://docs.puppetlabs.com/latest/function.html#asserttype)関数を参照してください。 #### `is_absolute_path` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 与えられたパスが絶対パスである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_array` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数が配列である場合に`true`を返します。 *タイプ*: 右辺値 #### `is_bool` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数がブーリアンである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_domain_name` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された文字列が構文的に正しいドメイン名である場合に`true`を返します。 *タイプ*: 右辺値 #### `is_email_address` この関数に渡された文字列が有効なメールアドレスである場合にtrueを返します。 *タイプ*: 右辺値 #### `is_float` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数がフロート型である場合に`true`を返します。 *タイプ*: 右辺値 #### `is_function_available` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 文字列を引数として受け入れ、Puppetランタイムがその名前を用いて関数にアクセスできるかどうかを判定します。関数が存在する場合は`true`、存在しない場合は`false`を返します。 *タイプ*: 右辺値 #### `is_hash` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数がハッシュである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_integer` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この文字列に返された変数が整数である場合に`true`を返します。 *タイプ*: 右辺値 #### `is_ip_address` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された文字列が有効なIPアドレスである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_ipv6_address` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された文字列が有効なIPv6アドレスである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_ipv4_address` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された文字列が有効なIPv4アドレスである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_mac_address` この関数に渡された文字列が有効なMACアドレスである場合に`true`を返します。 *タイプ*: 右辺値 #### `is_numeric` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数が数字である場合に`true`を返します。 *タイプ*: 右辺値 #### `is_string` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** この関数に渡された変数が文字列である場合に`true`を返します。 *タイプ*: 右辺値 #### `join` 区切り文字を用いて、配列を文字列に結合します。たとえば、`join(['a','b','c'], ",")`は"a,b,c"になります。 *タイプ*: 右辺値 #### `join_keys_to_values` 区切り文字を用いて、ハッシュの各キーをそのキーに対応する値と結合し、結果を文字列として返します。 値が配列の場合は、キーは各要素の前に置かれます。返される値は、平坦化した配列になります。 たとえば、`join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")`は["a is 1","b is 2","b is 3"]になります。 *タイプ*: 右辺値 #### `keys` ハッシュのキーを配列として返します。 *タイプ*: 右辺値 #### `length` 与えられた文字列、配列、ハッシュの長さを返します。廃止された`size()`関数に代わるものです。 *タイプ*: 右辺値 #### `loadyaml` 配列、文字列、ハッシュを含むYAMLファイルをロードし、対応するネイティブデータタイプでデータを返します。 例: ```puppet $myhash = loadyaml('/etc/puppet/data/myhash.yaml') ``` 第2のパラメータは、ファイルが見つからなかった場合、または構文解析できなかった場合に返されます。 例: ```puppet $myhash = loadyaml('no-file.yaml', {'default'=>'value'}) ``` *タイプ*: 右辺値 #### `loadjson` 配列、文字列、ハッシュを含むJSONファイルをロードし、対応するネイティブデータタイプでデータを返します。 例: ```puppet $myhash = loadjson('/etc/puppet/data/myhash.json') ``` 第2のパラメータは、ファイルが見つからなかった場合、または構文解析できなかった場合に返されます。 例: ```puppet $myhash = loadjson('no-file.json', {'default'=>'value'}) ``` *タイプ*: 右辺値 #### `load_module_metadata` ターゲットモジュールのmetadata.jsonをロードします。モジュールのバージョンや、モジュールの動的サポートに関するオーサーシップの判定に使用できます。 ```puppet $metadata = load_module_metadata('archive') notify { $metadata['author']: } ``` モジュールのメタデータファイルが存在しない場合、カタログコンパイルに失敗します。これを避ける方法は、以下のとおりです: ``` $metadata = load_module_metadata('mysql', true) if empty($metadata) { notify { "This module does not have a metadata.json file.": } } ``` *タイプ*: 右辺値 #### `lstrip` 文字列の左側のスペースを取り除きます。 *タイプ*: 右辺値 #### `max` すべての引数の最大値を返します。少なくとも1つの引数が必要です。 引数: 数字または数字を表す文字列。 *タイプ*: 右辺値 #### `member` 変数が配列の構成要素かどうかを判定します。変数には文字列、配列、fixnumが使用できます。 たとえば、`member(['a','b'], 'b')`および`member(['a','b','c'], ['b','c'])`は`true`を返し、`member(['a','b'], 'c')`および`member(['a','b','c'], ['c','d'])`は`false`を返します。 *注*: この関数は、ネスト化した配列には対応していません。最初の引数にネスト化した配列が含まれている場合は、再帰的処理は行われません。 *タイプ*: 右辺値 #### `merge` 2つ以上のハッシュを統合し、その結果得られたハッシュを返します。 *例*: ```puppet $hash1 = {'one' => 1, 'two' => 2} $hash2 = {'two' => 'dos', 'three' => 'tres'} $merged_hash = merge($hash1, $hash2) # 得られるハッシュは、以下に相当します: # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} ``` 重複キーが存在する場合は、最右のハッシュのキーが上位になります。 *タイプ*: 右辺値 #### `min` すべての引数の最小値を返します。少なくとも1つの引数が必要です。 引数: 数字または数字を表す文字列。 *タイプ*: 右辺値 #### `num2bool` 数字または数字の文字列表現を正当なブーリアンに変換します。0または非数字は`false`になります。0より大きい数字は`true`になります。 *タイプ*: 右辺値 #### `parsejson` JSONの文字列を正確なPuppet構造に変換します(ハッシュ、配列、文字列、整数、またはそれらの組み合わせとして)。 引数: * 第1の引数として、変換されるJSON文字列。 * オプションで、第2のエラーとして、変換に失敗した場合に返される結果。 *タイプ*: 右辺値 #### `parseyaml` YAMLの文字列を正確なPuppet構造に変換します。 引数: * 第1の引数として、変換されるYAML文字列。 * オプションで、第2のエラーとして、変換に失敗した場合に返される結果。 *タイプ*: 右辺値 #### `pick` 値のリストから、未定義または空文字列ではない最初の値を返します。引数から任意の数字をとり、すべての値が未定義または空の場合はエラーが生じます。 ```puppet $real_jenkins_version = pick($::jenkins_version, '1.449') ``` *タイプ*: 右辺値 #### `pick_default` 値のリストにある最初の値を返します。`pick()`関数とは異なり、`pick_default()`は、すべての引数が空の場合も失敗にはなりません。そのため、デフォルトとして空の値を使用できます。 *タイプ*: 右辺値 #### `prefix` 配列のすべての要素、またはハッシュのキーに接頭辞を適用します。 例: * `prefix(['a','b','c'], 'p')`は['pa','pb','pc']を返します。 * `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')`は{'pa'=>'b','pb'=>'c','pc'=>'d'}を返します。 *タイプ*: 右辺値 #### `pry` 現在のスコープオブジェクトでpryデバッグセッションを起動します。コンパイル中の特定ポイントにおけるマニフェストコードのデバッグに役立ちます。`puppet apply`の実行中またはフォアグラウンドでPuppet masterを実行しているときにのみ使用する必要があります。PuppetのRubyGemsに`pry` gemがインストールされている必要があります。 *例:* ```puppet pry() ``` pryセッションで役立つコマンドは以下のとおりです: * `catalog`を実行すると、現在カタログをコンパイルしているコンテンツを見られます。 * `cd catalog`および`ls`を実行すると、カタログメソッドおよびインスタンス変数を見られます。 * `@resource_table`を実行すると、現在のカタログリソーステーブルを見られます。 #### `pw_hash` crypt関数を用いてパスワードをハッシュします。ほとんどのPOSIXシステムで使えるハッシュを提供します。 この関数の最初の引数は、ハッシュするパスワードです。`undef`または空文字列の場合は、この関数により`undef`が返されます。 この関数の第2の引数は、使用するハッシュのタイプです。適切なcrypt(3)ハッシュ指定子に変換されます。有効なハッシュタイプは以下のとおりです: |ハッシュタイプ |指定子| |---------------------|---------| |MD5 |1 | |SHA-256 |5 | |SHA-512 (推奨)|6 | この関数の第3の引数は、使用するソルトです。 この関数は、Puppet masterのcrypt(3)実装を使用しています。お使いの環境に複数の異なるオペレーティングシステムが含まれている場合は、この関数を使用する前に、互換性があることを確認してください。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `range` '(start, stop)'の形式で与えられた場合に、領域を配列として外挿します。たとえば、`range("0", "9")`は[0,1,2,3,4,5,6,7,8,9]を返します。ゼロパディングされた文字列は、自動的に整数に変換されます。したがって、`range("00", "09")`は[0,1,2,3,4,5,6,7,8,9]を返します。 非整数文字列を使用できます: * `range("a", "c")`は["a","b","c"]を返します。 * `range("host01", "host10")`は["host01", "host02", ..., "host09", "host10"]を返します。 末尾のゼロを明示的に含める必要があります。そうでないと、下層のRuby関数が適切に機能しません。 第3の引数を渡すと、生成された領域がその間隔で刻まれます。例: * `range("0", "9", "2")`は["0","2","4","6","8"]を返します。 *タイプ*: 右辺値 #### `regexpescape` 文字列または文字列の配列を正規表現エスケープします。インプットとして、単一の文字列または配列のいずれかが必要です。 *タイプ*: 右辺値 #### `reject` 配列を検索し、提示された正規表現に一致する要素をすべてリジェクトします。 たとえば、`reject(['aaa','bbb','ccc','aaaddd'], 'aaa')`は['bbb','ccc']を返します。 *タイプ*: 右辺値 #### `reverse` 文字列または配列の順序を逆転します。 #### `round` 数値を最も近い整数に丸めます。 *タイプ*: 右辺値 #### `rstrip` 文字列の右側のスペースを取り除きます。 *タイプ*: 右辺値 #### `seeded_rand` 整数の最大値と文字列のシード値を取り、最大値よりも小さい反復可能かつランダムな整数を返します。`fqdn_rand`と同様ですが、シードにノード固有のデータが追加されません。 *タイプ*: 右辺値 #### `shell_escape` 文字列をエスケープし、Bourneシェルコマンドラインで安全に使用できるようにします。得られる文字列はクォートなしで使用する必要があり、ダブルクォートまたはシングルクォートでの使用は意図されていません。この関数は、Rubyの`Shellwords.shellescape()`関数と同様に挙動します。[Rubyドキュメント](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape)を参照してください。 例: ```puppet shell_escape('foo b"ar') => 'foo\ b\"ar' ``` *タイプ*: 右辺値 #### `shell_join` 与えられた文字列の配列からコマンドライン文字列を構築します。各配列アイテムが、Bourneシェルで使用できるようにエスケープされます。その後、すべてのアイテムがまとめられ、間にシングルスペースが配されます。この関数は、Rubyの`Shellwords.shelljoin()`関数と同様に挙動します。[Rubyドキュメント](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin)を参照してください。 例: ```puppet shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z' ``` *タイプ*: 右辺値 #### `shell_split` 文字列をトークンの配列に分割します。この関数は、Rubyの`Shellwords.shellsplit()`関数と同様に挙動します。[Rubyドキュメント](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit)を参照してください。 *例:* ```puppet shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z'] ``` *タイプ*: 右辺値 #### `shuffle` 文字列または配列の順序をランダム化します。 *タイプ*: 右辺値 #### `size` 文字列、配列、ハッシュの要素数を返します。この関数は、今後のリリースでは廃止されます。Puppet 4では、`length`関数を使用してください。 *タイプ*: 右辺値 #### `sprintf_hash` 名前が指定されたテキストのリファレンスでprintfスタイルのフォーマットを実行します。 最初のパラメータは、ハッシュ内での残りのパラメータのフォーマット方法を記述するフォーマット文字列です。詳細については、Rubyの`Kernel::sprintf`機能のマニュアルを参照してください。 例: ```puppet $output = sprintf_hash('String: %s / number converted to binary: %b', { 'foo' => 'a string', 'number' => 5 }) # $output = 'String: a string / number converted to binary: 101' ``` *Type*: rvalue #### `sort` 文字列と配列を語彙的に分類します。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `squeeze` 文字列内の連続した繰り返し('aaaa'など)を単一文字に置き換え、新たな文字列を返します。 *タイプ*: 右辺値 #### `str2bool` 特定の文字列をブーリアンに変換します。値'1'、'true'、't'、'y'、'yes'を含む文字列は`true`に変換されます。値'0'、'false'、'f'、'n'、'no'を含む文字列、および空文字列または未定義文字列は`false`に変換されます。その他の値の場合、エラーが生じます。このチェックでは、大文字と小文字は区別されません。 *タイプ*: 右辺値 #### `str2saltedsha512` OS Xバージョン10.7以上で使用されるソルト付きSHA512パスワードハッシュに文字列を変換します。hexバージョンのソルト付きSHA512パスワードハッシュを返します。これは、有効なパスワード属性としてPuppetマニフェストに挿入することができます。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `strftime` フォーマットされた時刻を返します。 たとえば、`strftime("%s")`はUnixエポックからの経過時間を返し、`strftime("%Y-%m-%d")`は日付を返します。 引数: `strftime`フォーマットで時間を指定する文字列。詳細については、Ruby [strftime](https://ruby-doc.org/core-2.1.9/Time.html#method-i-strftime)ドキュメントを参照してください。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 *フォーマット:* * `%a`: 曜日の名称の短縮形('Sun') * `%A`: 曜日の完全な名称('Sunday') * `%b`: 月の名称の短縮形('Jan') * `%B`: 月の完全な名称('January') * `%c`: 推奨される地域の日付および時刻の表現 * `%C`: 世紀(2009年であれば20) * `%d`: その月の日(01..31) * `%D`: 日付(%m/%d/%y) * `%e`: その月の日、1桁の場合は半角空白で埋める( 1..31) * `%F`: %Y-%m-%d(ISO 8601の日付フォーマット)と同等 * `%h`: %bと同等 * `%H`: 24時間制の時(00..23) * `%I`: 12時間制の時(01..12) * `%j`: 年中の通算日(001..366) * `%k`: 24時間制の時、1桁の場合は半角空白で埋める( 0..23) * `%l`: 12時間制の時、1桁の場合は半角空白で埋める( 0..12) * `%L`: ミリ秒(000..999) * `%m`: その年の月(01..12) * `%M`: 分(00..59) * `%n`: 改行(\n) * `%N`: 秒の小数点以下の桁、デフォルトは9桁(ナノ秒) * `%3N`: ミリ秒(3桁) * `%6N`: マイクロ秒(6桁) * `%9N`: ナノ秒(9桁) * `%p`: 午前または午後('AM'または'PM') * `%P`: 午前または午後('am'または'pm') * `%r`: 12時間制の時刻(%I:%M:%S %pと同等) * `%R`: 24時間制の時刻(%H:%M) * `%s`: Unixエポック、1970-01-01 00:00:00 UTCからの経過秒 * `%S`: 秒(00..60) * `%t`: タブ文字( ) * `%T`: 24時間制の時刻(%H:%M:%S) * `%u`: 月曜日を1とした、曜日の数値表現(1..7) * `%U`: 最初の日曜日を第1週の始まりとした、現在の週を表す数(00..53) * `%v`: VMS形式の日付(%e-%b-%Y) * `%V`: ISO 8601形式の暦週(01..53) * `%W`: 最初の月曜日を第1週の始まりとした、現在の週を表す数(00..53) * `%w`: 曜日(日曜が0、0..6) * `%x`: 推奨される日付のみの表現、時刻はなし * `%X`: 推奨される時刻のみの表現、日付はなし * `%y`: 世紀なしの年(00..99) * `%Y`: 世紀ありの年 * `%z`: タイムゾーン、UTCからのオフセット(+0900など) * `%Z`: タイムゾーンの名称 * `%%`: '%'文字 #### `strip` 1つの文字列、または配列内のすべての文字列から、冒頭および末尾の空白を削除します。たとえば、`strip(" aaa ")`は"aaa"になります。 *タイプ*: 右辺値 #### `suffix` 配列のすべての要素、またはハッシュのすべてのキーに接尾辞を適用します。 例: * `suffix(['a','b','c'], 'p')`は['ap','bp','cp']を返します。 * `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')`は{'ap'=>'b','bp'=>'c','cp'=>'d'}を返します。 *タイプ*: 右辺値 #### `swapcase` 文字列の現在の大文字と小文字を入れ替えます。たとえば、`swapcase("aBcD")`は"AbCd"になります。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `time` 現在のUnixエポック時刻を整数として返します。 たとえば、`time()`は'1311972653'などを返します。 *タイプ*: 右辺値 #### `to_bytes` 引数をバイトに変換します。 たとえば、"4 kB"は"4096"になります。 引数: 単一の文字列。 *タイプ*: 右辺値 #### `to_json` 入力値をJSON形式の文字列に変換します。 例えば、`{ "key" => "value" }`は`{"key":"value"}`になります。 *タイプ*: 右辺値 #### `to_json_pretty` 入力値を整形されたJSON形式の文字列に変換します。 例えば、`{ "key" => "value" }`は`{\n \"key\": \"value\"\n}`になります。 *タイプ*: 右辺値 #### `to_yaml` 入力値をYAML形式の文字列に変換します。 例えば、`{ "key" => "value" }`は`"---\nkey: value\n"`になります。 *タイプ*: 右辺値 #### `try_get_value` **非推奨:** `dig()`に置き換えられました。 ハッシュおよび配列の複数レイヤー内の値を取得します。 引数: * 第1の引数として、パスを含む文字列。この引数は、ゼロではじまり、パス区切り文字(デフォルトは"/")で区切ったハッシュキーまたは配列インデックスの文字列として提示してください。この関数は各パスコンポーネントにより構造内を移動し、パスの最後で値を返すよう試みます。 *デフォルトの第2の引数。パスが正しくない場合や、値が見つからない場合、その他のエラーが生じた場合は、この引数が返されます。 * 最後の引数として、パス区切り文字。 ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = try_get_value($data, 'a/b/2') # $value = 'b3' # 可能なすべてのオプションを使用 $value = try_get_value($data, 'a/b/2', 'not_found', '/') # $value = 'b3' # デフォルト値を使用 $value = try_get_value($data, 'a/b/c/d', 'not_found') # $value = 'not_found' # カスタム区切りを使用 $value = try_get_value($data, 'a|b', [], '|') # $value = ['b1','b2','b3'] ``` 1. **$data** 取り扱うデータ構造。 2. **'a/b/2'** パス文字列。 3. **'not_found'** デフォルト値。何も見つからない場合に返されます。 (オプション、デフォルトは`undef`) 4. **'/'** パス区切り文字。 (オプション、デフォルトは*'/'*) *タイプ*: 右辺値 #### `type3x` **非推奨**。この関数は、今後のリリースで廃止されます。 与えられた値のタイプを説明する文字列を返します。タイプとしては、文字列、配列、ハッシュ、フロート、整数、ブーリアンが可能です。Puppet 4では、この代わりに新しいタイプシステムを使用してください。 引数: * 文字列 * 配列 * ハッシュ * フロート * 整数 * ブーリアン *タイプ*: 右辺値 #### `type_of` この関数は下位互換性を得るために提供されていますが、Puppetで提供されている内蔵の[type()関数](https://docs.puppet.com/puppet/latest/reference/function.html#type)の使用を推奨します。 与えられた値のリテラル型を返します。Puppet 4が必要です。`if type_of($some_value) <= Array[String] { ... }`のように(これは`if $some_value =~ Array[String] { ... }`に相当します)、`<=`を用いたタイプの比較に役立ちます。 *タイプ*: 右辺値 #### `union` 2つ以上の配列を重複なしで結合したものを返します。 たとえば、`union(["a","b","c"],["b","c","d"])`は["a","b","c","d"]を返します。 *タイプ*: 右辺値 #### `unique` 文字列および配列から重複を削除します。 たとえば、`unique("aabbcc")`は'abc'を、`unique(["a","a","b","b","c","c"])`は["a","b","c"]を返します。 *タイプ*: 右辺値 #### `unix2dos` 与えられた文字列のDOSバージョンを返します。クロスプラットフォームテンプレートでファイルリソースを使用する場合に役立ちます。 *タイプ*: 右辺値 ```puppet file { $config_file: ensure => file, content => unix2dos(template('my_module/settings.conf.erb')), } ``` [dos2unix](#dos2unix)も参照してください。 #### `upcase` オブジェクト、配列、オブジェクトのハッシュを大文字に変換します。変換されるオブジェクトは、大文字化に対応するものでなければなりません。 たとえば、`upcase('abcd')`は'ABCD'を返します。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `uriescape` 文字列または文字列の配列をURLエンコードします。 引数: 単一の文字列または文字列の配列。 *タイプ*: 右辺値 *注:* この関数はRubyクラスの実装にあたり、UTF8との互換性がない可能性があります。互換性を確保するには、Ruby 2.4.0以降でこの関数を使用してください。 #### `validate_absolute_path` ファイルシステムの絶対パスを表す任意の文字列の有効性を確認します。WindowsおよびUnix形式のパスで機能します。 以下の値が渡されます: ```puppet $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' validate_absolute_path($my_path) $my_path2 = '/var/lib/puppet' validate_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet'] validate_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet','/usr/share/puppet'] validate_absolute_path($my_path4) ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_absolute_path(true) validate_absolute_path('../var/lib/puppet') validate_absolute_path('var/lib/puppet') validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = `undef` validate_absolute_path($undefined) ``` *タイプ*: ステートメント #### `validate_array` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 渡されたすべての値が配列データ構造であることを確認します。このチェックで不合格となった値がある場合は、カタログコンパイルが中止されます。 以下の値が渡されます: ```puppet $my_array = [ 'one', 'two' ] validate_array($my_array) ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_array(true) validate_array('some_string') $undefined = `undef` validate_array($undefined) ``` *タイプ*: ステートメント #### `validate_augeas` Augeasレンズを用いて文字列を確認します。 引数: * 第1の引数として、テストする文字列。 * 第2の引数として、使用するAugeasレンズの名前。 * オプションの第3の文字列として、ファイル内で見つかるべき**ではない**パスのリスト。 * オプションの第4の引数として、ユーザに表示するエラーメッセージ。 Augeasがレンズによる文字列の構文解析に失敗した場合は、構文エラーによりコンパイルが中止されます。 `$file`変数は、Augeasツリーでテストされる一時ファイルのロケーションを示します。 たとえば、$passwdcontentにユーザの`foo`が含まれないようにするには、第3の引数を以下のようにします: ```puppet validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) ``` エラーメッセージを生成して表示するには、第4の引数を以下のようにします: ```puppet validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') ``` *タイプ*: ステートメント #### `validate_bool` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 渡されたすべての値が`true`または`false`のいずれかであることを確認します。 このチェックで不合格となった値がある場合は、カタログコンパイルが中止されます。 以下の値が渡されます: ```puppet $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) ``` *タイプ*: ステートメント #### `validate_cmd` 外部コマンドにより文字列を確認します。 引数: * 第1の引数として、テストする文字列。 * 第2の引数として、テストコマンドのパス。この引数は、ファイルパスのプレースホルダ―として%をとります(%プレースホルダーが与えられていない場合、デフォルトはコマンド末尾)。パスした文字列を含む一時ファイルに対してコマンドが起動した場合や、ゼロではない値が返された場合は、構文エラーによりコンパイルが中止されます。 * オプションの第3の引数として、ユーザに表示するエラーメッセージ。 ```puppet # デフォルトのパス末尾 validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') ``` ```puppet # ファイルロケーションとして%を使用 validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') ``` *タイプ*: ステートメント #### `validate_domain_name` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 渡されたすべての値が構文的に正しいドメイン名であることを確認します。このチェックで不合格となった値がある場合は、カタログコンパイルが中止されます。 以下の値が渡されます: ~~~ $my_domain_name = 'server.domain.tld' validate_domain_name($my_domain_name) validate_domain_name('domain.tld', 'puppet.com', $my_domain_name) ~~~ 以下の値が不合格となり、コンパイルが中止されます: ~~~ validate_domain_name(1) validate_domain_name(true) validate_domain_name('invalid domain') validate_domain_name('-foo.example.com') validate_domain_name('www.example.2com') ~~~ *タイプ*: ステートメント #### `validate_email_address` 渡されたすべての値が有効なメールアドレスであることを確認します。このチェックで不合格となった値がある場合、コンパイルが失敗します。 以下の値が渡されます: ~~~ $my_email = "waldo@gmail.com" validate_email_address($my_email) validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email) ~~~ 以下の値が不合格となり、コンパイルが中止されます: ~~~ $some_array = [ 'bad_email@/d/efdf.com' ] validate_email_address($some_array) ~~~ *タイプ*: ステートメント #### `validate_hash` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 渡されたすべての値がハッシュデータ構造であることを確認します。このチェックで不合格となった値がある場合は、カタログコンパイルが中止されます。 以下の値が渡されます: ```puppet $my_hash = { 'one' => 'two' } validate_hash($my_hash) ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_hash(true) validate_hash('some_string') $undefined = `undef` validate_hash($undefined) ``` *タイプ*: ステートメント #### `validate_integer` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 整数または整数の配列を確認します。いずれかがチェックで不合格になった場合には、カタログコンパイルが中止されます。 引数: * 第1の引数として、整数または整数の配列。 * オプションの第2の引数として、最大値。第1の引数(のすべての要素)は、この最大値以下でなければなりません。 * オプションの第3の引数として、最小値。第1の引数(のすべての要素)は、この最小値以上でなければなりません。 第1の引数が整数または整数の配列でない場合や、第2または第3の引数が整数に変換できない場合は、この関数は失敗になります。ただし、最小値が与えられている場合は(この場合に限られます)、第2の引数を空文字列または`undef`にすることが可能です。これは、最小チェックを確実に行うためのプレースホルダーとして機能します。 以下の値が渡されます: ```puppet validate_integer(1) validate_integer(1, 2) validate_integer(1, 1) validate_integer(1, 2, 0) validate_integer(2, 2, 2) validate_integer(2, '', 0) validate_integer(2, `undef`, 0) $foo = `undef` validate_integer(2, $foo, 0) validate_integer([1,2,3,4,5], 6) validate_integer([1,2,3,4,5], 6, 0) ``` * 加えて、上述のすべて。ただし、文字列として渡された値を任意に組み合わせたもの('1'または"1")。 * 加えて、上述のすべて。ただし、負の整数値を(適切に)組み合わせたもの。 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_integer(true) validate_integer(false) validate_integer(7.0) validate_integer({ 1 => 2 }) $foo = `undef` validate_integer($foo) validate_integer($foobaridontexist) validate_integer(1, 0) validate_integer(1, true) validate_integer(1, '') validate_integer(1, `undef`) validate_integer(1, , 0) validate_integer(1, 2, 3) validate_integer(1, 3, 2) validate_integer(1, 3, true) ``` * 加えて、上述のすべて。ただし、文字列として渡された値を任意に組み合わせたもの (`false`、または"false")。 * 加えて、上述のすべて。ただし、負の整数値を不適切に組み合わせたもの。 * 加えて、上述のすべて。ただし、配列内の非整数アイテムまたは最大/最小引数を用いたもの。 *タイプ*: ステートメント #### `validate_ip_address` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** IPv4アドレスかIPv6アドレスかにかかわらず、引数がIPアドレスであることを確認します。また、ネットマスクによりIPアドレスを確認します。 引数: IPアドレスを指定する文字列。 以下の値が渡されます: ```puppet validate_ip_address('0.0.0.0') validate_ip_address('8.8.8.8') validate_ip_address('127.0.0.1') validate_ip_address('194.232.104.150') validate_ip_address('3ffe:0505:0002::') validate_ip_address('::1/64') validate_ip_address('fe80::a00:27ff:fe94:44d6/64') validate_ip_address('8.8.8.8/32') ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_ip_address(1) validate_ip_address(true) validate_ip_address(0.0.0.256) validate_ip_address('::1', {}) validate_ip_address('0.0.0.0.0') validate_ip_address('3.3.3') validate_ip_address('23.43.9.22/64') validate_ip_address('260.2.32.43') ``` #### `validate_legacy` 指定したタイプおよび非推奨の確認関数の両方に照らして値を確認します。両方にパスした場合はそのままパスし、片方の確認のみにパスした場合はエラーが生じ、両方の確認でfalseが返された場合は失敗になります。 引数: * 値のチェックに用いるタイプ。 * 過去の確認関数のフルネーム。 * チェックする値。 * 過去の確認関数に必要な引数の不特定数。 例: ```puppet validate_legacy('Optional[String]', 'validate_re', 'Value to be validated', ["."]) ``` この関数は、Puppet 3形式の引数確認(stdlibの`validate_*`関数を使用)からPuppet 4データタイプへのモジュールのアップデートに対応しており、Puppet 3形式の確認に頼っている場合も機能性が中断することはありません。 > 注: この関数は、Puppet 4.4.0 (PE 2016.1)以降にのみ対応しています。 ##### モジュールユーザへ Puppet 4を使用している場合、`validate_legacy`関数を使えば、非推奨のPuppet 3の`validate_*`関数を探し、分離することができます。これらの関数は、stdlibバージョン4.13時点で非推奨になっており、今後のstdlibバージョンでは削除されます。 Puppet 4では、[データタイプ](https://docs.puppet.com/puppet/latest/reference/lang_data.html)を用いた改良版の定義タイプチェックが可能です。データタイプでは、Puppet 3の`validate_*`関数で見られた、矛盾につながるいくつかの問題を回避できます。たとえば、[validate_numeric](#validate_numeric)では、数字だけでなく、数字の配列や数字のように見える文字列も意図せず許可されていました。 Puppet 4とともに、非推奨の `validate_*`関数を用いたモジュールを使用している場合は、非推奨メッセージが表示されることがあります。`validate_legacy`関数を使えば、そうした差異を可視化し、より明快なPuppet 4構文に簡単に移行することができます。 表示される非推奨メッセージは、使用しているモジュールやデータによって異なることがあります。以下の非推奨メッセージは、Puppet 4でのみデフォルトで表示されます: * `Notice: Accepting previously invalid value for target type ''`: このメッセージは、情報提供の目的のみで表示されるものです。使用している値は、新形式で許可されていますが、旧確認関数では無効となります。 * `Warning: This method is deprecated, please use the stdlib validate_legacy function`: モジュールがまだ`validate_legacy`にアップグレードされていません。[deprecation](#deprecation)オプションを使用してさしあたり警告を解除するか、モジュールの開発者によりフィックスを提出してください。この問題の解決方法については、以下の[モジュール開発者へ](#モジュール開発者へ)を参照してください。 * `Warning: validate_legacy() expected value, got _`: コードが渡す値は、Puppet 3形式の確認では認められますが、次バージョンのモジュールでは認められません。ほとんどの場合、数字またはブーリアンからクォートを削除すれば、この問題を解決することができます。 * `Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, validate_legacy() expected value, got `: コードの渡す値は、新形式の確認でも旧形式の確認でも認められません。 ##### モジュール開発者へ `validate_legacy`関数は、モジュールユーザの使用している機能を中断させずに、 Puppet 3形式の確認からPuppet 4形式の確認に移行するのに役立ちます。 Puppet 4形式の確認に移行すれば、[データタイプ](https://docs.puppet.com/puppet/latest/reference/lang_data.html)を用いた、より明確な定義タイプチェックが可能になります。Puppet 3の`validate_*` 関数の多くは、確認という点で驚くほど多くの穴があります。たとえば、[validate_numeric](#validate_numeric)では、細部をコントロールできないため、数字だけでなく、数字の配列や数字のように見える文字列も許可されます。 クラスおよび定義タイプの各パラメータについて、使用する新しいPuppet 4データタイプを選択してください。たいていの場合、新しいデータタイプにより、元の`validate_*`関数とは異なる値のセットを使用できるようになります。以下のような状況になります: | | `validate_` pass | `validate_` fail | | ------------ | ---------------- | ---------------- | | マッチタイプ | パス | パス、通告 | | 失敗タイプ | パス、非推奨 | 失敗 | 現在のところ、確認後のコードでも、すべての可能な値に対処する必要がありますが、新形式にマッチする値のみを渡すように、コードのユーザがマニフェストを変更することができます。 stdlibの`validate_*`関数それぞれについて、マッチする`Stdlib::Compat::*`タイプがあり、適切な値のセットが許可されます。注意事項については、stdlibソースコードの `types/`ディレクトリにあるドキュメントを参照してください。 たとえば、数字のみが許可されるクラスを与えると、以下のようになります: ```puppet class example($value) { validate_numeric($value) ``` 得られる確認コードは、以下のようになります: ```puppet class example( Variant[Stdlib::Compat::Numeric, Numeric] $value ) { validate_legacy(Numeric, 'validate_numeric', $value) ``` ここでは、`$value`のタイプが`Variant[Stdlib::Compat::Numeric, Numeric]`と定義されています。これにより、任意の`Numeric` (新形式)のほか、`validate_numeric`で(`Stdlib::Compat::Numeric`を通じて)これまで許可されていたすべての値を使用できます。 `validate_legacy`を呼び出すと、適切なログまたは失敗メッセージのトリガーが処理されます。これには、新形式、以前の確認関数の名称、およびその関数のすべての引数が必要です。 お使いのモジュールがまだPuppet 3をサポートしている場合は、これは互換性を破る変更になります。`metadata.json`要件セクションをアップデートしてモジュールがもうPuppet 3をサポートしていないことを示し、モジュールのメジャーバージョンを放棄してください。この変更を加えても、モジュールに関する既存のすべてのテストにパスするはずです。新たに可能になった値について、追加のテストを作成してください。 これは互換性を破る変更であることから、取り除きたいすべてのパラメータについて [`deprecation`](#deprecation)をコールしたり、パラメータにさらなる制約を追加したりする良い機会でもあります。 このバージョンのリリース後、互換性を破る変更を加えた別のリリースを公開し、すべての互換性タイプおよび `validate_legacy`のコールを削除することができます。その時点で、コードを実行し、過去に可能だった値に関する残余要素を取り除くこともできます。 そうした変更については、必ずCHANGELOGおよびREADMEで通告してください。 #### `validate_numeric` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 数値または数値の配列や文字列を確認します。いずれかがチェックに失敗した場合には、カタログコンパイルが中止されます。 引数: * 数値、または数値の配列か文字列。 * オプションで、最大値。第1の引数(のすべての要素) は、この最大値以下でなければなりません。 * オプションで、最小値。第1の引数(のすべての要素)は、この最小値以上でなければなりません。 第1の引数が数値(整数またはフロート)または数値の配列が文字列でない場合や、第2および第3の引数が数値に変換できない場合は、この関数は失敗になります。最小値が与えられている場合は(この場合に限られます)、第2の引数を空文字列または`undef`にすることが可能です。これは、最小チェックを確実に行うためのプレースホルダーとして機能します。 パスおよび失敗の使用については、[`validate_integer`](#validate-integer)を参照してください。同じ値がパスおよび失敗します。ただし、`validate_numeric`では、浮動小数点値も許可されます。 *タイプ*: ステートメント #### `validate_re` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 1つまたは複数の正規表現に照らして、文字列の簡単な確認を行います。 引数: * 第1の引数として、テストする文字列。この引数が文字列でない場合、コンパイルが中止されます。クォートを用いて強制的に文字列化してください。 * 第2の引数として、文字列化した正規表現(区切り文字//なし)または正規表現の配列。 * オプションの第3の引数として、ユーザに表示するエラーメッセージ。 第2の引数の正規表現が第1の引数で渡した文字列にマッチしない場合は、構文エラーによりコンパイルが中止されます。 以下の文字列により、正規表現に照らして確認が行われます: ```puppet validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) ``` 以下の文字列では、確認に失敗し、コンパイルが中止されます: ```puppet validate_re('one', [ '^two', '^three' ]) ``` エラーメッセージの設定方法: ```puppet validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') ``` 強制的に文字列化するには、クォートを使用してください: ``` validate_re("${::operatingsystemmajrelease}", '^[57]$') ``` *タイプ*: ステートメント #### `validate_slength` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 文字列(または文字列の配列)が指定した長さ以下であることを確認します。 引数: * 第1の引数として、文字列または文字列の配列。 * 第2の引数として、長さの最大値を示す数値。 * オプションの第3の引数として、長さの最小値を示す数値。 以下の値が渡されます: ```puppet validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) validate_slength(["discombobulate","moo"],17,3) ``` 以下の値は失敗になります: ```puppet validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) validate_slength(["discombobulate","moo"],17,10) ``` *タイプ*: ステートメント #### `validate_string` **非推奨。今後のバージョンのstdlibでは削除されます。[`validate_legacy`](#validate_legacy)を参照してください。** 渡したすべての値が文字列データ構造であることを確認します。このチェックに失敗した値がある場合は、カタログコンパイルが中止されます。 以下の値が渡されます: ```puppet $my_string = "one two" validate_string($my_string, 'three') ``` 以下の値は失敗になり、コンパイルが中止されます: ```puppet validate_string(true) validate_string([ 'some', 'array' ]) ``` *注:* validate_string(`undef`)は、このバージョンの関数APIでは失敗しません。 代わりに、以下を使用してください: ``` if $var == `undef` { fail('...') } ``` *タイプ*: ステートメント #### `validate_x509_rsa_key_pair` OpenSSLにより、PEMフォーマットされたX.509認証およびプライベートキーを確認します。 認証の署名が提供されたキーから作成されたものであることを確認します。 このチェックに失敗した値がある場合は、カタログコンパイルが中止されます。 引数: * 第1の引数として、X.509認証。 * 第2の引数として、RSAプライベートキー。 ```puppet validate_x509_rsa_key_pair($cert, $key) ``` *タイプ*: ステートメント #### `values` 与えられたハッシュの値を返します。 たとえば、`$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)`を与えると、[1,2,3]を返します。 *タイプ*: 右辺値 #### `values_at` ロケーションをもとに、配列内の値を探します。 引数: * 第1の引数として、解析したい配列。 * 第2の引数として、以下の値の任意の組み合わせ: * 単一の数値インデックス。 * 'start-stop'の形式での範囲(4-9など)。 * 上記を組み合わせた配列。 例: * `values_at(['a','b','c'], 2)`は['c']を返します。 * `values_at(['a','b','c'], ["0-1"])`は['a','b']を返します。 * `values_at(['a','b','c','d','e'], [0, "2-3"])`は['a','c','d']を返します。 *タイプ*: 右辺値 #### `zip` 与えられた第1の配列から1つの要素をとり、与えられた第2の配列の対応する要素と結合します。これにより、n-要素配列のシーケンスが生成されます。*n*は、引数の数より1大きくなります。たとえば、`zip(['1','2','3'],['4','5','6'])`は["1", "4"], ["2", "5"], ["3", "6"]を返します。*タイプ*: 右辺値。 ## 制約 Puppet Enterprise 3.7では、stdlibモジュールがPEに含まれていません。PEユーザは、Puppetと互換性のあるstdlibの最新リリースをインストールする必要があります。 ### バージョン互換性 バージョン | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x | :---------------|:-----:|:---:|:---:|:----: **stdlib 2.x** | **あり** | **あり** | なし | なし **stdlib 3.x** | なし | **あり** | **あり** | なし **stdlib 4.x** | なし | **あり** | **あり** | なし **stdlib 4.6+** | なし | **あり** | **あり** | **あり** **stdlib 5.x** | なし | なし | **あり** | **あり** **stdlib 5.x**: stdlib 5.xのリリース時には、Puppet 2.7.xのサポートが廃止されます。[この説明](https://github.com/puppetlabs/puppetlabs-stdlib/pull/176#issuecomment-30251414)を参照してください。 ## 開発 Puppet ForgeのPuppet Labsモジュールはオープンプロジェクトで、良い状態に保つためには、コミュニティの貢献が必要不可欠です。Puppetが役に立つはずでありながら、私たちがアクセスできないプラットフォームやハードウェア、ソフトウェア、デプロイ構成は無数にあります。私たちの目標は、できる限り簡単に変更に貢献し、みなさまの環境で私たちのモジュールが機能できるようにすることにあります。最高の状態を維持できるようにするために、コントリビュータが従う必要のあるいくつかのガイドラインが存在します。詳細については、[モジュールコントリビューションガイド](https://docs.puppetlabs.com/forge/contributing.html)を参照してください。 このモジュールのバグの報告または調査は、 [http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES)からお願いします。 ## コントリビュータ コントリビュータのリストは、[https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors)で見ることができます。puppetlabs-stdlib-4.25.0/spec0040755005276200011600000000000013252003413013074 5ustar00puppetlabs-stdlib-4.25.0/spec/acceptance0040755005276200011600000000000013252003413015162 5ustar00puppetlabs-stdlib-4.25.0/spec/acceptance/abs_spec.rb0100755005276200011600000000121313212471613017351 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'abs function' do describe 'success' do pp1 = <<-DOC $input = '-34.56' $output = abs($input) notify { "$output": } DOC it 'accepts a string' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 34.56}) end end pp2 = <<-DOC $input = -35.46 $output = abs($input) notify { "$output": } DOC it 'accepts a float' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 35.46}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/anchor_spec.rb0100755005276200011600000000111013212471613020052 0ustar00require 'spec_helper_acceptance' describe 'anchor type' do describe 'success' do pp = <<-DOC class anchored { anchor { 'anchored::begin': } ~> anchor { 'anchored::end': } } class anchorrefresh { notify { 'first': } ~> class { 'anchored': } ~> anchor { 'final': } } include anchorrefresh DOC it 'effects proper chaining of resources' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Anchor\[final\]: Triggered 'refresh'}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/any2array_spec.rb0100755005276200011600000000240313212471613020516 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'any2array function' do describe 'success' do pp1 = <<-DOC $input = '' $output = any2array($input) validate_array($output) notify { "Output: ${output}": } DOC it 'creates an empty array' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: Output: }) end end pp2 = <<-DOC $input = ['array', 'test'] $output = any2array($input) validate_array($output) notify { "Output: ${output}": } DOC it 'leaves arrays modified' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: Output: (\[|)array(,\s|)test(\]|)}) end end pp3 = <<-DOC $input = {'test' => 'array'} $output = any2array($input) validate_array($output) # Check each element of the array is a plain string. validate_string($output[0]) validate_string($output[1]) notify { "Output: ${output}": } DOC it 'turns a hash into an array' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: Output: (\[|)test(,\s|)array(\]|)}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/base64_spec.rb0100755005276200011600000000070713212471613017677 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'base64 function' do describe 'success' do pp = <<-DOC $encodestring = base64('encode', 'thestring') $decodestring = base64('decode', $encodestring) notify { $decodestring: } DOC it 'encodes then decode a string' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{thestring}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/bool2num_spec.rb0100755005276200011600000000152313212471613020345 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'bool2num function' do describe 'success' do %w[false f 0 n no].each do |bool| pp1 = <<-DOC $input = "#{bool}" $output = bool2num($input) notify { "$output": } DOC it "should convert a given boolean, #{bool}, to 0" do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 0}) end end end %w[true t 1 y yes].each do |bool| pp2 = <<-DOC $input = "#{bool}" $output = bool2num($input) notify { "$output": } DOC it "should convert a given boolean, #{bool}, to 1" do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 1}) end end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/build_csv.rb0100755005276200011600000000510113206047630017545 0ustar00#!/usr/bin/env ruby # vim: set sw=2 sts=2 et tw=80 : require 'rspec' # XXX Super ugly hack to keep from starting beaker nodes module Kernel # make an alias of the original require alias original_require require # rewrite require def require(name) original_require name if name != 'spec_helper_acceptance' end end UNSUPPORTED_PLATFORMS = [].freeze def fact(*_args) [] end # XXX End hax # Get a list of functions for test coverage function_list = Dir[File.join(File.dirname(__FILE__), '..', '..', 'lib', 'puppet', 'parser', 'functions', '*.rb')].map do |function_rb| File.basename(function_rb, '.rb') end ## Configure rspec to parse tests options = RSpec::Core::ConfigurationOptions.new(['spec/acceptance']) configuration = RSpec.configuration world = RSpec.world options.parse_options options.configure(configuration) configuration.load_spec_files ## Collect up tests and example groups into a hash def get_tests(children) children.each_with_object({}) do |c, memo| memo[c.description] = {} memo[c.description]['groups'] = get_tests(c.children) unless c.children.empty? unless c.examples.empty? memo[c.description]['tests'] = c.examples.map { |e| e.description unless e.pending? }.compact end next if c.examples.empty? memo[c.description]['pending_tests'] = c.examples.map { |e| e.description if e.pending? }.compact end end def count_test_types_in(type, group) return 0 if group.nil? group.reduce(0) do |m, (k, v)| m += v.length if k == type m += count_tests_in(v) if v.is_a?(Hash) m end end def count_tests_in(group) count_test_types_in('tests', group) end def count_pending_tests_in(group) count_test_types_in('pending_tests', group) end # Convert tests hash to csv format def to_csv(function_list, tests) function_list.map { |function_name| v = tests["#{function_name} function"] if v positive_tests = count_tests_in(v['groups']['success']) negative_tests = count_tests_in(v['groups']['failure']) pending_tests = count_pending_tests_in(v['groups']['failure']) + count_pending_tests_in(v['groups']['failure']) else positive_tests = 0 negative_tests = 0 pending_tests = 0 end '%-25s, %-9d, %-9d, %-9d' % [function_name, positive_tests, negative_tests, pending_tests] }.compact end tests = get_tests(world.example_groups) csv = to_csv(function_list, tests) percentage_tested = "#{tests.count * 100 / function_list.count}%" printf("%-25s, %-9s, %-9s, %-9s\n", "#{percentage_tested} have tests.", 'Positive', 'Negative', 'Pending') puts csv puppetlabs-stdlib-4.25.0/spec/acceptance/capitalize_spec.rb0100755005276200011600000000157613212471613020745 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'capitalize function' do describe 'success' do pp1 = <<-DOC $input = 'this is a string' $output = capitalize($input) notify { $output: } DOC it 'capitalizes the first letter of a string' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: This is a string}) end end pp2 = <<-DOC $input = ['this', 'is', 'a', 'string'] $output = capitalize($input) notify { $output: } DOC regex_array = [%r{Notice: This}, %r{Notice: Is}, %r{Notice: A}, %r{Notice: String}] it 'capitalizes the first letter of an array of strings' do apply_manifest(pp2, :catch_failures => true) do |r| regex_array.each do |i| expect(r.stdout).to match(i) end end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/ceiling_spec.rb0100755005276200011600000000152513212471613020224 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'ceiling function' do describe 'success' do pp1 = <<-DOC $a = 12.8 $b = 13 $o = ceiling($a) if $o == $b { notify { 'output correct': } } DOC it 'ceilings floats' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = 7 $b = 7 $o = ceiling($a) if $o == $b { notify { 'output is correct': } } DOC it 'ceilings integers' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output is correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-numbers' end end puppetlabs-stdlib-4.25.0/spec/acceptance/chomp_spec.rb0100755005276200011600000000070513212471613017717 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'chomp function' do describe 'success' do pp = <<-DOC $input = "test\n" if size($input) != 5 { fail("Size of ${input} is not 5.") } $output = chomp($input) if size($output) != 4 { fail("Size of ${input} is not 4.") } DOC it 'eats the newline' do apply_manifest(pp, :catch_failures => true) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/chop_spec.rb0100755005276200011600000000173113212471613017542 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'chop function' do describe 'success' do pp1 = <<-DOC $input = "test" if size($input) != 4 { fail("Size of ${input} is not 4.") } $output = chop($input) if size($output) != 3 { fail("Size of ${input} is not 3.") } DOC it 'eats the last character' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-'DOC' $input = "test\r\n" if size($input) != 6 { fail("Size of ${input} is not 6.") } $output = chop($input) if size($output) != 4 { fail("Size of ${input} is not 4.") } DOC it 'eats the last two characters of \r\n' do apply_manifest(pp2, :catch_failures => true) end pp3 = <<-DOC $input = "" $output = chop($input) DOC it 'does not fail on empty strings' do apply_manifest(pp3, :catch_failures => true) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/clamp_spec.rb0100755005276200011600000000156613212471613017713 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'clamp function' do describe 'success' do pp1 = <<-DOC $x = 17 $y = 225 $z = 155 $o = clamp($x, $y, $z) if $o == $z { notify { 'output correct': } } DOC it 'clamps list of values' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = [7, 19, 66] $b = 19 $o = clamp($a) if $o == $b { notify { 'output correct': } } DOC it 'clamps array of values' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/concat_spec.rb0100755005276200011600000000273013212471613020060 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'concat function' do describe 'success' do pp1 = <<-DOC $output = concat(['1','2','3'],['4','5','6']) validate_array($output) if size($output) != 6 { fail("${output} should have 6 elements.") } DOC it 'concats one array to another' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $output = concat(['1','2','3'],'4','5','6',['7','8','9']) validate_array($output) if size($output) != 9 { fail("${output} should have 9 elements.") } DOC it 'concats arrays and primitives to array' do apply_manifest(pp2, :catch_failures => true) end pp3 = <<-DOC $output = concat(['1','2','3'],['4','5','6'],['7','8','9']) validate_array($output) if size($output) != 9 { fail("${output} should have 9 elements.") } DOC it 'concats multiple arrays to one' do apply_manifest(pp3, :catch_failures => true) end pp4 = <<-DOC $output = concat([{"a" => "b"}], {"c" => "d", "e" => "f"}) validate_array($output) if size($output) != 2 { fail("${output} should have 2 elements.") } if $output[1] != {"c" => "d", "e" => "f"} { fail("${output} does not have the expected hash for the second element.") } DOC it 'concats hash arguments' do apply_manifest(pp4, :catch_failures => true) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/count_spec.rb0100755005276200011600000000130213212471613017733 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'count function' do describe 'success' do pp1 = <<-DOC $input = [1,2,3,4] $output = count($input) notify { "$output": } DOC it 'counts elements in an array' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 4}) end end pp2 = <<-DOC $input = [1,1,1,2] $output = count($input, 1) notify { "$output": } DOC it 'counts elements in an array that match a second argument' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: 3}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/deep_merge_spec.rb0100755005276200011600000000110413212471613020677 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'deep_merge function' do describe 'success' do pp = <<-DOC $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) if $merged_hash != { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } { fail("Hash was incorrectly merged.") } DOC it 'deeps merge two hashes' do apply_manifest(pp, :catch_failures => true) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/defined_with_params_spec.rb0100755005276200011600000000103713212471613022604 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'defined_with_params function' do describe 'success' do pp = <<-DOC user { 'dan': ensure => present, } if defined_with_params(User[dan], {'ensure' => 'present' }) { notify { 'User defined with ensure=>present': } } DOC it 'successfullies notify' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: User defined with ensure=>present}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/delete_at_spec.rb0100755005276200011600000000071713212471613020542 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'delete_at function' do describe 'success' do pp = <<-DOC $output = delete_at(['a','b','c','b'], 1) if $output == ['a','c','b'] { notify { 'output correct': } } DOC it 'deletes elements of the array' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/delete_spec.rb0100755005276200011600000000070313212471613020051 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'delete function' do pp = <<-DOC $output = delete(['a','b','c','b'], 'b') if $output == ['a','c'] { notify { 'output correct': } } DOC describe 'success' do it 'deletes elements of the array' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/delete_undef_values_spec.rb0100755005276200011600000000101013212471613022601 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'delete_undef_values function' do describe 'success' do pp = <<-DOC $output = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) if $output == { a => 'A', b => '', d => false } { notify { 'output correct': } } DOC it 'deletes elements of the array' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/delete_values_spec.rb0100755005276200011600000000120413212471613021425 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'delete_values function' do describe 'success' do pp = <<-DOC $a = { 'a' => 'A', 'b' => 'B', 'B' => 'C', 'd' => 'B' } $b = { 'a' => 'A', 'B' => 'C' } $o = delete_values($a, 'B') if $o == $b { notify { 'output correct': } } DOC it 'deletes elements of the hash' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles non-hash arguments' it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/deprecation_spec.rb0100644005276200011600000000536513252003272021106 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'deprecation function' do test_file = if fact('operatingsystem') == 'windows' 'C:/deprecation' else '/tmp/deprecation' end # It seems that Windows needs everything to be on one line when using puppet apply -e, otherwise the manifests would be in an easier format add_file_manifest = "\"deprecation('key', 'message') file { '#{test_file}': ensure => present, content => 'test', }\"" remove_file_manifest = "file { '#{test_file}': ensure => absent }" before :all do apply_manifest(remove_file_manifest) end context 'with --strict=error', :if => return_puppet_version =~ %r{^4} do let(:result) { on(default, puppet('apply', '--strict=error', '-e', add_file_manifest), :acceptable_exit_codes => (0...256)) } after :all do apply_manifest(remove_file_manifest) end it 'returns an error' do expect(result.exit_code).to eq(1) end it 'shows the error message' do expect(result.stderr).to match(%r{deprecation. key. message}) end describe file(test_file.to_s) do it { is_expected.not_to be_file } end end context 'with --strict=warning', :if => return_puppet_version =~ %r{^4} do let(:result) { on(default, puppet('apply', '--strict=warning', '-e', add_file_manifest), :acceptable_exit_codes => (0...256)) } after :all do apply_manifest(remove_file_manifest) end it 'does not return an error' do expect(result.exit_code).to eq(0) end it 'shows the error message' do expect(result.stderr).to match(%r{Warning: message}) end describe file(test_file.to_s) do it { is_expected.to be_file } end end context 'with --strict=off', :if => return_puppet_version =~ %r{^4} do let(:result) { on(default, puppet('apply', '--strict=off', '-e', add_file_manifest), :acceptable_exit_codes => (0...256)) } after :all do apply_manifest(remove_file_manifest) end it 'does not return an error' do expect(result.exit_code).to eq(0) end it 'does not show the error message' do expect(result.stderr).not_to match(%r{Warning: message}) end describe file(test_file.to_s) do it { is_expected.to be_file } end end context 'puppet 3 test', :if => return_puppet_version =~ %r{^3} do let(:result) { on(default, puppet('apply', '--parser=future', '-e', add_file_manifest), :acceptable_exit_codes => (0...256)) } after :all do apply_manifest(remove_file_manifest) end it 'returns a deprecation error' do expect(result.stderr).to match(%r{Warning: message}) end it 'passes without error' do expect(result.exit_code).to eq(0) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/difference_spec.rb0100755005276200011600000000115213212471613020700 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'difference function' do describe 'success' do pp = <<-DOC $a = ['a','b','c'] $b = ['b','c','d'] $c = ['a'] $o = difference($a, $b) if $o == $c { notify { 'output correct': } } DOC it 'returns non-duplicates in the first array' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles non-array arguments' it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/dirname_spec.rb0100755005276200011600000000177313212471613020236 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'dirname function' do describe 'success' do context 'with absolute path' do pp1 = <<-DOC $a = '/path/to/a/file.txt' $b = '/path/to/a' $o = dirname($a) if $o == $b { notify { 'output correct': } } DOC it 'returns the dirname' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end context 'with relative path' do pp2 = <<-DOC $a = 'path/to/a/file.txt' $b = 'path/to/a' $o = dirname($a) if $o == $b { notify { 'output correct': } } DOC it 'returns the dirname' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/downcase_spec.rb0100755005276200011600000000157713212471613020424 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'downcase function' do describe 'success' do pp1 = <<-DOC $a = 'AOEU' $b = 'aoeu' $o = downcase($a) if $o == $b { notify { 'output correct': } } DOC it 'returns the downcase' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = 'aoeu aoeu' $b = 'aoeu aoeu' $o = downcase($a) if $o == $b { notify { 'output correct': } } DOC it 'doesn\'t affect lowercase words' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/empty_spec.rb0100755005276200011600000000224313212471613017746 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'empty function' do describe 'success' do pp1 = <<-DOC $a = '' $b = true $o = empty($a) if $o == $b { notify { 'output correct': } } DOC it 'recognizes empty strings' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = 'aoeu' $b = false $o = empty($a) if $o == $b { notify { 'output correct': } } DOC it 'recognizes non-empty strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = 7 $b = false $o = empty($a) if $o == $b { notify { 'output correct': } } DOC it 'handles numerical values' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/ensure_resource_spec.rb0100755005276200011600000000135013212471613022016 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'ensure_resource function' do describe 'success' do pp1 = <<-DOC notify { "test": loglevel => 'err' } ensure_resource('notify', 'test', { 'loglevel' => 'err' }) DOC it 'ensures a resource already declared' do apply_manifest('') apply_manifest(pp1, :expect_changes => true) end pp2 = <<-DOC ensure_resource('notify', 'test', { 'loglevel' => 'err' }) DOC it 'ensures a undeclared resource' do apply_manifest('') apply_manifest(pp2, :expect_changes => true) end it 'takes defaults arguments' end describe 'failure' do it 'handles no arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/flatten_spec.rb0100755005276200011600000000171113212471613020244 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'flatten function' do describe 'success' do pp1 = <<-DOC $a = ["a","b",["c",["d","e"],"f","g"]] $b = ["a","b","c","d","e","f","g"] $o = flatten($a) if $o == $b { notify { 'output correct': } } DOC it 'flattens arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = ["a","b","c","d","e","f","g"] $b = ["a","b","c","d","e","f","g"] $o = flatten($a) if $o == $b { notify { 'output correct': } } DOC it 'does not affect flat arrays' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/floor_spec.rb0100755005276200011600000000150513212471613017731 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'floor function' do describe 'success' do pp1 = <<-DOC $a = 12.8 $b = 12 $o = floor($a) if $o == $b { notify { 'output correct': } } DOC it 'floors floats' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = 7 $b = 7 $o = floor($a) if $o == $b { notify { 'output correct': } } DOC it 'floors integers' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-numbers' end end puppetlabs-stdlib-4.25.0/spec/acceptance/fqdn_rand_string_spec.rb0100644005276200011600000000420613252003272022124 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'fqdn_rand_string function' do describe 'success' do include_context 'with faked facts' context "when the FQDN is 'fakehost.localdomain'" do before :each do fake_fact('fqdn', 'fakehost.localdomain') end pp1 = <<-PUPPETCODE $l = 10 $o = fqdn_rand_string($l) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) PUPPETCODE it 'generates random alphanumeric strings' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rand_string is "(7oDp0KOr1b|9Acvnhkt4J)"}) end end pp2 = <<-PUPPETCODE $l = 10 $c = '0123456789' $o = fqdn_rand_string($l, $c) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) PUPPETCODE it 'generates random alphanumeric strings with custom charsets' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rand_string is "(7203048515|2383756694)"}) end end pp3 = <<-PUPPETCODE $l = 10 $s = 'seed' $o = fqdn_rand_string($l, undef, $s) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) PUPPETCODE it 'generates random alphanumeric strings with custom seeds' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rand_string is "(3HS4mbuI3E|1jJtAMs94d)"}) end end pp4 = <<-PUPPETCODE $l = 10 $c = '0123456789' $s = 'seed' $o = fqdn_rand_string($l, $c, $s) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) PUPPETCODE it 'generates random alphanumeric strings with custom charsets and seeds' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rand_string is "(3104058232|7100592312)"}) end end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-numbers for length argument' end end puppetlabs-stdlib-4.25.0/spec/acceptance/fqdn_rotate_spec.rb0100755005276200011600000000347213212471613021123 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'fqdn_rotate function' do describe 'success' do include_context 'with faked facts' context "when the FQDN is 'fakehost.localdomain'" do before :each do fake_fact('fqdn', 'fakehost.localdomain') end pp1 = <<-DOC $a = ['a','b','c','d'] $o = fqdn_rotate($a) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) DOC it 'rotates arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rotate is \["d", "a", "b", "c"\]}) end end pp2 = <<-DOC $a = ['a','b','c','d'] $s = 'seed' $o = fqdn_rotate($a, $s) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) DOC it 'rotates arrays with custom seeds' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rotate is \["c", "d", "a", "b"\]}) end end pp3 = <<-DOC $a = 'abcd' $o = fqdn_rotate($a) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) DOC it 'rotates strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rotate is "dabc"}) end end pp4 = <<-DOC $a = 'abcd' $s = 'seed' $o = fqdn_rotate($a, $s) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) DOC it 'rotates strings with custom seeds' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{fqdn_rotate is "cdab"}) end end end end describe 'failure' do it 'handles improper argument counts' it 'handles invalid arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/get_module_path_spec.rb0100755005276200011600000000121513212471613021746 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'get_module_path function' do describe 'success' do pp = <<-DOC $a = $::is_pe ? { 'true' => '/etc/puppetlabs/puppet/modules/dne', 'false' => '/etc/puppet/modules/dne', } $o = get_module_path('dne') if $o == $a { notify { 'output correct': } } else { notify { "failed; module path is '$o'": } } DOC it 'get_module_paths dne' do apply_manifest(pp, :expect_failures => true) end end describe 'failure' do it 'handles improper argument counts' it 'handles non-numbers' end end puppetlabs-stdlib-4.25.0/spec/acceptance/getparam_spec.rb0100755005276200011600000000114013212471613020403 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'getparam function' do describe 'success' do pp = <<-DOC notify { 'rspec': message => 'custom rspec message', } $o = getparam(Notify['rspec'], 'message') notice(inline_template('getparam is <%= @o.inspect %>')) DOC it 'getparam a notify' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{getparam is "custom rspec message"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/getvar_spec.rb0100755005276200011600000000113013212471613020072 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'getvar function' do describe 'success' do pp = <<-DOC class a::data { $foo = 'aoeu' } include a::data $b = 'aoeu' $o = getvar("a::data::foo") if $o == $b { notify { 'output correct': } } DOC it 'getvars from classes' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-numbers' end end puppetlabs-stdlib-4.25.0/spec/acceptance/grep_spec.rb0100755005276200011600000000111413212471613017541 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'grep function' do describe 'success' do pp = <<-DOC $a = ['aaabbb','bbbccc','dddeee'] $b = 'bbb' $c = ['aaabbb','bbbccc'] $o = grep($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'greps arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/has_interface_with_spec.rb0100755005276200011600000000324513212471613022441 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'has_interface_with function', :unless => ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do pp1 = <<-DOC $a = $::ipaddress $o = has_interface_with('ipaddress', $a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) DOC it 'has_interface_with existing ipaddress' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_interface_with is true}) end end pp2 = <<-DOC $a = '128.0.0.1' $o = has_interface_with('ipaddress', $a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) DOC it 'has_interface_with absent ipaddress' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_interface_with is false}) end end pp3 = <<-DOC if $osfamily == 'Solaris' or $osfamily == 'Darwin' { $a = 'lo0' }elsif $osfamily == 'windows' { $a = $::kernelmajversion ? { /6\.(2|3|4)/ => 'Ethernet0', /6\.(0|1)/ => 'Local_Area_Connection', /5\.(1|2)/ => undef, #Broken current in facter } }else { $a = 'lo' } $o = has_interface_with($a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) DOC it 'has_interface_with existing interface' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_interface_with is true}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/has_ip_address_spec.rb0100755005276200011600000000170413212471613021561 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'has_ip_address function', :unless => ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do pp1 = <<-DOC $a = '127.0.0.1' $o = has_ip_address($a) notice(inline_template('has_ip_address is <%= @o.inspect %>')) DOC it 'has_ip_address existing ipaddress' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_ip_address is true}) end end pp2 = <<-DOC $a = '128.0.0.1' $o = has_ip_address($a) notice(inline_template('has_ip_address is <%= @o.inspect %>')) DOC it 'has_ip_address absent ipaddress' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_ip_address is false}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/has_ip_network_spec.rb0100755005276200011600000000170413212471613021625 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'has_ip_network function', :unless => ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do pp1 = <<-DOC $a = '127.0.0.0' $o = has_ip_network($a) notice(inline_template('has_ip_network is <%= @o.inspect %>')) DOC it 'has_ip_network existing ipaddress' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_ip_network is true}) end end pp2 = <<-DOC $a = '128.0.0.0' $o = has_ip_network($a) notice(inline_template('has_ip_network is <%= @o.inspect %>')) DOC it 'has_ip_network absent ipaddress' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{has_ip_network is false}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/has_key_spec.rb0100755005276200011600000000173713212471613020242 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'has_key function' do describe 'success' do pp1 = <<-DOC $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } $b = 'bbb' $c = true $o = has_key($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'has_keys in hashes' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } $b = 'ccc' $c = false $o = has_key($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'has_keys not in hashes' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-hashes' end end puppetlabs-stdlib-4.25.0/spec/acceptance/hash_spec.rb0100755005276200011600000000120313212471613017526 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'hash function' do describe 'success' do pp = <<-DOC $a = ['aaa','bbb','bbb','ccc','ddd','eee'] $b = { 'aaa' => 'bbb', 'bbb' => 'ccc', 'ddd' => 'eee' } $o = hash($a) if $o == $b { notify { 'output correct': } } DOC it 'hashs arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end it 'handles odd-length arrays' end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/intersection_spec.rb0100755005276200011600000000121513212471613021314 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'intersection function' do describe 'success' do pp = <<-DOC $a = ['aaa','bbb','ccc'] $b = ['bbb','ccc','ddd','eee'] $c = ['bbb','ccc'] $o = intersection($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'intersections arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end it 'intersections empty arrays' end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_a_spec.rb0100644005276200011600000000127013252003272017513 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' if return_puppet_version =~ %r{^4} describe 'is_a function' do pp1 = <<-DOC if 'hello world'.is_a(String) { notify { 'output correct': } } DOC it 'matches a string' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC if 5.is_a(String) { notify { 'output wrong': } } DOC it 'does not match a integer as string' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).not_to match(%r{Notice: output wrong}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_array_spec.rb0100755005276200011600000000275713212471613020433 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_array function' do describe 'success' do pp1 = <<-DOC $a = ['aaa','bbb','ccc'] $b = true $o = is_array($a) if $o == $b { notify { 'output correct': } } DOC it 'is_arrays arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = [] $b = true $o = is_array($a) if $o == $b { notify { 'output correct': } } DOC it 'is_arrays empty arrays' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "aoeu" $b = false $o = is_array($a) if $o == $b { notify { 'output correct': } } DOC it 'is_arrays strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = {'aaa'=>'bbb'} $b = false $o = is_array($a) if $o == $b { notify { 'output correct': } } DOC it 'is_arrays hashes' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_bool_spec.rb0100755005276200011600000000343113212471613020236 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_bool function' do describe 'success' do pp1 = <<-DOC $a = ['aaa','bbb','ccc'] $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } DOC it 'is_bools arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = true $b = true $o = is_bool($a) if $o == $b { notify { 'output correct': } } DOC it 'is_bools true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = false $b = true $o = is_bool($a) if $o == $b { notify { 'output correct': } } DOC it 'is_bools false' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = "true" $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } DOC it 'is_bools strings' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = {'aaa'=>'bbb'} $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } DOC it 'is_bools hashes' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_domain_name_spec.rb0100755005276200011600000000431513212471613021554 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_domain_name function' do describe 'success' do pp1 = <<-DOC $a = ['aaa.com','bbb','ccc'] $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) DOC it 'is_domain_names arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_domain_name is false}) end end pp2 = <<-DOC $a = true $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) DOC it 'is_domain_names true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_domain_name is false}) end end pp3 = <<-DOC $a = false $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) DOC it 'is_domain_names false' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_domain_name is false}) end end pp4 = <<-DOC $a = "3foo-bar.2bar-fuzz.com" $b = true $o = is_domain_name($a) if $o == $b { notify { 'output correct': } } DOC it 'is_domain_names strings with hyphens' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = "-bar.2bar-fuzz.com" $b = false $o = is_domain_name($a) if $o == $b { notify { 'output correct': } } DOC it 'is_domain_names strings beginning with hyphens' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp6 = <<-DOC $a = {'aaa'=>'www.com'} $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) DOC it 'is_domain_names hashes' do apply_manifest(pp6, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_domain_name is false}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_float_spec.rb0100755005276200011600000000403413212471613020410 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_float function' do describe 'success' do pp1 = <<-DOC $a = ['aaa.com','bbb','ccc'] $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) DOC it 'is_floats arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_float is false}) end end pp2 = <<-DOC $a = true $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) DOC it 'is_floats true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_float is false}) end end pp3 = <<-DOC $a = "3.5" $b = true $o = is_float($a) if $o == $b { notify { 'output correct': } } DOC it 'is_floats strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = 3.5 $b = true $o = is_float($a) if $o == $b { notify { 'output correct': } } DOC it 'is_floats floats' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = 3 $b = false $o = is_float($a) if $o == $b { notify { 'output correct': } } DOC it 'is_floats integers' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp6 = <<-DOC $a = {'aaa'=>'www.com'} $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) DOC it 'is_floats hashes' do apply_manifest(pp6, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_float is false}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_function_available_spec.rb0100755005276200011600000000320313212471613023125 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_function_available function' do describe 'success' do pp1 = <<-DOC $a = ['fail','include','require'] $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) DOC it 'is_function_availables arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_function_available is false}) end end pp2 = <<-DOC $a = true $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) DOC it 'is_function_availables true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_function_available is false}) end end pp3 = <<-DOC $a = "fail" $b = true $o = is_function_available($a) if $o == $b { notify { 'output correct': } } DOC it 'is_function_availables strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = "is_function_available" $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) DOC it 'is_function_availables function_availables' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_function_available is true}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_hash_spec.rb0100755005276200011600000000265713212471613020237 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_hash function' do describe 'success' do pp1 = <<-DOC $a = ['aaa','bbb','ccc'] $o = is_hash($a) notice(inline_template('is_hash is <%= @o.inspect %>')) DOC it 'is_hashs arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_hash is false}) end end pp2 = <<-DOC $a = {} $b = true $o = is_hash($a) if $o == $b { notify { 'output correct': } } DOC it 'is_hashs empty hashs' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "aoeu" $b = false $o = is_hash($a) if $o == $b { notify { 'output correct': } } DOC it 'is_hashs strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = {'aaa'=>'bbb'} $b = true $o = is_hash($a) if $o == $b { notify { 'output correct': } } DOC it 'is_hashs hashes' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_integer_spec.rb0100755005276200011600000000417413212471613020745 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_integer function' do describe 'success' do pp1 = <<-DOC $a = ['aaa.com','bbb','ccc'] $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = true $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "3" $b = true $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = 3.5 $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers floats' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = 3 $b = true $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers integers' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp6 = <<-DOC $a = {'aaa'=>'www.com'} $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } DOC it 'is_integers hashes' do apply_manifest(pp6, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_ip_address_spec.rb0100755005276200011600000000355513212471613021427 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_ip_address function' do describe 'success' do pp1 = <<-DOC $a = '1.2.3.4' $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ip_addresss ipv4' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74" $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ip_addresss ipv6' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "fe00::1" $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ip_addresss ipv6 compressed' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = "aoeu" $b = false $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ip_addresss strings' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = '1.2.3.400' $b = false $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ip_addresss ipv4 out of range' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_ipv4_address_spec.rb0100755005276200011600000000227513212471613021677 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_ipv4_address function' do describe 'success' do pp1 = <<-DOC $a = '1.2.3.4' $b = true $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv4_addresss' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = "aoeu" $b = false $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv4_addresss strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = '1.2.3.400' $b = false $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv4_addresss ipv4 out of range' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_ipv6_address_spec.rb0100755005276200011600000000311713212471613021675 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_ipv6_address function' do describe 'success' do pp1 = <<-DOC $a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74" $b = true $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv6_addresss' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = "fe00::1" $b = true $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv6_addresss ipv6 compressed' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "aoeu" $b = false $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv6_addresss strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = 'fe80:0000:cd12:d123:e2f8:47ff:fe09:gggg' $b = false $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_ipv6_addresss ip out of range' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_mac_address_spec.rb0100755005276200011600000000160513212471613021551 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_mac_address function' do describe 'success' do pp1 = <<-DOC $a = '00:a0:1f:12:7f:a0' $b = true $o = is_mac_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_mac_addresss a mac' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = '00:a0:1f:12:7f:g0' $b = false $o = is_mac_address($a) if $o == $b { notify { 'output correct': } } DOC it 'is_mac_addresss a mac out of range' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_numeric_spec.rb0100755005276200011600000000417313212471613020751 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_numeric function' do describe 'success' do pp1 = <<-DOC $a = ['aaa.com','bbb','ccc'] $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = true $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "3" $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp4 = <<-DOC $a = 3.5 $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics floats' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp5 = <<-DOC $a = 3 $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics integers' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp6 = <<-DOC $a = {'aaa'=>'www.com'} $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } DOC it 'is_numerics hashes' do apply_manifest(pp6, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'failure' do it 'handles improper argument counts' it 'handles non-arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/is_string_spec.rb0100755005276200011600000000522513212471613020614 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'is_string function' do describe 'success' do pp1 = <<-DOC $a = ['aaa.com','bbb','ccc'] $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } DOC it 'is_strings arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp2 = <<-DOC $a = true $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } DOC it 'is_strings true' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp3 = <<-DOC $a = "aoeu" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) DOC it 'is_strings strings' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_string is true}) end end pp4 = <<-DOC $a = "3" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) DOC it 'is_strings number strings' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_string is false}) end end pp5 = <<-DOC $a = 3.5 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } DOC it 'is_strings floats' do apply_manifest(pp5, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp6 = <<-DOC $a = 3 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } DOC it 'is_strings integers' do apply_manifest(pp6, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp7 = <<-DOC $a = {'aaa'=>'www.com'} $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } DOC it 'is_strings hashes' do apply_manifest(pp7, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end pp8 = <<-DOC $a = undef $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) DOC it 'is_strings undef' do apply_manifest(pp8, :catch_failures => true) do |r| expect(r.stdout).to match(%r{is_string is true}) end end end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/join_keys_to_values_spec.rb0100755005276200011600000000123413212471613022662 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'join_keys_to_values function' do describe 'success' do pp = <<-DOC $a = {'aaa'=>'bbb','ccc'=>'ddd'} $b = ':' $o = join_keys_to_values($a,$b) notice(inline_template('join_keys_to_values is <%= @o.sort.inspect %>')) DOC it 'join_keys_to_valuess hashes' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{join_keys_to_values is \["aaa:bbb", "ccc:ddd"\]}) end end it 'handles non hashes' it 'handles empty hashes' end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/join_spec.rb0100755005276200011600000000107313212471613017547 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'join function' do describe 'success' do pp = <<-DOC $a = ['aaa','bbb','ccc'] $b = ':' $c = 'aaa:bbb:ccc' $o = join($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'joins arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end it 'handles non arrays' end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/keys_spec.rb0100755005276200011600000000106713212471613017566 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'keys function' do describe 'success' do pp = <<-DOC $a = {'aaa'=>'bbb','ccc'=>'ddd'} $o = keys($a) notice(inline_template('keys is <%= @o.sort.inspect %>')) DOC it 'keyss hashes' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{keys is \["aaa", "ccc"\]}) end end it 'handles non hashes' it 'handles empty hashes' end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/loadjson_spec.rb0100644005276200011600000000347413252003272020421 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') describe 'loadjson function' do describe 'success' do shell("echo '{\"aaa\":1,\"bbb\":2,\"ccc\":3,\"ddd\":4}' > #{tmpdir}/test1json.json") pp1 = <<-DOC $o = loadjson('#{tmpdir}/test1json.json') notice(inline_template('loadjson[aaa] is <%= @o["aaa"].inspect %>')) notice(inline_template('loadjson[bbb] is <%= @o["bbb"].inspect %>')) notice(inline_template('loadjson[ccc] is <%= @o["ccc"].inspect %>')) notice(inline_template('loadjson[ddd] is <%= @o["ddd"].inspect %>')) DOC regex_array = [%r{loadjson\[aaa\] is 1}, %r{loadjson\[bbb\] is 2}, %r{loadjson\[ccc\] is 3}, %r{loadjson\[ddd\] is 4}] it 'loadjsons array of values' do apply_manifest(pp1, :catch_failures => true) do |r| regex_array.each do |i| expect(r.stdout).to match(i) end end end pp2 = <<-DOC $o = loadjson('#{tmpdir}/no-file.json', {'default' => 'value'}) notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>')) DOC it 'returns the default value if there is no file to load' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{loadjson\[default\] is "value"}) end end shell("echo '!' > #{tmpdir}/test2json.json") pp3 = <<-DOC $o = loadjson('#{tmpdir}/test2json.json', {'default' => 'value'}) notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>')) DOC it 'returns the default value if the file was parsed with an error' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{loadjson\[default\] is "value"}) end end end describe 'failure' do it 'fails with no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/loadyaml_spec.rb0100644005276200011600000000351213252003272020403 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') describe 'loadyaml function' do describe 'success' do shell("echo '--- aaa: 1 bbb: 2 ccc: 3 ddd: 4' > #{tmpdir}/test1yaml.yaml") pp1 = <<-DOC $o = loadyaml('#{tmpdir}/test1yaml.yaml') notice(inline_template('loadyaml[aaa] is <%= @o["aaa"].inspect %>')) notice(inline_template('loadyaml[bbb] is <%= @o["bbb"].inspect %>')) notice(inline_template('loadyaml[ccc] is <%= @o["ccc"].inspect %>')) notice(inline_template('loadyaml[ddd] is <%= @o["ddd"].inspect %>')) DOC regex_array = [%r{loadyaml\[aaa\] is 1}, %r{loadyaml\[bbb\] is 2}, %r{loadyaml\[ccc\] is 3}, %r{loadyaml\[ddd\] is 4}] it 'loadyamls array of values' do apply_manifest(pp1, :catch_failures => true) do |r| regex_array.each do |i| expect(r.stdout).to match(i) end end end pp2 = <<-DOC $o = loadyaml('#{tmpdir}/no-file.yaml', {'default' => 'value'}) notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>')) DOC it 'returns the default value if there is no file to load' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{loadyaml\[default\] is "value"}) end end shell("echo '!' > #{tmpdir}/test2yaml.yaml") pp3 = <<-DOC $o = loadyaml('#{tmpdir}/test2yaml.yaml', {'default' => 'value'}) notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>')) DOC it 'returns the default value if the file was parsed with an error' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{loadyaml\[default\] is "value"}) end end end describe 'failure' do it 'fails with no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/lstrip_spec.rb0100755005276200011600000000174313212471613020131 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'lstrip function' do describe 'success' do pp1 = <<-DOC $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = lstrip($a) notice(inline_template('lstrip is <%= @o.inspect %>')) DOC it 'lstrips arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{lstrip is \["the ", "public ", "art", "galleries "\]}) end end pp2 = <<-DOC $a = " blowzy night-frumps vex'd jack q " $o = lstrip($a) notice(inline_template('lstrip is <%= @o.inspect %>')) DOC it 'lstrips strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{lstrip is "blowzy night-frumps vex'd jack q "}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/max_spec.rb0100755005276200011600000000072313212471613017376 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'max function' do describe 'success' do pp = <<-DOC $o = max("the","public","art","galleries") notice(inline_template('max is <%= @o.inspect %>')) DOC it 'maxs arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{max is "the"}) end end end describe 'failure' do it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/member_spec.rb0100755005276200011600000000242213252003272020052 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'member function' do shared_examples 'item found' do it 'outputs correctly' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'success' do pp1 = <<-DOC $a = ['aaa','bbb','ccc'] $b = 'ccc' $c = true $o = member($a,$b) if $o == $c { notify { 'output correct': } } DOC it 'members arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{Notice: output correct}) end end describe 'members array of integers' do let(:pp) do <<-DOC if member( [1,2,3,4], 4 ){ notify { 'output correct': } } DOC end it_behaves_like 'item found' do end end describe 'members of mixed array' do let(:pp) do <<-DOC if member( ['a','4',3], 'a' ){ notify { 'output correct': } } DOC end it_behaves_like 'item found' do end end it 'members arrays without members' end describe 'failure' do it 'handles improper argument counts' end end puppetlabs-stdlib-4.25.0/spec/acceptance/merge_spec.rb0100755005276200011600000000147613212471613017716 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'merge function' do describe 'success' do pp = <<-DOC $a = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $b = {'two' => 'dos', 'three' => { 'five' => 5 } } $o = merge($a, $b) notice(inline_template('merge[one] is <%= @o["one"].inspect %>')) notice(inline_template('merge[two] is <%= @o["two"].inspect %>')) notice(inline_template('merge[three] is <%= @o["three"].inspect %>')) DOC regex_array = [%r{merge\[one\] is ("1"|1)}, %r{merge\[two\] is "dos"}, %r{merge\[three\] is {"five"=>("5"|5)}}] it 'merges two hashes' do apply_manifest(pp, :catch_failures => true) do |r| regex_array.each do |i| expect(r.stdout).to match(i) end end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/min_spec.rb0100755005276200011600000000072313212471613017374 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'min function' do describe 'success' do pp = <<-DOC $o = min("the","public","art","galleries") notice(inline_template('min is <%= @o.inspect %>')) DOC it 'mins arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{min is "art"}) end end end describe 'failure' do it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets0040755005276200011600000000000013252003413017006 5ustar00puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/centos-7-x64.yml0100644005276200011600000000025613206047630021676 0ustar00HOSTS: centos-7-x64: roles: - agent - default platform: el-7-x86_64 hypervisor: vagrant box: puppetlabs/centos-7.2-64-nocm CONFIG: type: foss puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/debian-8-x64.yml0100644005276200011600000000026113206047630021622 0ustar00HOSTS: debian-8-x64: roles: - agent - default platform: debian-8-amd64 hypervisor: vagrant box: puppetlabs/debian-8.2-64-nocm CONFIG: type: foss puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/default.yml0100644005276200011600000000027213206047630021242 0ustar00HOSTS: ubuntu-1404-x64: roles: - agent - default platform: ubuntu-14.04-amd64 hypervisor: vagrant box: puppetlabs/ubuntu-14.04-64-nocm CONFIG: type: foss puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/docker0040755005276200011600000000000013252003413020255 5ustar00puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/docker/centos-7.yml0100644005276200011600000000057513206047630022532 0ustar00HOSTS: centos-7-x64: platform: el-7-x86_64 hypervisor: docker image: centos:7 docker_preserve_image: true docker_cmd: '["/usr/sbin/init"]' # install various tools required to get the image up to usable levels docker_image_commands: - 'yum install -y crontabs tar wget openssl sysvinit-tools iproute which initscripts' CONFIG: trace_limit: 200 puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/docker/debian-8.yml0100644005276200011600000000054413206047630022456 0ustar00HOSTS: debian-8-x64: platform: debian-8-amd64 hypervisor: docker image: debian:8 docker_preserve_image: true docker_cmd: '["/sbin/init"]' docker_image_commands: - 'apt-get update && apt-get install -y net-tools wget locales strace lsof && echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && locale-gen' CONFIG: trace_limit: 200 puppetlabs-stdlib-4.25.0/spec/acceptance/nodesets/docker/ubuntu-14.04.yml0100644005276200011600000000073213206047630023054 0ustar00HOSTS: ubuntu-1404-x64: platform: ubuntu-14.04-amd64 hypervisor: docker image: ubuntu:14.04 docker_preserve_image: true docker_cmd: '["/sbin/init"]' docker_image_commands: # ensure that upstart is booting correctly in the container - 'rm /usr/sbin/policy-rc.d && rm /sbin/initctl && dpkg-divert --rename --remove /sbin/initctl && apt-get update && apt-get install -y net-tools wget && locale-gen en_US.UTF-8' CONFIG: trace_limit: 200 puppetlabs-stdlib-4.25.0/spec/acceptance/num2bool_spec.rb0100755005276200011600000000446613212471613020356 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'num2bool function' do describe 'success' do pp1 = <<-DOC $a = 1 $b = "1" $c = "50" $ao = num2bool($a) $bo = num2bool($b) $co = num2bool($c) notice(inline_template('a is <%= @ao.inspect %>')) notice(inline_template('b is <%= @bo.inspect %>')) notice(inline_template('c is <%= @co.inspect %>')) DOC regex_array_true = [%r{a is true}, %r{b is true}, %r{c is true}] it 'bools positive numbers and numeric strings as true' do apply_manifest(pp1, :catch_failures => true) do |r| regex_array_true.each do |i| expect(r.stdout).to match(i) end end end pp2 = <<-DOC $a = 0 $b = -0.1 $c = ["-50","1"] $ao = num2bool($a) $bo = num2bool($b) $co = num2bool($c) notice(inline_template('a is <%= @ao.inspect %>')) notice(inline_template('b is <%= @bo.inspect %>')) notice(inline_template('c is <%= @co.inspect %>')) DOC regex_array_false = [%r{a is false}, %r{b is false}, %r{c is false}] it 'bools negative numbers as false' do apply_manifest(pp2, :catch_failures => true) do |r| regex_array_false.each do |i| expect(r.stdout).to match(i) end end end end describe 'failure' do pp3 = <<-DOC $a = "a" $ao = num2bool($a) notice(inline_template('a is <%= @ao.inspect %>')) DOC it 'fails on words' do expect(apply_manifest(pp3, :expect_failures => true).stderr).to match(%r{not look like a number}) end pp4 = <<-DOC $b = "1b" $bo = num2bool($b) notice(inline_template('b is <%= @bo.inspect %>')) DOC it 'fails on numberwords' do expect(apply_manifest(pp4, :expect_failures => true).stderr).to match(%r{not look like a number}) end pp5 = <<-DOC # rubocop:disable Lint/UselessAssignment $c = {"c" => "-50"} $co = num2bool($c) notice(inline_template('c is <%= @co.inspect %>')) DOC it 'fails on non-numeric/strings' do pending "The function will call .to_s.to_i on anything not a Numeric or String, and results in 0. Is this intended?" expect(apply_manifest(pp5(:expect_failures => true)).stderr).to match(%r{Unable to parse}) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/parsejson_spec.rb0100755005276200011600000000300013212471613020604 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'parsejson function' do describe 'success' do pp1 = <<-DOC $a = '{"hunter": "washere", "tests": "passing"}' $ao = parsejson($a) $tests = $ao['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'parses valid json' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{tests are "passing"}) end end end describe 'failure' do pp2 = <<-DOC $a = '{"hunter": "washere", "tests": "passing",}' $ao = parsejson($a, 'tests are using the default value') notice(inline_template('a is <%= @ao.inspect %>')) DOC it 'raises error on incorrect json - default value is used' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{tests are using the default value}) end end pp3 = <<-DOC $a = '{"hunter": "washere", "tests": "passing",}' $ao = parsejson($a) notice(inline_template('a is <%= @ao.inspect %>')) DOC it 'raises error on incorrect json' do apply_manifest(pp3, :expect_failures => true) do |r| expect(r.stderr).to match(%r{expected next name}) end end pp4 = <<-DOC $o = parsejson() DOC it 'raises error on incorrect number of arguments' do apply_manifest(pp4, :expect_failures => true) do |r| expect(r.stderr).to match(%r{wrong number of arguments}i) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/parseyaml_spec.rb0100755005276200011600000000311113212471613020600 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'parseyaml function' do describe 'success' do pp1 = <<-DOC $a = "---\nhunter: washere\ntests: passing\n" $o = parseyaml($a) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'parses valid yaml' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{tests are "passing"}) end end end describe 'failure' do pp2 = <<-DOC $a = "---\nhunter: washere\ntests: passing\n:" $o = parseyaml($a, {'tests' => 'using the default value'}) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'returns the default value on incorrect yaml' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{tests are "using the default value"}) end end pp3 = <<-DOC $a = "---\nhunter: washere\ntests: passing\n:" $o = parseyaml($a) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'raises error on incorrect yaml' do apply_manifest(pp3, :expect_failures => true) do |r| expect(r.stderr).to match(%r{(syntax error|did not find expected key)}) end end pp4 = <<-DOC $o = parseyaml() DOC it 'raises error on incorrect number of arguments' do apply_manifest(pp4, :expect_failures => true) do |r| expect(r.stderr).to match(%r{wrong number of arguments}i) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/pick_default_spec.rb0100755005276200011600000000266413212471613021251 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'pick_default function' do describe 'success' do pp1 = <<-DOC $a = undef $o = pick_default($a, 'default') notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'pick_defaults a default value' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{picked is "default"}) end end pp2 = <<-DOC $a = undef $b = undef $o = pick_default($a,$b) notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'pick_defaults with no value' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{picked is ""}) end end pp3 = <<-DOC $a = "something" $b = "long" $o = pick_default($a, $b, 'default') notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'pick_defaults the first set value' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{picked is "something"}) end end end describe 'failure' do pp4 = <<-DOC $o = pick_default() notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'raises error with no values' do apply_manifest(pp4, :expect_failures => true) do |r| expect(r.stderr).to match(%r{Must receive at least one argument}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/pick_spec.rb0100755005276200011600000000217313212471613017540 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'pick function' do describe 'success' do pp1 = <<-DOC $a = undef $o = pick($a, 'default') notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'picks a default value' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{picked is "default"}) end end pp2 = <<-DOC $a = "something" $b = "long" $o = pick($a, $b, 'default') notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'picks the first set value' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{picked is "something"}) end end end describe 'failure' do pp3 = <<-DOC $a = undef $b = undef $o = pick($a, $b) notice(inline_template('picked is <%= @o.inspect %>')) DOC it 'raises error with all undef values' do apply_manifest(pp3, :expect_failures => true) do |r| expect(r.stderr).to match(%r{must receive at least one non empty value}) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/prefix_spec.rb0100755005276200011600000000225013212471613020103 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'prefix function' do describe 'success' do pp1 = <<-DOC $o = prefix(['a','b','c'],'p') notice(inline_template('prefix is <%= @o.inspect %>')) DOC it 'prefixes array of values' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{prefix is \["pa", "pb", "pc"\]}) end end pp2 = <<-DOC $o = prefix([],'p') notice(inline_template('prefix is <%= @o.inspect %>')) DOC it 'prefixs with empty array' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{prefix is \[\]}) end end pp3 = <<-DOC $o = prefix(['a','b','c'], undef) notice(inline_template('prefix is <%= @o.inspect %>')) DOC it 'prefixs array of values with undef' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{prefix is \["a", "b", "c"\]}) end end end describe 'failure' do it 'fails with no arguments' it 'fails when first argument is not array' it 'fails when second argument is not string' end end puppetlabs-stdlib-4.25.0/spec/acceptance/pw_hash_spec.rb0100644005276200011600000000213313252003272020230 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' # Windows and OS X do not have useful implementations of crypt(3) describe 'pw_hash function', :unless => %w[windows Darwin SLES].include?(fact('operatingsystem')) do describe 'success' do pp1 = <<-DOC $o = pw_hash('password', 'sha-512', 'salt') notice(inline_template('pw_hash is <%= @o.inspect %>')) DOC it 'hashes passwords' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{pw_hash is "\$6\$salt\$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy\.g\."}) end end pp2 = <<-DOC $o = pw_hash('', 'sha-512', 'salt') notice(inline_template('pw_hash is <%= @o.inspect %>')) DOC it 'returns nil if no password is provided' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{pw_hash is nil}) end end end describe 'failure' do it 'handles less than three arguments' it 'handles more than three arguments' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/range_spec.rb0100755005276200011600000000173213212471613017706 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'range function' do describe 'success' do pp1 = <<-DOC $o = range('a','d') notice(inline_template('range is <%= @o.inspect %>')) DOC it 'ranges letters' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{range is \["a", "b", "c", "d"\]}) end end pp2 = <<-DOC $o = range('a','d', '2') notice(inline_template('range is <%= @o.inspect %>')) DOC it 'ranges letters with a step' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{range is \["a", "c"\]}) end end it 'ranges letters with a negative step' it 'ranges numbers' it 'ranges numbers with a step' it 'ranges numbers with a negative step' it 'ranges numeric strings' it 'ranges zero padded numbers' end describe 'failure' do it 'fails with no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/reject_spec.rb0100755005276200011600000000227113212471613020065 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'reject function' do describe 'success' do pp1 = <<-DOC $o = reject(['aaa','bbb','ccc','aaaddd'], 'aaa') notice(inline_template('reject is <%= @o.inspect %>')) DOC it 'rejects array of values' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{reject is \["bbb", "ccc"\]}) end end pp2 = <<-DOC $o = reject([],'aaa') notice(inline_template('reject is <%= @o.inspect %>')) DOC it 'rejects with empty array' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{reject is \[\]}) end end pp3 = <<-DOC $o = reject(['aaa','bbb','ccc','aaaddd'], undef) notice(inline_template('reject is <%= @o.inspect %>')) DOC it 'rejects array of values with undef' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{reject is \[\]}) end end end describe 'failure' do it 'fails with no arguments' it 'fails when first argument is not array' it 'fails when second argument is not string' end end puppetlabs-stdlib-4.25.0/spec/acceptance/reverse_spec.rb0100755005276200011600000000113213212471613020257 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'reverse function' do describe 'success' do pp1 = <<-DOC $a = "the public art galleries" # Anagram: Large picture halls, I bet $o = reverse($a) notice(inline_template('reverse is <%= @o.inspect %>')) DOC it 'reverses strings' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{reverse is "seirellag tra cilbup eht"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/rstrip_spec.rb0100755005276200011600000000174213212471613020136 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'rstrip function' do describe 'success' do pp1 = <<-DOC $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = rstrip($a) notice(inline_template('rstrip is <%= @o.inspect %>')) DOC it 'rstrips arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{rstrip is \[" the", " public", " art", "galleries"\]}) end end pp2 = <<-DOC $a = " blowzy night-frumps vex'd jack q " $o = rstrip($a) notice(inline_template('rstrip is <%= @o.inspect %>')) DOC it 'rstrips strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{rstrip is " blowzy night-frumps vex'd jack q"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/shuffle_spec.rb0100755005276200011600000000204113212471613020240 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'shuffle function' do describe 'success' do pp1 = <<-DOC $a = ["1", "2", "3", "4", "5", "6", "7", "8", "the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = shuffle($a) notice(inline_template('shuffle is <%= @o.inspect %>')) DOC it 'shuffles arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).not_to match(%r{shuffle is \["1", "2", "3", "4", "5", "6", "7", "8", "the", "public", "art", "galleries"\]}) end end pp2 = <<-DOC $a = "blowzy night-frumps vex'd jack q" $o = shuffle($a) notice(inline_template('shuffle is <%= @o.inspect %>')) DOC it 'shuffles strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).not_to match(%r{shuffle is "blowzy night-frumps vex'd jack q"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/size_spec.rb0100755005276200011600000000251213212471613017561 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'size function' do describe 'success' do pp1 = <<-DOC $a = 'discombobulate' $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) DOC it 'single string size' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{size is 14}) end end pp2 = <<-DOC $a = '' $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) DOC it 'with empty string' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{size is 0}) end end pp3 = <<-DOC $a = undef $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) DOC it 'with undef' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{size is 0}) end end pp4 = <<-DOC $a = ['discombobulate', 'moo'] $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) DOC it 'strings in array' do apply_manifest(pp4, :catch_failures => true) do |r| expect(r.stdout).to match(%r{size is 2}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/sort_spec.rb0100755005276200011600000000165613212471613017606 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'sort function' do describe 'success' do pp1 = <<-DOC $a = ["the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = sort($a) notice(inline_template('sort is <%= @o.inspect %>')) DOC it 'sorts arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{sort is \["art", "galleries", "public", "the"\]}) end end pp2 = <<-DOC $a = "blowzy night-frumps vex'd jack q" $o = sort($a) notice(inline_template('sort is <%= @o.inspect %>')) DOC it 'sorts strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{sort is " '-abcdefghijklmnopqrstuvwxyz"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/squeeze_spec.rb0100755005276200011600000000272313212471613020274 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'squeeze function' do describe 'success' do pp1 = <<-DOC # Real words! $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] $o = squeeze($a) notice(inline_template('squeeze is <%= @o.inspect %>')) DOC it 'squeezes arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{squeeze is \["wales", "laparohysterosalpingophorectomy", "br", "godeship"\]}) end end it 'squeezez arrays with an argument' pp2 = <<-DOC $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = squeeze($a) notice(inline_template('squeeze is <%= @o.inspect %>')) DOC it 'squeezes strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{squeeze is "wales laparohysterosalpingophorectomy br godeship"}) end end pp3 = <<-DOC $a = "countessship duchessship governessship hostessship" $o = squeeze($a, 's') notice(inline_template('squeeze is <%= @o.inspect %>')) DOC it 'squeezes strings with an argument' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{squeeze is "counteship ducheship governeship hosteship"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/str2bool_spec.rb0100755005276200011600000000135713212471613020363 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'str2bool function' do describe 'success' do pp = <<-DOC $o = str2bool('y') notice(inline_template('str2bool is <%= @o.inspect %>')) DOC it 'works with "y"' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{str2bool is true}) end end it 'works with "Y"' it 'works with "yes"' it 'works with "1"' it 'works with "true"' it 'works with "n"' it 'works with "N"' it 'works with "no"' it 'works with "0"' it 'works with "false"' it 'works with undef' end describe 'failure' do it 'handles no arguments' it 'handles non arrays or strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/str2saltedsha512_spec.rb0100755005276200011600000000110313212471613021615 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'str2saltedsha512 function' do describe 'success' do pp = <<-DOC $o = str2saltedsha512('password') notice(inline_template('str2saltedsha512 is <%= @o.inspect %>')) DOC it 'works with "y"' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{str2saltedsha512 is "[a-f0-9]{136}"}) end end end describe 'failure' do it 'handles no arguments' it 'handles more than one argument' it 'handles non strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/strftime_spec.rb0100755005276200011600000000103313212471613020441 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'strftime function' do describe 'success' do pp = <<-DOC $o = strftime('%C') notice(inline_template('strftime is <%= @o.inspect %>')) DOC it 'gives the Century' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{strftime is "20"}) end end it 'takes a timezone argument' end describe 'failure' do it 'handles no arguments' it 'handles invalid format strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/strip_spec.rb0100755005276200011600000000171613212471613017755 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'strip function' do describe 'success' do pp1 = <<-DOC $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = strip($a) notice(inline_template('strip is <%= @o.inspect %>')) DOC it 'strips arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{strip is \["the", "public", "art", "galleries"\]}) end end pp2 = <<-DOC $a = " blowzy night-frumps vex'd jack q " $o = strip($a) notice(inline_template('strip is <%= @o.inspect %>')) DOC it 'strips strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{strip is "blowzy night-frumps vex'd jack q"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/suffix_spec.rb0100755005276200011600000000225013212471613020112 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'suffix function' do describe 'success' do pp1 = <<-DOC $o = suffix(['a','b','c'],'p') notice(inline_template('suffix is <%= @o.inspect %>')) DOC it 'suffixes array of values' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{suffix is \["ap", "bp", "cp"\]}) end end pp2 = <<-DOC $o = suffix([],'p') notice(inline_template('suffix is <%= @o.inspect %>')) DOC it 'suffixs with empty array' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{suffix is \[\]}) end end pp3 = <<-DOC $o = suffix(['a','b','c'], undef) notice(inline_template('suffix is <%= @o.inspect %>')) DOC it 'suffixs array of values with undef' do apply_manifest(pp3, :catch_failures => true) do |r| expect(r.stdout).to match(%r{suffix is \["a", "b", "c"\]}) end end end describe 'failure' do it 'fails with no arguments' it 'fails when first argument is not array' it 'fails when second argument is not string' end end puppetlabs-stdlib-4.25.0/spec/acceptance/swapcase_spec.rb0100755005276200011600000000102713212471613020415 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'swapcase function' do describe 'success' do pp = <<-DOC $o = swapcase('aBcD') notice(inline_template('swapcase is <%= @o.inspect %>')) DOC it 'works with strings' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{swapcase is "AbCd"}) end end it 'works with arrays' end describe 'failure' do it 'handles no arguments' it 'handles non arrays or strings' end end puppetlabs-stdlib-4.25.0/spec/acceptance/time_spec.rb0100755005276200011600000000156313212471613017552 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'time function' do describe 'success' do pp1 = <<-DOC $o = time() notice(inline_template('time is <%= @o.inspect %>')) DOC it 'gives the time' do apply_manifest(pp1, :catch_failures => true) do |r| m = r.stdout.match(%r{time is (\d+)\D}) # When I wrote this test expect(Integer(m[1])).to be > 1_398_894_170 end end pp2 = <<-DOC $o = time('UTC') notice(inline_template('time is <%= @o.inspect %>')) DOC it 'takes a timezone argument' do apply_manifest(pp2, :catch_failures => true) do |r| m = r.stdout.match(%r{time is (\d+)\D}) expect(Integer(m[1])).to be > 1_398_894_170 end end end describe 'failure' do it 'handles more arguments' it 'handles invalid timezones' end end puppetlabs-stdlib-4.25.0/spec/acceptance/to_bytes_spec.rb0100755005276200011600000000131013212471613020432 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'to_bytes function' do describe 'success' do pp = <<-DOC $o = to_bytes('4 kB') notice(inline_template('to_bytes is <%= @o.inspect %>')) DOC it 'converts kB to B' do apply_manifest(pp, :catch_failures => true) do |r| m = r.stdout.match(%r{to_bytes is (\d+)\D}) expect(m[1]).to eq('4096') end end it 'works without the B in unit' it 'works without a space before unit' it 'works without a unit' it 'converts fractions' end describe 'failure' do it 'handles no arguments' it 'handles non integer arguments' it 'handles unknown units like uB' end end puppetlabs-stdlib-4.25.0/spec/acceptance/try_get_value_spec.rb0100755005276200011600000000221313212471613021456 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'try_get_value function' do describe 'success' do pp1 = <<-DOC $data = { 'a' => { 'b' => 'passing'} } $tests = try_get_value($data, 'a/b') notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'gets a value' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{tests are "passing"}) end end end describe 'failure' do pp2 = <<-DOC $data = { 'a' => { 'b' => 'passing'} } $tests = try_get_value($data, 'c/d', 'using the default value') notice(inline_template('tests are <%= @tests.inspect %>')) DOC it 'uses a default value' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{using the default value}) end end pp = <<-DOC $o = try_get_value() DOC it 'raises error on incorrect number of arguments' do apply_manifest(pp, :expect_failures => true) do |r| expect(r.stderr).to match(%r{wrong number of arguments}i) end end end end puppetlabs-stdlib-4.25.0/spec/acceptance/type3x_spec.rb0100755005276200011600000000145313212471613020046 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'type3x function' do describe 'success' do { %{type3x({ 'a' => 'hash' })} => 'Hash', %{type3x(['array'])} => 'Array', %{type3x(false)} => 'Boolean', %{type3x('asdf')} => 'String', %{type3x(242)} => 'Integer', %{type3x(3.14)} => 'Float', }.each do |pp, type| it "with type #{type}" do apply_manifest(pp, :catch_failures => true) end end end describe 'failure' do pp_fail = <<-MANIFEST type3x('one','two') MANIFEST it 'handles improper number of arguments' do expect(apply_manifest(pp_fail, :expect_failures => true).stderr).to match(%r{Wrong number of arguments}) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/type_spec.rb0100755005276200011600000000171113212471613017570 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'type function' do describe 'success' do pp1 = <<-DOC $a = ["the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = type($a) notice(inline_template('type is <%= @o.to_s %>')) DOC it 'types arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{type is Tuple\[String.*, String.*, String.*, String.*\]}) end end pp2 = <<-DOC $a = "blowzy night-frumps vex'd jack q" $o = type($a) notice(inline_template('type is <%= @o.to_s %>')) DOC it 'types strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{type is String}) end end it 'types hashes' it 'types integers' it 'types floats' it 'types booleans' end describe 'failure' do it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/union_spec.rb0100755005276200011600000000116713212471613017744 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'union function' do describe 'success' do pp = <<-DOC $a = ["the","public"] $b = ["art"] $c = ["galleries"] # Anagram: Large picture halls, I bet $o = union($a,$b,$c) notice(inline_template('union is <%= @o.inspect %>')) DOC it 'unions arrays' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{union is \["the", "public", "art", "galleries"\]}) end end end describe 'failure' do it 'handles no arguments' it 'handles non arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/unique_spec.rb0100755005276200011600000000165513212471613020124 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'unique function' do describe 'success' do pp1 = <<-DOC $a = ["wallless", "wallless", "brrr", "goddessship"] $o = unique($a) notice(inline_template('unique is <%= @o.inspect %>')) DOC it 'uniques arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{unique is \["wallless", "brrr", "goddessship"\]}) end end pp2 = <<-DOC $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = unique($a) notice(inline_template('unique is <%= @o.inspect %>')) DOC it 'uniques strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{unique is "wales prohytingcmbd"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/upcase_spec.rb0100755005276200011600000000202313212471613020064 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'upcase function' do describe 'success' do pp1 = <<-DOC $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] $o = upcase($a) notice(inline_template('upcase is <%= @o.inspect %>')) DOC it 'upcases arrays' do apply_manifest(pp1, :catch_failures => true) do |r| expect(r.stdout).to match(%r{upcase is \["WALLLESS", "LAPAROHYSTEROSALPINGOOOPHORECTOMY", "BRRR", "GODDESSSHIP"\]}) end end pp2 = <<-DOC $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = upcase($a) notice(inline_template('upcase is <%= @o.inspect %>')) DOC it 'upcases strings' do apply_manifest(pp2, :catch_failures => true) do |r| expect(r.stdout).to match(%r{upcase is "WALLLESS LAPAROHYSTEROSALPINGOOOPHORECTOMY BRRR GODDESSSHIP"}) end end end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/uriescape_spec.rb0100755005276200011600000000117113212471613020567 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'uriescape function' do describe 'success' do pp = <<-DOC $a = ":/?#[]@!$&'()*+,;= \\\"{}" $o = uriescape($a) notice(inline_template('uriescape is <%= @o.inspect %>')) DOC it 'uriescape strings' do apply_manifest(pp, :catch_failures => true) do |r| expect(r.stdout).to match(%r{uriescape is ":\/\?%23\[\]@!\$&'\(\)\*\+,;=%20%22%7B%7D"}) end end it 'does nothing if a string is already safe' end describe 'failure' do it 'handles no arguments' it 'handles non strings or arrays' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_absolute_path_spec.rb0100755005276200011600000000124613212471613023315 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_absolute_path function' do describe 'success' do %w[ C:/ C:\\\\ C:\\\\WINDOWS\\\\System32 C:/windows/system32 X:/foo/bar X:\\\\foo\\\\bar /var/tmp /var/lib/puppet /var/opt/../lib/puppet ].each do |path| pp = <<-DOC $one = '#{path}' validate_absolute_path($one) DOC it "validates a single argument #{path}" do apply_manifest(pp, :catch_failures => true) end end end describe 'failure' do it 'handles improper number of arguments' it 'handles relative paths' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_array_spec.rb0100755005276200011600000000165113212471613021601 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_array function' do describe 'success' do pp1 = <<-DOC $one = ['a', 'b'] validate_array($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = ['a', 'b'] $two = [['c'], 'd'] validate_array($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end [ %{validate_array({'a' => 'hash' })}, %{validate_array('string')}, %{validate_array(false)}, %{validate_array(undef)}, ].each do |pp| it "rejects #{pp.inspect}" do expect(apply_manifest(pp, :expect_failures => true).stderr).to match(%r{is not an Array\. It looks to be a}) end end end describe 'failure' do it 'handles improper number of arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_augeas_spec.rb0100755005276200011600000000365113212471613021732 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_augeas function', :unless => (fact('osfamily') == 'windows') do describe 'prep' do it 'installs augeas for tests' end describe 'success' do context 'with valid inputs with no 3rd argument' do { 'root:x:0:0:root:/root:/bin/bash\n' => 'Passwd.lns', 'proc /proc proc nodev,noexec,nosuid 0 0\n' => 'Fstab.lns', }.each do |line, lens| pp1 = <<-DOC $line = "#{line}" $lens = "#{lens}" validate_augeas($line, $lens) DOC it "validates a single argument for #{lens}" do apply_manifest(pp1, :catch_failures => true) end end end context 'with valid inputs with 3rd and 4th arguments' do line = 'root:x:0:0:root:/root:/bin/barsh\n' lens = 'Passwd.lns' restriction = '$file/*[shell="/bin/barsh"]' pp2 = <<-DOC $line = "#{line}" $lens = "#{lens}" $restriction = ['#{restriction}'] validate_augeas($line, $lens, $restriction, "my custom failure message") DOC it 'validates a restricted value' do expect(apply_manifest(pp2, :expect_failures => true).stderr).to match(%r{my custom failure message}) end end context 'with invalid inputs' do { 'root:x:0:0:root' => 'Passwd.lns', '127.0.1.1' => 'Hosts.lns', }.each do |line, lens| pp3 = <<-DOC $line = "#{line}" $lens = "#{lens}" validate_augeas($line, $lens) DOC it "validates a single argument for #{lens}" do apply_manifest(pp3, :expect_failures => true) end end end context 'with garbage inputs' do it 'raises an error on invalid inputs' end end describe 'failure' do it 'handles improper number of arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_bool_spec.rb0100755005276200011600000000161113212471613021412 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_bool function' do describe 'success' do pp1 = <<-DOC $one = true validate_bool($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = true $two = false validate_bool($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end [ %{validate_bool('true')}, %{validate_bool('false')}, %{validate_bool([true])}, %{validate_bool(undef)}, ].each do |pp3| it "rejects #{pp3.inspect}" do expect(apply_manifest(pp3, :expect_failures => true).stderr).to match(%r{is not a boolean\. It looks to be a}) end end end describe 'failure' do it 'handles improper number of arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_cmd_spec.rb0100755005276200011600000000232513212471613021225 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_cmd function' do describe 'success' do pp1 = <<-DOC $one = 'foo' if $::osfamily == 'windows' { $two = 'echo' #shell built-in } else { $two = '/bin/echo' } validate_cmd($one,$two) DOC it 'validates a true command' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = 'foo' if $::osfamily == 'windows' { $two = 'C:/aoeu' } else { $two = '/bin/aoeu' } validate_cmd($one,$two) DOC it 'validates a fail command' do apply_manifest(pp2, :expect_failures => true) end pp3 = <<-DOC $one = 'foo' if $::osfamily == 'windows' { $two = 'C:/aoeu' } else { $two = '/bin/aoeu' } validate_cmd($one,$two,"aoeu is dvorak") DOC it 'validates a fail command with a custom error message' do apply_manifest(pp3, :expect_failures => true) do |output| expect(output.stderr).to match(%r{aoeu is dvorak}) end end end describe 'failure' do it 'handles improper number of arguments' it 'handles improper argument types' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_hash_spec.rb0100755005276200011600000000162013212471613021402 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_hash function' do describe 'success' do pp1 = <<-DOC $one = { 'a' => 1 } validate_hash($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = { 'a' => 1 } $two = { 'b' => 2 } validate_hash($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end [ %{validate_hash('{ "not" => "hash" }')}, %{validate_hash('string')}, %{validate_hash(["array"])}, %{validate_hash(undef)}, ].each do |pp3| it "rejects #{pp3.inspect}" do expect(apply_manifest(pp3, :expect_failures => true).stderr).to match(%r{}) end end end describe 'failure' do it 'handles improper number of arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_ipv4_address_spec.rb0100755005276200011600000000133713212471613023053 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_ipv4_address function' do describe 'success' do pp1 = <<-DOC $one = '1.2.3.4' validate_ipv4_address($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = '1.2.3.4' $two = '5.6.7.8' validate_ipv4_address($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end end describe 'failure' do it 'handles improper number of arguments' it 'handles ipv6 addresses' it 'handles non-ipv4 strings' it 'handles numbers' it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_ipv6_address_spec.rb0100755005276200011600000000137213212471613023054 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_ipv6_address function' do describe 'success' do pp1 = <<-DOC $one = '3ffe:0505:0002::' validate_ipv6_address($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = '3ffe:0505:0002::' $two = '3ffe:0505:0001::' validate_ipv6_address($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end end describe 'failure' do it 'handles improper number of arguments' it 'handles ipv6 addresses' it 'handles non-ipv6 strings' it 'handles numbers' it 'handles no arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_re_spec.rb0100755005276200011600000000217013212471613021066 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_re function' do describe 'success' do pp1 = <<-DOC $one = 'one' $two = '^one$' validate_re($one,$two) DOC it 'validates a string' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = 'one' $two = ['^one$', '^two'] validate_re($one,$two) DOC it 'validates an array' do apply_manifest(pp2, :catch_failures => true) end pp3 = <<-DOC $one = 'one' $two = ['^two$', '^three'] validate_re($one,$two) DOC it 'validates a failed array' do apply_manifest(pp3, :expect_failures => true) end pp4 = <<-DOC $one = '3.4.3' $two = '^2.7' validate_re($one,$two,"The $puppetversion fact does not match 2.7") DOC it 'validates a failed array with a custom error message' do expect(apply_manifest(pp4, :expect_failures => true).stderr).to match(%r{does not match}) end end describe 'failure' do it 'handles improper number of arguments' it 'handles improper argument types' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_slength_spec.rb0100755005276200011600000000353213212471613022127 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_slength function' do describe 'success' do pp1 = <<-DOC $one = 'discombobulate' $two = 17 validate_slength($one,$two) DOC it 'validates a single string max' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = ['discombobulate', 'moo'] $two = 17 validate_slength($one,$two) DOC it 'validates multiple string maxes' do apply_manifest(pp2, :catch_failures => true) end pp3 = <<-DOC $one = ['discombobulate', 'moo'] $two = 17 $three = 3 validate_slength($one,$two,$three) DOC it 'validates min/max of strings in array' do apply_manifest(pp3, :catch_failures => true) end pp4 = <<-DOC $one = 'discombobulate' $two = 1 validate_slength($one,$two) DOC it 'validates a single string max of incorrect length' do apply_manifest(pp4, :expect_failures => true) end pp5 = <<-DOC $one = ['discombobulate', 'moo'] $two = 3 validate_slength($one,$two) DOC it 'validates multiple string maxes of incorrect length' do apply_manifest(pp5, :expect_failures => true) end pp6 = <<-DOC $one = ['discombobulate', 'moo'] $two = 17 $three = 10 validate_slength($one,$two,$three) DOC it 'validates multiple strings min/maxes of incorrect length' do apply_manifest(pp6, :expect_failures => true) end end describe 'failure' do it 'handles improper number of arguments' it 'handles improper first argument type' it 'handles non-strings in array of first argument' it 'handles improper second argument type' it 'handles improper third argument type' it 'handles negative ranges' it 'handles improper ranges' end end puppetlabs-stdlib-4.25.0/spec/acceptance/validate_string_spec.rb0100755005276200011600000000212513212471613021766 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'validate_string function' do describe 'success' do pp1 = <<-DOC $one = 'string' validate_string($one) DOC it 'validates a single argument' do apply_manifest(pp1, :catch_failures => true) end pp2 = <<-DOC $one = 'string' $two = 'also string' validate_string($one,$two) DOC it 'validates an multiple arguments' do apply_manifest(pp2, :catch_failures => true) end pp3 = <<-DOC validate_string(undef) DOC it 'validates undef' do apply_manifest(pp3, :catch_failures => true) end { %{validate_string({ 'a' => 'hash' })} => 'Hash', %{validate_string(['array'])} => 'Array', %{validate_string(false)} => 'FalseClass', }.each do |pp4, type| it "validates a non-string: #{pp4.inspect}" do expect(apply_manifest(pp4, :expect_failures => true).stderr).to match(%r{a #{type}}) end end end describe 'failure' do it 'handles improper number of arguments' end end puppetlabs-stdlib-4.25.0/spec/acceptance/values_at_spec.rb0100755005276200011600000000435513212471613020601 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'values_at function' do describe 'success' do pp1 = <<-DOC $one = ['a','b','c','d','e'] $two = 1 $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'returns a specific value' do expect(apply_manifest(pp1, :catch_failures => true).stdout).to match(%r{\["b"\]}) end pp2 = <<-DOC $one = ['a','b','c','d','e'] $two = -1 $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'returns a specific negative index value' do pending("negative numbers don't work") expect(apply_manifest(pp2, :catch_failures => true).stdout).to match(%r{\["e"\]}) end pp3 = <<-DOC $one = ['a','b','c','d','e'] $two = "1-3" $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'returns a range of values' do expect(apply_manifest(pp3, :catch_failures => true).stdout).to match(%r{\["b", "c", "d"\]}) end pp4 = <<-DOC $one = ['a','b','c','d','e'] $two = ["1-3",0] $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'returns a negative specific value and range of values' do expect(apply_manifest(pp4, :catch_failures => true).stdout).to match(%r{\["b", "c", "d", "a"\]}) end end describe 'failure' do pp5 = <<-DOC $one = ['a','b','c','d','e'] $output = values_at($one) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles improper number of arguments' do expect(apply_manifest(pp5, :expect_failures => true).stderr).to match(%r{Wrong number of arguments}) end pp6 = <<-DOC $one = ['a','b','c','d','e'] $two = [] $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles non-indicies arguments' do expect(apply_manifest(pp6, :expect_failures => true).stderr).to match(%r{at least one positive index}) end it 'detects index ranges smaller than the start range' it 'handles index ranges larger than array' it 'handles non-integer indicies' end end puppetlabs-stdlib-4.25.0/spec/acceptance/values_spec.rb0100755005276200011600000000137113212471613020110 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'values function' do describe 'success' do pp1 = <<-DOC $arg = { 'a' => 1, 'b' => 2, 'c' => 3, } $output = values($arg) notice(inline_template('<%= @output.sort.inspect %>')) DOC it 'returns an array of values' do expect(apply_manifest(pp1, :catch_failures => true).stdout).to match(%r{\[1, 2, 3\]}) end end describe 'failure' do pp2 = <<-DOC $arg = "foo" $output = values($arg) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles non-hash arguments' do expect(apply_manifest(pp2, :expect_failures => true).stderr).to match(%r{Requires hash}) end end end puppetlabs-stdlib-4.25.0/spec/acceptance/zip_spec.rb0100755005276200011600000000440613212471613017415 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' describe 'zip function' do describe 'success' do pp1 = <<-DOC $one = [1,2,3,4] $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'zips two arrays of numbers together' do expect(apply_manifest(pp1, :catch_failures => true).stdout).to match(%r{\[\[1, 5\], \[2, 6\], \[3, 7\], \[4, 8\]\]}) end pp2 = <<-DOC $one = [1,2,"three",4] $two = [true,true,false,false] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'zips two arrays of numbers & bools together' do expect(apply_manifest(pp2, :catch_failures => true).stdout).to match(%r{\[\[1, true\], \[2, true\], \["three", false\], \[4, false\]\]}) end # XXX This only tests the argument `true`, even though the following are valid: # 1 t y true yes # 0 f n false no # undef undefined pp3 = <<-DOC $one = [1,2,3,4] $two = [5,6,7,8] $output = zip($one,$two,true) notice(inline_template('<%= @output.inspect %>')) DOC it 'zips two arrays of numbers together and flattens them' do expect(apply_manifest(pp3, :catch_failures => true).stdout).to match(%r{\[1, 5, 2, 6, 3, 7, 4, 8\]}) end # XXX Is this expected behavior? pp4 = <<-DOC $one = [1,2] $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles unmatched length' do expect(apply_manifest(pp4, :catch_failures => true).stdout).to match(%r{\[\[1, 5\], \[2, 6\]\]}) end end describe 'failure' do pp5 = <<-DOC $one = [1,2] $output = zip($one) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles improper number of arguments' do expect(apply_manifest(pp5, :expect_failures => true).stderr).to match(%r{Wrong number of arguments}) end pp6 = <<-DOC $one = "a string" $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) DOC it 'handles improper argument types' do expect(apply_manifest(pp6, :expect_failures => true).stderr).to match(%r{Requires array}) end end end puppetlabs-stdlib-4.25.0/spec/fixtures0040755005276200011600000000000013252003413014745 5ustar00puppetlabs-stdlib-4.25.0/spec/fixtures/dscacheutil0040755005276200011600000000000013252003413017235 5ustar00puppetlabs-stdlib-4.25.0/spec/fixtures/dscacheutil/root0100644005276200011600000000012713206047630020227 0ustar00name: root password: * uid: 0 gid: 0 dir: /var/root shell: /bin/bash gecos: rawr Root puppetlabs-stdlib-4.25.0/spec/fixtures/lsuser0040755005276200011600000000000013252003413016262 5ustar00puppetlabs-stdlib-4.25.0/spec/fixtures/lsuser/root0100644005276200011600000000002613206047630017252 0ustar00#name:home root:/root puppetlabs-stdlib-4.25.0/spec/fixtures/test0040755005276200011600000000000013252003413015724 5ustar00puppetlabs-stdlib-4.25.0/spec/fixtures/test/manifests0040755005276200011600000000000013252003413017715 5ustar00puppetlabs-stdlib-4.25.0/spec/fixtures/test/manifests/base32.pp0100644005276200011600000000017413252003272021416 0ustar00# Class to test the Stdlib::Base32 type alias class test::base32 ( Stdlib::Base32 $value, ) { notice('Success') } puppetlabs-stdlib-4.25.0/spec/fixtures/test/manifests/base64.pp0100644005276200011600000000017413252003272021423 0ustar00# Class to test the Stdlib::Base64 type alias class test::base64 ( Stdlib::Base64 $value, ) { notice('Success') } puppetlabs-stdlib-4.25.0/spec/fixtures/test/manifests/deftype.pp0100644005276200011600000000014513212471613022001 0ustar00# Class to test deftype define test::deftype( $param = 'foo' ) { notify { "deftype: ${title}": } } puppetlabs-stdlib-4.25.0/spec/fixtures/test/manifests/ensure_resources.pp0100644005276200011600000000031313212471613023731 0ustar00# A helper class to test the ensure_resources function class test::ensure_resources( $resource_type, $title_hash, $attributes_hash ) { ensure_resources($resource_type, $title_hash, $attributes_hash) } puppetlabs-stdlib-4.25.0/spec/functions0040755005276200011600000000000013252003413015104 5ustar00puppetlabs-stdlib-4.25.0/spec/functions/abs_spec.rb0100755005276200011600000000332313212471613017277 0ustar00require 'spec_helper' describe 'abs' do it { is_expected.not_to eq(nil) } describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'signature validation in puppet4', :if => RSpec.configuration.puppet_future do it { pending 'the puppet 4 implementation' is_expected.to run.with_params.and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params([]).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params({}).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(true).and_raise_error(ArgumentError) } end it { is_expected.to run.with_params(-34).and_return(34) } it { is_expected.to run.with_params('-34').and_return(34) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params('34').and_return(34) } it { is_expected.to run.with_params(-34.5).and_return(34.5) } it { is_expected.to run.with_params('-34.5').and_return(34.5) } it { is_expected.to run.with_params(34.5).and_return(34.5) } it { is_expected.to run.with_params('34.5').and_return(34.5) } end puppetlabs-stdlib-4.25.0/spec/functions/any2array_spec.rb0100755005276200011600000000210013206047630020433 0ustar00require 'spec_helper' describe 'any2array' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_return([]) } it { is_expected.to run.with_params(true).and_return([true]) } it { is_expected.to run.with_params('one').and_return(['one']) } it { is_expected.to run.with_params('one', 'two').and_return(%w[one two]) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params(%w[one two]).and_return(%w[one two]) } it { is_expected.to run.with_params({}).and_return([]) } it { is_expected.to run.with_params('key' => 'value').and_return(%w[key value]) } it { is_expected.to run.with_params('‰').and_return(['‰']) } it { is_expected.to run.with_params('竹').and_return(['竹']) } it { is_expected.to run.with_params('Ü').and_return(['Ü']) } it { is_expected.to run.with_params('∇').and_return(['∇']) } it { is_expected.to run.with_params('€', '万', 'Ö', '♥', '割').and_return(['€', '万', 'Ö', '♥', '割']) } end puppetlabs-stdlib-4.25.0/spec/functions/any2bool_spec.rb0100755005276200011600000000254613212471613020265 0ustar00require 'spec_helper' describe 'any2bool' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true).and_return(true) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('1.5').and_return(true) } describe 'when testing stringy values that mean "true"' do %w[TRUE 1 t y true yes].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing stringy values that mean "false"' do ['FALSE', '', '0', 'f', 'n', 'false', 'no', 'undef', 'undefined', nil, :undef].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'when testing numeric values that mean "true"' do [1, '1', 1.5, '1.5'].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing numeric that mean "false"' do [-1, '-1', -1.5, '-1.5', '0', 0].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'everything else returns true' do [[], {}, ['1'], [1], { :one => 1 }].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end end puppetlabs-stdlib-4.25.0/spec/functions/assert_private_spec.rb0100755005276200011600000000267013206047630021572 0ustar00require 'spec_helper' describe 'assert_private' do context 'when called from inside module' do it 'does not fail' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('foo') is_expected.to run.with_params end end context 'when called from private class' do before :each do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') end it 'fails with a class error message' do scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('hostclass') is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Class foo::baz is private}) end context 'with an explicit failure message' do it { is_expected.to run.with_params('failure message!').and_raise_error(Puppet::ParseError, %r{failure message!}) } end end context 'when called from private definition' do it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('definition') is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Definition foo::baz is private}) end end end puppetlabs-stdlib-4.25.0/spec/functions/base64_spec.rb0100755005276200011600000001042013206047630017613 0ustar00require 'spec_helper' describe 'base64' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument must be one of}) } it { is_expected.to run.with_params('encode', ['two']).and_raise_error(Puppet::ParseError, %r{second argument must be a string}) } it { is_expected.to run.with_params('encode', 2).and_raise_error(Puppet::ParseError, %r{second argument must be a string}) } it { is_expected.to run.with_params('encode', 'thestring', 'three').and_raise_error(Puppet::ParseError, %r{third argument must be one of}) } it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n", 'strict').and_raise_error(ArgumentError) } it { is_expected.to run.with_params('encode', 'thestring').and_return("dGhlc3RyaW5n\n") } it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n').and_return('thestring') } it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n").and_return('thestring') } it { is_expected.to run.with_params('encode', 'thestring', 'default').and_return("dGhlc3RyaW5n\n") } it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n', 'default').and_return('thestring') } it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n", 'default').and_return('thestring') } it { is_expected.to run.with_params('encode', 'thestring', 'strict').and_return('dGhlc3RyaW5n') } it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n', 'strict').and_return('thestring') } it { is_expected.to run.with_params('encode', 'a very long string that will cause the base64 encoder to produce output with multiple lines') .and_return("YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n") } it { is_expected.to run.with_params('decode', "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n") .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') } it { is_expected.to run.with_params('decode', 'YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==') .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') } it { is_expected.to run.with_params('encode', 'a very long string that will cause the base64 encoder to produce output with multiple lines', 'strict') .and_return('YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==') } it { is_expected.to run.with_params('decode', 'YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==', 'strict') .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') } it { is_expected.to run.with_params('encode', 'https://www.google.com.tw/?gws_rd=ssl#q=hello+world', 'urlsafe') .and_return('aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk') } it { is_expected.to run.with_params('decode', 'aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk', 'urlsafe') .and_return('https://www.google.com.tw/?gws_rd=ssl#q=hello+world') } it { is_expected.to run.with_params('encode', 'https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add', 'urlsafe') .and_return('aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=') } it { is_expected.to run.with_params('decode', 'aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=', 'urlsafe') .and_return('https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add') } end puppetlabs-stdlib-4.25.0/spec/functions/basename_spec.rb0100755005276200011600000000221513212471613020304 0ustar00require 'spec_helper' describe 'basename' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('/path/to/a/file.ext', []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('/path/to/a/file.ext').and_return('file.ext') } it { is_expected.to run.with_params('relative_path/to/a/file.ext').and_return('file.ext') } it { is_expected.to run.with_params('/path/to/a/file.ext', '.ext').and_return('file') } it { is_expected.to run.with_params('relative_path/to/a/file.ext', '.ext').and_return('file') } it { is_expected.to run.with_params('scheme:///path/to/a/file.ext').and_return('file.ext') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('scheme:///√ạĺűē/竹.ext').and_return('竹.ext') } it { is_expected.to run.with_params('ҝẽγ:/√ạĺűē/竹.ㄘ', '.ㄘ').and_return('竹') } end end puppetlabs-stdlib-4.25.0/spec/functions/bool2num_spec.rb0100755005276200011600000000064713206047630020276 0ustar00require 'spec_helper' describe 'bool2num' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } [true, 'true', AlsoString.new('true')].each do |truthy| it { is_expected.to run.with_params(truthy).and_return(1) } end [false, 'false', AlsoString.new('false')].each do |falsey| it { is_expected.to run.with_params(falsey).and_return(0) } end end puppetlabs-stdlib-4.25.0/spec/functions/bool2str_spec.rb0100755005276200011600000000155713206047630020310 0ustar00require 'spec_helper' describe 'bool2str' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } ['true', 'false', nil, :undef, ''].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(true, 'yes', 'no', 'maybe').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(true, 'maybe').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(true, 0, 1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(true).and_return('true') } it { is_expected.to run.with_params(false).and_return('false') } it { is_expected.to run.with_params(true, 'yes', 'no').and_return('yes') } it { is_expected.to run.with_params(false, 'yes', 'no').and_return('no') } end puppetlabs-stdlib-4.25.0/spec/functions/camelcase_spec.rb0100755005276200011600000000166613206047630020460 0ustar00require 'spec_helper' describe 'camelcase' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('abc').and_return('Abc') } it { is_expected.to run.with_params('aa_bb_cc').and_return('AaBbCc') } it { is_expected.to run.with_params('_aa__bb__cc_').and_return('AaBbCc') } it { is_expected.to run.with_params('100').and_return('100') } it { is_expected.to run.with_params('1_00').and_return('100') } it { is_expected.to run.with_params('_').and_return('') } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(%w[abc aa_bb_cc]).and_return(%w[Abc AaBbCc]) } it { is_expected.to run.with_params(['abc', 1, 'aa_bb_cc']).and_return(['Abc', 1, 'AaBbCc']) } end puppetlabs-stdlib-4.25.0/spec/functions/capitalize_spec.rb0100755005276200011600000000137313206047630020663 0ustar00require 'spec_helper' describe 'capitalize' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('One') } it { is_expected.to run.with_params('one two').and_return('One two') } it { is_expected.to run.with_params('ONE TWO').and_return('One two') } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('One') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(%w[one two]).and_return(%w[One Two]) } it { is_expected.to run.with_params(['one', 1, 'two']).and_return(['One', 1, 'Two']) } end puppetlabs-stdlib-4.25.0/spec/functions/ceiling_spec.rb0100755005276200011600000000107013206047630020142 0ustar00require 'spec_helper' describe 'ceiling' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } it { is_expected.to run.with_params(33.1).and_return(34) } it { is_expected.to run.with_params(-33.1).and_return(-33) } end puppetlabs-stdlib-4.25.0/spec/functions/chomp_spec.rb0100755005276200011600000000243413212471613017642 0ustar00require 'spec_helper' describe 'chomp' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } it { is_expected.to run.with_params(%W[one\n two three\n]).and_return(%w[one two three]) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(%w[one two three]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end puppetlabs-stdlib-4.25.0/spec/functions/chop_spec.rb0100755005276200011600000000242713212471613017467 0ustar00require 'spec_helper' describe 'chop' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_return('on') } it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } it { is_expected.to run.with_params(%W[one\n two three\n]).and_return(%w[one tw three]) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return('on') } it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(%w[one tw three]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end puppetlabs-stdlib-4.25.0/spec/functions/clamp_spec.rb0100644005276200011600000000203213206047630017620 0ustar00require 'spec_helper' describe 'clamp' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(12, 88, 71, 190).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, need three to clamp}) } it { is_expected.to run.with_params('12string', 88, 15).and_raise_error(Puppet::ParseError, %r{Required explicit numeric}) } it { is_expected.to run.with_params(1, 2, 'a' => 55).and_raise_error(Puppet::ParseError, %r{The Hash type is not allowed}) } it { is_expected.to run.with_params('24', [575, 187]).and_return(187) } it { is_expected.to run.with_params([4, 3, '99']).and_return(4) } it { is_expected.to run.with_params(16, 750, 88).and_return(88) } it { is_expected.to run.with_params([3, 873], 73).and_return(73) } it { is_expected.to run.with_params([4], 8, 75).and_return(8) } it { is_expected.to run.with_params([6], [31], 9911).and_return(31) } end puppetlabs-stdlib-4.25.0/spec/functions/concat_spec.rb0100755005276200011600000000275413212471613020010 0ustar00require 'spec_helper' describe 'concat' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, [2]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([1], [2], [3]).and_return([1, 2, 3]) } it { is_expected.to run.with_params(%w[1 2 3], %w[4 5 6]).and_return(%w[1 2 3 4 5 6]) } it { is_expected.to run.with_params(%w[1 2 3], '4').and_return(%w[1 2 3 4]) } it { is_expected.to run.with_params(%w[1 2 3], [%w[4 5], '6']).and_return(['1', '2', '3', %w[4 5], '6']) } it { is_expected.to run.with_params(%w[1 2], %w[3 4], %w[5 6]).and_return(%w[1 2 3 4 5 6]) } it { is_expected.to run.with_params(%w[1 2], '3', '4', %w[5 6]).and_return(%w[1 2 3 4 5 6]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params([{ 'a' => 'b' }], 'c' => 'd', 'e' => 'f').and_return([{ 'a' => 'b' }, { 'c' => 'd', 'e' => 'f' }]) } it { is_expected.to run.with_params(['ấ', 'β', '©'], %w[đ ể 文字列]).and_return(['ấ', 'β', '©', 'đ', 'ể', '文字列']) } end arguments = [%w[1 2 3], %w[4 5 6]] originals = [arguments[0].dup, arguments[1].dup] it 'leaves the original array intact' do _result = subject.call([arguments[0], arguments[1]]) arguments.each_with_index do |argument, index| expect(argument).to eq(originals[index]) end end end puppetlabs-stdlib-4.25.0/spec/functions/convert_base_spec.rb0100644005276200011600000000317613206047630021210 0ustar00require 'spec_helper' describe 'convert_base' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('asdf').and_raise_error(ArgumentError) } it { is_expected.to run.with_params('asdf', 'moo', 'cow').and_raise_error(ArgumentError) } it { is_expected.to run.with_params(['1'], '2').and_raise_error(Puppet::ParseError, %r{argument must be either a string or an integer}) } it { is_expected.to run.with_params('1', ['2']).and_raise_error(Puppet::ParseError, %r{argument must be either a string or an integer}) } it { is_expected.to run.with_params('1', 1).and_raise_error(Puppet::ParseError, %r{base must be at least 2 and must not be greater than 36}) } it { is_expected.to run.with_params('1', 37).and_raise_error(Puppet::ParseError, %r{base must be at least 2 and must not be greater than 36}) } it 'raises a ParseError if argument 1 is a string that does not correspond to an integer in base 10' do is_expected.to run.with_params('ten', 6).and_raise_error(Puppet::ParseError, %r{argument must be an integer or a string corresponding to an integer in base 10}) end it 'raises a ParseError if argument 2 is a string and does not correspond to an integer in base 10' do is_expected.to run.with_params(100, 'hex').and_raise_error(Puppet::ParseError, %r{argument must be an integer or a string corresponding to an integer in base 10}) end it { is_expected.to run.with_params('11', '16').and_return('b') } it { is_expected.to run.with_params('35', '36').and_return('z') } it { is_expected.to run.with_params(5, 2).and_return('101') } end puppetlabs-stdlib-4.25.0/spec/functions/count_spec.rb0100755005276200011600000000241013206047630017657 0ustar00require 'spec_helper' describe 'count' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('one').and_raise_error(ArgumentError) } it { is_expected.to run.with_params('one', 'two').and_return(1) } it { pending('should actually be like this, and not like above') is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(ArgumentError) } it { is_expected.to run.with_params(%w[one two three]).and_return(3) } it { is_expected.to run.with_params(%w[one two two], 'two').and_return(2) } it { is_expected.to run.with_params(['one', nil, 'two']).and_return(2) } it { is_expected.to run.with_params(['one', '', 'two']).and_return(2) } it { is_expected.to run.with_params(['one', :undef, 'two']).and_return(2) } it { is_expected.to run.with_params(['ổņ℮', 'ŧщộ', 'three']).and_return(3) } it { is_expected.to run.with_params(['ổņ℮', 'ŧщộ', 'ŧщộ'], 'ŧщộ').and_return(2) } it { is_expected.to run.with_params(['ổņ℮', nil, 'ŧщộ']).and_return(2) } it { is_expected.to run.with_params(['ổņ℮', :undef, 'ŧщộ']).and_return(2) } end puppetlabs-stdlib-4.25.0/spec/functions/deep_merge_spec.rb0100755005276200011600000000545413212471613020635 0ustar00require 'spec_helper' describe 'deep_merge' do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('key' => 'value').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}, '2').and_raise_error(Puppet::ParseError, %r{unexpected argument type String}) } it { is_expected.to run.with_params({}, 2).and_raise_error(Puppet::ParseError, %r{unexpected argument}) } it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, {}).and_return({}) } it { is_expected.to run.with_params({}, {}, {}).and_return({}) } it { is_expected.to run.with_params({}, {}, {}, {}).and_return({}) } it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } it { is_expected.to run.with_params({ 'key1' => 'value1' }, 'key2' => 'value2').and_return('key1' => 'value1', 'key2' => 'value2') } describe 'when arguments have key collisions' do it 'prefers values from the last hash' do is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2' }, 'key2' => 'replacement_value', 'key3' => 'value3') \ .and_return('key1' => 'value1', 'key2' => 'replacement_value', 'key3' => 'value3') end it { is_expected.to run \ .with_params({ 'key1' => 'value1' }, { 'key1' => 'value2' }, 'key1' => 'value3') \ .and_return('key1' => 'value3') } end describe 'when arguments have subhashes' do it { is_expected.to run \ .with_params({ 'key1' => 'value1' }, 'key2' => 'value2', 'key3' => { 'subkey1' => 'value4' }) \ .and_return('key1' => 'value1', 'key2' => 'value2', 'key3' => { 'subkey1' => 'value4' }) } it { is_expected.to run \ .with_params({ 'key1' => { 'subkey1' => 'value1' } }, 'key1' => { 'subkey2' => 'value2' }) \ .and_return('key1' => { 'subkey1' => 'value1', 'subkey2' => 'value2' }) } it { is_expected.to run \ .with_params({ 'key1' => { 'subkey1' => { 'subsubkey1' => 'value1' } } }, 'key1' => { 'subkey1' => { 'subsubkey1' => 'value2' } }) \ .and_return('key1' => { 'subkey1' => { 'subsubkey1' => 'value2' } }) } end arguments = { 'key1' => 'value1' }, { 'key2' => 'value2' } originals = [arguments[0].dup, arguments[1].dup] it 'does not change the original hashes' do subject.call([arguments[0], arguments[1]]) arguments.each_with_index do |argument, index| expect(argument).to eq(originals[index]) end end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params({ 'ĸέỹ1' => 'ϋǻļủë1' }, 'この文字列' => '万').and_return('ĸέỹ1' => 'ϋǻļủë1', 'この文字列' => '万') } end end puppetlabs-stdlib-4.25.0/spec/functions/defined_with_params_spec.rb0100755005276200011600000000541713212471613022534 0ustar00require 'spec_helper' describe 'defined_with_params' do describe 'when no resource is specified' do it { is_expected.to run.with_params.and_raise_error(ArgumentError) } end describe 'when compared against a resource with no attributes' do let :pre_condition do 'user { "dan": }' end it { is_expected.to run.with_params('User[dan]', {}).and_return(true) } it { is_expected.to run.with_params('User[bob]', {}).and_return(false) } it { is_expected.to run.with_params('User[dan]', 'foo' => 'bar').and_return(false) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('User[ĵĭмოү]', {}).and_return(false) } it { is_expected.to run.with_params('User[ポーラ]', {}).and_return(false) } end end describe 'when compared against a resource with attributes' do let :pre_condition do 'user { "dan": ensure => present, shell => "/bin/csh", managehome => false}' end it { is_expected.to run.with_params('User[dan]', {}).and_return(true) } it { is_expected.to run.with_params('User[dan]', '').and_return(true) } it { is_expected.to run.with_params('User[dan]', 'ensure' => 'present').and_return(true) } it { is_expected.to run.with_params('User[dan]', 'ensure' => 'present', 'managehome' => false).and_return(true) } it { is_expected.to run.with_params('User[dan]', 'ensure' => 'absent', 'managehome' => false).and_return(false) } end describe 'when passing undef values' do let :pre_condition do 'file { "/tmp/a": ensure => present }' end it { is_expected.to run.with_params('File[/tmp/a]', {}).and_return(true) } it { is_expected.to run.with_params('File[/tmp/a]', 'ensure' => 'present', 'owner' => :undef).and_return(true) } end describe 'when the reference is a' do let :pre_condition do 'user { "dan": }' end context 'with reference' do it { is_expected.to run.with_params(Puppet::Resource.new('User[dan]'), {}).and_return(true) } end if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 context 'with array' do it 'fails' do expect { subject.call([['User[dan]'], {}]) }.to raise_error ArgumentError, %r{not understood: 'Array'} end end end end describe 'when passed a defined type' do let :pre_condition do 'test::deftype { "foo": }' end it { is_expected.to run.with_params('Test::Deftype[foo]', {}).and_return(true) } it { is_expected.to run.with_params('Test::Deftype[bar]', {}).and_return(false) } it { is_expected.to run.with_params(Puppet::Resource.new('Test::Deftype[foo]'), {}).and_return(true) } it { is_expected.to run.with_params(Puppet::Resource.new('Test::Deftype[bar]'), {}).and_return(false) } end end puppetlabs-stdlib-4.25.0/spec/functions/delete_at_spec.rb0100755005276200011600000000233513206047630020463 0ustar00require 'spec_helper' describe 'delete_at' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, 1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(['one'], 'two').and_raise_error(Puppet::ParseError) } it { pending('Current implementation ignores parameters after the first two.') is_expected.to run.with_params(['one'], 0, 1).and_raise_error(Puppet::ParseError) } describe 'argument validation' do it { is_expected.to run.with_params([0, 1, 2], 3).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params([0, 1, 2], 1).and_return([0, 2]) } it { is_expected.to run.with_params([0, 1, 2], -1).and_return([0, 1]) } it { is_expected.to run.with_params([0, 1, 2], -4).and_return([0, 1, 2]) } it { is_expected.to run.with_params(%w[ƒờở βāř ьầż], 1).and_return(%w[ƒờở ьầż]) } it 'leaves the original array intact' do argument = [1, 2, 3] original = argument.dup _result = subject.call([argument, 2]) expect(argument).to eq(original) end end puppetlabs-stdlib-4.25.0/spec/functions/delete_regex_spec.rb0100755005276200011600000000533713206047630021176 0ustar00require 'spec_helper' describe 'delete_regex' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params({}, 'two') } it { is_expected.to run.with_params([], 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two', 'three', 'four').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError) } describe 'deleting from an array' do it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['two'], 'two').and_return([]) } it { is_expected.to run.with_params(%w[two two], 'two').and_return([]) } it { is_expected.to run.with_params(%w[one two three], '^t.*').and_return(['one']) } it { is_expected.to run.with_params(%w[ab b c b], 'b').and_return(%w[ab c]) } it { is_expected.to run.with_params(%w[one two three], 'four').and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two three], 'e').and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(%w[two one two three two], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(['abracadabra'], 'abr').and_return(['abracadabra']) } it { is_expected.to run.with_params(['abracadabra'], '^.*jimbob.*$').and_return(['abracadabra']) } end describe 'deleting from an array' do it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, 'key').and_return({}) } it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return({}) } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'key2') \ .and_return('key1' => 'value1', 'key3' => 'value3') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, %w[key1 key2]) \ .and_return('key3' => 'value3') } end it 'leaves the original array intact' do argument1 = %w[one two three] original1 = argument1.dup subject.call([argument1, 'two']) expect(argument1).to eq(original1) end it 'leaves the original hash intact' do argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup subject.call([argument1, 'key2']) expect(argument1).to eq(original1) end end puppetlabs-stdlib-4.25.0/spec/functions/delete_spec.rb0100755005276200011600000000760113206047630020000 0ustar00require 'spec_helper' describe 'delete' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params([], 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError) } describe 'deleting from an array' do it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['two'], 'two').and_return([]) } it { is_expected.to run.with_params(%w[two two], 'two').and_return([]) } it { is_expected.to run.with_params(%w[ab b c b], 'b').and_return(%w[ab c]) } it { is_expected.to run.with_params(%w[one two three], 'four').and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two three], 'e').and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(%w[two one two three two], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(%w[one two three two], %w[one two]).and_return(['three']) } it { is_expected.to run.with_params(['ồאּẻ', 'ŧẅơ', 'ŧңŗё℮', 'ŧẅơ'], %w[ồאּẻ ŧẅơ]).and_return(['ŧңŗё℮']) } end describe 'deleting from a string' do it { is_expected.to run.with_params('', '').and_return('') } it { is_expected.to run.with_params('bar', '').and_return('bar') } it { is_expected.to run.with_params('', 'bar').and_return('') } it { is_expected.to run.with_params('bar', 'bar').and_return('') } it { is_expected.to run.with_params('barbar', 'bar').and_return('') } it { is_expected.to run.with_params('barfoobar', 'bar').and_return('foo') } it { is_expected.to run.with_params('foobarbabarz', 'bar').and_return('foobaz') } it { is_expected.to run.with_params('foobarbabarz', %w[foo bar]).and_return('baz') } it { is_expected.to run.with_params('ƒōōβậяβậβậяź', %w[ƒōō βậя]).and_return('βậź') } it { is_expected.to run.with_params('barfoobar', %w[barbar foo]).and_return('barbar') } it { is_expected.to run.with_params('barfoobar', %w[foo barbar]).and_return('') } end describe 'deleting from an array' do it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, 'key').and_return({}) } it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return({}) } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'key2') \ .and_return('key1' => 'value1', 'key3' => 'value3') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, %w[key1 key2]) \ .and_return('key3' => 'value3') } it { is_expected.to run \ .with_params({ 'ĸəұ1' => 'νãŀủĕ1', 'ĸəұ2' => 'νãŀủĕ2', 'ĸəұ3' => 'νãŀủĕ3' }, %w[ĸəұ1 ĸəұ2]) \ .and_return('ĸəұ3' => 'νãŀủĕ3') } end it 'leaves the original array intact' do argument1 = %w[one two three] original1 = argument1.dup _result = subject.call([argument1, 'two']) expect(argument1).to eq(original1) end it 'leaves the original string intact' do argument1 = 'onetwothree' original1 = argument1.dup _result = subject.call([argument1, 'two']) expect(argument1).to eq(original1) end it 'leaves the original hash intact' do argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup _result = subject.call([argument1, 'key2']) expect(argument1).to eq(original1) end end puppetlabs-stdlib-4.25.0/spec/functions/delete_undef_values_spec.rb0100755005276200011600000000501313206047630022533 0ustar00require 'spec_helper' describe 'delete_undef_values' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } describe 'when deleting from an array' do [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" do before(:each) do pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == '' pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value.nil? end it { is_expected.to run.with_params([undef_value]).and_return([]) } it { is_expected.to run.with_params(['one', undef_value, 'two', 'three']).and_return(%w[one two three]) } it { is_expected.to run.with_params(['ớņέ', undef_value, 'ŧשּׁō', 'ŧħґëə']).and_return(%w[ớņέ ŧשּׁō ŧħґëə]) } end it 'leaves the original argument intact' do argument = ['one', undef_value, 'two'] original = argument.dup _result = subject.call([argument, 2]) expect(argument).to eq(original) end end it { is_expected.to run.with_params(['undef']).and_return(['undef']) } end describe 'when deleting from a hash' do [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" do before(:each) do pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == '' pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value.nil? end it { is_expected.to run.with_params('key' => undef_value).and_return({}) } it { is_expected.to run \ .with_params('key1' => 'value1', 'undef_key' => undef_value, 'key2' => 'value2') \ .and_return('key1' => 'value1', 'key2' => 'value2') } end it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => undef_value } original = argument.dup _result = subject.call([argument, 2]) expect(argument).to eq(original) end end it { is_expected.to run.with_params('key' => 'undef').and_return('key' => 'undef') } end end puppetlabs-stdlib-4.25.0/spec/functions/delete_values_spec.rb0100755005276200011600000000347013206047630021357 0ustar00require 'spec_helper' describe 'delete_values' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } describe 'when the first argument is not a hash' do it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(TypeError) } it { is_expected.to run.with_params([], 'two').and_raise_error(TypeError) } end describe 'when deleting from a hash' do it { is_expected.to run.with_params({}, 'value').and_return({}) } it { is_expected.to run \ .with_params({ 'key1' => 'value1' }, 'non-existing value') \ .and_return('key1' => 'value1') } it { is_expected.to run \ .with_params({ 'ҝếỵ1 ' => 'νâĺūẹ1', 'ҝếỵ2' => 'value to delete' }, 'value to delete') \ .and_return('ҝếỵ1 ' => 'νâĺūẹ1') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'νǎŀữ℮ ťớ đêłểťė' }, 'νǎŀữ℮ ťớ đêłểťė') \ .and_return('key1' => 'value1') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value to delete', 'key3' => 'value to delete' }, 'value to delete') \ .and_return('key1' => 'value1') } end it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => 'value2' } original = argument.dup _result = subject.call([argument, 'value2']) expect(argument).to eq(original) end end puppetlabs-stdlib-4.25.0/spec/functions/deprecation_spec.rb0100644005276200011600000000376313206047630021035 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'deprecation' do before(:each) do # this is to reset the strict variable to default Puppet.settings[:strict] = :warning end it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it 'displays a single warning' do Puppet.expects(:warning).with(includes('heelo')) is_expected.to run.with_params('key', 'heelo') end it 'displays a single warning, despite multiple calls' do Puppet.expects(:warning).with(includes('heelo')).once (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo') end end it 'fails twice with message, with multiple calls. when strict= :error' do Puppet.settings[:strict] = :error Puppet.expects(:warning).with(includes('heelo')).never (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo').and_raise_error(RuntimeError, %r{deprecation. key. heelo}) end end it 'displays nothing, despite multiple calls. strict= :off' do Puppet.settings[:strict] = :off Puppet.expects(:warning).with(includes('heelo')).never (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo') end end after(:each) do # this is to reset the strict variable to default Puppet.settings[:strict] = :warning end end elsif Puppet.version.to_f < 4.0 # Puppet version < 4 will use these tests. describe 'deprecation' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end before(:each) do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' end it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it 'displays a single warning' do scope.expects(:warning).with(includes('heelo')) is_expected.to run.with_params('key', 'heelo') end end end puppetlabs-stdlib-4.25.0/spec/functions/difference_spec.rb0100755005276200011600000000323213206047630020624 0ustar00require 'spec_helper' describe 'difference' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([], ['one']).and_return([]) } it { is_expected.to run.with_params(['one'], ['one']).and_return([]) } it { is_expected.to run.with_params(['ớņέ'], ['']).and_return(['ớņέ']) } it { is_expected.to run.with_params(['one'], []).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(['one']) } it { is_expected.to run.with_params(['ớņέ', 'ŧשּׁō', 'ŧħґëə', 2], %w[ŧשּׁō ŧħґëə]).and_return(['ớņέ', 2]) } it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three], %w[two three four]).and_return(['one']) } it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return(%w[1 2 3]) end end puppetlabs-stdlib-4.25.0/spec/functions/dig44_spec.rb0100644005276200011600000000712013212471613017441 0ustar00require 'spec_helper' describe 'dig44' do let(:data) do { 'a' => { 'g' => '2', 'e' => [ 'f0', 'f1', { 'x' => { 'y' => 'z', }, }, 'f3', ], }, 'b' => true, 'c' => false, 'd' => '1', 'e' => :undef, 'f' => nil, } end let(:utf8_data) do { 'ẵ' => { 'в' => [ '©', 'ĝ', 'に', ], }, } end context 'with single values' do it 'exists' do is_expected.not_to be_nil end it 'requires two arguments' do is_expected.to run.with_params.and_raise_error(ArgumentError) end it 'fails if the data is not a structure' do is_expected.to run.with_params('test', []).and_raise_error(Puppet::Error) end it 'fails if the path is not an array' do is_expected.to run.with_params({}, '').and_raise_error(Puppet::Error) end it 'returns the value if the value is string' do is_expected.to run.with_params(data, ['d'], 'default').and_return('1') end it 'returns true if the value is true' do is_expected.to run.with_params(data, ['b'], 'default').and_return(true) end it 'returns false if the value is false' do is_expected.to run.with_params(data, ['c'], 'default').and_return(false) end it 'returns the default if the value is nil' do is_expected.to run.with_params(data, ['f'], 'default').and_return('default') end it 'returns the default if the value is :undef (same as nil)' do is_expected.to run.with_params(data, ['e'], 'default').and_return('default') end it 'returns the default if the path is not found' do is_expected.to run.with_params(data, ['missing'], 'default').and_return('default') end end context 'with structured values' do it 'is able to extract a deeply nested hash value' do is_expected.to run.with_params(data, %w[a g], 'default').and_return('2') end it 'returns the default value if the path is too long' do is_expected.to run.with_params(data, %w[a g c d], 'default').and_return('default') end it 'supports an array index (number) in the path' do is_expected.to run.with_params(data, ['a', 'e', 1], 'default').and_return('f1') end it 'supports an array index (string) in the path' do is_expected.to run.with_params(data, %w[a e 1], 'default').and_return('f1') end it 'returns the default value if an array index is not a number' do is_expected.to run.with_params(data, %w[a b c], 'default').and_return('default') end it 'returns the default value if and index is out of array length' do is_expected.to run.with_params(data, %w[a e 5], 'default').and_return('default') end it 'is able to path though both arrays and hashes' do is_expected.to run.with_params(data, %w[a e 2 x y], 'default').and_return('z') end it 'returns "nil" if value is not found and no default value is provided' do is_expected.to run.with_params(data, %w[a 1]).and_return(nil) end end context 'with internationalization (i18N) values' do it 'is able to return a unicode character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 0]).and_return('©') end it 'is able to return a utf8 character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 1]).and_return('ĝ') end it 'is able to return a double byte character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 2]).and_return('に') end end end puppetlabs-stdlib-4.25.0/spec/functions/dig_spec.rb0100644005276200011600000000063013206047630017271 0ustar00require 'spec_helper' describe 'dig' do it 'exists' do expect(Puppet::Parser::Functions.function('dig')).to eq('function_dig') end it 'gives a deprecation warning when called' do scope.expects(:warning).with('dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.') scope.function_dig([{}, []]) end end puppetlabs-stdlib-4.25.0/spec/functions/dirname_spec.rb0100755005276200011600000000205413212471613020151 0ustar00require 'spec_helper' describe 'dirname' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('/path/to/a/file.ext', []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('/path/to/a/file.ext').and_return('/path/to/a') } it { is_expected.to run.with_params('relative_path/to/a/file.ext').and_return('relative_path/to/a') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('scheme:///√ạĺűē/竹.ext').and_return('scheme:///√ạĺűē') } it { is_expected.to run.with_params('ҝẽγ:/√ạĺűē/竹.ㄘ').and_return('ҝẽγ:/√ạĺűē') } end end puppetlabs-stdlib-4.25.0/spec/functions/dos2unix_spec.rb0100644005276200011600000000275013212471613020305 0ustar00require 'spec_helper' describe 'dos2unix' do context 'when checking parameter validity' do it { is_expected.not_to eq(nil) } it do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) end end context 'when converting from dos to unix format' do sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\nWorld\n" it 'outputs unix format' do is_expected.to run.with_params(sample_text).and_return(desired_output) end end context 'with internationalization (i18N) values' do sample_text_utf8 = "Ħ℮ļłǿ\r\nשׁөŕłđ\r\n" desired_output_utf8 = "Ħ℮ļłǿ\nשׁөŕłđ\n" sample_text_doublebyte = "こんにちは\r\n世界\r\n" desired_output_doublebyte = "こんにちは\n世界\n" it 'outputs uft8 string' do is_expected.to run.with_params(sample_text_utf8).and_return(desired_output_utf8) end it 'outputs double byte string' do is_expected.to run.with_params(sample_text_doublebyte).and_return(desired_output_doublebyte) end end end puppetlabs-stdlib-4.25.0/spec/functions/downcase_spec.rb0100755005276200011600000000135113206047630020335 0ustar00require 'spec_helper' describe 'downcase' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('abc').and_return('abc') } it { is_expected.to run.with_params('Abc').and_return('abc') } it { is_expected.to run.with_params('ABC').and_return('abc') } it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('abc') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(%w[ONE TWO]).and_return(%w[one two]) } it { is_expected.to run.with_params(['One', 1, 'Two']).and_return(['one', 1, 'two']) } end puppetlabs-stdlib-4.25.0/spec/functions/empty_spec.rb0100755005276200011600000000165613206047630017700 0ustar00require 'spec_helper' describe 'empty' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(0).and_return(false) } it { is_expected.to run.with_params('').and_return(true) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(AlsoString.new('')).and_return(true) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return(false) } it { is_expected.to run.with_params([]).and_return(true) } it { is_expected.to run.with_params(['one']).and_return(false) } it { is_expected.to run.with_params({}).and_return(true) } it { is_expected.to run.with_params('key' => 'value').and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/ensure_packages_spec.rb0100755005276200011600000000650113212471613021672 0ustar00require 'spec_helper' describe 'ensure_packages' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { pending('should not accept numbers as arguments') is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { pending('should not accept numbers as arguments') is_expected.to run.with_params(['packagename', 1]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('packagename') } it { is_expected.to run.with_params(%w[packagename1 packagename2]) } context 'when given a catalog with "package { puppet: ensure => absent }"' do let(:pre_condition) { 'package { puppet: ensure => absent }' } describe 'after running ensure_package("facter")' do before(:each) { subject.call(['facter']) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('absent') } it { expect(-> { catalogue }).to contain_package('facter').with_ensure('present') } end describe 'after running ensure_package("facter", { "provider" => "gem" })' do before(:each) { subject.call(['facter', { 'provider' => 'gem' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('absent').without_provider } it { expect(-> { catalogue }).to contain_package('facter').with_ensure('present').with_provider('gem') } end end context 'when given an empty packages array' do let(:pre_condition) { 'notify { "hi": } -> Package <| |>; $somearray = ["vim",""]; ensure_packages($somearray)' } describe 'after running ensure_package(["vim", ""])' do it { expect { catalogue }.to raise_error(Puppet::ParseError, %r{Empty String provided}) } end end context 'when given hash of packages' do before(:each) do subject.call([{ 'foo' => { 'provider' => 'rpm' }, 'bar' => { 'provider' => 'gem' } }, { 'ensure' => 'present' }]) subject.call([{ 'パッケージ' => { 'ensure' => 'absent' } }]) subject.call([{ 'ρǻ¢κầģẻ' => { 'ensure' => 'absent' } }]) end # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_package('foo').with('provider' => 'rpm', 'ensure' => 'present') } it { expect(-> { catalogue }).to contain_package('bar').with('provider' => 'gem', 'ensure' => 'present') } context 'with UTF8 and double byte characters' do it { expect(-> { catalogue }).to contain_package('パッケージ').with('ensure' => 'absent') } it { expect(-> { catalogue }).to contain_package('ρǻ¢κầģẻ').with('ensure' => 'absent') } end end context 'when given a catalog with "package { puppet: ensure => present }"' do let(:pre_condition) { 'package { puppet: ensure => present }' } describe 'after running ensure_package("puppet", { "ensure" => "installed" })' do before(:each) { subject.call(['puppet', { 'ensure' => 'installed' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('present') } end end end puppetlabs-stdlib-4.25.0/spec/functions/ensure_resource_spec.rb0100755005276200011600000001511313212471613021742 0ustar00require 'spec_helper' describe 'ensure_resource' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a type}) } it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, %r{Must specify a title}) } if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 it { is_expected.to run.with_params('type', 'title', {}, 'extras').and_raise_error(ArgumentError) } else it { is_expected.to run.with_params('type', 'title', {}, 'extras').and_raise_error(Puppet::ParseError) } end it { pending('should not accept numbers as arguments') is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError) } context 'when given an empty catalog' do describe 'after running ensure_resource("user", "username1", {})' do before(:each) { subject.call(['User', 'username1', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').without_ensure } end describe 'after running ensure_resource("user", "username1", { gid => undef })' do before(:each) { subject.call(['User', 'username1', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').without_ensure } it { expect(-> { catalogue }).to contain_user('username1').without_gid } end describe 'after running ensure_resource("user", "username1", { ensure => present, gid => undef })' do before(:each) { subject.call(['User', 'username1', { 'ensure' => 'present', 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('username1').without_gid } end describe 'after running ensure_resource("test::deftype", "foo", {})' do before(:each) { subject.call(['test::deftype', 'foo', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end context 'when given a catalog with UTF8 chars' do describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", {})' do before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } end describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { gid => undef })' do before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } end describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { ensure => present, gid => undef })' do before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', { 'ensure' => 'present', 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } end end context 'when given a catalog with "user { username1: ensure => present }"' do let(:pre_condition) { 'user { username1: ensure => present }' } describe 'after running ensure_resource("user", "username1", {})' do before(:each) { subject.call(['User', 'username1', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", "username2", {})' do before(:each) { subject.call(['User', 'username2', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('username2').without_ensure } end describe 'after running ensure_resource("user", "username1", { gid => undef })' do before(:each) { subject.call(['User', 'username1', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", ["username1", "username2"], {})' do before(:each) { subject.call(['User', %w[username1 username2], {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('username2').without_ensure } end describe 'when providing already set params' do let(:params) { { 'ensure' => 'present' } } before(:each) { subject.call(['User', %w[username2 username3], params]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with(params) } it { expect(-> { catalogue }).to contain_user('username2').with(params) } end context 'when trying to add params' do it { is_expected.to run \ .with_params('User', 'username1', 'ensure' => 'present', 'shell' => true) \ .and_raise_error(Puppet::Resource::Catalog::DuplicateResourceError, %r{User\[username1\] is already declared}) } end end context 'when given a catalog with "test::deftype { foo: }"' do let(:pre_condition) { 'test::deftype { "foo": }' } describe 'after running ensure_resource("test::deftype", "foo", {})' do before(:each) { subject.call(['test::deftype', 'foo', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end end puppetlabs-stdlib-4.25.0/spec/functions/ensure_resources_spec.rb0100644005276200011600000000266013206047630022126 0ustar00require 'spec_helper' describe 'ensure_resources' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a type}) } it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, %r{Must specify a title}) } describe 'given a title hash of multiple resources' do before(:each) { subject.call(['user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' }, 'alex' => { 'gid' => 'mygroup', 'uid' => '700' } }, { 'ensure' => 'present' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('dan').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('alex').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('dan').with('gid' => 'mygroup', 'uid' => '600') } it { expect(-> { catalogue }).to contain_user('alex').with('gid' => 'mygroup', 'uid' => '700') } end describe 'given a title hash of a single resource' do before(:each) { subject.call(['user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' } }, { 'ensure' => 'present' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('dan').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('dan').with('gid' => 'mygroup', 'uid' => '600') } end end puppetlabs-stdlib-4.25.0/spec/functions/flatten_spec.rb0100755005276200011600000000163313206047630020172 0ustar00require 'spec_helper' describe 'flatten' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params([['one']]).and_return(['one']) } it { is_expected.to run.with_params(%w[a b c d e f g]).and_return(%w[a b c d e f g]) } it { is_expected.to run.with_params([['a', 'b', ['c', %w[d e], 'f', 'g']]]).and_return(%w[a b c d e f g]) } it { is_expected.to run.with_params(['ã', 'β', ['ĉ', %w[đ ẽ ƒ ġ]]]).and_return(%w[ã β ĉ đ ẽ ƒ ġ]) } end puppetlabs-stdlib-4.25.0/spec/functions/floor_spec.rb0100755005276200011600000000106613206047630017656 0ustar00require 'spec_helper' describe 'floor' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } it { is_expected.to run.with_params(33.1).and_return(33) } it { is_expected.to run.with_params(-33.1).and_return(-34) } end puppetlabs-stdlib-4.25.0/spec/functions/fqdn_rand_string_spec.rb0100644005276200011600000000677013212471613022062 0ustar00require 'spec_helper' describe 'fqdn_rand_string' do let(:default_charset) { %r{\A[a-zA-Z0-9]{100}\z} } it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1.5).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(-10).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('-10').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('string').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params([]).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params({}).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(100).and_return(default_charset) } it { is_expected.to run.with_params('100').and_return(default_charset) } it { is_expected.to run.with_params(100, nil).and_return(default_charset) } it { is_expected.to run.with_params(100, '').and_return(default_charset) } it { is_expected.to run.with_params(100, 'a').and_return(%r{\Aa{100}\z}) } it { is_expected.to run.with_params(100, 'ab').and_return(%r{\A[ab]{100}\z}) } it { is_expected.to run.with_params(100, 'ãβ').and_return(%r{\A[ãβ]{100}\z}) } it "provides the same 'random' value on subsequent calls for the same host" do expect(fqdn_rand_string(10)).to eql(fqdn_rand_string(10)) end it 'considers the same host and same extra arguments to have the same random sequence' do first_random = fqdn_rand_string(10, :extra_identifier => [1, 'same', 'host']) second_random = fqdn_rand_string(10, :extra_identifier => [1, 'same', 'host']) expect(first_random).to eql(second_random) end it 'allows extra arguments to control the random value on a single host' do first_random = fqdn_rand_string(10, :extra_identifier => [1, 'different', 'host']) second_different_random = fqdn_rand_string(10, :extra_identifier => [2, 'different', 'host']) expect(first_random).not_to eql(second_different_random) end it 'returns different strings for different hosts' do val1 = fqdn_rand_string(10, :host => 'first.host.com') val2 = fqdn_rand_string(10, :host => 'second.host.com') expect(val1).not_to eql(val2) end def fqdn_rand_string(max, args = {}) host = args[:host] || '127.0.0.1' charset = args[:charset] extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context scope.stubs(:lookupvar).with('::fqdn', {}).returns(host) function_args = [max] if args.key?(:charset) || !extra.empty? function_args << charset end function_args += extra scope.function_fqdn_rand_string(function_args) end end puppetlabs-stdlib-4.25.0/spec/functions/fqdn_rotate_spec.rb0100755005276200011600000000550113212471613021040 0ustar00require 'spec_helper' describe 'fqdn_rotate' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('ã').and_return('ã') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it 'rotates a string and the result should be the same size' do expect(fqdn_rotate('asdf').size).to eq(4) end it 'rotates a string to give the same results for one host' do val1 = fqdn_rotate('abcdefg', :host => 'one') val2 = fqdn_rotate('abcdefg', :host => 'one') expect(val1).to eq(val2) end it 'allows extra arguments to control the random rotation on a single host' do val1 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'different', 'host']) val2 = fqdn_rotate('abcdefg', :extra_identifier => [2, 'different', 'host']) expect(val1).not_to eq(val2) end it 'considers the same host and same extra arguments to have the same random rotation' do val1 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'same', 'host']) val2 = fqdn_rotate('abcdefg', :extra_identifier => [1, 'same', 'host']) expect(val1).to eq(val2) end it 'rotates a string to give different values on different hosts' do val1 = fqdn_rotate('abcdefg', :host => 'one') val2 = fqdn_rotate('abcdefg', :host => 'two') expect(val1).not_to eq(val2) end it 'accepts objects which extend String' do result = fqdn_rotate(AlsoString.new('asdf')) expect(result).to eq('dfas') end it 'uses the Puppet::Util.deterministic_rand function' do skip 'Puppet::Util#deterministic_rand not available' unless Puppet::Util.respond_to?(:deterministic_rand) Puppet::Util.expects(:deterministic_rand).with(44_489_829_212_339_698_569_024_999_901_561_968_770, 4) fqdn_rotate('asdf') end it 'does not leave the global seed in a deterministic state' do fqdn_rotate('asdf') rand1 = rand fqdn_rotate('asdf') rand2 = rand expect(rand1).not_to eql(rand2) end def fqdn_rotate(value, args = {}) host = args[:host] || '127.0.0.1' extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context scope.stubs(:lookupvar).with('::fqdn').returns(host) function_args = [value] + extra scope.function_fqdn_rotate(function_args) end end puppetlabs-stdlib-4.25.0/spec/functions/fqdn_uuid_spec.rb0100644005276200011600000000070413212471613020505 0ustar00require 'spec_helper' describe 'fqdn_uuid' do context 'with invalid parameters' do it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{No arguments given$}) } end context 'with given string' do it { is_expected.to run.with_params('puppetlabs.com').and_return('9c70320f-6815-5fc5-ab0f-debe68bf764c') } it { is_expected.to run.with_params('google.com').and_return('64ee70a4-8cc1-5d25-abf2-dea6c79a09c8') } end end puppetlabs-stdlib-4.25.0/spec/functions/get_module_path_spec.rb0100755005276200011600000000361413252003272021671 0ustar00require 'spec_helper' describe 'get_module_path' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Could not find module}) } class StubModule attr_reader :path def initialize(path) @path = path end end describe 'when locating a module' do let(:modulepath) { '/tmp/does_not_exist' } let(:path_of_module_foo) { StubModule.new('/tmp/does_not_exist/foo') } before(:each) { Puppet[:modulepath] = modulepath } context 'when in the default environment' do before(:each) { Puppet::Module.expects(:find).with('foo', 'rp_env').returns(path_of_module_foo) } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } context 'when the modulepath is a list' do before(:each) { Puppet[:modulepath] = modulepath + 'tmp/something_else' } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } end end context 'when in a non-default default environment' do let(:environment) { 'test' } before(:each) { Puppet::Module.expects(:find).with('foo', 'test').returns(path_of_module_foo) } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } context 'when the modulepath is a list' do before(:each) { Puppet[:modulepath] = modulepath + 'tmp/something_else' } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } end end end end puppetlabs-stdlib-4.25.0/spec/functions/getparam_spec.rb0100755005276200011600000000360213206047630020333 0ustar00require 'spec_helper' describe 'getparam' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a reference}) } it { is_expected.to run.with_params('User[one]').and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } it { is_expected.to run.with_params('User[one]', 2).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } it { is_expected.to run.with_params('User[one]', []).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } it { is_expected.to run.with_params('User[one]', {}).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } describe 'when compared against a user resource with no params' do let(:pre_condition) { 'user { "one": }' } it { is_expected.to run.with_params('User[one]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[two]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[one]', 'shell').and_return('') } end describe 'when compared against a user resource with params' do let(:pre_condition) { 'user { "one": ensure => present, shell => "/bin/sh", managehome => false, }' } it { is_expected.to run.with_params('User[one]', 'ensure').and_return('present') } it { is_expected.to run.with_params('User[two]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[one]', 'shell').and_return('/bin/sh') } it { is_expected.to run.with_params('User[one]', 'managehome').and_return(false) } end describe 'when compared against a user resource with UTF8 and double byte params' do let(:pre_condition) { 'user { ["三", "ƒốưř"]: ensure => present }' } it { is_expected.to run.with_params('User[三]', 'ensure').and_return('present') } it { is_expected.to run.with_params('User[ƒốưř]', 'ensure').and_return('present') } end end puppetlabs-stdlib-4.25.0/spec/functions/getvar_spec.rb0100755005276200011600000000243213212471613020022 0ustar00require 'spec_helper' describe 'getvar' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('$::foo').and_return(nil) } context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::data { $foo = 'baz' } include site::data PUPPETCODE end it { is_expected.to run.with_params('site::data::foo').and_return('baz') } it { is_expected.to run.with_params('::site::data::foo').and_return('baz') } it { is_expected.to run.with_params('::site::data::bar').and_return(nil) } end context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::info { $lock = 'ŧҺîš íš ắ śţřĭŋĝ' } class site::new { $item = '万Ü€‰' } include site::info include site::new PUPPETCODE end it { is_expected.to run.with_params('site::info::lock').and_return('ŧҺîš íš ắ śţřĭŋĝ') } it { is_expected.to run.with_params('::site::new::item').and_return('万Ü€‰') } end end puppetlabs-stdlib-4.25.0/spec/functions/glob_spec.rb0100755005276200011600000000100213206047630017446 0ustar00require 'spec_helper' describe 'glob' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('').and_return([]) } it { is_expected.to run.with_params(['']).and_return([]) } it { is_expected.to run.with_params(['', '']).and_return([]) } it { is_expected.to run.with_params(['/etc/xyzxyzxyz', '/etcxyzxyzxyz']).and_return([]) } end puppetlabs-stdlib-4.25.0/spec/functions/grep_spec.rb0100755005276200011600000000234213206047630017470 0ustar00require 'spec_helper' describe 'grep' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('grep does not actually check this, and raises NoMethodError instead') is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { pending('grep does not actually check this, and raises NoMethodError instead') is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(%w[one two three], 'two').and_return(['two']) } it { is_expected.to run.with_params(%w[one two three], 't(wo|hree)').and_return(%w[two three]) } it { is_expected.to run.with_params(%w[ờאּê ţשּׂỡ ţһŗəè], 'ţ(שּׂỡ|һŗəè)').and_return(%w[ţשּׂỡ ţһŗəè]) } end puppetlabs-stdlib-4.25.0/spec/functions/has_interface_with_spec.rb0100755005276200011600000000321713212471613022362 0ustar00require 'spec_helper' describe 'has_interface_with' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } # We need to mock out the Facts so we can specify how we expect this function # to behave on different platforms. context 'when on Mac OS X Systems' do let(:facts) { { :interfaces => 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } it { is_expected.to run.with_params('lo0').and_return(true) } it { is_expected.to run.with_params('lo').and_return(false) } end context 'when on Linux Systems' do let(:facts) do { :interfaces => 'eth0,lo', :ipaddress => '10.0.0.1', :ipaddress_lo => '127.0.0.1', :ipaddress_eth0 => '10.0.0.1', :muppet => 'kermit', :muppet_lo => 'mspiggy', :muppet_eth0 => 'kermit', } end it { is_expected.to run.with_params('lo').and_return(true) } it { is_expected.to run.with_params('lo0').and_return(false) } it { is_expected.to run.with_params('ipaddress', '127.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '10.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '8.8.8.8').and_return(false) } it { is_expected.to run.with_params('muppet', 'kermit').and_return(true) } it { is_expected.to run.with_params('muppet', 'mspiggy').and_return(true) } it { is_expected.to run.with_params('muppet', 'bigbird').and_return(false) } end end puppetlabs-stdlib-4.25.0/spec/functions/has_ip_address_spec.rb0100755005276200011600000000140113212471613021475 0ustar00require 'spec_helper' describe 'has_ip_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when on Linux Systems' do let(:facts) do { :interfaces => 'eth0,lo', :ipaddress => '10.0.0.1', :ipaddress_lo => '127.0.0.1', :ipaddress_eth0 => '10.0.0.1', } end it { is_expected.to run.with_params('127.0.0.1').and_return(true) } it { is_expected.to run.with_params('10.0.0.1').and_return(true) } it { is_expected.to run.with_params('8.8.8.8').and_return(false) } end end puppetlabs-stdlib-4.25.0/spec/functions/has_ip_network_spec.rb0100755005276200011600000000133313212471613021545 0ustar00require 'spec_helper' describe 'has_ip_network' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when on Linux Systems' do let(:facts) do { :interfaces => 'eth0,lo', :network_lo => '127.0.0.0', :network_eth0 => '10.0.0.0', } end it { is_expected.to run.with_params('127.0.0.0').and_return(true) } it { is_expected.to run.with_params('10.0.0.0').and_return(true) } it { is_expected.to run.with_params('8.8.8.0').and_return(false) } end end puppetlabs-stdlib-4.25.0/spec/functions/has_key_spec.rb0100755005276200011600000000250713212471613020160 0ustar00require 'spec_helper' describe 'has_key' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } it { is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return(true) } it { is_expected.to run.with_params({}, 'key').and_return(false) } it { is_expected.to run.with_params({ 'key' => 'value' }, 'not a key').and_return(false) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params({ 'κéỳ ' => '٧ậļųể' }, 'κéỳ ').and_return(true) } it { is_expected.to run.with_params({ 'キー' => '٧ậļųể' }, 'キー').and_return(true) } end end puppetlabs-stdlib-4.25.0/spec/functions/hash_spec.rb0100755005276200011600000000155513206047630017463 0ustar00require 'spec_helper' describe 'hash' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(['one']).and_raise_error(Puppet::ParseError, %r{Unable to compute}) } it { is_expected.to run.with_params([]).and_return({}) } it { is_expected.to run.with_params(%w[key1 value1]).and_return('key1' => 'value1') } it { is_expected.to run.with_params(['κ℮ұ1', '√āĺűẻ1']).and_return('κ℮ұ1' => '√āĺűẻ1') } it { is_expected.to run.with_params(%w[key1 value1 key2 value2]).and_return('key1' => 'value1', 'key2' => 'value2') } end puppetlabs-stdlib-4.25.0/spec/functions/intersection_spec.rb0100755005276200011600000000312613206047630021242 0ustar00require 'spec_helper' describe 'intersection' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([], ['one']).and_return([]) } it { is_expected.to run.with_params(['one'], []).and_return([]) } it { is_expected.to run.with_params(['one'], ['one']).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(%w[two three]) } it { is_expected.to run.with_params(%w[ōŋể ŧשợ ţђŕẽё], %w[ŧשợ ţђŕẽё]).and_return(%w[ŧשợ ţђŕẽё]) } it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(%w[two three]) } it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(%w[two three]) } it { is_expected.to run.with_params(%w[one two three], %w[two three four]).and_return(%w[two three]) } it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return([]) end end puppetlabs-stdlib-4.25.0/spec/functions/is_a_spec.rb0100644005276200011600000000201513206047630017440 0ustar00require 'spec_helper' if ENV['FUTURE_PARSER'] == 'yes' describe 'type_of' do pending 'teach rspec-puppet to load future-only functions under 3.7.5' do it { is_expected.not_to eq(nil) } end end end if Puppet.version.to_f >= 4.0 describe 'is_a' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('', '').and_raise_error(ArgumentError) } it 'succeeds when comparing a string and a string' do is_expected.to run.with_params('hello world', String).and_return(true) end it 'fails when comparing an integer and a string' do is_expected.to run.with_params(5, String).and_return(false) end it 'suceeds when comparing an UTF8 and double byte characters' do comparison_array = ['このテキスト', 'ŧћịś ŧêχŧ'] comparison_array.each do |comparison_value| is_expected.to run.with_params(comparison_value, String).and_return(true) end end end end puppetlabs-stdlib-4.25.0/spec/functions/is_array_spec.rb0100755005276200011600000000320313212471613020340 0ustar00require 'spec_helper' describe 'is_array' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([]).and_return(true) } it { is_expected.to run.with_params(['one']).and_return(true) } it { is_expected.to run.with_params([1]).and_return(true) } it { is_expected.to run.with_params([{}]).and_return(true) } it { is_expected.to run.with_params([[]]).and_return(true) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(['1.2.3.4']).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(['1.2.3.4']).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_bool_spec.rb0100755005276200011600000000277213212471613020167 0ustar00require 'spec_helper' describe 'is_bool' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true, false).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true).and_return(true) } it { is_expected.to run.with_params(false).and_return(true) } it { is_expected.to run.with_params([1]).and_return(false) } it { is_expected.to run.with_params([{}]).and_return(false) } it { is_expected.to run.with_params([[]]).and_return(false) } it { is_expected.to run.with_params([true]).and_return(false) } it { is_expected.to run.with_params('true').and_return(false) } it { is_expected.to run.with_params('false').and_return(false) } context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(true).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(false).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_domain_name_spec.rb0100755005276200011600000000500713206047630021476 0ustar00require 'spec_helper' describe 'is_domain_name' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('.').and_return(true) } it { is_expected.to run.with_params('com').and_return(true) } it { is_expected.to run.with_params('com.').and_return(true) } it { is_expected.to run.with_params('x.com').and_return(true) } it { is_expected.to run.with_params('x.com.').and_return(true) } it { is_expected.to run.with_params('foo.example.com').and_return(true) } it { is_expected.to run.with_params('foo.example.com.').and_return(true) } it { is_expected.to run.with_params('2foo.example.com').and_return(true) } it { is_expected.to run.with_params('2foo.example.com.').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com.').and_return(true) } describe 'inputs with spaces' do it { is_expected.to run.with_params('invalid domain').and_return(false) } end describe 'inputs with hyphens' do it { is_expected.to run.with_params('foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('foo-bar.example.com.').and_return(true) } it { is_expected.to run.with_params('www.foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('www.foo-bar.example.com.').and_return(true) } it { is_expected.to run.with_params('-foo.example.com').and_return(false) } it { is_expected.to run.with_params('-foo.example.com.').and_return(false) } end # Values obtained from Facter values will be frozen strings # in newer versions of Facter: it { is_expected.to run.with_params('www.example.com'.freeze).and_return(true) } describe 'top level domain must be alphabetic if there are multiple labels' do it { is_expected.to run.with_params('2com').and_return(true) } it { is_expected.to run.with_params('www.example.2com').and_return(false) } end describe 'IP addresses are not domain names' do it { is_expected.to run.with_params('192.168.1.1').and_return(false) } end end puppetlabs-stdlib-4.25.0/spec/functions/is_email_address_spec.rb0100755005276200011600000000150413206047630022021 0ustar00require 'spec_helper' describe 'is_email_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('bob@gmail.com').and_return(true) } it { is_expected.to run.with_params('alice+puppetlabs.com@gmail.com').and_return(true) } it { is_expected.to run.with_params('peter.parker@gmail.com').and_return(true) } it { is_expected.to run.with_params('1.2.3@domain').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5@').and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/is_float_spec.rb0100755005276200011600000000322613212471613020334 0ustar00require 'spec_helper' describe 'is_float' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0.1, 0.2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'passing a string' do it { is_expected.to run.with_params('0.1').and_return(true) } it { is_expected.to run.with_params('1.0').and_return(true) } it { is_expected.to run.with_params('1').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params('one 1.0').and_return(false) } it { is_expected.to run.with_params('1.0 one').and_return(false) } end describe 'passing numbers' do it { is_expected.to run.with_params(0.1).and_return(true) } it { is_expected.to run.with_params(1.0).and_return(true) } it { is_expected.to run.with_params(1).and_return(false) } end context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(2.2).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(1.0).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_function_available_spec.rb0100755005276200011600000000073313206047630023055 0ustar00require 'spec_helper' describe 'is_function_available' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('include').and_return(true) } it { is_expected.to run.with_params('no_such_function').and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/is_hash_spec.rb0100755005276200011600000000105313206047630020147 0ustar00require 'spec_helper' describe 'is_hash' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params({}).and_return(true) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params(1).and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/is_integer_spec.rb0100755005276200011600000000417313212471613020666 0ustar00require 'spec_helper' describe 'is_integer' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(true) } it { is_expected.to run.with_params('3').and_return(true) } it { is_expected.to run.with_params(-3).and_return(true) } it { is_expected.to run.with_params('-3').and_return(true) } it { is_expected.to run.with_params("123\nfoo").and_return(true) } it { is_expected.to run.with_params("foo\n123").and_return(true) } it { is_expected.to run.with_params(3.7).and_return(false) } it { is_expected.to run.with_params('3.7').and_return(false) } it { is_expected.to run.with_params(-3.7).and_return(false) } it { is_expected.to run.with_params('-3.7').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params([1]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('0001234').and_return(false) } it { is_expected.to run.with_params("foo\nbar").and_return(false) } context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(50).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(50).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_ip_address_spec.rb0100755005276200011600000000437013212471613021345 0ustar00require 'spec_helper' describe 'is_ip_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('1.2.3.4').and_return(true) } it { is_expected.to run.with_params('1.2.3.255').and_return(true) } it { is_expected.to run.with_params('1.2.3.256').and_return(false) } it { is_expected.to run.with_params('1.2.3').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5').and_return(false) } it { is_expected.to run.with_params('fe00::1').and_return(true) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74').and_return(true) } it { is_expected.to run.with_params('FE80:0000:CD12:D123:E2F8:47FF:FE09:DD74').and_return(true) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:zzzz').and_return(false) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09').and_return(false) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74:dd74').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1.2.3.4').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('1.2.3.4').and_return(true) end after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end end end puppetlabs-stdlib-4.25.0/spec/functions/is_ipv4_address_spec.rb0100644005276200011600000000233013212471613021606 0ustar00require 'spec_helper' describe 'is_ipv4_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(true) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(false) } end context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_ipv6_address_spec.rb0100644005276200011600000000271713212471613021621 0ustar00require 'spec_helper' describe 'is_ipv6_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) } it { is_expected.to run.with_params('85a3:0000:0000:8a2e:0370:7334:100.100.100.100').and_return(true) } it { is_expected.to run.with_params('1.2.3').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_mac_address_spec.rb0100755005276200011600000000233513212471613021474 0ustar00require 'spec_helper' describe 'is_mac_address' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('00:a0:1f:12:7f:a0').and_return(true) } it { is_expected.to run.with_params('00:A0:1F:12:7F:A0').and_return(true) } it { is_expected.to run.with_params('00:00:00:00:00:0g').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('ƒốưř').and_return(false) } it { is_expected.to run.with_params('三+').and_return(false) } end it { pending 'should properly typecheck its arguments' is_expected.to run.with_params(1).and_return(false) } it { pending 'should properly typecheck its arguments' is_expected.to run.with_params({}).and_return(false) } it { pending 'should properly typecheck its arguments' is_expected.to run.with_params([]).and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/is_numeric_spec.rb0100755005276200011600000000406513212471613020673 0ustar00require 'spec_helper' describe 'is_numeric' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(true) } it { is_expected.to run.with_params('3').and_return(true) } it { is_expected.to run.with_params(-3).and_return(true) } it { is_expected.to run.with_params('-3').and_return(true) } it { is_expected.to run.with_params(3.7).and_return(true) } it { is_expected.to run.with_params('3.7').and_return(true) } it { is_expected.to run.with_params(-3.7).and_return(true) } it { is_expected.to run.with_params('-3.7').and_return(true) } it { is_expected.to run.with_params('-342.2315e-12').and_return(true) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params([1]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('0001234').and_return(false) } it { is_expected.to run.with_params(' - 1234').and_return(false) } context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(7).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(7).and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/is_string_spec.rb0100755005276200011600000000400713212471613020533 0ustar00require 'spec_helper' describe 'is_string' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(false) } it { is_expected.to run.with_params('3').and_return(false) } it { is_expected.to run.with_params(-3).and_return(false) } it { is_expected.to run.with_params('-3').and_return(false) } it { is_expected.to run.with_params(3.7).and_return(false) } it { is_expected.to run.with_params('3.7').and_return(false) } it { is_expected.to run.with_params(-3.7).and_return(false) } it { is_expected.to run.with_params('-3.7').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params([1]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('one').and_return(true) } it { is_expected.to run.with_params('0001234').and_return(true) } context 'with deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('sponge').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('bob').and_return(true) end end end puppetlabs-stdlib-4.25.0/spec/functions/join_keys_to_values_spec.rb0100755005276200011600000000334613212471613022612 0ustar00require 'spec_helper' describe 'join_keys_to_values' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Takes exactly two arguments}) } it { is_expected.to run.with_params({}, '', '').and_raise_error(Puppet::ParseError, %r{Takes exactly two arguments}) } it { is_expected.to run.with_params('one', '').and_raise_error(TypeError, %r{The first argument must be a hash}) } it { is_expected.to run.with_params({}, 2).and_raise_error(TypeError, %r{The second argument must be a string}) } it { is_expected.to run.with_params({}, '').and_return([]) } it { is_expected.to run.with_params({}, ':').and_return([]) } it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return(['keyvalue']) } it { is_expected.to run.with_params({ 'key' => 'value' }, ':').and_return(['key:value']) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params({ 'ҝẽγ' => '√ạĺűē' }, ':').and_return(['ҝẽγ:√ạĺűē']) } it { is_expected.to run.with_params({ 'ҝẽγ' => '√ạĺűē' }, '万').and_return(['ҝẽγ万√ạĺűē']) } end it { is_expected.to run.with_params({ 'key' => nil }, ':').and_return(['key:']) } it 'runs join_keys_to_values(, ":") and return the proper array' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }, ':']) expect(result.sort).to eq(['key1:value1', 'key2:value2'].sort) end it 'runs join_keys_to_values(, " ") and return the proper array' do result = subject.call([{ 'key1' => 'value1', 'key2' => %w[value2 value3] }, ' ']) expect(result.sort).to eq(['key1 value1', 'key2 value2', 'key2 value3'].sort) end end puppetlabs-stdlib-4.25.0/spec/functions/join_spec.rb0100755005276200011600000000224013206047630017467 0ustar00require 'spec_helper' describe 'join' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the second.') is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Requires array to work with}) } it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{Requires string to work with}) } it { is_expected.to run.with_params([]).and_return('') } it { is_expected.to run.with_params([], ':').and_return('') } it { is_expected.to run.with_params(['one']).and_return('one') } it { is_expected.to run.with_params(['one'], ':').and_return('one') } it { is_expected.to run.with_params(%w[one two three]).and_return('onetwothree') } it { is_expected.to run.with_params(%w[one two three], ':').and_return('one:two:three') } it { is_expected.to run.with_params(%w[ōŋể ŧשợ ţђŕẽё], ':').and_return('ōŋể:ŧשợ:ţђŕẽё') } end puppetlabs-stdlib-4.25.0/spec/functions/keys_spec.rb0100755005276200011600000000227713206047630017515 0ustar00require 'spec_helper' describe 'keys' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params({}).and_return([]) } it { is_expected.to run.with_params('key' => 'value').and_return(['key']) } it 'returns the array of keys' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }]) expect(result).to match_array(%w[key1 key2]) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'ҝểү' => '√ẳŀμệ', 'キー' => '値' }]) expect(result).to match_array(%w[ҝểү キー]) end end puppetlabs-stdlib-4.25.0/spec/functions/length_spec.rb0100755005276200011600000000340213206047630020012 0ustar00require 'spec_helper' describe 'length' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'length' expects 1 argument, got none}) } it { is_expected.to run.with_params([], 'extra').and_raise_error(ArgumentError, %r{'length' expects 1 argument, got 2}) } it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Integer}) } it { is_expected.to run.with_params(true).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Boolean}) } it { is_expected.to run.with_params('1').and_return(1) } it { is_expected.to run.with_params('1.0').and_return(3) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } it { is_expected.to run.with_params(%w[one two three]).and_return(3) } it { is_expected.to run.with_params(%w[one two three four]).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } it { is_expected.to run.with_params('1' => '2').and_return(1) } it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } context 'when using a class extending String' do it { is_expected.to run.with_params(AlsoString.new('asdfghjkl')).and_return(9) } end end puppetlabs-stdlib-4.25.0/spec/functions/load_module_metadata_spec.rb0100755005276200011600000000465713212471613022671 0ustar00require 'spec_helper' describe 'load_module_metadata' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'when calling with valid arguments' do before :each do allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') end context 'when calling with valid utf8 and double byte character arguments' do before :each do allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') end let(:prefix) { 'C:' if Puppet::Util::Platform.windows? } it 'jsons parse the file' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(true) allow(File).to receive(:read).with("#{prefix}/path/to/module/metadata.json").and_return('{"name": "spencer-science"}') result = subject.call(['science']) expect(result['name']).to eq('spencer-science') end it 'fails by default if there is no metadata.json' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) expect { subject.call(['science']) }.to raise_error(Puppet::ParseError) end it 'returns nil if user allows empty metadata.json' do allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) result = subject.call(['science', true]) expect(result).to eq({}) end end end end puppetlabs-stdlib-4.25.0/spec/functions/loadjson_spec.rb0100644005276200011600000000530713212471613020344 0ustar00require 'spec_helper' describe 'loadjson' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } describe 'when calling with valid arguments' do before :each do allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, :encoding => 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') end context 'when a non-existing file is specified' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesnotexist' else '/tmp/doesnotexist' end end before(:each) do allow(File).to receive(:exists?).with(filename).and_return(false).once allow(PSON).to receive(:load).never end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } it { is_expected.to run.with_params(filename, 'đẽƒằưļŧ' => '٧ẵłựέ').and_return('đẽƒằưļŧ' => '٧ẵłựέ') } it { is_expected.to run.with_params(filename, 'デフォルト' => '値').and_return('デフォルト' => '値') } end context 'when an existing file is specified' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).and_return(data).once end it { is_expected.to run.with_params(filename).and_return(data) } end context 'when the file could not be parsed' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:json) { '{"key":"value"}' } before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).once.and_raise StandardError, 'Something terrible have happened!' end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end end puppetlabs-stdlib-4.25.0/spec/functions/loadyaml_spec.rb0100755005276200011600000000310213206047630020330 0ustar00require 'spec_helper' describe 'loadyaml' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } context 'when a non-existing file is specified' do let(:filename) { '/tmp/doesnotexist' } before(:each) do File.expects(:exists?).with(filename).returns(false).once YAML.expects(:load_file).never end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } it { is_expected.to run.with_params(filename, 'đẽƒằưļŧ' => '٧ẵłựέ').and_return('đẽƒằưļŧ' => '٧ẵłựέ') } it { is_expected.to run.with_params(filename, 'デフォルト' => '値').and_return('デフォルト' => '値') } end context 'when an existing file is specified' do let(:filename) { '/tmp/doesexist' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } before(:each) do File.expects(:exists?).with(filename).returns(true).once YAML.expects(:load_file).with(filename).returns(data).once end it { is_expected.to run.with_params(filename).and_return(data) } end context 'when the file could not be parsed' do let(:filename) { '/tmp/doesexist' } before(:each) do File.expects(:exists?).with(filename).returns(true).once YAML.stubs(:load_file).with(filename).once.raises StandardError, 'Something terrible have happened!' end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end puppetlabs-stdlib-4.25.0/spec/functions/lstrip_spec.rb0100755005276200011600000000427313206047630020055 0ustar00require 'spec_helper' describe 'lstrip' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t one").and_return('one') } it { is_expected.to run.with_params('one ').and_return('one ') } it { is_expected.to run.with_params(' one ').and_return('one ') } it { is_expected.to run.with_params(' one ').and_return('one ') } it { is_expected.to run.with_params(' ǿňè ').and_return('ǿňè ') } it { is_expected.to run.with_params("\tone ").and_return('one ') } it { is_expected.to run.with_params("\t one ").and_return('one ') } it { is_expected.to run.with_params("one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params("\tone \t").and_return("one \t") } it { is_expected.to run.with_params("\t one \t").and_return("one \t") } it { is_expected.to run.with_params(' o n e ').and_return('o n e ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one ') } end puppetlabs-stdlib-4.25.0/spec/functions/max_spec.rb0100755005276200011600000000206313206047630017320 0ustar00require 'spec_helper' describe 'max' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(2) } it { is_expected.to run.with_params(1, 2, 3).and_return(3) } it { is_expected.to run.with_params(3, 2, 1).and_return(3) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('two') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('two') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('two') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return('one') } it { is_expected.to run.with_params('1', 'one').and_return('one') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.4e0') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.3e1) } end end puppetlabs-stdlib-4.25.0/spec/functions/member_spec.rb0100755005276200011600000000274513206047630020011 0ustar00require 'spec_helper' describe 'member' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], [], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], '').and_return(false) } it { is_expected.to run.with_params([], ['']).and_return(false) } it { is_expected.to run.with_params([''], '').and_return(true) } it { is_expected.to run.with_params([''], ['']).and_return(true) } it { is_expected.to run.with_params([], 'one').and_return(false) } it { is_expected.to run.with_params([], ['one']).and_return(false) } it { is_expected.to run.with_params(['one'], 'one').and_return(true) } it { is_expected.to run.with_params(['one'], ['one']).and_return(true) } it { is_expected.to run.with_params(%w[one two three four], %w[four two]).and_return(true) } it { is_expected.to run.with_params(%w[ọאּẹ ŧẅồ ţҺŗęē ƒơџŕ], %w[ƒơџŕ ŧẅồ]).and_return(true) } it { is_expected.to run.with_params(%w[one two three four], %w[four five]).and_return(false) } it { is_expected.to run.with_params(%w[ọאּẹ ŧẅồ ţҺŗęē ƒơџŕ], ['ƒơџŕ', 'ƒί√ə']).and_return(false) } end puppetlabs-stdlib-4.25.0/spec/functions/merge_spec.rb0100755005276200011600000000244313206047630017634 0ustar00require 'spec_helper' describe 'merge' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}, 'two').and_raise_error(Puppet::ParseError, %r{unexpected argument type String}) } it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, %r{unexpected argument type (Fixnum|Integer)}) } it { pending 'should not special case this' is_expected.to run.with_params({}).and_return({}) } it { is_expected.to run.with_params({}, {}).and_return({}) } it { is_expected.to run.with_params({}, {}, {}).and_return({}) } describe 'should accept empty strings as puppet undef' do it { is_expected.to run.with_params({}, '').and_return({}) } end it { is_expected.to run.with_params({ 'key' => 'value' }, {}).and_return('key' => 'value') } it { is_expected.to run.with_params({}, 'key' => 'value').and_return('key' => 'value') } it { is_expected.to run.with_params({ 'key' => 'value1' }, 'key' => 'value2').and_return('key' => 'value2') } it { is_expected.to run \ .with_params({ 'key1' => 'value1' }, { 'key2' => 'value2' }, 'key3' => 'value3') \ .and_return('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3') } end puppetlabs-stdlib-4.25.0/spec/functions/min_spec.rb0100755005276200011600000000215213206047630017315 0ustar00require 'spec_helper' describe 'min' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(1) } it { is_expected.to run.with_params(1, 2, 3).and_return(1) } it { is_expected.to run.with_params(3, 2, 1).and_return(1) } it { is_expected.to run.with_params(12, 8).and_return(8) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('one') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('one') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return(1) } it { is_expected.to run.with_params('1', 'one').and_return('1') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.3e1') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.4e0) } end end puppetlabs-stdlib-4.25.0/spec/functions/num2bool_spec.rb0100755005276200011600000000257613206047630020301 0ustar00require 'spec_helper' describe 'num2bool' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('abc').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } it { is_expected.to run.with_params(1).and_return(true) } it { is_expected.to run.with_params('1').and_return(true) } it { is_expected.to run.with_params(1.5).and_return(true) } it { is_expected.to run.with_params('1.5').and_return(true) } it { is_expected.to run.with_params(-1).and_return(false) } it { is_expected.to run.with_params('-1').and_return(false) } it { is_expected.to run.with_params(-1.5).and_return(false) } it { is_expected.to run.with_params('-1.5').and_return(false) } it { is_expected.to run.with_params(0).and_return(false) } it { is_expected.to run.with_params('0').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params('[]').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params('{}').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } end puppetlabs-stdlib-4.25.0/spec/functions/parsejson_spec.rb0100755005276200011600000000444313206047630020543 0ustar00require 'spec_helper' describe 'parsejson' do it 'exists' do is_expected.not_to eq(nil) end it 'raises an error if called without any arguments' do is_expected.to run.with_params .and_raise_error(%r{wrong number of arguments}i) end context 'with correct JSON data' do it 'is able to parse JSON data with a Hash' do is_expected.to run.with_params('{"a":"1","b":"2"}') .and_return('a' => '1', 'b' => '2') end it 'is able to parse JSON data with an Array' do is_expected.to run.with_params('["a","b","c"]') .and_return(%w[a b c]) end it 'is able to parse empty JSON values' do actual_array = %w[[] {}] expected = [[], {}] actual_array.each_with_index do |actual, index| is_expected.to run.with_params(actual).and_return(expected[index]) end end it 'is able to parse JSON data with a mixed structure' do is_expected.to run.with_params('{"a":"1","b":2,"c":{"d":[true,false]}}') .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [true, false] }) end it 'is able to parse JSON data with a UTF8 and double byte characters' do is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}') .and_return('×' => 'これ', 'ý' => '記号', 'です' => { '©' => %w[Á ß] }) end it 'does not return the default value if the data was parsed correctly' do is_expected.to run.with_params('{"a":"1"}', 'default_value') .and_return('a' => '1') end end context 'with incorrect JSON data' do it 'raises an error with invalid JSON and no default' do is_expected.to run.with_params('') .and_raise_error(PSON::ParserError) end it 'supports a structure for a default value' do is_expected.to run.with_params('', 'a' => '1') .and_return('a' => '1') end ['', 1, 1.2, nil, true, false, [], {}, :yaml].each do |value| it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end end end puppetlabs-stdlib-4.25.0/spec/functions/parseyaml_spec.rb0100755005276200011600000000605013212471613020527 0ustar00require 'spec_helper' describe 'parseyaml' do it 'exists' do is_expected.not_to eq(nil) end it 'raises an error if called without any arguments' do is_expected.to run.with_params .and_raise_error(%r{wrong number of arguments}i) end context 'with correct YAML data' do it 'is able to parse a YAML data with a String' do actual_array = ['--- just a string', 'just a string'] actual_array.each do |actual| is_expected.to run.with_params(actual).and_return('just a string') end end it 'is able to parse YAML data with a Hash' do is_expected.to run.with_params("---\na: '1'\nb: '2'\n") .and_return('a' => '1', 'b' => '2') end it 'is able to parse YAML data with an Array' do is_expected.to run.with_params("---\n- a\n- b\n- c\n") .and_return(%w[a b c]) end it 'is able to parse YAML data with a mixed structure' do is_expected.to run.with_params("---\na: '1'\nb: 2\nc:\n d:\n - :a\n - true\n - false\n") .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [:a, true, false] }) end it 'is able to parse YAML data with a UTF8 and double byte characters' do is_expected.to run.with_params("---\na: ×\nこれ: 記号\nです:\n ©:\n - Á\n - ß\n") .and_return('a' => '×', 'これ' => '記号', 'です' => { '©' => %w[Á ß] }) end it 'does not return the default value if the data was parsed correctly' do is_expected.to run.with_params("---\na: '1'\n", 'default_value') .and_return('a' => '1') end end context 'on a modern ruby', :unless => RUBY_VERSION == '1.8.7' do it 'raises an error with invalid YAML and no default' do is_expected.to run.with_params('["one"') .and_raise_error(Psych::SyntaxError) end end context 'when running on ruby 1.8.7, which does not have Psych', :if => RUBY_VERSION == '1.8.7' do it 'raises an error with invalid YAML and no default' do is_expected.to run.with_params('["one"') .and_raise_error(ArgumentError) end end context 'with incorrect YAML data' do it 'supports a structure for a default value' do is_expected.to run.with_params('', 'a' => '1') .and_return('a' => '1') end [1, 1.2, nil, true, false, [], {}, :yaml].each do |value| it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do ['---', '...', '*8', ''].each do |value| it "should return the default value for an incorrect #{value.inspect} string parameter" do is_expected.to run.with_params(value, 'default_value') .and_return('default_value') end end end end end puppetlabs-stdlib-4.25.0/spec/functions/pick_default_spec.rb0100755005276200011600000000257313206047630021173 0ustar00require 'spec_helper' describe 'pick_default' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(RuntimeError, %r{Must receive at least one argument}) } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('ớņệ', 'ťωơ').and_return('ớņệ') } it { is_expected.to run.with_params('', 'two').and_return('two') } it { is_expected.to run.with_params(:undef, 'two').and_return('two') } it { is_expected.to run.with_params(:undefined, 'two').and_return('two') } it { is_expected.to run.with_params(nil, 'two').and_return('two') } ['', :undef, :undefined, nil, {}, [], 1, 'default'].each do |value| describe "when providing #{value.inspect} as default" do it { is_expected.to run.with_params('one', value).and_return('one') } it { is_expected.to run.with_params('ớņệ', value).and_return('ớņệ') } it { is_expected.to run.with_params([], value).and_return([]) } it { is_expected.to run.with_params({}, value).and_return({}) } it { is_expected.to run.with_params(value, value).and_return(value) } it { is_expected.to run.with_params(:undef, value).and_return(value) } it { is_expected.to run.with_params(:undefined, value).and_return(value) } it { is_expected.to run.with_params(nil, value).and_return(value) } end end end puppetlabs-stdlib-4.25.0/spec/functions/pick_spec.rb0100755005276200011600000000200613212471613017455 0ustar00require 'spec_helper' describe 'pick' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{must receive at least one non empty value}) } it { is_expected.to run.with_params('', nil, :undef, :undefined).and_raise_error(Puppet::ParseError, %r{must receive at least one non empty value}) } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('', 'two').and_return('two') } it { is_expected.to run.with_params(:undef, 'two').and_return('two') } it { is_expected.to run.with_params(:undefined, 'two').and_return('two') } it { is_expected.to run.with_params(nil, 'two').and_return('two') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(nil, 'このテキスト').and_return('このテキスト') } it { is_expected.to run.with_params('', 'ŝẳмрłề џţƒ8 ţẽם', 'このテキスト').and_return('ŝẳмрłề џţƒ8 ţẽם') } end end puppetlabs-stdlib-4.25.0/spec/functions/prefix_spec.rb0100755005276200011600000000345113206047630020032 0ustar00require 'spec_helper' describe 'prefix' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the second.') is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{expected first argument to be an Array or a Hash}) } it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{expected second argument to be a String}) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one', 2]).and_return(%w[one 2]) } it { is_expected.to run.with_params(['ớņệ', 2]).and_return(%w[ớņệ 2]) } it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([''], '').and_return(['']) } it { is_expected.to run.with_params(['one'], 'pre').and_return(['preone']) } it { is_expected.to run.with_params(%w[one two three], 'pre').and_return(%w[preone pretwo prethree]) } it { is_expected.to run.with_params({}).and_return({}) } it { is_expected.to run.with_params('key1' => 'value1', 2 => 3).and_return('key1' => 'value1', '2' => 3) } it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } it { is_expected.to run.with_params({ 'key' => 'value' }, 'pre').and_return('prekey' => 'value') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'pre') \ .and_return('prekey1' => 'value1', 'prekey2' => 'value2', 'prekey3' => 'value3') } end puppetlabs-stdlib-4.25.0/spec/functions/private_spec.rb0100644005276200011600000000406013252003272020174 0ustar00require 'spec_helper' describe 'private' do it 'issues a warning' do scope.expects(:warning).with("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : unable to cut line to required length begin subject.call [] rescue # rubocop:disable Lint/HandleExceptions # ignore this end end context 'when called from inside module' do it 'does not fail' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('foo') expect { subject.call [] }.not_to raise_error end end context 'with an explicit failure message' do it 'prints the failure message on error' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') expect { subject.call ['failure message!'] }.to raise_error Puppet::ParseError, %r{failure message!} end end context 'when called from private class' do it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('hostclass') expect { subject.call [] }.to raise_error Puppet::ParseError, %r{Class foo::baz is private} end end context 'when called from private definition' do it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('definition') expect { subject.call [] }.to raise_error Puppet::ParseError, %r{Definition foo::baz is private} end end end puppetlabs-stdlib-4.25.0/spec/functions/pw_hash_spec.rb0100644005276200011600000001226713206047630020170 0ustar00require 'spec_helper' describe 'pw_hash' do it { is_expected.not_to eq(nil) } context 'when there are less than 3 arguments' do it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('password').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('password', 'sha-256').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } end context 'when there are more than 3 arguments' do it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra', 'extra').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } end context 'when the first argument is not a string' do it { is_expected.to run.with_params([], 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } it { is_expected.to run.with_params({}, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } it { is_expected.to run.with_params(1, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } it { is_expected.to run.with_params(true, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } end context 'when the first argument is undefined' do it { is_expected.to run.with_params('', 'sha-256', 'salt').and_return(nil) } it { is_expected.to run.with_params(nil, 'sha-256', 'salt').and_return(nil) } end context 'when the second argument is not a string' do it { is_expected.to run.with_params('password', [], 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params('password', {}, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params('password', 1, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params('password', true, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } end context 'when the second argument is not one of the supported hashing algorithms' do it { is_expected.to run.with_params('password', 'no such algo', 'salt').and_raise_error(ArgumentError, %r{is not a valid hash type}) } end context 'when the third argument is not a string' do it { is_expected.to run.with_params('password', 'sha-256', []).and_raise_error(ArgumentError, %r{third argument must be a string}) } it { is_expected.to run.with_params('password', 'sha-256', {}).and_raise_error(ArgumentError, %r{third argument must be a string}) } it { is_expected.to run.with_params('password', 'sha-256', 1).and_raise_error(ArgumentError, %r{third argument must be a string}) } it { is_expected.to run.with_params('password', 'sha-256', true).and_raise_error(ArgumentError, %r{third argument must be a string}) } end context 'when the third argument is empty' do it { is_expected.to run.with_params('password', 'sha-512', '').and_raise_error(ArgumentError, %r{third argument must not be empty}) } end context 'when the third argument contains invalid characters' do it { is_expected.to run.with_params('password', 'sha-512', 'one%').and_raise_error(ArgumentError, %r{characters in salt must be in the set}) } end context 'when running on a platform with a weak String#crypt implementation' do before(:each) { allow_any_instance_of(String).to receive(:crypt).with('$1$1').and_return('a bad hash') } # rubocop:disable RSpec/AnyInstance : Unable to find a viable replacement it { is_expected.to run.with_params('password', 'sha-512', 'salt').and_raise_error(Puppet::ParseError, %r{system does not support enhanced salts}) } end if RUBY_PLATFORM == 'java' || 'test'.crypt('$1$1') == '$1$1$Bp8CU9Oujr9SSEw53WV6G.' describe 'on systems with enhanced salts support' do it { is_expected.to run.with_params('password', 'md5', 'salt').and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } it { is_expected.to run.with_params('password', 'sha-256', 'salt').and_return('$5$salt$Gcm6FsVtF/Qa77ZKD.iwsJlCVPY0XSMgLJL0Hnww/c1') } it { is_expected.to run.with_params('password', 'sha-512', 'salt').and_return('$6$salt$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy.g.') } end if Puppet::Util::Package.versioncmp(Puppet.version, '4.7.0') >= 0 describe 'when arguments are sensitive' do it { is_expected.to run.with_params(Puppet::Pops::Types::PSensitiveType::Sensitive.new('password'), 'md5', 'salt').and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } it { is_expected.to run.with_params(Puppet::Pops::Types::PSensitiveType::Sensitive.new('password'), 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')) .and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } it { is_expected.to run.with_params('password', 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')).and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } end end end end puppetlabs-stdlib-4.25.0/spec/functions/range_spec.rb0100755005276200011600000001757013212471613017637 0ustar00require 'spec_helper' describe 'range' do it { is_expected.not_to eq(nil) } describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the third.') is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('1..2..3').and_raise_error(Puppet::ParseError, %r{Unable to compute range}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Unknown range format}i) } end describe 'signature validation in puppet4', :if => RSpec.configuration.puppet_future do it { pending 'the puppet 4 implementation' is_expected.to run.with_params.and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params('').and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params({}).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params([]).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(true).and_raise_error(ArgumentError) } it { is_expected.to run.with_params(1, 2, 'foo').and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, []).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, {}).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, true).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(ArgumentError) } it { pending 'the puppet 4 implementation' is_expected.to run.with_params('1..2..3').and_raise_error(ArgumentError) } end context 'with characters as bounds' do it { is_expected.to run.with_params('d', 'a').and_return([]) } it { is_expected.to run.with_params('a', 'a').and_return(['a']) } it { is_expected.to run.with_params('a', 'b').and_return(%w[a b]) } it { is_expected.to run.with_params('a', 'd').and_return(%w[a b c d]) } it { is_expected.to run.with_params('a', 'd', 1).and_return(%w[a b c d]) } it { is_expected.to run.with_params('a', 'd', '1').and_return(%w[a b c d]) } it { is_expected.to run.with_params('a', 'd', 2).and_return(%w[a c]) } it { is_expected.to run.with_params('a', 'd', -2).and_return(%w[a c]) } it { is_expected.to run.with_params('a', 'd', 3).and_return(%w[a d]) } it { is_expected.to run.with_params('a', 'd', 4).and_return(['a']) } end context 'with strings as bounds' do it { is_expected.to run.with_params('onea', 'oned').and_return(%w[onea oneb onec oned]) } it { is_expected.to run.with_params('two', 'one').and_return([]) } it { is_expected.to run.with_params('true', 'false').and_return([]) } it { is_expected.to run.with_params('false', 'true').and_return(['false']) } end context 'with integers as bounds' do it { is_expected.to run.with_params(4, 1).and_return([]) } it { is_expected.to run.with_params(1, 1).and_return([1]) } it { is_expected.to run.with_params(1, 2).and_return([1, 2]) } it { is_expected.to run.with_params(1, 4).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, -2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, 3).and_return([1, 4]) } it { is_expected.to run.with_params(1, 4, 4).and_return([1]) } end context 'with integers as strings as bounds' do it { is_expected.to run.with_params('4', '1').and_return([]) } it { is_expected.to run.with_params('1', '1').and_return([1]) } it { is_expected.to run.with_params('1', '2').and_return([1, 2]) } it { is_expected.to run.with_params('1', '4').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', -2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', 3).and_return([1, 4]) } it { is_expected.to run.with_params('1', '4', 4).and_return([1]) } end context 'with prefixed numbers as strings as bounds' do it { is_expected.to run.with_params('host01', 'host04').and_return(%w[host01 host02 host03 host04]) } it { is_expected.to run.with_params('01', '04').and_return([1, 2, 3, 4]) } end context 'with prefixed numbers as utf8 strings as bounds' do it { is_expected.to run.with_params('ħөŝŧ01', 'ħөŝŧ04').and_return(%w[ħөŝŧ01 ħөŝŧ02 ħөŝŧ03 ħөŝŧ04]) } end context 'with prefixed numbers as double byte character strings as bounds' do it { is_expected.to run.with_params('ホスト01', 'ホスト04').and_return(%w[ホスト01 ホスト02 ホスト03 ホスト04]) } end context 'with dash-range syntax' do it { is_expected.to run.with_params('4-1').and_return([]) } it { is_expected.to run.with_params('1-1').and_return([1]) } it { is_expected.to run.with_params('1-2').and_return([1, 2]) } it { is_expected.to run.with_params('1-4').and_return([1, 2, 3, 4]) } end context 'with two-dot-range syntax' do it { is_expected.to run.with_params('4..1').and_return([]) } it { is_expected.to run.with_params('1..1').and_return([1]) } it { is_expected.to run.with_params('1..2').and_return([1, 2]) } it { is_expected.to run.with_params('1..4').and_return([1, 2, 3, 4]) } end context 'with three-dot-range syntax' do it { is_expected.to run.with_params('4...1').and_return([]) } it { is_expected.to run.with_params('1...1').and_return([]) } it { is_expected.to run.with_params('1...2').and_return([1]) } it { is_expected.to run.with_params('1...3').and_return([1, 2]) } it { is_expected.to run.with_params('1...5').and_return([1, 2, 3, 4]) } end describe 'when passing mixed arguments as bounds' do it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length is_expected.to run.with_params('0', 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length is_expected.to run.with_params(0, 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length is_expected.to run.with_params('h0', 'ha').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } end end puppetlabs-stdlib-4.25.0/spec/functions/regexpescape_spec.rb0100644005276200011600000000376013212471613021207 0ustar00require 'spec_helper' describe 'regexpescape' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end describe 'handling normal strings' do it 'calls ruby\'s Regexp.escape function' do Regexp.expects(:escape).with('regexp_string').returns('escaped_regexp_string').once is_expected.to run.with_params('regexp_string').and_return('escaped_regexp_string') end end describe 'handling classes derived from String' do it 'calls ruby\'s Regexp.escape function' do regexp_string = AlsoString.new('regexp_string') Regexp.expects(:escape).with(regexp_string).returns('escaped_regexp_string').once is_expected.to run.with_params(regexp_string).and_return('escaped_regexp_string') end end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one*', 'two']).and_return(['one\*', 'two']) } it { is_expected.to run.with_params(['one*', 1, true, {}, 'two']).and_return(['one\*', 1, true, {}, 'two']) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(['ŏʼnε*']).and_return(['ŏʼnε\*']) } it { is_expected.to run.with_params(['インターネット*']).and_return(['インターネット\*']) } end end end puppetlabs-stdlib-4.25.0/spec/functions/reject_spec.rb0100755005276200011600000000213613206047630020010 0ustar00require 'spec_helper' describe 'reject' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], 'pattern', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('reject does not actually check this, and raises NoMethodError instead') is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { pending('reject does not actually check this, and raises NoMethodError instead') is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(%w[one two three], 't(wo|hree)').and_return(['one']) } it { is_expected.to run.with_params(%w[όʼnệ ţщồ ţңяέέ], 'ţ(щồ|ңяέέ)').and_return(['όʼnệ']) } end puppetlabs-stdlib-4.25.0/spec/functions/reverse_spec.rb0100755005276200011600000000351413206047630020210 0ustar00require 'spec_helper' describe 'reverse' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three]).and_return(%w[three two one]) } it { is_expected.to run.with_params(%w[one two three four]).and_return(%w[four three two one]) } it { is_expected.to run.with_params(%w[ổňë ťŵọ ŧңяəė ƒŏůŗ]).and_return(%w[ƒŏůŗ ŧңяəė ťŵọ ổňë]) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('abc').and_return('cba') } it { is_expected.to run.with_params('abcd').and_return('dcba') } it { is_expected.to run.with_params('āβćđ').and_return('đćβā') } context 'when using a class extending String' do it 'calls its reverse method' do value = AlsoString.new('asdfghjkl') value.expects(:reverse).returns('foo') expect(subject).to run.with_params(value).and_return('foo') end end end puppetlabs-stdlib-4.25.0/spec/functions/round_spec.rb0100755005276200011600000000130613206047630017661 0ustar00require 'spec_helper' describe 'round' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params(34.3).and_return(34) } it { is_expected.to run.with_params(-34.3).and_return(-34) } it { is_expected.to run.with_params(34.5).and_return(35) } it { is_expected.to run.with_params(-34.5).and_return(-35) } it { is_expected.to run.with_params(34.7).and_return(35) } it { is_expected.to run.with_params(-34.7).and_return(-35) } it { is_expected.to run.with_params('test').and_raise_error Puppet::ParseError } it { is_expected.to run.with_params('test', 'best').and_raise_error Puppet::ParseError } it { is_expected.to run.with_params(3, 4).and_raise_error Puppet::ParseError } end puppetlabs-stdlib-4.25.0/spec/functions/rstrip_spec.rb0100755005276200011600000000430213206047630020054 0ustar00require 'spec_helper' describe 'rstrip' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return(' one') } it { is_expected.to run.with_params(' one').and_return(' one') } it { is_expected.to run.with_params("\tone").and_return("\tone") } it { is_expected.to run.with_params("\t one").and_return("\t one") } it { is_expected.to run.with_params('one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return(' one') } it { is_expected.to run.with_params(' one ').and_return(' one') } it { is_expected.to run.with_params(' ǿňè ').and_return(' ǿňè') } it { is_expected.to run.with_params("\tone ").and_return("\tone") } it { is_expected.to run.with_params("\t one ").and_return("\t one") } it { is_expected.to run.with_params("one\t").and_return('one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params("\tone\t").and_return("\tone") } it { is_expected.to run.with_params("\t one\t").and_return("\t one") } it { is_expected.to run.with_params(' o n e ').and_return(' o n e') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return(' one') } end puppetlabs-stdlib-4.25.0/spec/functions/seeded_rand_spec.rb0100644005276200011600000000614613212471613020772 0ustar00require 'spec_helper' describe 'seeded_rand' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(0, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1.5, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(-10, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('-10', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params('string', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params([], '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params({}, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be a string}) } it 'provides a random number strictly less than the given max' do expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i < 3 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end it 'provides a random number greater or equal to zero' do expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i >= 0 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end it "provides the same 'random' value on subsequent calls for the same host" do expect(seeded_rand(10, 'seed')).to eql(seeded_rand(10, 'seed')) end it 'allows seed to control the random value on a single host' do first_random = seeded_rand(1000, 'seed1') second_different_random = seeded_rand(1000, 'seed2') expect(first_random).not_to eql(second_different_random) end it 'does not return different values for different hosts' do val1 = seeded_rand(1000, 'foo', :host => 'first.host.com') val2 = seeded_rand(1000, 'foo', :host => 'second.host.com') expect(val1).to eql(val2) end def seeded_rand(max, seed, args = {}) host = args[:host] || '127.0.0.1' # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context scope.stubs(:lookupvar).with('::fqdn', {}).returns(host) scope.function_seeded_rand([max, seed]) end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(1000, 'ǿňè') } it { is_expected.to run.with_params(1000, '文字列') } end end puppetlabs-stdlib-4.25.0/spec/functions/shell_escape_spec.rb0100644005276200011600000000233113212471613021154 0ustar00require 'spec_helper' describe 'shell_escape' do it { is_expected.not_to eq(nil) } describe 'signature validation' do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'stringification' do it { is_expected.to run.with_params(10).and_return('10') } it { is_expected.to run.with_params(false).and_return('false') } end describe 'escaping' do it { is_expected.to run.with_params('foo').and_return('foo') } it { is_expected.to run.with_params('foo bar').and_return('foo\ bar') } it { is_expected.to run.with_params('~`!@#$%^&*()_+-=[]\{}|;\':",./<>?') .and_return('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') } end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('スペー スを含むテ キスト').and_return('\\ス\\ペ\\ー\\ \\ス\\を\\含\\む\\テ\\ \\ \\キ\\ス\\ト') } it { is_expected.to run.with_params('μťƒ 8 ŧĕχť').and_return('\\μ\\ť\\ƒ\\ 8\\ \\ \\ŧ\\ĕ\\χ\\ť') } end end puppetlabs-stdlib-4.25.0/spec/functions/shell_join_spec.rb0100644005276200011600000000263413212471613020661 0ustar00require 'spec_helper' describe 'shell_join' do it { is_expected.not_to eq(nil) } describe 'signature validation' do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(['foo'], ['bar']).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{is not an Array}i) } end describe 'shell argument joining' do it { is_expected.to run.with_params(['foo']).and_return('foo') } it { is_expected.to run.with_params(%w[foo bar]).and_return('foo bar') } it { is_expected.to run.with_params(['foo', 'bar baz']).and_return('foo bar\ baz') } it { is_expected.to run.with_params(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) .and_return('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(%w[μťƒ 8 ŧĕχť]).and_return('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť') } it { is_expected.to run.with_params(['スペー', 'スを含むテ', ' キスト']).and_return('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト') } end end describe 'stringification' do it { is_expected.to run.with_params([10, false, 'foo']).and_return('10 false foo') } end end puppetlabs-stdlib-4.25.0/spec/functions/shell_split_spec.rb0100644005276200011600000000270113212471613021050 0ustar00require 'spec_helper' describe 'shell_split' do it { is_expected.not_to eq(nil) } describe 'signature validation' do it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'stringification' do it { is_expected.to run.with_params(10).and_return(['10']) } it { is_expected.to run.with_params(false).and_return(['false']) } end describe 'shell line spliting' do it { is_expected.to run.with_params('foo').and_return(['foo']) } it { is_expected.to run.with_params('foo bar').and_return(%w[foo bar]) } it { is_expected.to run.with_params('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') .and_return(['~`!@#$%^&*()_+-=[]\{}|;\':",./<>?']) } it { is_expected.to run.with_params('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') .and_return(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť').and_return(%w[μťƒ 8 ŧĕχť]) } it { is_expected.to run.with_params('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト').and_return(['スペー', 'スを含むテ', ' キスト']) } end end end puppetlabs-stdlib-4.25.0/spec/functions/shuffle_spec.rb0100755005276200011600000000370513212471613020172 0ustar00require 'spec_helper' describe 'shuffle' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } context 'when running with a specific seed' do # make tests deterministic before(:each) { srand(2) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params(%w[one two three]).and_return(%w[two one three]) } it { is_expected.to run.with_params(%w[one two three four]).and_return(%w[four three two one]) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('abc').and_return('bac') } it { is_expected.to run.with_params('abcd').and_return('dcba') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('ůţƒ8 ŧέχŧ şŧґíńģ').and_return('ģńş ůχţέƒŧí8ґŧŧ ') } it { is_expected.to run.with_params('日本語の文字列').and_return('字本日語文列の') } end context 'when using a class extending String' do it { is_expected.to run.with_params(AlsoString.new('asdfghjkl')).and_return('lkhdsfajg') } end end end puppetlabs-stdlib-4.25.0/spec/functions/size_spec.rb0100755005276200011600000000377413206047630017517 0ustar00require 'spec_helper' describe 'size' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } it { is_expected.to run.with_params('1').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } it { is_expected.to run.with_params('1.0').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } it { is_expected.to run.with_params(%w[one two three]).and_return(3) } it { is_expected.to run.with_params(%w[one two three four]).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } it { is_expected.to run.with_params('1' => '2').and_return(1) } it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } context 'when using a class extending String' do it 'calls its size method' do value = AlsoString.new('asdfghjkl') value.expects(:size).returns('foo') expect(subject).to run.with_params(value).and_return('foo') end end end puppetlabs-stdlib-4.25.0/spec/functions/sort_spec.rb0100755005276200011600000000247613206047630017532 0ustar00require 'spec_helper' describe 'sort' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('stricter input checking') is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{requires string or array}) } it { pending('stricter input checking') is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{requires string or array}) } it { pending('stricter input checking') is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{requires string or array}) } end context 'when called with an array' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(%w[c b a]).and_return(%w[a b c]) } end context 'when called with a string' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('cbda').and_return('abcd') } end end puppetlabs-stdlib-4.25.0/spec/functions/sprintf_hash_spec.rb0100644005276200011600000000240713212471613021221 0ustar00require 'spec_helper' describe 'sprintf_hash' do it 'exists' do is_expected.not_to eq(nil) end context 'with param count' do it 'fails with no arguments' do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects 2 arguments}i) end it 'fails with 1 argument' do is_expected.to run.with_params('').and_raise_error(ArgumentError, %r{expects 2 arguments}i) end it 'fails with too many arguments' do is_expected.to run.with_params('', '', '').and_raise_error(ArgumentError, %r{expects 2 arguments}i) end end context 'with param type' do it 'fails with wrong format type' do is_expected.to run.with_params(false, {}).and_raise_error(ArgumentError, %r{parameter 'format' expects a String value}i) end it 'fails with wrong arguments type' do is_expected.to run.with_params('', false).and_raise_error(ArgumentError, %r{parameter 'arguments' expects a Hash value}i) end end it 'prints formats with name placeholders' do is_expected.to run.with_params('string %s and integer %b', 'foo' => '_foo_', 'bar' => 5) # rubocop:disable Style/FormatStringToken : Template tokens needed for purposes of test .and_return('string _foo_ and integer 101') end end puppetlabs-stdlib-4.25.0/spec/functions/squeeze_spec.rb0100755005276200011600000000440013212471613020210 0ustar00require 'spec_helper' describe 'squeeze' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(NoMethodError) } it { is_expected.to run.with_params({}).and_raise_error(NoMethodError) } it { is_expected.to run.with_params(true).and_raise_error(NoMethodError) } context 'when squeezing a single string' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('aaaaaaaaa').and_return('a') } it { is_expected.to run.with_params('aaaaaaaaa', 'a').and_return('a') } it { is_expected.to run.with_params('aaaaaaaaabbbbbbbbbbcccccccccc', 'b-c').and_return('aaaaaaaaabc') } end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('ậậậậậậậậậậậậậậậậậậậậ').and_return('ậ') } it { is_expected.to run.with_params('語語語語語語語', '語').and_return('語') } it { is_expected.to run.with_params('ậậậậậậậậậậậậậậậậậ語語語語©©©©©', '©').and_return('ậậậậậậậậậậậậậậậậậ語語語語©') } end context 'when squeezing values in an array' do it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc']) \ .and_return(['', 'a', 'a', 'abc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'a') \ .and_return(['', 'a', 'a', 'abbbbbbbbbbcccccccccc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'b-c') \ .and_return(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabc']) } end context 'when using a class extending String' do it 'calls its squeeze method' do value = AlsoString.new('aaaaaaaaa') value.expects(:squeeze).returns('foo') expect(subject).to run.with_params(value).and_return('foo') end end end puppetlabs-stdlib-4.25.0/spec/functions/str2bool_spec.rb0100755005276200011600000000166513206047630020310 0ustar00require 'spec_helper' describe 'str2bool' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('true', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Unknown type of boolean given}) } describe 'when testing values that mean "true"' do ['TRUE', '1', 't', 'y', 'true', 'yes', true].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing values that mean "false"' do ['FALSE', '', '0', 'f', 'n', 'false', 'no', false, 'undef', 'undefined'].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end end puppetlabs-stdlib-4.25.0/spec/functions/str2saltedsha512_spec.rb0100755005276200011600000000237313206047630021552 0ustar00require 'spec_helper' describe 'str2saltedsha512' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('password', 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires a String argument}) } context 'when running with a specific seed' do # make tests deterministic before(:each) { srand(2) } it { is_expected.to run.with_params('') .and_return('0f8a612f4eeed08e47b3875d00f33c5688f7926298f2d9b5fe19d1323f910bc78b6f7b5892596d2fabaa65e7a8d99b3768c102610cf0432c4827eee01f09451e3fae4f7a') } it { is_expected.to run.with_params('password') .and_return('0f8a612f43134376566c5707718d600effcfb17581fc9d3fa64d7f447dfda317c174ffdb498d2c5bd5c2075dab41c9d7ada5afbdc6b55354980eb5ba61802371e6b64956') } it { is_expected.to run.with_params('verylongpassword') .and_return('0f8a612f7a448537540e062daa8621f9bae326ca8ccb899e1bdb10e7c218cebfceae2530b856662565fdc4d81e986fc50cfbbc46d50436610ed9429ff5e43f2c45b5d039') } end end puppetlabs-stdlib-4.25.0/spec/functions/strftime_spec.rb0100755005276200011600000000141613206047630020371 0ustar00require 'spec_helper' describe 'strftime' do it 'exists' do expect(Puppet::Parser::Functions.function('strftime')).to eq('function_strftime') end it 'raises a ParseError if there is less than 1 arguments' do expect { scope.function_strftime([]) }.to(raise_error(Puppet::ParseError)) end it 'using %s should be higher then when I wrote this test' do result = scope.function_strftime(['%s']) expect(result.to_i).to(be > 1_311_953_157) end it 'using %s should be greater than 1.5 trillion' do result = scope.function_strftime(['%s']) expect(result.to_i).to(be > 1_500_000_000) end it 'returns a date when given %Y-%m-%d' do result = scope.function_strftime(['%Y-%m-%d']) expect(result).to match(%r{^\d{4}-\d{2}-\d{2}$}) end end puppetlabs-stdlib-4.25.0/spec/functions/strip_spec.rb0100755005276200011600000000424713206047630017702 0ustar00require 'spec_helper' describe 'strip' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").and_return('') } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params(' one').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t one").and_return('one') } it { is_expected.to run.with_params('one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return('one') } it { is_expected.to run.with_params(' one ').and_return('one') } it { is_expected.to run.with_params("\tone ").and_return('one') } it { is_expected.to run.with_params("\t one ").and_return('one') } it { is_expected.to run.with_params("one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params("\tone \t").and_return('one') } it { is_expected.to run.with_params("\t one \t").and_return('one') } it { is_expected.to run.with_params(' o n e ').and_return('o n e') } it { is_expected.to run.with_params(' ỏŋέ ').and_return('ỏŋέ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one') } end puppetlabs-stdlib-4.25.0/spec/functions/suffix_spec.rb0100755005276200011600000000364113206047630020042 0ustar00require 'spec_helper' describe 'suffix' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the second.') is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{expected first argument to be an Array}) } it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{expected second argument to be a String}) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one', 2]).and_return(%w[one 2]) } it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([''], '').and_return(['']) } it { is_expected.to run.with_params(['one'], 'post').and_return(['onepost']) } it { is_expected.to run.with_params(%w[one two three], 'post').and_return(%w[onepost twopost threepost]) } it { is_expected.to run.with_params(['ỗńέ', 'ťשׂǿ', 'ŧҺř℮ə'], 'рổŝţ').and_return(['ỗńέрổŝţ', 'ťשׂǿрổŝţ', 'ŧҺř℮əрổŝţ']) } it { is_expected.to run.with_params({}).and_return({}) } it { is_expected.to run.with_params('key1' => 'value1', 2 => 3).and_return('key1' => 'value1', '2' => 3) } it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } it { is_expected.to run.with_params({ 'key' => 'value' }, 'post').and_return('keypost' => 'value') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'post') \ .and_return('key1post' => 'value1', 'key2post' => 'value2', 'key3post' => 'value3') } end puppetlabs-stdlib-4.25.0/spec/functions/swapcase_spec.rb0100755005276200011600000000433313206047630020343 0ustar00require 'spec_helper' describe 'swapcase' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } describe 'with strings as inputs' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('one').and_return('ONE') } it { is_expected.to run.with_params('ONE').and_return('one') } it { is_expected.to run.with_params('oNe').and_return('OnE') } end describe 'with arrays as inputs' do it { is_expected.to run.with_params([]).and_return([]) } describe 'only containing strings' do it { is_expected.to run.with_params(['']).and_return(['']) } it { is_expected.to run.with_params(['one']).and_return(['ONE']) } it { is_expected.to run.with_params(['ONE']).and_return(['one']) } it { is_expected.to run.with_params(['oNe']).and_return(['OnE']) } it { is_expected.to run.with_params(%w[one ONE]).and_return(%w[ONE one]) } it { is_expected.to run.with_params(%w[ONE OnE]).and_return(%w[one oNe]) } it { is_expected.to run.with_params(%w[oNe one]).and_return(%w[OnE ONE]) } end describe 'containing mixed types' do it { is_expected.to run.with_params(['OnE', {}]).and_return(['oNe', {}]) } it { is_expected.to run.with_params(['OnE', 1]).and_return(['oNe', 1]) } it { is_expected.to run.with_params(['OnE', []]).and_return(['oNe', []]) } it { is_expected.to run.with_params(['OnE', ['two']]).and_return(['oNe', ['two']]) } end end it 'accepts objects which extend String' do is_expected.to run.with_params(AlsoString.new('OnE')).and_return('oNe') end end puppetlabs-stdlib-4.25.0/spec/functions/time_spec.rb0100755005276200011600000000167713206047630017503 0ustar00require 'spec_helper' describe 'time' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when running at a specific time' do before(:each) do # get a value before stubbing the function test_time = Time.utc(2006, 10, 13, 8, 15, 11) Time.expects(:new).with.returns(test_time).once end it { is_expected.to run.with_params.and_return(1_160_727_311) } it { is_expected.to run.with_params('').and_return(1_160_727_311) } it { is_expected.to run.with_params([]).and_return(1_160_727_311) } it { is_expected.to run.with_params({}).and_return(1_160_727_311) } it { is_expected.to run.with_params('foo').and_return(1_160_727_311) } it { is_expected.to run.with_params('UTC').and_return(1_160_727_311) } it { is_expected.to run.with_params('America/New_York').and_return(1_160_727_311) } end end puppetlabs-stdlib-4.25.0/spec/functions/to_bytes_spec.rb0100755005276200011600000001003113206047630020355 0ustar00require 'spec_helper' describe 'to_bytes' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('1', 'extras').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([]).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) Array (in)?to String}) } it { is_expected.to run.with_params({}).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) Hash (in)?to String}) } it { is_expected.to run.with_params(true).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) (TrueClass|true) (in)?to String}) } describe 'when passing numbers' do it { is_expected.to run.with_params(0).and_return(0) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(-1).and_return(-1) } it { is_expected.to run.with_params(1.1).and_return(1.1) } it { is_expected.to run.with_params(-1.1).and_return(-1.1) } end describe 'when passing numbers as strings' do describe 'without a unit' do it { is_expected.to run.with_params('1').and_return(1) } it { is_expected.to run.with_params('-1').and_return(-1) } # these are so wrong it { is_expected.to run.with_params('1.1').and_return(1) } it { is_expected.to run.with_params('-1.1').and_return(-1) } end describe 'with a unit' do it { is_expected.to run.with_params('1k').and_return(1024) } it { is_expected.to run.with_params('-1kB').and_return(-1024) } it { is_expected.to run.with_params('1M').and_return(1024 * 1024) } it { is_expected.to run.with_params('1G').and_return(1024 * 1024 * 1024) } it { is_expected.to run.with_params('1T').and_return(1024 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('1P').and_return(1024 * 1024 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('1E').and_return(1024 * 1024 * 1024 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('1.5e3M').and_return(1_572_864_000) } it { is_expected.to run.with_params('4k').and_return(4 * 1024) } it { is_expected.to run.with_params('-4kB').and_return(4 * -1024) } it { is_expected.to run.with_params('4M').and_return(4 * 1024 * 1024) } it { is_expected.to run.with_params('4G').and_return(4 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('4T').and_return(4 * 1024 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('4P').and_return(4 * 1024 * 1024 * 1024 * 1024 * 1024) } it { is_expected.to run.with_params('4E').and_return(4 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024) } # these are so wrong it { is_expected.to run.with_params('1.0001 k').and_return(1024) } it { is_expected.to run.with_params('-1.0001 kB').and_return(-1024) } end describe 'with a unknown unit' do it { is_expected.to run.with_params('1KB').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } it { is_expected.to run.with_params('1K').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } it { is_expected.to run.with_params('1mb').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } it { is_expected.to run.with_params('1m').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } it { is_expected.to run.with_params('1%').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } it { is_expected.to run.with_params('1 p').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } end end # these are so wrong describe 'when passing random stuff' do it { is_expected.to run.with_params('-1....1').and_return(-1) } it { is_expected.to run.with_params('-1.e.e.e.1').and_return(-1) } it { is_expected.to run.with_params('-1+1').and_return(-1) } it { is_expected.to run.with_params('1-1').and_return(1) } it { is_expected.to run.with_params('1 kaboom').and_return(1024) } it { is_expected.to run.with_params('kaboom').and_return(0) } end end puppetlabs-stdlib-4.25.0/spec/functions/to_json_pretty_spec.rb0100755005276200011600000000224113212471613021612 0ustar00require 'spec_helper' describe 'to_json_pretty' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params([]).and_return("[\n\n]\n") } it { is_expected.to run.with_params(['one']).and_return("[\n \"one\"\n]\n") } it { is_expected.to run.with_params(%w[one two]).and_return("[\n \"one\",\n \"two\"\n]\n") } it { is_expected.to run.with_params({}).and_return("{\n}\n") } it { is_expected.to run.with_params('key' => 'value').and_return("{\n \"key\": \"value\"\n}\n") } it { is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) .and_return("{\n \"one\": {\n \"oneA\": \"A\",\n \"oneB\": {\n \"oneB1\": \"1\",\n \"oneB2\": \"2\"\n }\n },\n \"two\": [\n \"twoA\",\n \"twoB\"\n ]\n}\n") # rubocop:disable Metrics/LineLength : Unable to reduce line to required length } it { is_expected.to run.with_params({ 'one' => '1', 'two' => nil }, true).and_return("{\n \"one\": \"1\"\n}\n") } it { is_expected.to run.with_params(['one', 'two', nil, 'three'], true).and_return("[\n \"one\",\n \"two\",\n \"three\"\n]\n") } end puppetlabs-stdlib-4.25.0/spec/functions/to_json_spec.rb0100755005276200011600000000221413206047630020204 0ustar00require 'spec_helper' describe 'to_json' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params('').and_return('""') } it { is_expected.to run.with_params(true).and_return('true') } it { is_expected.to run.with_params('one').and_return('"one"') } it { is_expected.to run.with_params([]).and_return('[]') } it { is_expected.to run.with_params(['one']).and_return('["one"]') } it { is_expected.to run.with_params(%w[one two]).and_return('["one","two"]') } it { is_expected.to run.with_params({}).and_return('{}') } it { is_expected.to run.with_params('key' => 'value').and_return('{"key":"value"}') } it { is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) .and_return('{"one":{"oneA":"A","oneB":{"oneB1":"1","oneB2":"2"}},"two":["twoA","twoB"]}') } it { is_expected.to run.with_params('‰').and_return('"‰"') } it { is_expected.to run.with_params('竹').and_return('"竹"') } it { is_expected.to run.with_params('Ü').and_return('"Ü"') } it { is_expected.to run.with_params('∇').and_return('"∇"') } end puppetlabs-stdlib-4.25.0/spec/functions/to_yaml_spec.rb0100755005276200011600000000212513206047630020176 0ustar00require 'spec_helper' describe 'to_yaml' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params('').and_return("--- ''\n") } it { is_expected.to run.with_params(true).and_return("--- true\n...\n") } it { is_expected.to run.with_params('one').and_return("--- one\n...\n") } it { is_expected.to run.with_params([]).and_return("--- []\n") } it { is_expected.to run.with_params(['one']).and_return("---\n- one\n") } it { is_expected.to run.with_params(%w[one two]).and_return("---\n- one\n- two\n") } it { is_expected.to run.with_params({}).and_return("--- {}\n") } it { is_expected.to run.with_params('key' => 'value').and_return("---\nkey: value\n") } it { is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) .and_return("---\none:\n oneA: A\n oneB:\n oneB1: '1'\n oneB2: '2'\ntwo:\n- twoA\n- twoB\n") } it { is_expected.to run.with_params('‰').and_return("--- \"‰\"\n") } it { is_expected.to run.with_params('∇').and_return("--- \"∇\"\n") } end puppetlabs-stdlib-4.25.0/spec/functions/try_get_value_spec.rb0100644005276200011600000000631413212471613021403 0ustar00require 'spec_helper' describe 'try_get_value' do let(:data) do { 'a' => { 'g' => '2', 'e' => [ 'f0', 'f1', { 'x' => { 'y' => 'z', }, }, 'f3', ], }, 'b' => true, 'c' => false, 'd' => '1', } end context 'with single values' do it 'exists' do is_expected.not_to eq(nil) end it 'is able to return a single value' do is_expected.to run.with_params('test').and_return('test') end it 'uses the default value if data is a single value and path is present' do is_expected.to run.with_params('test', 'path', 'default').and_return('default') end it 'returns default if there is no data' do is_expected.to run.with_params(nil, nil, 'default').and_return('default') end it 'is able to use data structures as default values' do is_expected.to run.with_params('test', 'path', data).and_return(data) end end context 'with structure values' do it 'is able to extracts a single hash value' do is_expected.to run.with_params(data, 'd', 'default').and_return('1') end it 'is able to extract a deeply nested hash value' do is_expected.to run.with_params(data, 'a/g', 'default').and_return('2') end it 'returns the default value if the path is not found' do is_expected.to run.with_params(data, 'missing', 'default').and_return('default') end it 'returns the default value if the path is too long' do is_expected.to run.with_params(data, 'a/g/c/d', 'default').and_return('default') end it 'supports an array index in the path' do is_expected.to run.with_params(data, 'a/e/1', 'default').and_return('f1') end it 'returns the default value if an array index is not a number' do is_expected.to run.with_params(data, 'a/b/c', 'default').and_return('default') end it 'returns the default value if and index is out of array length' do is_expected.to run.with_params(data, 'a/e/5', 'default').and_return('default') end it 'is able to path though both arrays and hashes' do is_expected.to run.with_params(data, 'a/e/2/x/y', 'default').and_return('z') end it 'is able to return "true" value: default' do is_expected.to run.with_params(data, 'b', 'default').and_return(true) end it 'is able to return "true" value' do is_expected.to run.with_params(data, 'm', true).and_return(true) end it 'is able to return "false" value: default' do is_expected.to run.with_params(data, 'c', 'default').and_return(false) end it 'is able to return "false" value' do is_expected.to run.with_params(data, 'm', false).and_return(false) end it 'returns "nil" if value is not found and no default value is provided' do is_expected.to run.with_params(data, 'a/1').and_return(nil) end it 'is able to use a custom path separator' do is_expected.to run.with_params(data, 'a::g', 'default', '::').and_return('2') end it 'is able to use a custom path separator: default' do is_expected.to run.with_params(data, 'a::c', 'default', '::').and_return('default') end end end puppetlabs-stdlib-4.25.0/spec/functions/type3x_spec.rb0100644005276200011600000000214713206047630017767 0ustar00require 'spec_helper' describe 'type3x' do it 'exists' do expect(Puppet::Parser::Functions.function('type3x')).to eq('function_type3x') end it 'raises a ParseError if there is less than 1 arguments' do expect { scope.function_type3x([]) }.to(raise_error(Puppet::ParseError)) end it 'returns string when given a string' do result = scope.function_type3x(['aaabbbbcccc']) expect(result).to(eq('string')) end it 'returns array when given an array' do result = scope.function_type3x([%w[aaabbbbcccc asdf]]) expect(result).to(eq('array')) end it 'returns hash when given a hash' do result = scope.function_type3x([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end it 'returns integer when given an integer' do result = scope.function_type3x(['1']) expect(result).to(eq('integer')) end it 'returns float when given a float' do result = scope.function_type3x(['1.34']) expect(result).to(eq('float')) end it 'returns boolean when given a boolean' do result = scope.function_type3x([true]) expect(result).to(eq('boolean')) end end puppetlabs-stdlib-4.25.0/spec/functions/type_of_spec.rb0100644005276200011600000000135413206047630020177 0ustar00require 'spec_helper' if ENV['FUTURE_PARSER'] == 'yes' describe 'type_of' do pending 'teach rspec-puppet to load future-only functions under 3.7.5' do it { is_expected.not_to eq(nil) } end end end if Puppet.version.to_f >= 4.0 describe 'type_of' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('', '').and_raise_error(ArgumentError) } it 'gives the type of a string' do expect(subject.call({}, 'hello world')).to be_kind_of(Puppet::Pops::Types::PStringType) end it 'gives the type of an integer' do expect(subject.call({}, 5)).to be_kind_of(Puppet::Pops::Types::PIntegerType) end end end puppetlabs-stdlib-4.25.0/spec/functions/type_spec.rb0100755005276200011600000000251413206047630017515 0ustar00require 'spec_helper' describe 'type' do it 'exists' do expect(Puppet::Parser::Functions.function('type')).to eq('function_type') end it 'gives a deprecation warning when called' do scope.expects(:warning).with("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : Unable to reduce to required length scope.function_type(['aoeu']) end it 'returns string when given a string' do result = scope.function_type(['aaabbbbcccc']) expect(result).to(eq('string')) end it 'returns array when given an array' do result = scope.function_type([%w[aaabbbbcccc asdf]]) expect(result).to(eq('array')) end it 'returns hash when given a hash' do result = scope.function_type([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end it 'returns integer when given an integer' do result = scope.function_type(['1']) expect(result).to(eq('integer')) end it 'returns float when given a float' do result = scope.function_type(['1.34']) expect(result).to(eq('float')) end it 'returns boolean when given a boolean' do result = scope.function_type([true]) expect(result).to(eq('boolean')) end end puppetlabs-stdlib-4.25.0/spec/functions/union_spec.rb0100755005276200011600000000370213206047630017664 0ustar00require 'spec_helper' describe 'union' do describe 'argument checking' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } end it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([], ['one']).and_return(['one']) } it { is_expected.to run.with_params(['one'], []).and_return(['one']) } it { is_expected.to run.with_params(['one'], ['one']).and_return(['one']) } it { is_expected.to run.with_params(['one'], ['two']).and_return(%w[one two]) } it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two], %w[two three], %w[one three]).and_return(%w[one two three]) } it { is_expected.to run.with_params(%w[one two], %w[three four], %w[one two three], ['four']).and_return(%w[one two three four]) } it { is_expected.to run.with_params(%w[ốńə ţשׂợ], %w[ŧĥяếệ ƒởųŗ], %w[ốńə ţשׂợ ŧĥяếệ], ['ƒởųŗ']).and_return(%w[ốńə ţשׂợ ŧĥяếệ ƒởųŗ]) } it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return(['1', '2', '3', 1, 2]) end end puppetlabs-stdlib-4.25.0/spec/functions/unique_spec.rb0100755005276200011600000000302013206047630020033 0ustar00require 'spec_helper' describe 'unique' do if Puppet.version.to_f < 5.0 describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end context 'when called with an array' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(%w[a b a]).and_return(%w[a b]) } it { is_expected.to run.with_params(%w[ã ъ ã]).and_return(%w[ã ъ]) } end context 'when called with a string' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('aaba').and_return('ab') } it { is_expected.to run.with_params('ããъã').and_return('ãъ') } end end end puppetlabs-stdlib-4.25.0/spec/functions/unix2dos_spec.rb0100644005276200011600000000225313212471613020303 0ustar00require 'spec_helper' describe 'unix2dos' do context 'when checking parameter validity' do it { is_expected.not_to eq(nil) } it do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) end end context 'when converting from unix to dos format' do sample_text = "Hello\nWorld\n" desired_output = "Hello\r\nWorld\r\n" it 'outputs dos format' do is_expected.to run.with_params(sample_text).and_return(desired_output) end end context 'when converting from dos to dos format' do sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\r\nWorld\r\n" it 'outputs dos format' do is_expected.to run.with_params(sample_text).and_return(desired_output) end end end puppetlabs-stdlib-4.25.0/spec/functions/upcase_spec.rb0100755005276200011600000000231313206047630020011 0ustar00require 'spec_helper' describe 'upcase' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } end describe 'normal string handling' do it { is_expected.to run.with_params('abc').and_return('ABC') } it { is_expected.to run.with_params('Abc').and_return('ABC') } it { is_expected.to run.with_params('ABC').and_return('ABC') } end describe 'handling classes derived from String' do it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('ABC') } end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(%w[One twO]).and_return(%w[ONE TWO]) } end end puppetlabs-stdlib-4.25.0/spec/functions/uriescape_spec.rb0100755005276200011600000000330413206047630020512 0ustar00require 'spec_helper' describe 'uriescape' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end describe 'handling normal strings' do it 'calls ruby\'s URI.escape function' do URI.expects(:escape).with('uri_string').returns('escaped_uri_string').once is_expected.to run.with_params('uri_string').and_return('escaped_uri_string') end end describe 'handling classes derived from String' do it 'calls ruby\'s URI.escape function' do uri_string = AlsoString.new('uri_string') URI.expects(:escape).with(uri_string).returns('escaped_uri_string').once is_expected.to run.with_params(uri_string).and_return('escaped_uri_string') end end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one}', 'two']).and_return(['one%7D', 'two']) } it { is_expected.to run.with_params(['one}', 1, true, {}, 'two']).and_return(['one%7D', 1, true, {}, 'two']) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_absolute_path_spec.rb0100755005276200011600000000415413212471613023240 0ustar00require 'spec_helper' describe 'validate_absolute_path' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('c:/') end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid paths handling' do %w[ C:/ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 X:/foo/bar X:\\foo\\bar \\\\host\\windows //host/windows / /var/tmp /var/opt/../lib/puppet ].each do |path| it { is_expected.to run.with_params(path) } it { is_expected.to run.with_params(['/tmp', path]) } end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', ].each do |path| it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } end end context 'with relative paths' do %w[ relative1 . .. ./foo ../foo etc/puppetlabs/puppet opt/puppet/bin relative\\windows ].each do |path| it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } end end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_array_spec.rb0100755005276200011600000000330713206047630021524 0ustar00require 'spec_helper' describe 'validate_array' do describe 'signature validation' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end it { is_expected.not_to eq(nil) } # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params([]) end it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params([]) } it { is_expected.to run.with_params(['one']) } it { is_expected.to run.with_params([], ['two']) } it { is_expected.to run.with_params(['one'], ['two']) } end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params([], {}).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params([], 1).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params([], true).and_raise_error(Puppet::ParseError, %r{is not an Array}) } it { is_expected.to run.with_params([], 'one').and_raise_error(Puppet::ParseError, %r{is not an Array}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_augeas_spec.rb0100755005276200011600000000536713206047630021663 0ustar00require 'spec_helper' describe 'validate_augeas' do if Puppet.features.augeas? describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', [], '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'one', 'MSG to User', '4th arg').and_raise_error(NoMethodError) } end describe 'valid inputs' do inputs = [ ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns'], ["proc /proc proc nodev,noexec,nosuid 0 0\n", 'Fstab.lns'], ] inputs.each do |input| it { is_expected.to run.with_params(*input) } end end describe 'valid inputs which fail augeas validation' do # The intent here is to make sure valid inputs raise exceptions when they # don't specify an error message to display. This is the behvior in # 2.2.x and prior. inputs = [ ["root:x:0:0:root\n", 'Passwd.lns'], ["127.0.1.1\n", 'Hosts.lns'], ] inputs.each do |input| it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{validate_augeas.*?matched less than it should}) } end end describe 'when specifying nice error messages' do # The intent here is to make sure the function returns the 4th argument # in the exception thrown inputs = [ ["root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content'], ["127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content'], ] inputs.each do |input| it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{#{input[3]}}) } end end describe 'matching additional tests' do inputs = [ ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| it { is_expected.to run.with_params(*input) } end end describe 'failing additional tests' do inputs = [ ["foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], ["root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{testing path}) } end end else skip 'ruby-augeas not installed' end end puppetlabs-stdlib-4.25.0/spec/functions/validate_bool_spec.rb0100755005276200011600000000327713206047630021347 0ustar00require 'spec_helper' describe 'validate_bool' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(true) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'acceptable values' do it { is_expected.to run.with_params(true) } it { is_expected.to run.with_params(false) } it { is_expected.to run.with_params(true, false, false, true) } end describe 'validation failures' do it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params(true, 'one').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params('one', false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params('true').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params('false').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params(true, 'false').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params('true', false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params('true', false, false, false, false, false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_cmd_spec.rb0100755005276200011600000000403613212471613021150 0ustar00require 'spec_helper' describe 'validate_cmd', :unless => Puppet::Util::Platform.windows? do let(:touch) { File.exist?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' } describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('should implement stricter type checking') is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{content must be a string}) } it { pending('should implement stricter type checking') is_expected.to run.with_params('', [], '').and_raise_error(Puppet::ParseError, %r{checkscript must be a string}) } it { pending('should implement stricter type checking') is_expected.to run.with_params('', '', []).and_raise_error(Puppet::ParseError, %r{custom error message must be a string}) } end context 'when validation fails' do context 'with % placeholder' do it { is_expected.to run .with_params('', "#{touch} % /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \S+ \/no\/such\/file' returned 1:.*(cannot touch|o such file or)}) } it { is_expected.to run.with_params('', "#{touch} % /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end context 'without % placeholder' do it { is_expected.to run .with_params('', "#{touch} /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \/no\/such\/file \S+' returned 1:.*(cannot touch|o such file or)}) } it { is_expected.to run.with_params('', "#{touch} /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_domain_name_spec.rb0100644005276200011600000000451513206047630022654 0ustar00require 'spec_helper' describe 'validate_domain_name' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('com', 'com.') } it { is_expected.to run.with_params('x.com', 'x.com.') } it { is_expected.to run.with_params('foo.example.com', 'foo.example.com.') } it { is_expected.to run.with_params('2foo.example.com', '2foo.example.com.') } it { is_expected.to run.with_params('www.2foo.example.com', 'www.2foo.example.com.') } it { is_expected.to run.with_params('domain.tld', 'puppet.com') } end describe 'invalid inputs' do it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('foo.example.com', []).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('foo.example.com', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('foo.example.com', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('foo.example.com', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } it { is_expected.to run.with_params('invalid domain').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } it { is_expected.to run.with_params('-foo.example.com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } it { is_expected.to run.with_params('www.example.2com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } it { is_expected.to run.with_params('192.168.1.1').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_email_address_spec.rb0100644005276200011600000000234713206047630023202 0ustar00require 'spec_helper' describe 'validate_email_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('bob@gmail.com') } it { is_expected.to run.with_params('alice+puppetlabs.com@gmail.com') } end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid email}) } it { is_expected.to run.with_params('bob@gmail.com', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('bob@gmail.com', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('bob@gmail.com', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid email}) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_hash_spec.rb0100755005276200011600000000347313206047630021335 0ustar00require 'spec_helper' describe 'validate_hash' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'check for deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('key' => 'value') end end describe 'valid inputs' do it { is_expected.to run.with_params({}) } it { is_expected.to run.with_params('key' => 'value') } it { is_expected.to run.with_params({}, 'key' => 'value') } it { is_expected.to run.with_params({ 'key1' => 'value1' }, 'key2' => 'value2') } end describe 'invalid inputs' do it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params({}, []).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params({}, true).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } it { is_expected.to run.with_params({}, 'one').and_raise_error(Puppet::ParseError, %r{is not a Hash}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_integer_spec.rb0100755005276200011600000001301113212471613022033 0ustar00require 'spec_helper' describe 'validate_integer' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', 7.0, -7.0, {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params(invalid, 10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params(invalid, 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } it { is_expected.to run.with_params([0, 1, 2, invalid, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end context 'with a maximum limit of 10' do describe 'rejects numbers greater than the limit' do it { is_expected.to run.with_params(11, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10, 100], 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do it { is_expected.to run.with_params(10, 10) } it { is_expected.to run.with_params(1, 10) } it { is_expected.to run.with_params(-1, 10) } it { is_expected.to run.with_params('1', 10) } it { is_expected.to run.with_params('-1', 10) } it { is_expected.to run.with_params([1, 2, 3, 4], 10) } it { is_expected.to run.with_params([1, '2', '3', 4], 10) } end end context 'with a minimum limit of -10' do describe 'rejects numbers greater than the upper limit' do it { is_expected.to run.with_params(11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10, 100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'rejects numbers smaller than the lower limit' do it { is_expected.to run.with_params(-11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params([-10, 1, 2, 10, -100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } end describe 'accepts numbers between and including the limits' do it { is_expected.to run.with_params(10, 10, -10) } it { is_expected.to run.with_params(-10, 10, -10) } it { is_expected.to run.with_params(1, 10, -10) } it { is_expected.to run.with_params(-1, 10, -10) } it { is_expected.to run.with_params('1', 10, -10) } it { is_expected.to run.with_params('-1', 10, -10) } it { is_expected.to run.with_params([1, 2, 3, 4], 10, -10) } it { is_expected.to run.with_params([1, '2', '3', 4], 10, -10) } end end it { is_expected.to run.with_params(10, 10, 10) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_ip_address_spec.rb0100644005276200011600000000707213212471613022522 0ustar00require 'spec_helper' describe 'validate_ip_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('0.0.0.0') } it { is_expected.to run.with_params('8.8.8.8') } it { is_expected.to run.with_params('127.0.0.1') } it { is_expected.to run.with_params('10.10.10.10') } it { is_expected.to run.with_params('194.232.104.150') } it { is_expected.to run.with_params('244.24.24.24') } it { is_expected.to run.with_params('255.255.255.255') } it { is_expected.to run.with_params('1.2.3.4', '5.6.7.8') } it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1.2.3.4') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('1.2.3.4') end end context 'with netmasks' do it { is_expected.to run.with_params('8.8.8.8/0') } it { is_expected.to run.with_params('8.8.8.8/16') } it { is_expected.to run.with_params('8.8.8.8/32') } it { is_expected.to run.with_params('8.8.8.8/255.255.0.0') } end end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('1.2.3.4', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('1.2.3.4', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_ipv4_address_spec.rb0100755005276200011600000000313013212471613022766 0ustar00require 'spec_helper' describe 'validate_ipv4_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end end SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_raise_error(Puppet::ParseError, %r{is not a valid IPv4}) } end describe 'invalid inputs' do [{}, [], 1, true].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first, invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_ipv6_address_spec.rb0100755005276200011600000000701413212471613022775 0ustar00require 'spec_helper' describe 'validate_ipv6_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('3ffe:0505:0002::') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('3ffe:0505:0002::') end end describe 'valid inputs' do it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } it { is_expected.to run.with_params('fe80:0000:0000:0000:0204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80::204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:0204:61ff:254.157.241.86') } it { is_expected.to run.with_params('::1') } it { is_expected.to run.with_params('fe80::') } it { is_expected.to run.with_params('2001::') } end describe 'invalid inputs' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:2.3.4').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:257.1.2.3').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::ffff:12345678901234567890.1.26').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('affe:beef').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } context 'unless running on ruby 1.8.7', :if => RUBY_VERSION != '1.8.7' do it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params('::1', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_legacy_spec.rb0100644005276200011600000000501513206047630021645 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.4.0') >= 0 describe 'validate_legacy' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } describe 'when passing the type assertion and passing the previous validation' do before(:each) do scope.expects(:function_validate_foo).with([5]).once Puppet.expects(:notice).never end it 'passes without notice' do is_expected.to run.with_params('Integer', 'validate_foo', 5) end end describe 'when passing the type assertion and failing the previous validation' do before(:each) do scope.expects(:function_validate_foo).with([5]).raises(Puppet::ParseError, 'foo').once Puppet.expects(:notice).with(includes('Accepting previously invalid value for target type')) end it 'passes with a notice about newly accepted value' do is_expected.to run.with_params('Integer', 'validate_foo', 5) end end describe 'when failing the type assertion and passing the previous validation' do before(:each) do scope.expects(:function_validate_foo).with(['5']).once subject.func.expects(:call_function).with('deprecation', 'validate_legacy', includes('Integer')).once end it 'passes with a deprecation message' do is_expected.to run.with_params('Integer', 'validate_foo', '5') end end describe 'when failing the type assertion and failing the previous validation' do before(:each) do scope.expects(:function_validate_foo).with(['5']).raises(Puppet::ParseError, 'foo').once subject.func.expects(:call_function).with('fail', includes('Integer')).once end it 'fails with a helpful message' do is_expected.to run.with_params('Integer', 'validate_foo', '5') end end describe 'when passing in undef' do before(:each) do scope.expects(:function_validate_foo).with([:undef]).once Puppet.expects(:notice).never end it 'works' do is_expected.to run.with_params('Optional[Integer]', 'validate_foo', :undef) end end describe 'when passing in multiple arguments' do before(:each) do scope.expects(:function_validate_foo).with([:undef, 1, 'foo']).once Puppet.expects(:notice).never end it 'passes with a deprecation message' do is_expected.to run.with_params('Optional[Integer]', 'validate_foo', :undef, 1, 'foo') end end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_numeric_spec.rb0100755005276200011600000001274513212471613022055 0ustar00require 'spec_helper' describe 'validate_numeric' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } it { is_expected.to run.with_params(invalid, 10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } it { is_expected.to run.with_params(invalid, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end context 'with a maximum limit of 10.0' do describe 'rejects numbers greater than the limit' do it { is_expected.to run.with_params(11, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do it { is_expected.to run.with_params(10.0, 10.0) } it { is_expected.to run.with_params(1, 10.0) } it { is_expected.to run.with_params(-1, 10.0) } it { is_expected.to run.with_params('1', 10.0) } it { is_expected.to run.with_params('-1', 10.0) } it { is_expected.to run.with_params([1, 2, 3, 4], 10.0) } it { is_expected.to run.with_params([1, '2', '3', 4], 10.0) } end end context 'with a minimum limit of -10.0' do describe 'rejects numbers greater than the upper limit' do it { is_expected.to run.with_params(11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params(2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'rejects numbers smaller than the lower limit' do it { is_expected.to run.with_params(-11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params(-2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } it { is_expected.to run.with_params([-10.0, 1, 2, 10.0, -100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } end describe 'accepts numbers between and including the limits' do it { is_expected.to run.with_params(10.0, 10.0, -10.0) } it { is_expected.to run.with_params(-10.0, 10.0, -10.0) } it { is_expected.to run.with_params(1, 10.0, -10.0) } it { is_expected.to run.with_params(-1, 10.0, -10.0) } it { is_expected.to run.with_params('1', 10.0, -10.0) } it { is_expected.to run.with_params('-1', 10.0, -10.0) } it { is_expected.to run.with_params([1, 2, 3, 4], 10.0, -10.0) } it { is_expected.to run.with_params([1, '2', '3', 4], 10.0, -10.0) } end end it { is_expected.to run.with_params(10.0, 10.0, 10.0) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10.0) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_re_spec.rb0100755005276200011600000000522013212471613021007 0ustar00require 'spec_helper' describe 'validate_re' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('', '') end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('', '') } it { is_expected.to run.with_params('', ['']) } it { is_expected.to run.with_params('', [''], 'custom error') } it { is_expected.to run.with_params('one', '^one') } it { is_expected.to run.with_params('one', ['^one', '^two']) } it { is_expected.to run.with_params('one', ['^one', '^two'], 'custom error') } end describe 'invalid inputs' do it { is_expected.to run.with_params('', []).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', ['two']).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('', ['two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } it { is_expected.to run.with_params('notone', '^one').and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('notone', ['^one', '^two']).and_raise_error(Puppet::ParseError, %r{does not match}) } it { is_expected.to run.with_params('notone', ['^one', '^two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end describe 'non-string inputs' do [ 1, # Fixnum 3.14, # Float nil, # NilClass true, # TrueClass false, # FalseClass ['10'], # Array :key, # Symbol { :key => 'val' }, # Hash ].each do |input| it { is_expected.to run.with_params(input, '.*').and_raise_error(Puppet::ParseError, %r{needs to be a String}) } end end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_slength_spec.rb0100755005276200011600000000764413206047630022062 0ustar00require 'spec_helper' describe 'validate_slength' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1234567890', 10) end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', 2, 3, 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{second argument to be a positive Numeric}) } it { is_expected.to run.with_params('', -1).and_raise_error(Puppet::ParseError, %r{second argument to be a positive Numeric}) } it { is_expected.to run.with_params('', 1, '').and_raise_error(Puppet::ParseError, %r{third argument to be unset or a positive Numeric}) } it { is_expected.to run.with_params('', 1, -1).and_raise_error(Puppet::ParseError, %r{third argument to be unset or a positive Numeric}) } it { is_expected.to run.with_params('', 1, 2).and_raise_error(Puppet::ParseError, %r{argument to be equal to or larger than third argument}) } end context 'with a maximum length of 10' do describe 'rejects strings longer than the limit' do it { is_expected.to run.with_params('1234567890a', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } it { is_expected.to run.with_params('1234567890abcdef', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } it { is_expected.to run.with_params(%w[one 1234567890abcdef], 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } end describe 'accepts strings shorter or equal to the limit' do it { is_expected.to run.with_params('1234567890', 10) } it { is_expected.to run.with_params('12345', 10) } it { is_expected.to run.with_params(%w[one two], 10) } end end context 'with a minimum length of 5' do describe 'rejects strings longer than the upper limit' do it { is_expected.to run.with_params('1234567890a', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } it { is_expected.to run.with_params('1234567890abcdef', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } end describe 'rejects numbers shorter than the lower limit' do it { is_expected.to run.with_params('one', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } it { is_expected.to run.with_params(%w[12345678 two], 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } end describe 'accepts strings of length between and including the limits' do it { is_expected.to run.with_params('12345', 10, 5) } it { is_expected.to run.with_params('123456', 10, 5) } it { is_expected.to run.with_params('1234567', 10, 5) } it { is_expected.to run.with_params('12345678', 10, 5) } it { is_expected.to run.with_params('123456789', 10, 5) } it { is_expected.to run.with_params('1234567890', 10, 5) } it { is_expected.to run.with_params(%w[1233456 12345678], 10, 5) } end end describe 'corner cases' do it { pending('this should work') is_expected.to run.with_params('', 0, 0) } it { is_expected.to run.with_params('1234567890', 10, 10) } end describe 'empty upper limit is interpreted as infinity' do it { pending('not implemented') is_expected.to run.with_params('1234567890ab', '', 10) } it { pending('not implemented') is_expected.to run.with_params('12345678', '', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } end end puppetlabs-stdlib-4.25.0/spec/functions/validate_string_spec.rb0100755005276200011600000000236313206047630021715 0ustar00require 'spec_helper' describe 'validate_string' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('', '') end describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('') } it { is_expected.to run.with_params(nil) } it { is_expected.to run.with_params('one') } it { is_expected.to run.with_params('one', 'two') } end describe 'invalid inputs' do it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end puppetlabs-stdlib-4.25.0/spec/functions/validate_x509_rsa_key_pair_spec.rb0100755005276200011600000002010313252003272023627 0ustar00require 'spec_helper' describe 'validate_x509_rsa_key_pair' do # rubocop:disable Layout/IndentHeredoc : Heredoc's are meant to be indented in this way let(:valid_cert) do < 'value').and_return(['value']) } it 'returns the array of values' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2', 'duplicate_value_key' => 'value2' }]) expect(result).to match_array(%w[value1 value2 value2]) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'かぎ' => '使用', 'ҝĕұ' => '√ẩŀứệ', 'ҝĕұďŭрļǐçằťè' => '√ẩŀứệ' }]) expect(result).to match_array(['使用', '√ẩŀứệ', '√ẩŀứệ']) end end puppetlabs-stdlib-4.25.0/spec/functions/zip_spec.rb0100755005276200011600000000223513212471613017335 0ustar00require 'spec_helper' describe 'zip' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('Current implementation ignores parameters after the third.') is_expected.to run.with_params([], [], true, []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6]).and_return([[1, 4], [2, 5], [3, 6]]) } it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6], false).and_return([[1, 4], [2, 5], [3, 6]]) } it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6], true).and_return([1, 4, 2, 5, 3, 6]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(%w[ầ ь ć], %w[đ ề ƒ]).and_return([%w[ầ đ], %w[ь ề], %w[ć ƒ]]) } it { is_expected.to run.with_params(%w[ペ 含 値], %w[ッ 文 イ]).and_return([%w[ペ ッ], %w[含 文], %w[値 イ]]) } end end puppetlabs-stdlib-4.25.0/spec/monkey_patches0040755005276200011600000000000013252003413016105 5ustar00puppetlabs-stdlib-4.25.0/spec/monkey_patches/alias_should_to_must.rb0100755005276200011600000000026113206047630022741 0ustar00#! /usr/bin/env ruby -S rspec require 'rspec' class Object # This is necessary because the RAL has a 'should' # method. alias must should alias must_not should_not end puppetlabs-stdlib-4.25.0/spec/monkey_patches/publicize_methods.rb0100755005276200011600000000055513206047630022237 0ustar00#! /usr/bin/env ruby -S rspec # Some monkey-patching to allow us to test private methods. class Class def publicize_methods(*methods) saved_private_instance_methods = methods.empty? ? private_instance_methods : methods class_eval { public(*saved_private_instance_methods) } yield class_eval { private(*saved_private_instance_methods) } end end puppetlabs-stdlib-4.25.0/spec/spec_helper.rb0100755005276200011600000000204013252003272015770 0ustar00require 'puppetlabs_spec_helper/module_spec_helper' require 'rspec-puppet-facts' begin require 'spec_helper_local' if File.file?(File.join(File.dirname(__FILE__), 'spec_helper_local.rb')) rescue LoadError => loaderror warn "Could not require spec_helper_local: #{loaderror.message}" end include RspecPuppetFacts # rubocop:disable Style/HashSyntax default_facts = { puppetversion: Puppet.version, facterversion: Facter.version, } # rubocop:enable Style/HashSyntax default_facts_path = File.expand_path(File.join(File.dirname(__FILE__), 'default_facts.yml')) default_module_facts_path = File.expand_path(File.join(File.dirname(__FILE__), 'default_module_facts.yml')) if File.exist?(default_facts_path) && File.readable?(default_facts_path) default_facts.merge!(YAML.safe_load(File.read(default_facts_path))) end if File.exist?(default_module_facts_path) && File.readable?(default_module_facts_path) default_facts.merge!(YAML.safe_load(File.read(default_module_facts_path))) end RSpec.configure do |c| c.default_facts = default_facts end puppetlabs-stdlib-4.25.0/spec/spec_helper_acceptance.rb0100755005276200011600000000265713212471613020160 0ustar00#! /usr/bin/env ruby -S rspec require 'puppet' require 'beaker-rspec' require 'beaker/puppet_install_helper' require 'beaker/module_install_helper' run_puppet_install_helper install_ca_certs unless ENV['PUPPET_INSTALL_TYPE'] =~ %r{pe}i install_module_on(hosts) install_module_dependencies_on(hosts) RSpec.configure do |c| # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do end end def return_puppet_version (on default, puppet('--version')).output.chomp end RSpec.shared_context 'with faked facts' do let(:facts_d) do puppet_version = return_puppet_version if fact('osfamily') =~ %r{windows}i if fact('kernelmajversion').to_f < 6.0 'C:/Documents and Settings/All Users/Application Data/PuppetLabs/facter/facts.d' else 'C:/ProgramData/PuppetLabs/facter/facts.d' end elsif Puppet::Util::Package.versioncmp(puppet_version, '4.0.0') < 0 && fact('is_pe', '--puppet') == 'true' '/etc/puppetlabs/facter/facts.d' else '/etc/facter/facts.d' end end before :each do # No need to create on windows, PE creates by default if fact('osfamily') !~ %r{windows}i shell("mkdir -p '#{facts_d}'") end end after :each do shell("rm -f '#{facts_d}/fqdn.txt'", :acceptable_exit_codes => [0, 1]) end def fake_fact(name, value) shell("echo #{name}=#{value} > '#{facts_d}/#{name}.txt'") end end puppetlabs-stdlib-4.25.0/spec/spec_helper_local.rb0100644005276200011600000000174213206047630017154 0ustar00# automatically load any shared examples or contexts Dir['./spec/support/**/*.rb'].sort.each { |f| require f } # HACK: to enable all the expect syntax (like allow_any_instance_of) in rspec-puppet examples RSpec::Mocks::Syntax.enable_expect(RSpec::Puppet::ManifestMatchers) RSpec.configure do |config| # supply tests with a possibility to test for the future parser config.add_setting :puppet_future config.puppet_future = Puppet.version.to_f >= 4.0 config.before :each do # Ensure that we don't accidentally cache facts and environment between # test cases. This requires each example group to explicitly load the # facts being exercised with something like # Facter.collection.loader.load(:ipaddress) Facter.clear Facter.clear_messages RSpec::Mocks.setup end config.after :each do RSpec::Mocks.verify RSpec::Mocks.teardown end end # Helper class to test handling of arguments which are derived from string class AlsoString < String end puppetlabs-stdlib-4.25.0/spec/support0040755005276200011600000000000013252003413014610 5ustar00puppetlabs-stdlib-4.25.0/spec/support/shared_data.rb0100644005276200011600000000132213206047630017456 0ustar00module SharedData IPV4_PATTERNS = [ '0.0.0.0', '1.2.3.4', '10.10.10.10', '127.0.0.1', '192.88.99.0', '194.232.104.150', '224.0.0.0', '244.24.24.24', '255.255.255.255', '8.8.8.8', '8.8.8.8/0', '8.8.8.8/16', '8.8.8.8/255.255.0.0', '8.8.8.8/32', ].freeze IPV4_NEGATIVE_PATTERNS = [ '', '0000', '0.0.0.0.', '0.0.0.0./0.0.0.0.', '0.0.0.0./1', '0.0.0.0.0', '0.0.0.0/0.0.0.0.', '0.0.0.256', '0.0.0', '1.2.3.4.5', '1.2.3', '10.010.10.10', '2001:0db8:85a3:0000:0000:8a2e:0370:73342001:0db8:85a3:0000:0000:8a2e:0370:7334', '4.4.4', '77', '9999.9999.9999.9999', 'affe::beef', 'nope', ].freeze end puppetlabs-stdlib-4.25.0/spec/type_aliases0040755005276200011600000000000013252003413015556 5ustar00puppetlabs-stdlib-4.25.0/spec/type_aliases/absolute_path_spec.rb0100644005276200011600000000261313212471613022034 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Absolute_path' do describe 'valid paths handling' do %w[ C:/ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 X:/foo/bar X:\\foo\\bar \\\\host\\windows //host/windows / /var/tmp /var/opt/../lib/puppet /var/opt//lib/puppet /var/ůťƒ8 /var/ネット ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end context 'with relative paths' do %w[ relative1 . .. ./foo ../foo etc/puppetlabs/puppet opt/puppet/bin relative\\windows \var\ůťƒ8 \var\ネット ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/array_spec.rb0100644005276200011600000000116613212471613020322 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Array' do describe 'accepts arrays' do [ [], ['one'], [1], [{}], [[]], ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', 'one', '1', {}, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/base32_spec.rb0100644005276200011600000000246013252003272020255 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Base32' do describe 'valid handling' do %w[ ASDASDDASD3453453 ASDASDDASD3453453= ASDASDDASD3453453== ASDASDDASD3453453=== ASDASDDASD3453453==== ASDASDDASD3453453===== ASDASDDASD3453453====== asdasddasd3453453 asdasddasd3453453= asdasddasd3453453== asdasddasd3453453=== asdasddasd3453453==== asdasddasd3453453===== asdasddasd3453453====== ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'asdasd!@#$', '=asdasd9879876876+/', 'asda=sd9879876876+/', 'asdaxsd9879876876+/===', 'asdads asdasd', 'asdasddasd3453453=======', 'asdaSddasd', 'asdasddasd1', 'asdasddasd9', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/base64_spec.rb0100644005276200011600000000163113252003272020261 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Base64' do describe 'valid handling' do %w[ asdasdASDSADA342386832/746+= asdasdASDSADA34238683274/6+ asdasdASDSADA3423868327/46+== ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'asdasd!@#$', '=asdasd9879876876+/', 'asda=sd9879876876+/', 'asdaxsd9879876876+/===', 'asdads asdasd', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/bool_spec.rb0100644005276200011600000000114613212471613020135 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Bool' do describe 'accepts booleans' do [ true, false, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ [1], [{}], [true], 'true', 'false', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/compat__ip_address.rb0100644005276200011600000000163113252003272022002 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ip_address' do describe 'accepts ipv4 and ipv6 addresses' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/compat__ipv4_spec.rb0100644005276200011600000000105313252003272021557 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ipv4' do describe 'accepts ipv4 addresses' do SharedData::IPV4_PATTERNS.each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/compat__ipv6_spec.rb0100644005276200011600000000212213252003272021557 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ipv6' do describe 'accepts ipv6 addresses' do [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', 'fe80:0000:0000:0000:0204:61ff:fe9d:f156', 'fe80:0:0:0:204:61ff:fe9d:f156', 'fe80::204:61ff:fe9d:f156', 'fe80:0:0:0:0204:61ff:254.157.241.86', '::1', 'fe80::', '2001::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2000:7334', '::ffff:2.3.4', '::ffff:257.1.2.3', '::ffff:12345678901234567890.1.26', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/filemode_spec.rb0100644005276200011600000000161413212471613020766 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Filemode' do describe 'valid modes' do %w[ 0644 1644 2644 4644 0123 0777 ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid modes' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'ネット', '644', '7777', '1', '22', '333', '55555', '0x123', '0649', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/filesource_spec.rb0100644005276200011600000000304113252003272021332 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Filesource' do describe 'valid handling' do %w[ https://hello.com https://notcreative.org https://canstillaccepthttps.co.uk http://anhttp.com http://runningoutofideas.gov file:///hello/bla file:///foo/bar.log puppet:///modules/foo/bar.log puppet://pm.example.com/modules/foo/bar.log puppet://192.0.2.1/modules/foo/bar.log /usr2/username/bin:/usr/local/bin:/usr/bin:. C:/ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 X:/foo/bar X:\\foo\\bar \\\\host\\windows //host/windows /var/tmp /var/opt/../lib/puppet ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', '*/Users//nope', '\\Users/hc/wksp/stdlib', 'C:noslashes', '\\var\\tmp', 'puppet:///foo/bar.log', 'puppet:///pm.example.com/modules/foo/bar.log', 'puppet://bob@pm.example.com/modules/foo/bar.log', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/float_spec.rb0100644005276200011600000000132713212471613020310 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Float' do describe 'accepts floats' do [ 3.7, '3.7', -3.7, '-342.2315e-12', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x', 3, '3', -3, '-3'].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/fqdn_spec.rb0100644005276200011600000000140513252003272020124 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Fqdn' do describe 'valid handling' do %w[ example example.com www.example.com ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', '2001:DB8::1', 'www www.example.com', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/hash_spec.rb0100644005276200011600000000121413212471613020121 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Hash' do describe 'accepts hashes' do [ {}, { 'one' => 'two' }, { 'wan' => 3 }, { '001' => 'helly' }, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', 'one', '1', [], ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/host_spec.rb0100644005276200011600000000177013252003272020156 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Host' do describe 'valid handling' do %w[ example example.com www.example.com 2001:0db8:85a3:0000:0000:8a2e:0370:7334 fa76:8765:34ac:0823:ab76:eee9:0987:1111 2001:0db8::1 224.0.0.0 255.255.255.255 0.0.0.0 192.88.99.0 ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'www www.example.com', 'bob@example.com', '%.example.com', '2001:0d8', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/httpsurl_spec.rb0100644005276200011600000000200013212471613021055 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::HTTPSUrl' do describe 'valid handling' do %w[ https://hello.com https://notcreative.org https://notexciting.co.uk https://graphemica.com/❤ https://graphemica.com/緩 ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'httds://notquiteright.org', 'hptts:/nah', 'https;//notrightbutclose.org', 'http://graphemica.com/❤', 'http://graphemica.com/緩', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/httpurl_spec.rb0100644005276200011600000000212213212471613020677 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::HTTPUrl' do describe 'valid handling' do %w[ https://hello.com https://notcreative.org https://canstillaccepthttps.co.uk http://anhttp.com http://runningoutofideas.gov http:// http://graphemica.com/❤ http://graphemica.com/緩 ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'httds://notquiteright.org', 'hptts:/nah', 'https;//notrightbutclose.org', 'hts://graphemica.com/❤', 'https:graphemica.com/緩', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/integer_spec.rb0100644005276200011600000000142613212471613020640 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Integer' do describe 'accepts integers' do [ 3, '3', -3, '-3', "123\nfoo", "foo\n123", ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do ["foo\nbar", true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x', 3.7, '3.7', -3.7, '-342.2315e-12'].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address.rb0100644005276200011600000000206213252003272020277 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Ip_address' do describe 'accepts ipv4 and ipv6 addresses' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', '2001::0db8::1', ' 2001:0db8::1', '2001:0db8::1 ', ' 2001:0db8::1 ', 'foobar2001:0db8::1', '2001:0db8::1foobar', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_nosubnet_spec.rb0100644005276200011600000000216513252003272023232 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::Nosubnet' do describe 'accepts ipv4 and ipv6 addresses without subnets' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', '127.0.0.1', '8.8.4.4', '52.10.10.141', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '10.1.240.4/24', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_spec.rb0100644005276200011600000000213313252003272021310 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address' do describe 'accepts ipv4 and ipv6 addresses' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', '127.0.0.1', '8.8.4.4', '10.1.240.4/24', '52.10.10.141', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v4_nosubnet_spec.rb0100644005276200011600000000134313252003272023640 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V4::Nosubnet' do describe 'accepts ipv4 addresses without subnets' do [ '127.0.0.1', '8.8.4.4', '52.10.10.141', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '10.1.240.4/24', '192.168.1', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v4_spec.rb0100644005276200011600000000131113252003272021716 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V4' do describe 'accepts ipv4 addresses' do [ '127.0.0.1', '8.8.4.4', '10.1.240.4/24', '52.10.10.141', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '192.168.1', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_alternative_spec.rb0100644005276200011600000000130213252003272024316 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Alternative' do describe 'accepts ipv6 addresses in alternative format' do [ '0:0:0:0:0:0:13.1.68.3', '0:0:0:0:0:FFFF:129.144.52.38', '0:0:0:0:0:FFFF:129.144.52.38/60', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_compressed_spec.rb0100644005276200011600000000135113252003272024150 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Compressed' do describe 'accepts ipv6 addresses in compressed format' do [ '1080::8:800:200C:417A', '1080::8:800:200C:417A/60', 'FF01::101', '::1', '::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', 'FEDC::BA98:7654:3210::3210', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_full_spec.rb0100644005276200011600000000131713252003272022750 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Full' do describe 'accepts ipv6 addresses in full format' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210/60', '1080:0:0:0:8:800:200C:417A', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb0100644005276200011600000000133413252003272026240 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Alternative' do describe 'accepts ipv6 addresses in alternative format without subnets' do [ '0:0:0:0:0:0:13.1.68.3', '0:0:0:0:0:FFFF:129.144.52.38', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '0:0:0:0:0:FFFF:129.144.52.38/60', 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb0100644005276200011600000000140313252003272026063 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Compressed' do describe 'accepts ipv6 addresses in compressed format without subnets' do [ '1080::8:800:200C:417A', 'FF01::101', '::1', '::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '1080::8:800:200C:417A/60', 'nope', '127.0.0.1', 'FEDC::BA98:7654:3210::3210', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb0100644005276200011600000000135113252003272024663 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Full' do describe 'accepts ipv6 addresses in full format without subnets' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '1080:0:0:0:8:800:200C:417A', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210/60', 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ip_address_v6_spec.rb0100644005276200011600000000140713252003272021726 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6' do describe 'accepts ipv6 addresses' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '127.0.0.1', '10.1.240.4/24', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ipv4_spec.rb0100644005276200011600000000104313252003272020054 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Ipv4' do describe 'accepts ipv4 addresses' do SharedData::IPV4_PATTERNS.each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/ipv6_spec.rb0100644005276200011600000000235313252003272020063 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Ipv6' do describe 'accepts ipv6 addresses' do [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', 'fe80:0000:0000:0000:0204:61ff:fe9d:f156', 'fe80:0:0:0:204:61ff:fe9d:f156', 'fe80::204:61ff:fe9d:f156', 'fe80:0:0:0:0204:61ff:254.157.241.86', '::1', 'fe80::', '2001::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2000:7334', '::ffff:2.3.4', '::ffff:257.1.2.3', '::ffff:12345678901234567890.1.26', '2001::0db8::1', ' 2001:0db8::1', '2001:0db8::1 ', ' 2001:0db8::1 ', 'foobar2001:0db8::1', '2001:0db8::1foobar', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/numeric_spec.rb0100644005276200011600000000137313212471613020646 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Numeric' do describe 'accepts numerics' do [ 3, '3', -3, '-3', 3.7, '3.7', -3.7, '-342.2315e-12', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/port__privileged_spec.rb0100644005276200011600000000143613252003272022535 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::Privileged' do describe 'valid ports' do [ 80, 443, 1023, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 1337, 1024, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/port__unprivileged_spec.rb0100644005276200011600000000147513252003272023103 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::Unprivileged' do describe 'valid unprivilegedport' do [ 1024, 1337, 65_000, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 80, 443, 1023, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/port_spec.rb0100644005276200011600000000142413252003272020161 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port' do describe 'valid ports' do [ 80, 443, 1337, 65_000, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 65_536, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/string_spec.rb0100644005276200011600000000112713212471613020507 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::String' do describe 'accepts strings' do [ '', 'one', nil, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ [], {}, 1, true, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/unixpath_spec.rb0100644005276200011600000000203413212471613021037 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Unixpath' do describe 'valid handling' do %w[ /usr2/username/bin:/usr/local/bin:/usr/bin:. /var/tmp /Users/helencampbell/workspace/puppetlabs-stdlib /var/ůťƒ8 /var/ネット /var//tmp /var/../tmp ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'C:/whatever', '\\var\\tmp', '\\Users/hc/wksp/stdlib', '*/Users//nope', "var\ůťƒ8", "var\ネット", ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/type_aliases/windowspath_spec.rb0100644005276200011600000000205413212471613021550 0ustar00require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Windowspath' do describe 'valid handling' do %w[ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 X:/foo/bar X:\\foo\\bar \\\\host\\windows X:/var/ůťƒ8 X:/var/ネット ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'httds://notquiteright.org', '/usr2/username/bin:/usr/local/bin:/usr/bin:.', 'C;//notright/here', 'C:noslashes', 'C:ネット', 'C:ůťƒ8', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end puppetlabs-stdlib-4.25.0/spec/unit0040755005276200011600000000000013252003413014053 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/facter0040755005276200011600000000000013252003413015317 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/facter/facter_dot_d_spec.rb0100755005276200011600000000175413212471613021370 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'facter/facter_dot_d' describe Facter::Util::DotD do # rubocop:disable RSpec/FilePath : Spec path is as it should be context 'with a simple fact' do before :each do Facter.stubs(:version).returns('1.6.1') subject.stubs(:entries).returns(['/etc/facter/facts.d/fake_fact.txt']) File.stubs(:readlines).with('/etc/facter/facts.d/fake_fact.txt').returns(['fake_fact=fake fact']) subject.create end it 'returns successfully' do expect(Facter.fact(:fake_fact).value).to eq('fake fact') end end context 'with a fact with equals signs' do before :each do Facter.stubs(:version).returns('1.6.1') subject.stubs(:entries).returns(['/etc/facter/facts.d/foo.txt']) File.stubs(:readlines).with('/etc/facter/facts.d/foo.txt').returns(['foo=1+1=2']) subject.create end it 'returns successfully' do expect(Facter.fact(:foo).value).to eq('1+1=2') end end end puppetlabs-stdlib-4.25.0/spec/unit/facter/package_provider_spec.rb0100644005276200011600000000246413252003272022250 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'puppet/type' require 'puppet/type/package' describe 'package_provider', :type => :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } ['4.2.2', '3.7.1 (Puppet Enterprise 3.2.1)'].each do |puppetversion| describe "on puppet ''#{puppetversion}''" do before :each do Facter.stubs(:value).returns puppetversion end context 'when darwin' do it 'returns pkgdmg' do provider = Puppet::Type.type(:package).provider(:pkgdmg) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider expect(Facter.fact(:package_provider).value).to eq('pkgdmg') end end context 'when centos 7' do it 'returns yum' do provider = Puppet::Type.type(:package).provider(:yum) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider expect(Facter.fact(:package_provider).value).to eq('yum') end end context 'when ubuntu' do it 'returns apt' do provider = Puppet::Type.type(:package).provider(:apt) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider expect(Facter.fact(:package_provider).value).to eq('apt') end end end end end puppetlabs-stdlib-4.25.0/spec/unit/facter/pe_version_spec.rb0100755005276200011600000000466713212471613021132 0ustar00#!/usr/bin/env rspec require 'spec_helper' describe 'PE Version specs' do before :each do # Explicitly load the pe_version.rb file which contains generated facts # that cannot be automatically loaded. Puppet 2.x implements # Facter.collection.load while Facter 1.x markes Facter.collection.load as # a private method. if Facter.collection.respond_to? :load Facter.collection.load(:pe_version) else Facter.collection.loader.load(:pe_version) end end context 'when puppetversion is nil' do before :each do Facter.fact(:puppetversion).stubs(:value).returns(nil) end it 'puppetversion is nil' do expect(Facter.fact(:puppetversion).value).to be_nil end it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end end context 'when PE is installed' do %w[2.6.1 2.10.300].each do |version| puppetversion = "2.7.19 (Puppet Enterprise #{version})" context "puppetversion => #{puppetversion}" do before :each do Facter.fact(:puppetversion).stubs(:value).returns(puppetversion) end (major, minor, patch) = version.split('.') it 'returns true' do expect(Facter.fact(:is_pe).value).to eq(true) end it "Should have a version of #{version}" do expect(Facter.fact(:pe_version).value).to eq(version) end it "Should have a major version of #{major}" do expect(Facter.fact(:pe_major_version).value).to eq(major) end it "Should have a minor version of #{minor}" do expect(Facter.fact(:pe_minor_version).value).to eq(minor) end it "Should have a patch version of #{patch}" do expect(Facter.fact(:pe_patch_version).value).to eq(patch) end end end end context 'when PE is not installed' do before :each do Facter.fact(:puppetversion).stubs(:value).returns('2.7.19') end it 'is_pe is false' do expect(Facter.fact(:is_pe).value).to eq(false) end it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end it 'pe_major_version is nil' do expect(Facter.fact(:pe_major_version).value).to be_nil end it 'pe_minor_version is nil' do expect(Facter.fact(:pe_minor_version).value).to be_nil end it 'has a patch version' do expect(Facter.fact(:pe_patch_version).value).to be_nil end end end puppetlabs-stdlib-4.25.0/spec/unit/facter/root_home_spec.rb0100755005276200011600000000433113212471613020740 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'facter/root_home' describe 'Root Home Specs' do describe Facter::Util::RootHome do context 'when solaris' do let(:root_ent) { 'root:x:0:0:Super-User:/:/sbin/sh' } let(:expected_root_home) { '/' } it 'returns /' do Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when linux' do let(:root_ent) { 'root:x:0:0:root:/root:/bin/bash' } let(:expected_root_home) { '/root' } it 'returns /root' do Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when windows' do before :each do Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(nil) end it 'is nil on windows' do expect(described_class.returnt_root_home).to be_nil end end end describe 'root_home', :type => :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do before(:each) do Facter.fact(:kernel).stubs(:value).returns('Darwin') Facter.fact(:osfamily).stubs(:value).returns('Darwin') end let(:expected_root_home) { '/var/root' } sample_dscacheutil = File.read(fixtures('dscacheutil', 'root')) it 'returns /var/root' do Facter::Util::Resolution.stubs(:exec).with('dscacheutil -q user -a name root').returns(sample_dscacheutil) expect(Facter.fact(:root_home).value).to eq(expected_root_home) end end context 'when aix' do before(:each) do Facter.fact(:kernel).stubs(:value).returns('AIX') Facter.fact(:osfamily).stubs(:value).returns('AIX') end let(:expected_root_home) { '/root' } sample_lsuser = File.read(fixtures('lsuser', 'root')) it 'returns /root' do Facter::Util::Resolution.stubs(:exec).with('lsuser -c -a home root').returns(sample_lsuser) expect(Facter.fact(:root_home).value).to eq(expected_root_home) end end end end puppetlabs-stdlib-4.25.0/spec/unit/facter/service_provider_spec.rb0100644005276200011600000000203513252003272022307 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'puppet/type' require 'puppet/type/service' describe 'service_provider', :type => :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do it 'returns launchd' do provider = Puppet::Type.type(:service).provider(:launchd) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider expect(Facter.fact(:service_provider).value).to eq('launchd') end end context 'when systemd' do it 'returns systemd' do provider = Puppet::Type.type(:service).provider(:systemd) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider expect(Facter.fact(:service_provider).value).to eq('systemd') end end context 'when redhat' do it 'returns redhat' do provider = Puppet::Type.type(:service).provider(:redhat) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider expect(Facter.fact(:service_provider).value).to eq('redhat') end end end puppetlabs-stdlib-4.25.0/spec/unit/facter/util0040755005276200011600000000000013252003413016274 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/facter/util/puppet_settings_spec.rb0100755005276200011600000000172413212471613023162 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'facter/util/puppet_settings' describe Facter::Util::PuppetSettings do describe '#with_puppet' do context 'without Puppet loaded' do before(:each) do Module.expects(:const_get).with('Puppet').raises(NameError) end it 'is nil' do expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end it 'does not yield to the block' do Puppet.expects(:[]).never expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end end context 'with Puppet loaded' do module Puppet; end let(:vardir) { '/var/lib/puppet' } before :each do Puppet.expects(:[]).with(:vardir).returns vardir end it 'yields to the block' do subject.with_puppet { Puppet[:vardir] } end it 'returns the nodes vardir' do expect(subject.with_puppet { Puppet[:vardir] }).to eq vardir end end end end puppetlabs-stdlib-4.25.0/spec/unit/puppet0040755005276200011600000000000013252003413015370 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/parser0040755005276200011600000000000013252003413016664 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/parser/functions0040755005276200011600000000000013252003413020674 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb0100644005276200011600000000507513252003272024715 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' describe 'the enclose_ipv6 function' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it 'exists' do expect(Puppet::Parser::Functions.function('enclose_ipv6')).to eq('function_enclose_ipv6') end it 'raises a ParseError if there is less than 1 arguments' do expect { scope.function_enclose_ipv6([]) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError if there is more than 1 arguments' do expect { scope.function_enclose_ipv6(%w[argument1 argument2]) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError when given garbage' do expect { scope.function_enclose_ipv6(['garbage']) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError when given something else than a string or an array' do expect { scope.function_enclose_ipv6([['1' => '127.0.0.1']]) }.to(raise_error(Puppet::ParseError)) end it 'does not raise a ParseError when given a single ip string' do expect { scope.function_enclose_ipv6(['127.0.0.1']) }.not_to raise_error end it 'does not raise a ParseError when given * as ip string' do expect { scope.function_enclose_ipv6(['*']) }.not_to raise_error end it 'does not raise a ParseError when given an array of ip strings' do expect { scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1']]) }.not_to raise_error end it 'does not raise a ParseError when given differently notations of ip addresses' do expect { scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1', '[fe80::1]']]) }.not_to raise_error end it 'raises a ParseError when given a wrong ipv4 address' do expect { scope.function_enclose_ipv6(['127..0.0.1']) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError when given a ipv4 address with square brackets' do expect { scope.function_enclose_ipv6(['[127.0.0.1]']) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError when given a wrong ipv6 address' do expect { scope.function_enclose_ipv6(['fe80:::1']) }.to(raise_error(Puppet::ParseError)) end it 'embraces ipv6 adresses within an array of ip addresses' do result = scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1', '[fe80::2]']]) expect(result).to(eq(['127.0.0.1', '[fe80::1]', '[fe80::2]'])) end it 'embraces a single ipv6 adresse' do result = scope.function_enclose_ipv6(['fe80::1']) expect(result).to(eq(['[fe80::1]'])) end it 'does not embrace a single ipv4 adresse' do result = scope.function_enclose_ipv6(['127.0.0.1']) expect(result).to(eq(['127.0.0.1'])) end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb0100644005276200011600000000320013206047630025637 0ustar00require 'spec_helper' describe 'is_absolute_path' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } let(:function_args) do [] end let(:function) do scope.function_is_absolute_path(function_args) end describe 'validate arity' do let(:function_args) do [1, 2] end it 'raises a ParseError if there is more than 1 arguments' do -> { function }.should(raise_error(ArgumentError)) end end it 'exists' do Puppet::Parser::Functions.function(subject).should == "function_#{subject}" end # help enforce good function defination it 'contains arity' do end it 'raises a ParseError if there is less than 1 arguments' do -> { function }.should(raise_error(ArgumentError)) end describe 'should retrun true' do let(:return_value) do true end describe 'windows' do let(:function_args) do ['c:\temp\test.txt'] end it 'returns data' do function.should eq(return_value) end end describe 'non-windows' do let(:function_args) do ['/temp/test.txt'] end it 'returns data' do function.should eq(return_value) end end end describe 'should return false' do let(:return_value) do false end describe 'windows' do let(:function_args) do ['..\temp\test.txt'] end it 'returns data' do function.should eq(return_value) end end describe 'non-windows' do let(:function_args) do ['../var/lib/puppet'] end it 'returns data' do function.should eq(return_value) end end end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/provider0040755005276200011600000000000013252003413017222 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/provider/file_line0040755005276200011600000000000013252003413021150 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/provider/file_line/ruby_spec.rb0100755005276200011600000001451213212471613023561 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass describe provider_class, :unless => Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ :name => 'foo', :path => tmpfile, :line => 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe 'line parameter' do context 'when line exists' do let(:content) { 'foo' } it 'detects the line' do expect(provider).to be_exists end end context 'when line does not exist' do let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end it 'appends the line' do provider.create expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end end end describe 'match parameter' do let(:params) { { :match => '^bar' } } describe 'does not match line - line does not exist - replacing' do let(:content) { "foo bar\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end end describe 'does not match line - line does not exist - appending' do let(:params) { super().merge(:replace => false) } let(:content) { "foo bar\nbar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when does not match line - line exists' do let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line exists' do let(:params) { { :match => '^foo' } } let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line does not exist' do let(:params) { { :match => '^foo' } } let(:content) { "foo bar\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("foo\nbar") end end end describe 'append_on_no_match' do let(:params) do { :append_on_no_match => false, :match => '^foo1$', } end context 'when matching' do let(:content) { "foo1\nbar" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nbar") end end context 'when not matching' do let(:content) { "foo3\nbar" } it 'does not affect the file' do expect(provider).to be_exists end end end describe 'replace_all_matches_not_matching_line' do context 'when replace is false' do let(:params) do { :replace_all_matches_not_matching_line => true, :replace => false, } end it 'raises an error' do expect { provider.exists? }.to raise_error(Puppet::Error, %r{replace must be true}) end end context 'when match matches line - when there are more matches than lines' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^foo', :multiple => true, } end let(:content) { "foo\nfoo bar\nbar\nfoo baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nbar\nfoo") end end context 'when match matches line - when there are the same matches and lines' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^foo', :multiple => true, } end let(:content) { "foo\nfoo\nbar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when match does not match line - when there are more matches than lines' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^bar', :multiple => true, } end let(:content) { "foo\nfoo bar\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo bar\nfoo\nfoo") end end context 'when match does not match line - when there are the same matches and lines' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^bar', :multiple => true, } end let(:content) { "foo\nfoo\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nfoo\nfoo") end end end context 'when match does not match line - when there are no matches' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^bar', :multiple => true, } end let(:content) { "foo\nfoo bar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when match does not match line - when there are no matches or lines' do let(:params) do { :replace_all_matches_not_matching_line => true, :match => '^bar', :multiple => true, } end let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end it 'appends the line' do provider.create expect(File.read(tmpfile).chomp).to eql("foo bar\nfoo") end end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb0100755005276200011600000003522613252003272024751 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass describe provider_class, :unless => Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ :name => 'foo', :path => tmpfile, :line => 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe '#create' do context 'when adding' do pending('To be added.') end context 'when replacing' do let :params do { :line => 'foo = bar', :match => '^foo\s*=.*$', :replace => false, } end let(:content) { "foo1\nfoo=blah\nfoo2\nfoo3" } it "providor 'be_exists'" do expect(provider).to be_exists end it 'does not replace the matching line' do provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo=blah\nfoo2\nfoo3") end it 'appends the line if no matches are found' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } expect(provider.exists?).to be false provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar") end it 'raises an error with invalid values' do expect { @resource = Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :replace => 'asgadga', ) }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) end end end describe '#destroy' do pending('To be added?') end context 'when matching' do # rubocop:disable RSpec/InstanceVariable : replacing before with let breaks the tests, variables need to be altered within it block : multi before :each do @resource = Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', ) @provider = provider_class.new(@resource) end describe 'using match' do it 'raises an error if more than one line matches, and should not have modified the file' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } expect { @provider.create }.to raise_error(Puppet::Error, %r{More than one line.*matches}) expect(File.read(tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz") end it 'replaces all lines that matches' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :multiple => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar") end it 'replaces all lines that match, even when some lines are correct' do @resource = Puppet::Type::File_line.new(:name => 'neil', :path => tmpfile, :line => "\thard\tcore\t0\n", :match => '^[ \t]hard[ \t]+core[ \t]+.*', :multiple => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") } @provider.create expect(File.read(tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0") end it 'raises an error with invalid values' do expect { @resource = Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', :multiple => 'asgadga', ) }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) end it 'replaces a line that matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end it 'adds a new line if no lines match' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } @provider.create expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n") end it 'does nothing if the exact line already exists' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = bar\nfoo2") } @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end end describe 'using match+append_on_no_match - when there is a match' do it 'replaces line' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :match => '^foo3$', :append_on_no_match => false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") end end describe 'using match+append_on_no_match - when there is no match' do it 'does not add line after no matches found' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :match => '^foo3$', :append_on_no_match => false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") end end end context 'when match+replace+append_on_no_match' do pending('to do') end context 'when after' do let :resource do Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'inserted = line', :after => '^foo1', ) end let :provider do provider_class.new(resource) end context 'when match and after set' do shared_context 'when resource_create' do let(:match) { '^foo2$' } let(:after) { '^foo1$' } let(:resource) do Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'inserted = line', :after => after, :match => match, ) end end before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nfoo = baz") } end describe 'inserts at match' do include_context 'resource_create' it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz") } end describe 'inserts a new line after when no match' do include_context 'resource_create' do let(:match) { '^nevergoingtomatch$' } end it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz") } end describe 'append to end of file if no match for both after and match' do include_context 'resource_create' do let(:match) { '^nevergoingtomatch$' } let(:after) { '^stillneverafter' } end it { provider.create expect(File.read(tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line") } end end context 'with one line matching the after expression' do before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } end it 'inserts the specified line after the line matching the "after" expression' do provider.create expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz") end end context 'with multiple lines matching the after expression' do before :each do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") } end it 'errors out stating "One or no line must match the pattern"' do expect { provider.create }.to raise_error(Puppet::Error, %r{One or no line must match the pattern}) end it 'adds the line after all lines matching the after expression' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'inserted = line', :after => '^foo1$', :multiple => true) @provider = provider_class.new(@resource) @provider.create expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz") end end context 'with no lines matching the after expression' do let :content do "foo3\nfoo = blah\nfoo2\nfoo = baz\n" end before :each do File.open(tmpfile, 'w') { |fh| fh.write(content) } end it 'appends the specified line to the file' do provider.create expect(File.read(tmpfile)).to eq(content << resource[:line] << "\n") end end end context 'when removing with a line' do before :each do # TODO: these should be ported over to use the PuppetLabs spec_helper # file fixtures once the following pull request has been merged: # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files @resource = Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'foo', :ensure => 'absent', ) @provider = provider_class.new(@resource) end it 'removes the line if it exists' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'removes the line without touching the last new line' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'removes any occurence of the line' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'example in the docs' do @resource = Puppet::Type::File_line.new(:name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128') @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end end context 'when removing with a match' do before :each do @resource = Puppet::Type::File_line.new( :name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$', :match_for_absence => true, ) @provider = provider_class.new(@resource) end it 'finds a line to match' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } expect(@provider.exists?).to be true end it 'removes one line if it matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'the line parameter is actually not used at all but is silently ignored if here' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'supercalifragilisticexpialidocious', :ensure => 'absent', :match => 'o$', :match_for_absence => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'and may not be here and does not need to be here' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :ensure => 'absent', :match => 'o$', :match_for_absence => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2") end it 'raises an error if more than one line matches' do File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } expect { @provider.destroy }.to raise_error(Puppet::Error, %r{More than one line}) end it 'removes multiple lines if :multiple is true' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$', :multiple => true, :match_for_absence => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end it 'ignores the match if match_for_absence is not specified' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$') @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo\n") end it 'ignores the match if match_for_absence is false' do @resource = Puppet::Type::File_line.new(:name => 'foo', :path => tmpfile, :line => 'foo2', :ensure => 'absent', :match => 'o$', :match_for_absence => false) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo\n") end it 'example in the docs' do @resource = Puppet::Type::File_line.new( :name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', :match => '^export\ HTTP_PROXY\=', :match_for_absence => true ) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end it 'example in the docs showing line is redundant' do @resource = Puppet::Type::File_line.new(:name => 'bashrc_proxy', :ensure => 'absent', :path => tmpfile, :match => '^export\ HTTP_PROXY\=', :match_for_absence => true) @provider = provider_class.new(@resource) File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } @provider.destroy expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") end end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb0100755005276200011600000000656613212471613025625 0ustar00#! /usr/bin/env ruby -S rspec require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) #  These tests fail on windows when run as part of the rake task. Individually they pass describe provider_class, :unless => Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do tmpfilename('file_line_test') end let :content do '' end let :params do {} end let :resource do Puppet::Type::File_line.new({ :name => 'foo', :path => tmpfile, :line => 'foo', }.merge(params)) end let :provider do provider_class.new(resource) end before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end describe 'customer use cases - no lines' do describe 'MODULES-5003' do let(:params) do { :line => "*\thard\tcore\t0", :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", :multiple => true, } end let(:content) { "* hard core 90\n* hard core 10\n" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") end end describe 'MODULES-5003 - one match, one line - just ensure the line exists' do let(:params) do { :line => "*\thard\tcore\t0", :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", :multiple => true, } end let(:content) { "* hard core 90\n* hard core 0\n" } it 'does not request changes' do expect(provider).to be_exists end end describe 'MODULES-5003 - one match, one line - replace all matches, even when line exists' do let(:params) do { :line => "*\thard\tcore\t0", :match => "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", :multiple => true, }.merge(:replace_all_matches_not_matching_line => true) end let(:content) { "* hard core 90\n* hard core 0\n" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") end end describe 'MODULES-5651 - match, no line' do let(:params) do { :line => 'LogLevel=notice', :match => '^#LogLevel$', } end let(:content) { "#LogLevel\nstuff" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the match' do provider.create expect(File.read(tmpfile).chomp).to eq("LogLevel=notice\nstuff") end end describe 'MODULES-5651 - match, line' do let(:params) do { :line => 'LogLevel=notice', :match => '^#LogLevel$', } end let(:content) { "#Loglevel\nLogLevel=notice\nstuff" } it 'does not request changes' do expect(provider).to be_exists end end describe 'MODULES-5651 - no match, line' do let(:params) do { :line => 'LogLevel=notice', :match => '^#LogLevel$', } end let(:content) { "LogLevel=notice\nstuff" } it 'does not request changes' do expect(provider).to be_exists end end end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/type0040755005276200011600000000000013252003413016351 5ustar00puppetlabs-stdlib-4.25.0/spec/unit/puppet/type/anchor_spec.rb0100755005276200011600000000033413212471613021250 0ustar00#!/usr/bin/env ruby require 'spec_helper' anchor = Puppet::Type.type(:anchor).new(:name => 'ntp::begin') describe anchor do it 'stringifies normally' do expect(anchor.to_s).to eq('Anchor[ntp::begin]') end end puppetlabs-stdlib-4.25.0/spec/unit/puppet/type/file_line_spec.rb0100755005276200011600000001013113252003272021714 0ustar00require 'spec_helper' require 'tempfile' describe Puppet::Type.type(:file_line) do let :tmp_path do if Puppet::Util::Platform.windows? 'C:\tmp\path' else '/tmp/path' end end let :my_path do if Puppet::Util::Platform.windows? 'C:\my\path' else '/my/path' end end let :file_line do Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => tmp_path) end it 'accepts a line' do file_line[:line] = 'my_line' expect(file_line[:line]).to eq('my_line') end it 'accepts a path' do file_line[:path] = my_path expect(file_line[:path]).to eq(my_path) end it 'accepts a match regex' do file_line[:match] = '^foo.*$' expect(file_line[:match]).to eq('^foo.*$') end it 'accepts a match regex that does not match the specified line' do expect { Puppet::Type.type(:file_line).new( :name => 'foo', :path => my_path, :line => 'foo=bar', :match => '^bar=blah$', ) }.not_to raise_error end it 'accepts a match regex that does match the specified line' do expect { Puppet::Type.type(:file_line).new( :name => 'foo', :path => my_path, :line => 'foo=bar', :match => '^\s*foo=.*$', ) }.not_to raise_error end it 'accepts utf8 characters' do expect { Puppet::Type.type(:file_line).new( :name => 'ƒồỗ', :path => my_path, :line => 'ƒồỗ=ьåя', :match => '^ьåя=βļάħ$', ) }.not_to raise_error end it 'accepts double byte characters' do expect { Puppet::Type.type(:file_line).new( :name => 'フーバー', :path => my_path, :line => 'この=それ', :match => '^この=ああ$', ) }.not_to raise_error end it 'accepts posix filenames' do file_line[:path] = tmp_path expect(file_line[:path]).to eq(tmp_path) end it 'does not accept unqualified path' do expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, %r{File paths must be fully qualified}) end it 'requires that a line is specified' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path) }.to raise_error(Puppet::Error, %r{line is a required attribute}) end it 'does not require that a line is specified when matching for absence' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error # rubocop:disable Metrics/LineLength end it 'although if a line is specified anyway when matching for absence it still works and the line is silently ignored' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :line => 'i_am_irrelevant', :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error # rubocop:disable Metrics/LineLength end it 'requires that a file is specified' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, %r{path is a required attribute}) end it 'defaults to ensure => present' do expect(file_line[:ensure]).to eq :present end it 'defaults to replace => true' do expect(file_line[:replace]).to eq :true end it 'defaults to encoding => UTF-8' do expect(file_line[:encoding]).to eq 'UTF-8' end it 'accepts encoding => iso-8859-1' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :present, :encoding => 'iso-8859-1', :line => 'bar') }.not_to raise_error end it 'autorequires the file it manages' do catalog = Puppet::Resource::Catalog.new file = Puppet::Type.type(:file).new(:name => tmp_path) catalog.add_resource file catalog.add_resource file_line relationship = file_line.autorequire.find do |rel| (rel.source.to_s == "File[#{tmp_path}]") && (rel.target.to_s == file_line.to_s) end expect(relationship).to be_a Puppet::Relationship end it 'does not autorequire the file it manages if it is not managed' do catalog = Puppet::Resource::Catalog.new catalog.add_resource file_line expect(file_line.autorequire).to be_empty end end puppetlabs-stdlib-4.25.0/types0040755005276200011600000000000013252003413013306 5ustar00puppetlabs-stdlib-4.25.0/types/absolutepath.pp0100644005276200011600000000015013206047630016422 0ustar00# A strict absolutepath type type Stdlib::Absolutepath = Variant[Stdlib::Windowspath, Stdlib::Unixpath] puppetlabs-stdlib-4.25.0/types/base32.pp0100644005276200011600000000014413252003272015004 0ustar00# Type to match base32 String type Stdlib::Base32 = Pattern[/^[a-z2-7]+={,6}$/, /^[A-Z2-7]+={,6}$/] puppetlabs-stdlib-4.25.0/types/base64.pp0100644005276200011600000000012713252003272015012 0ustar00# Type to match base64 String type Stdlib::Base64 = Pattern[/^[a-zA-Z0-9\/\+]+={,2}$/] puppetlabs-stdlib-4.25.0/types/compat0040755005276200011600000000000013252003413014571 5ustar00puppetlabs-stdlib-4.25.0/types/compat/absolute_path.pp0100644005276200011600000000102313212471613020043 0ustar00# Emulate the is_absolute_path and validate_absolute_path functions # # The first pattern is originally from is_absolute_path, which had it from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? # slash = '[\\\\/]' # name = '[^\\\\/]+' # %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i, type Stdlib::Compat::Absolute_path = Variant[Pattern[/^(([a-zA-Z]:[\\\/])|([\\\/][\\\/][^\\\/]+[\\\/][^\\\/]+)|([\\\/][\\\/]\?[\\\/][^\\\/]+))/], Pattern[/^\//]] # lint:ignore:140chars puppetlabs-stdlib-4.25.0/types/compat/array.pp0100644005276200011600000000013413206047630016332 0ustar00# Emulate the is_array and validate_array functions type Stdlib::Compat::Array = Array[Any] puppetlabs-stdlib-4.25.0/types/compat/bool.pp0100644005276200011600000000012613206047630016150 0ustar00# Emulate the is_bool and validate_bool functions type Stdlib::Compat::Bool = Boolean puppetlabs-stdlib-4.25.0/types/compat/float.pp0100644005276200011600000000135213206047630016324 0ustar00# Emulate the is_float function # The regex is what's currently used in is_float # To keep your development moving forward, you can also add a deprecation warning using the Integer type: # # ```class example($value) { validate_float($value,) }``` # # would turn into # # ``` # class example(Stdlib::Compat::Float $value) { # validate_float($value, 10, 0) # assert_type(Integer[0, 10], $value) |$expected, $actual| { # warning("The 'value' parameter for the 'ntp' class has type ${actual}, but should be ${expected}.") # } # } # ``` # # This allows you to find all places where a consumers of your code call it with unexpected values. type Stdlib::Compat::Float = Variant[Float, Pattern[/^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)(?:[eE]-?\d+)?$/]] puppetlabs-stdlib-4.25.0/types/compat/hash.pp0100644005276200011600000000013513206047630016140 0ustar00# Emulate the is_hash and validate_hash functions type Stdlib::Compat::Hash = Hash[Any, Any] puppetlabs-stdlib-4.25.0/types/compat/integer.pp0100644005276200011600000000226613212471613016660 0ustar00# Emulate the is_integer and validate_integer functions # The regex is what's currently used in is_integer # validate_numeric also allows range checking, which cannot be mapped to the string parsing inside the function. # For full backwards compatibility, you will need to keep the validate_numeric call around to catch everything. # To keep your development moving forward, you can also add a deprecation warning using the Integer type: # # ```class example($value) { validate_integer($value, 10, 0) }``` # # would turn into # # ``` # class example(Stdlib::Compat::Integer $value) { # validate_numeric($value, 10, 0) # assert_type(Integer[0, 10], $value) |$expected, $actual| { # warning("The 'value' parameter for the 'ntp' class has type ${actual}, but should be ${expected}.") # } # } # ``` # # > Note that you need to use Variant[Integer[0, 10], Float[0, 10]] if you want to match both integers and floating point numbers. # # This allows you to find all places where a consumers of your code call it with unexpected values. type Stdlib::Compat::Integer = Variant[Integer, Pattern[/^-?(?:(?:[1-9]\d*)|0)$/], Array[Variant[Integer, Pattern[/^-?(?:(?:[1-9]\d*)|0)$/]]]] # lint:ignore:140chars puppetlabs-stdlib-4.25.0/types/compat/ip_address.pp0100644005276200011600000000012613206047630017332 0ustar00type Stdlib::Compat::Ip_address = Variant[Stdlib::Compat::Ipv4, Stdlib::Compat::Ipv6] puppetlabs-stdlib-4.25.0/types/compat/ipv4.pp0100644005276200011600000000073313212471613016102 0ustar00# Emulate the validate_ipv4_address and is_ipv4_address functions type Stdlib::Compat::Ipv4 = Pattern[/^((([0-9](?!\d)|[1-9][0-9](?!\d)|1[0-9]{2}(?!\d)|2[0-4][0-9](?!\d)|25[0-5](?!\d))[.]){3}([0-9](?!\d)|[1-9][0-9](?!\d)|1[0-9]{2}(?!\d)|2[0-4][0-9](?!\d)|25[0-5](?!\d)))(\/((([0-9](?!\d)|[1-9][0-9](?!\d)|1[0-9]{2}(?!\d)|2[0-4][0-9](?!\d)|25[0-5](?!\d))[.]){3}([0-9](?!\d)|[1-9][0-9](?!\d)|1[0-9]{2}(?!\d)|2[0-4][0-9](?!\d)|25[0-5](?!\d))|[0-9]+))?$/] # lint:ignore:140chars puppetlabs-stdlib-4.25.0/types/compat/ipv6.pp0100644005276200011600000000216513212471613016105 0ustar00type Stdlib::Compat::Ipv6 = Pattern[/\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/] # lint:ignore:140chars puppetlabs-stdlib-4.25.0/types/compat/numeric.pp0100644005276200011600000000234613212471613016664 0ustar00# Emulate the is_numeric and validate_numeric functions # The regex is what's currently used in is_numeric # validate_numeric also allows range checking, which cannot be mapped to the string parsing inside the function. # For full backwards compatibility, you will need to keep the validate_numeric call around to catch everything. # To keep your development moving forward, you can also add a deprecation warning using the Integer type: # # ```class example($value) { validate_numeric($value, 10, 0) }``` # # would turn into # # ``` # class example(Stdlib::Compat::Numeric $value) { # validate_numeric($value, 10, 0) # assert_type(Integer[0, 10], $value) |$expected, $actual| { # warning("The 'value' parameter for the 'ntp' class has type ${actual}, but should be ${expected}.") # } # } # ``` # # > Note that you need to use Variant[Integer[0, 10], Float[0, 10]] if you want to match both integers and floating point numbers. # # This allows you to find all places where a consumers of your code call it with unexpected values. type Stdlib::Compat::Numeric = Variant[Numeric, Pattern[/^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$/], Array[Variant[Numeric, Pattern[/^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$/]]]] # lint:ignore:140chars puppetlabs-stdlib-4.25.0/types/compat/re.pp0100644005276200011600000000033613206047630015626 0ustar00# Emulate the validate_re function # validate_re(value, re) translates to Pattern[re], which is not directly mappable as a type alias, but can be specified as Pattern[re]. # Therefore this needs to be translated directly. puppetlabs-stdlib-4.25.0/types/compat/string.pp0100644005276200011600000000014513206047630016524 0ustar00# Emulate the is_string and validate_string functions type Stdlib::Compat::String = Optional[String] puppetlabs-stdlib-4.25.0/types/ensure0040755005276200011600000000000013252003413014607 5ustar00puppetlabs-stdlib-4.25.0/types/ensure/service.pp0100644005276200011600000000007213206047630016673 0ustar00type Stdlib::Ensure::Service = Enum['stopped', 'running'] puppetlabs-stdlib-4.25.0/types/filemode.pp0100644005276200011600000000006713206047630015522 0ustar00type Stdlib::Filemode = Pattern[/^[0124]{1}[0-7]{3}$/] puppetlabs-stdlib-4.25.0/types/filesource.pp0100644005276200011600000000036213252003272016067 0ustar00# Validate the source parameter on file types type Stdlib::Filesource = Variant[ Stdlib::Absolutepath, Stdlib::HTTPUrl, Pattern[ /^file:\/\/\/([^\/\0]+(\/)?)+$/, /^puppet:\/\/(([\w-]+\.?)+)?\/modules\/([^\/\0]+(\/)?)+$/, ], ] puppetlabs-stdlib-4.25.0/types/fqdn.pp0100644005276200011600000000021313252003272014652 0ustar00type Stdlib::Fqdn = Pattern[/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/] puppetlabs-stdlib-4.25.0/types/host.pp0100644005276200011600000000010613252003272014700 0ustar00type Stdlib::Host = Variant[Stdlib::Fqdn, Stdlib::Compat::Ip_address] puppetlabs-stdlib-4.25.0/types/httpsurl.pp0100644005276200011600000000005713206047630015622 0ustar00type Stdlib::HTTPSUrl = Pattern[/^https:\/\//] puppetlabs-stdlib-4.25.0/types/httpurl.pp0100644005276200011600000000005713206047630015437 0ustar00type Stdlib::HTTPUrl = Pattern[/^https?:\/\//] puppetlabs-stdlib-4.25.0/types/ip0040755005276200011600000000000013252003413013716 5ustar00puppetlabs-stdlib-4.25.0/types/ip/address0040755005276200011600000000000013252003413015343 5ustar00puppetlabs-stdlib-4.25.0/types/ip/address/nosubnet.pp0100644005276200011600000000017213252003272017620 0ustar00type Stdlib::IP::Address::Nosubnet = Variant[ Stdlib::IP::Address::V4::Nosubnet, Stdlib::IP::Address::V6::Nosubnet, ] puppetlabs-stdlib-4.25.0/types/ip/address/v40040755005276200011600000000000013252003413015674 5ustar00puppetlabs-stdlib-4.25.0/types/ip/address/v4/cidr.pp0100644005276200011600000000026713252003272017242 0ustar00type Stdlib::IP::Address::V4::CIDR = Pattern[/\A([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\/([1-9]|[12][0-9]|3[0-2])?\z/] puppetlabs-stdlib-4.25.0/types/ip/address/v4/nosubnet.pp0100644005276200011600000000024013252003272020145 0ustar00type Stdlib::IP::Address::V4::Nosubnet = Pattern[/\A([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/] puppetlabs-stdlib-4.25.0/types/ip/address/v4.pp0100644005276200011600000000016013252003272016311 0ustar00type Stdlib::IP::Address::V4 = Variant[ Stdlib::IP::Address::V4::CIDR, Stdlib::IP::Address::V4::Nosubnet, ] puppetlabs-stdlib-4.25.0/types/ip/address/v60040755005276200011600000000000013252003413015676 5ustar00puppetlabs-stdlib-4.25.0/types/ip/address/v6/alternative.pp0100644005276200011600000000262713252003272020643 0ustar00type Stdlib::IP::Address::V6::Alternative = Pattern[ /\A([[:xdigit:]]{1,4}:){6}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){5}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){4}(:[[:xdigit:]]{1,4}){0,1}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){3}(:[[:xdigit:]]{1,4}){0,2}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){2}(:[[:xdigit:]]{1,4}){0,3}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){1}(:[[:xdigit:]]{1,4}){0,4}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A:(:[[:xdigit:]]{1,4}){0,5}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, ] puppetlabs-stdlib-4.25.0/types/ip/address/v6/compressed.pp0100644005276200011600000000153413252003272020465 0ustar00type Stdlib::IP::Address::V6::Compressed = Pattern[ /\A:(:|(:[[:xdigit:]]{1,4}){1,7})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){1}(:|(:[[:xdigit:]]{1,4}){1,6})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){2}(:|(:[[:xdigit:]]{1,4}){1,5})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){3}(:|(:[[:xdigit:]]{1,4}){1,4})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){4}(:|(:[[:xdigit:]]{1,4}){1,3})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){5}(:|(:[[:xdigit:]]{1,4}){1,2})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){6}(:|(:[[:xdigit:]]{1,4}){1,1})(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, /\A([[:xdigit:]]{1,4}:){7}:(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/, ] puppetlabs-stdlib-4.25.0/types/ip/address/v6/full.pp0100644005276200011600000000021213252003272017253 0ustar00type Stdlib::IP::Address::V6::Full = Pattern[/\A[[:xdigit:]]{1,4}(:[[:xdigit:]]{1,4}){7}(\/(1([01][0-9]|[2][0-8])|[1-9][0-9]|[1-9]))?\z/] puppetlabs-stdlib-4.25.0/types/ip/address/v6/nosubnet0040755005276200011600000000000013252003413017533 5ustar00puppetlabs-stdlib-4.25.0/types/ip/address/v6/nosubnet/alternative.pp0100644005276200011600000000214613252003272022474 0ustar00type Stdlib::IP::Address::V6::Nosubnet::Alternative = Pattern[ /\A([[:xdigit:]]{1,4}:){6}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A([[:xdigit:]]{1,4}:){5}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A([[:xdigit:]]{1,4}:){4}(:[[:xdigit:]]{1,4}){0,1}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A([[:xdigit:]]{1,4}:){3}(:[[:xdigit:]]{1,4}){0,2}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A([[:xdigit:]]{1,4}:){2}(:[[:xdigit:]]{1,4}){0,3}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A([[:xdigit:]]{1,4}:){1}(:[[:xdigit:]]{1,4}){0,4}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, /\A:(:[[:xdigit:]]{1,4}){0,5}:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\z/, ] puppetlabs-stdlib-4.25.0/types/ip/address/v6/nosubnet/compressed.pp0100644005276200011600000000077613252003272022331 0ustar00type Stdlib::IP::Address::V6::Nosubnet::Compressed = Pattern[ /\A:(:|(:[[:xdigit:]]{1,4}){1,7})\z/, /\A([[:xdigit:]]{1,4}:){1}(:|(:[[:xdigit:]]{1,4}){1,6})\z/, /\A([[:xdigit:]]{1,4}:){2}(:|(:[[:xdigit:]]{1,4}){1,5})\z/, /\A([[:xdigit:]]{1,4}:){3}(:|(:[[:xdigit:]]{1,4}){1,4})\z/, /\A([[:xdigit:]]{1,4}:){4}(:|(:[[:xdigit:]]{1,4}){1,3})\z/, /\A([[:xdigit:]]{1,4}:){5}(:|(:[[:xdigit:]]{1,4}){1,2})\z/, /\A([[:xdigit:]]{1,4}:){6}(:|(:[[:xdigit:]]{1,4}){1,1})\z/, /\A([[:xdigit:]]{1,4}:){7}:\z/, ] puppetlabs-stdlib-4.25.0/types/ip/address/v6/nosubnet/full.pp0100644005276200011600000000014713252003272021117 0ustar00type Stdlib::IP::Address::V6::Nosubnet::Full = Pattern[/\A[[:xdigit:]]{1,4}(:[[:xdigit:]]{1,4}){7}\z/] puppetlabs-stdlib-4.25.0/types/ip/address/v6/nosubnet.pp0100644005276200011600000000030213252003272020146 0ustar00type Stdlib::IP::Address::V6::Nosubnet = Variant[ Stdlib::IP::Address::V6::Nosubnet::Full, Stdlib::IP::Address::V6::Nosubnet::Compressed, Stdlib::IP::Address::V6::Nosubnet::Alternative, ] puppetlabs-stdlib-4.25.0/types/ip/address/v6.pp0100644005276200011600000000027713252003272016324 0ustar00type Stdlib::IP::Address::V6 = Variant[ Stdlib::IP::Address::V6::Full, Stdlib::IP::Address::V6::Compressed, Stdlib::IP::Address::V6::Alternative, Stdlib::IP::Address::V6::Nosubnet, ] puppetlabs-stdlib-4.25.0/types/ip/address.pp0100644005276200011600000000013413252003272015761 0ustar00type Stdlib::IP::Address = Variant[ Stdlib::IP::Address::V4, Stdlib::IP::Address::V6, ] puppetlabs-stdlib-4.25.0/types/ip_address.pp0100644005276200011600000000007613252003272016046 0ustar00type Stdlib::Ip_address = Variant[Stdlib::Ipv4, Stdlib::Ipv6] puppetlabs-stdlib-4.25.0/types/ipv4.pp0100644005276200011600000000005113252003272014604 0ustar00type Stdlib::Ipv4 = Stdlib::Compat::Ipv4 puppetlabs-stdlib-4.25.0/types/ipv6.pp0100644005276200011600000000212113252003272014606 0ustar00type Stdlib::Ipv6 = Pattern[/^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?$/] puppetlabs-stdlib-4.25.0/types/mac.pp0100644005276200011600000000014313206047630014471 0ustar00# A type for a MAC address type Stdlib::MAC = Pattern[/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/] puppetlabs-stdlib-4.25.0/types/port0040755005276200011600000000000013252003413014272 5ustar00puppetlabs-stdlib-4.25.0/types/port/privileged.pp0100644005276200011600000000006113252003272017041 0ustar00type Stdlib::Port::Privileged = Integer[1, 1023] puppetlabs-stdlib-4.25.0/types/port/unprivileged.pp0100644005276200011600000000006713252003272017412 0ustar00type Stdlib::Port::Unprivileged = Integer[1024, 65535] puppetlabs-stdlib-4.25.0/types/port.pp0100644005276200011600000000004613252003272014712 0ustar00type Stdlib::Port = Integer[0, 65535] puppetlabs-stdlib-4.25.0/types/unixpath.pp0100644005276200011600000000020513252003272015563 0ustar00# this regex rejects any path component that does not start with "/" or is NUL type Stdlib::Unixpath = Pattern[/^\/([^\/\0]+\/*)*$/] puppetlabs-stdlib-4.25.0/types/windowspath.pp0100644005276200011600000000017713206047630016307 0ustar00type Stdlib::Windowspath = Pattern[/^(([a-zA-Z]:[\\\/])|([\\\/][\\\/][^\\\/]+[\\\/][^\\\/]+)|([\\\/][\\\/]\?[\\\/][^\\\/]+))/]