diff options
326 files changed, 7090 insertions, 2621 deletions
diff --git a/.gitattributes b/.gitattributes index 900ea0c..02d4646 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,5 @@ #This file is generated by ModuleSync, do not edit. -*.rb eol=lf +*.rb eol=lf *.erb eol=lf -*.pp eol=lf -*.sh eol=lf +*.pp eol=lf +*.sh eol=lf @@ -1,15 +1,26 @@ -#This file is generated by ModuleSync, do not edit. -pkg/ -Gemfile.lock -vendor/ -spec/fixtures/manifests/ -spec/fixtures/modules/ -.vagrant/ +#This file is generated by ModuleSync, do not edit.Z +*.iml +.*.sw[op] +.DS_Store .bundle/ +.idea/ +.metadata +.vagrant/ +.yardoc +.yardwarns +Gemfile.local +Gemfile.lock +bin/ coverage/ +doc/ +junit/ log/ -.idea/ -*.iml +pkg/ +spec/fixtures/manifests/ +spec/fixtures/modules/ +tmp/ +vendor/ + !spec/fixtures/ spec/fixtures/manifests/site.pp spec/fixtures/modules/* @@ -1,12 +1,12 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> - <name>stdlib</name> + <name>puppetlabs-stdlib</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> - <name>org.cloudsmith.geppetto.pp.dsl.ui.modulefileBuilder</name> + <name>com.puppetlabs.geppetto.pp.dsl.ui.modulefileBuilder</name> <arguments> </arguments> </buildCommand> @@ -17,7 +17,7 @@ </buildCommand> </buildSpec> <natures> - <nature>org.cloudsmith.geppetto.pp.dsl.ui.puppetNature</nature> + <nature>com.puppetlabs.geppetto.pp.dsl.ui.puppetNature</nature> <nature>org.eclipse.xtext.ui.shared.xtextNature</nature> </natures> </projectDescription> @@ -1,4 +1,6 @@ --- +NOTICE: + unmanaged: true .gitignore: paths: - '!spec/fixtures/' diff --git a/.travis.yml b/.travis.yml index d972387..0c6f904 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ sudo: false language: ruby cache: bundler -script: "bundle exec rake validate lint spec" +script: "bundle exec rake release_checks" #Inserting below due to the following issue: https://github.com/travis-ci/travis-ci/issues/3531#issuecomment-88311203 before_install: - gem update bundler @@ -22,20 +22,11 @@ matrix: script: bundle exec rake beaker services: docker sudo: required - - rvm: 2.3.1 + - rvm: 2.4.0 bundler_args: --without system_tests - env: PUPPET_GEM_VERSION="~> 4.0" + env: PUPPET_GEM_VERSION="~> 5.0" - rvm: 2.1.9 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 4.0" - - rvm: 2.1.5 - bundler_args: --without system_tests - env: PUPPET_GEM_VERSION="~> 3.0" FUTURE_PARSER="yes" - - rvm: 2.1.5 - bundler_args: --without system_tests - env: PUPPET_GEM_VERSION="~> 3.0" - - rvm: 1.9.3 - bundler_args: --without system_tests - env: PUPPET_GEM_VERSION="~> 3.0" notifications: email: false diff --git a/CHANGELOG.md b/CHANGELOG.md index 9157b2d..57b9ebb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,135 @@ +# 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.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 @@ -61,11 +193,11 @@ Special thanks to [Voxpupuli's](https://voxpupuli.org/) Igor Galić for donating * 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 +### Summary This release provides several new functions, bugfixes, modulesync changes, and some documentation updates. -####Features +#### 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. @@ -77,7 +209,7 @@ This release provides several new functions, bugfixes, modulesync changes, and s - Apply modulesync changes. - Add validate_email_address function. -####Bugfixes +#### 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. @@ -86,39 +218,39 @@ This release provides several new functions, bugfixes, modulesync changes, and s - Fixes concat with Hash arguments. ## Supported Release 4.11.0 -###Summary +### 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 +#### Features - Adds new parser called is_absolute_path - Supports Debian 8 -####Bugfixes +#### Bugfixes - Allow package_provider fact to resolve on PE 3.x -####Improvements +#### Improvements - ensures that the test passes independently of changes to rubygems for ensure_resource -##2015-12-15 - Supported Release 4.10.0 -###Summary +## 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 +#### Features - Adds service_provider fact - Adds is_a() function - Adds package_provider fact - Adds validate_ip_address function - Adds seeded_rand function -####Bugfixes +#### 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 +#### Improvements - (MODULES-2462) Improvement of parseyaml function - Improvement of str2bool function - Improvement to readme @@ -133,26 +265,26 @@ Includes the addition of several new functions and considerable improvements to - Improvement to naming convention in validate_ipv4_address function ## Supported Release 4.9.1 -###Summary +### 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 +## 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 +#### 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 +#### Bugfixes - n/a -####Improvements +#### Improvements - (MODULES-2478) Support root_home fact on AIX through "lsuser" command - Acceptance test improvements - Unit test improvements @@ -171,15 +303,15 @@ This release adds a function for reading metadata.json from any module, and expa - Fix various docs typos - Fix `file_line` resource on puppet < 3.3 -##2015-06-22 - Supported Release 4.7.0 -###Summary +## 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 +#### Features - Add support for Solaris 12 -####Bugfixes +#### Bugfixes - Fix for AIO Puppet 4 - Fix time for ruby 1.8.7 - Specify rspec-puppet version @@ -189,7 +321,7 @@ Adds Solaris 12 support along with improved Puppet 4 support. There are signific - catch and rescue from looking up non-existent facts - Use puppet_install_helper, for Puppet 4 -####Improvements +#### Improvements - Enforce support for Puppet 4 testing - fqdn_rotate/fqdn_rand_string acceptance tests and implementation - Simplify mac address regex @@ -200,12 +332,12 @@ Adds Solaris 12 support along with improved Puppet 4 support. There are signific - Add validate_slength optional 3rd arg - Move tests directory to examples directory -##2015-04-14 - Supported Release 4.6.0 -###Summary +## 2015-04-14 - Supported Release 4.6.0 +### Summary Adds functions and function argument abilities, and improves compatibility with the new puppet parser -####Features +#### 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 @@ -222,7 +354,7 @@ Adds functions and function argument abilities, and improves compatibility with - Adds `validate_integer()` - Adds `validate_numeric()` (like `validate_integer()` but also accepts floats) -####Bugfixes +#### Bugfixes - Fix seeding of `fqdn_rotate()` - `ensure_resource()` is more verbose on debug mode - Stricter argument checking for `dirname()` @@ -230,37 +362,37 @@ Adds functions and function argument abilities, and improves compatibility with - 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 +## 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 +#### Bugfixes - Facter_dot_d cache will now be stored in puppet libdir instead of tmp -##2014-12-15 - Supported Release 4.5.0 -###Summary +## 2014-12-15 - Supported Release 4.5.0 +### Summary This release improves functionality of the member function and adds improved future parser support. -####Features +#### Features - MODULES-1329: Update member() to allow the variable to be an array. - Sync .travis.yml, Gemfile, Rakefile, and CONTRIBUTING.md via modulesync -####Bugfixes +#### 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 +## 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 +#### Features - All new shiny README - New `private()` function for making private manifests (yay!) -####Bugfixes +#### 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) @@ -272,20 +404,20 @@ This release has an overhauled readme, new private manifest function, and fixes - Fix `file_line` matching on older rubies -##2014-07-15 - Supported Release 4.3.2 -###Summary +## 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 +## 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 +## 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. @@ -297,7 +429,7 @@ backwards-compatible with the stdlib 3 series. It adds two new functions, one bu #### Bugfixes - Fix `has_interface_with()` when interfaces fact is nil -##2014-06-04 - Release 4.2.2 +## 2014-06-04 - Release 4.2.2 ### Summary This release adds PE3.3 support in the metadata and fixes a few tests. @@ -341,14 +473,14 @@ This release adds many new functions and fixes, and continues to be backwards co - Add/update unit & acceptance tests. -##2014-03-04 - Supported Release - 3.2.1 -###Summary +## 2014-03-04 - Supported Release - 3.2.1 +### Summary This is a supported release -####Bugfixes +#### Bugfixes - Fixed `is_integer`/`is_float`/`is_numeric` for checking the value of arithmatic expressions. -####Known bugs +#### Known bugs * No known bugs --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c3f1e7..1a9fb3a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,63 +1,75 @@ -Checklist (and a short version for the impatient) -================================================= +# Contributing to Puppet modules - * Commits: +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. - - Make commits of logical units. +### Table of Contents - - Check for unnecessary whitespace with "git diff --check" before - committing. +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) - - Commit using Unix line endings (check the settings around "crlf" in - git-config(1)). +## Getting Started - - Do not check in commented out code or unneeded files. +- Fork the module repository on GitHub and clone to your workspace - - The first line of the commit message should be a short - description (50 characters is the soft limit, excluding ticket - number(s)), and should skip the full stop. +- Make your changes! - - Associate the issue in the message. The first line should include - the issue number in the form "(#XXXX) Rest of message". +## Commit Checklist - - The body should provide a meaningful commit message, which: +### The Basics - - uses the imperative, present tense: "change", not "changed" or - "changes". +- [x] my commit is a single logical unit of work - - includes motivation for the change, and contrasts its - implementation with the previous behavior. +- [x] I have checked for unnecessary whitespace with "git diff --check" - - Make sure that you have tests for the bug you are fixing, or - feature you are adding. +- [x] my commit does not include commented out code or unneeded files - - Make sure the test suites passes after your commit: - `bundle exec rspec spec/acceptance` More information on [testing](#Testing) below +### The Content - - When introducing a new feature, make sure it is properly - documented in the README.md +- [x] my commit includes tests for the bug I fixed or feature I added - * Submission: +- [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 - * Pre-requisites: +### The Commit Message - - Make sure you have a [GitHub account](https://github.com/join) +- [x] the first line of my commit message includes: - - [Create a ticket](https://tickets.puppetlabs.com/secure/CreateIssue!default.jspa), or [watch the ticket](https://tickets.puppetlabs.com/browse/) you are patching for. + - [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)) - * Preferred method: +- [x] the body of my commit message: - - Fork the repository on GitHub. + - [x] is meaningful - - Push your changes to a topic branch in your fork of the - repository. (the format ticket/1234-short_description_of_change is - usually preferred for this project). + - [x] uses the imperative, present tense: "change", not "changed" or "changes" - - Submit a pull request to the repository in the puppetlabs - organization. + - [x] includes motivation for the change, and contrasts its implementation with the previous behavior -The long version -================ +## 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. @@ -104,37 +116,32 @@ The long version GitHub has some pretty good [general documentation](http://help.github.com/) on using their site. They also have documentation on - [creating pull requests](http://help.github.com/send-pull-requests/). + [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. - 3. Update the related GitHub issue. - - If there is a GitHub issue associated with the change you + 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 -======= +# Testing -Getting Started ---------------- +## 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, +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, then use it to install all dependencies needed for this project, -by running +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 +% bundle install --path .bundle/gems Fetching gem metadata from https://rubygems.org/........ Fetching gem metadata from https://rubygems.org/.. Using rake (10.1.0) @@ -148,7 +155,7 @@ 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. +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: @@ -156,26 +163,27 @@ If you already have those gems installed, make sure they are up-to-date: % bundle update ``` -With all dependencies in place and up-to-date we can now run the tests: +## Running Tests + +With all dependencies in place and up-to-date, run the tests: + +### Unit Tests ```shell % bundle exec rake spec ``` -This will execute all the [rspec tests](http://rspec-puppet.com/) tests -under [spec/defines](./spec/defines), [spec/classes](./spec/classes), -and so on. rspec tests may have the same kind of dependencies as the -module they are testing. While the module defines in its [Modulefile](./Modulefile), +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). -Some puppet modules also come with [beaker](https://github.com/puppetlabs/beaker) -tests. These tests spin up a virtual machine under -[VirtualBox](https://www.virtualbox.org/)) with, controlling it with -[Vagrant](http://www.vagrantup.com/) to actually simulate scripted test -scenarios. In order to run these, you will need both of those tools -installed on your system. +### 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. -You can run them by issuing the following command +Run the tests by issuing the following command ```shell % bundle exec rake spec_clean @@ -183,36 +191,81 @@ You can run them by issuing the following command ``` 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) +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 -------------- +## Writing Tests -XXX getting started writing tests. +### Unit Tests -If you have commit access to the repository -=========================================== +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: -Even if you have commit access to the repository, you will 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 -developer on the project (that did not write the code) to ensure that -all changes go through a code review process. +Sample manifest: -Having someone other than the author of the topic branch recorded as -performing the merge is the record that they performed the code -review. +```puppet +file { "a test file": + ensure => present, + path => "/etc/sample", +} +``` +Sample test: -Additional Resources -==================== +```ruby +it 'does a thing' do + expect(subject).to contain_file("a test file").with({:path => "/etc/sample"}) +end +``` -* [Getting additional help](http://puppet.com/community/get-help) +### 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 -* [Writing tests](https://docs.puppet.com/guides/module_guides/bgtm.html#step-three-module-testing) +``` -* [General GitHub documentation](http://help.github.com/) +# 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 @@ -29,39 +29,28 @@ end # Used for gem conditionals supports_windows = false +ruby_version_segments = Gem::Version.new(RUBY_VERSION.dup).segments +minor_version = "#{ruby_version_segments[0]}.#{ruby_version_segments[1]}" group :development do - gem 'puppet-lint', :require => false - gem 'metadata-json-lint', :require => false, :platforms => 'ruby' - gem 'puppet_facts', :require => false - gem 'puppet-blacksmith', '>= 3.4.0', :require => false, :platforms => 'ruby' - gem 'puppetlabs_spec_helper', '>= 1.2.1', :require => false - gem 'rspec-puppet', '>= 2.3.2', :require => false - gem 'rspec-puppet-facts', :require => false, :platforms => 'ruby' - gem 'mocha', '< 1.2.0', :require => false - gem 'simplecov', :require => false, :platforms => 'ruby' - gem 'parallel_tests', '< 2.10.0', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') - gem 'parallel_tests', :require => false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.0.0') - gem 'rubocop', '0.41.2', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') - gem 'rubocop', :require => false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.0.0') - gem 'rubocop-rspec', '~> 1.6', :require => false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.3.0') - gem 'pry', :require => false - gem 'json_pure', '<= 2.0.1', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') - 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 "puppet-module-posix-default-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-posix-dev-r#{minor_version}", :require => false, :platforms => "ruby" + gem "puppet-module-win-dev-r#{minor_version}", '0.0.7', :require => false, :platforms => ["mswin", "mingw", "x64_mingw"] + gem "json_pure", '<= 2.0.1', :require => false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') + 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') end group :system_tests do - gem 'beaker', *location_for(ENV['BEAKER_VERSION'] || '~> 2.20') if supports_windows - gem 'beaker', *location_for(ENV['BEAKER_VERSION']) if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.3.0') and ! supports_windows - gem 'beaker', *location_for(ENV['BEAKER_VERSION'] || '< 3') if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.3.0') and ! supports_windows - gem 'beaker-pe', :require => false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.3.0') - gem 'beaker-rspec', *location_for(ENV['BEAKER_RSPEC_VERSION'] || '>= 3.4') if ! supports_windows - gem 'beaker-rspec', *location_for(ENV['BEAKER_RSPEC_VERSION'] || '~> 5.1') if supports_windows - gem 'beaker-puppet_install_helper', :require => false - gem 'master_manipulator', :require => false - gem 'beaker-hostgenerator', *location_for(ENV['BEAKER_HOSTGENERATOR_VERSION']) - gem 'beaker-abs', *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.1') + 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') + gem "beaker-pe", :require => false + gem "beaker-rspec", *location_for(ENV['BEAKER_RSPEC_VERSION']) + gem "beaker-hostgenerator", *location_for(ENV['BEAKER_HOSTGENERATOR_VERSION']) + gem "beaker-abs", *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.1') + gem "puppet-blacksmith", '~> 3.4', :require => false end gem 'puppet', *location_for(ENV['PUPPET_GEM_VERSION']) diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000..e8004a5 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,6 @@ +## 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`. diff --git a/README.markdown b/README.markdown deleted file mode 100644 index a4c30b5..0000000 --- a/README.markdown +++ /dev/null @@ -1,1743 +0,0 @@ -# stdlib - -#### Table of Contents - -1. [Overview](#overview) -2. [Module Description - What the module does and why it is useful](#module-description) -3. [Setup - The basics of getting started with stdlib](#setup) -4. [Usage - Configuration options and additional functionality](#usage) -5. [Reference - An under-the-hood peek at what the module is doing and how](#reference) -5. [Limitations - OS compatibility, etc.](#limitations) -6. [Development - Guide for contributing to the module](#development) - -## Overview - -Adds a standard library of resources for Puppet modules. - -## Module Description - -This module provides a standard library of resources for the development of Puppet modules. Puppet modules make heavy use of this standard library. The stdlib module adds the following resources to Puppet: - - * Stages - * Facts - * Functions - * Defined resource 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 - -Installing the stdlib module adds the functions, facts, and resources of this standard library to Puppet. - -## Usage - -After you've installed stdlib, all of its functions, facts, and resources are available for module use or development. - -If you want to use a standardized set of run stages for Puppet, `include stdlib` in your manifest. - -* `stdlib`: 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: - - ~~~ - node default { - include stdlib - class { java: stage => 'runtime' } - } - ~~~ - -## Reference - -### Classes - -#### Public Classes - - The stdlib class has no parameters. - -#### Private Classes - -* `stdlib::stages`: Manages a standard set of run stages for Puppet. It is managed by the stdlib class and should not be declared independently. - -### Resource 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: - - 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 ensures that 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` looks for a line beginning with export followed by HTTP_PROXY and replaces it with the value in line. - -Match Example With `ensure => absent`: - - file_line { 'bashrc_proxy': - ensure => absent, - path => '/etc/bashrc', - line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', - match => '^export\ HTTP_PROXY\=', - match_for_absence => true, - } - -In this code example, `match` looks 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. - -**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.) Valid options: String containing a regex. Default: Undefined. -* `ensure`: Ensures whether the resource is present. Valid options: 'present', 'absent'. Default: 'present'. -* `line`: **Required.** Sets the line to be added to the file located by the `path` parameter. Valid options: String. Default: Undefined. -* `match`: Specifies a regular expression to run against existing lines in the file; if a match is found, it is replaced rather than adding a new line. A regex comparison is performed against the line value, and if it does not match, an exception is raised. Valid options: String containing a regex. Default: Undefined. -* `match_for_absence`: 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` and the value of `line` is used instead. Ignored when `ensure => present`. Default: false. -* `multiple`: Determines if `match` and/or `after` can change multiple lines. If set to false, an exception will be raised if more than one line matches. Valid options: 'true', 'false'. Default: Undefined. -* `name`: Sets the name to use as the identity of the resource. This is necessary if you want the resource namevar to differ from the supplied `title` of the resource. Valid options: String. Default: Undefined. -* `path`: **Required.** Defines the file in which Puppet will ensure the line specified by `line`. Must be an absolute path to the file. -* `replace`: Defines whether the resource will overwrite an existing line that matches the `match` parameter. If set to false and a line is found matching the `match` param, the line will not be placed in the file. Valid options: true, false, yes, no. Default: true - -### Data Types - -#### `Stdlib::Absolutepath` - -A strict absolute path type. Uses a Variant of Unixpath and Windowspath types. - -Acceptable input examples: /var/log - /usr2/username/bin:/usr/local/bin:/usr/bin:. - C:\\WINDOWS\\System32 -Unacceptable input example: ../relative_path - -#### `Stdlib::Httpsurl` - -Matches https URLs. - -Acceptable input example: https://hello.com -Unacceptable input example: httds://notquiteright.org - -#### `Stdlib::Httpurl` - -Matches both https and http URLs. - -Acceptable input example: https://hello.com - http://hello.com -Unacceptable input example: httds://notquiteright.org - -#### `Stdlib::Unixpath` - -Matches paths on Unix type Operating Systems. - -Acceptable input example: /usr2/username/bin:/usr/local/bin:/usr/bin:. - /var/tmp -Unacceptable input example: C:/whatever - -#### `Stdlib::Windowspath` - -Matches paths on Windows Operating systems. - -Acceptable input example: C:\\WINDOWS\\System32 - C:\\ - \\\\host\\windows -Unacceptable input example: /usr2/username/bin:/usr/local/bin:/usr/bin:. - -### Functions - -#### `abs` - -Returns the absolute value of a number; for example, '-34.56' becomes '34.56'. Takes a single integer and float value as an argument. *Type*: rvalue. - -#### `any2array` - -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. *Type*: rvalue. - -#### `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` will be set as `default` if not specified. - -*Examples:* -~~~ -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 (optionally stripping an 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. - Requires 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:* -~~~ -bool2str(true) => 'true' -bool2str(true, 'yes', 'no') => 'yes' -bool2str(false, 't', 'f') => 'f' -~~~ - -Requires a single boolean as input. *Type*: rvalue. - -#### `capitalize` - -Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string. Requires either a single string or an array as an input. *Type*: rvalue. - -#### `ceiling` - -Returns the smallest integer greater than or equal to the argument. Takes a single numeric value as an argument. *Type*: rvalue. - -#### `chomp` - -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. *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. If you want to merely remove record separators, then you should use the `chomp` function. Requires 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 (order of params doesn't matter). Takes strings, arrays or numerics. 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. - *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, it counts the number of elements that are **not** nil/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. - $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.". -*Type*: rvalue, 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. - - ~~~ - 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 will be treated as a one-item array. - -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: - -``` -deprecation(key, message) -``` - -* key: to keep the number of messages low, during the lifetime of a puppet process, only one message per key is logged. -* message: the text to be logged. - -The Puppet settings '[disable_warnings](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings)', '[max_deprecations](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations)', and '[strict](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict)' affect this function. Set 'strict' to `error` to fail immediately with the deprecation message, `off` to output emit no messages at all, or `warning` (default) to log all warnings. - -Additionally you can set the environment variable `STDLIB_LOG_DEPRECATIONS` to decide whether or not to log deprecation warnings: if this environment variable is set to `true`, the functions log a warning, if it is set to `false`, no warnings are logged. If no value is set at all, Puppet 4 will emit warnings, while Puppet 3 will not. Using this setting is especially useful for automated tests to avoid flooding your logs before you are ready to migrate. - -*Type*: String, String. - -#### `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 in Puppet 4.5.0, use dig44() for backwards compatibility or use the new version. - -*Type*: rvalue. - -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 will be returned if nothing is found. - (optional, defaults to *undef*) - -#### `dig44` - -*Type*: rvalue. - -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 = 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' -~~~ - -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. *Type*: rvalue. - -~~~ -file{$config_file: - ensure => file, - content => dos2unix(template('my_module/settings.conf.erb')), -} -~~~ - -See also [unix2dos](#unix2dos). - -#### `downcase` - -Converts the case of a string or of all strings in an array to lowercase. *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 array/hash and only installs them if they don't already exist. It 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 Array: - - ensure_packages(['ksh','openssl'], {'ensure' => 'present'}) - -For Hash: - - 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` - -Takes a resource type, title (only hash), and a hash of attributes that describe the resource(s). - -~~~ -user { 'dan': - gid => 'mygroup', - ensure => present, -} - -ensure_resources($user) -~~~ - -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' - -ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) -~~~ - -### `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` - -Takes a single numeric value as an argument, and returns the largest integer less than or equal to the argument. *Type*: rvalue. - -#### `fqdn_rand_string` - -Generates a random alphanumeric string using an optionally-specified character set (default is alphanumeric), combining the `$fqdn` fact and an optional seed for repeatable randomness. - -*Usage:* -~~~ -fqdn_rand_string(LENGTH, [CHARSET], [SEED]) -~~~ -*Examples:* -~~~ -fqdn_rand_string(10) -fqdn_rand_string(10, 'ABCDEF!@#$%^') -fqdn_rand_string(10, '', 'custom seed') -~~~ - -*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:* - -~~~ -fqdn_rotate(VALUE, [SEED]) -~~~ - -*Examples:* - -~~~ -fqdn_rotate(['a', 'b', 'c', 'd']) -fqdn_rotate('abcd') -fqdn_rotate([1, 2, 3], 'custom seed') -~~~ - -*Type*: rvalue. - -#### `fqdn_uuid` - -Returns a 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. - - `$module_path = get_module_path('stdlib')` - -*Type*: rvalue. - -#### `getparam` - -Takes a resource reference and the name of the parameter, and returns the value of the resource's parameter. - -For example, the following returns 'param_value': - - ~~~ - 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: - - ~~~ - $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 - ~~~ - -*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:* - - ~~~ - 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: - - ~~~ - 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. *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. *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/references/latest/type.html#about-resource-types) for more information about types. -See the [`assert_type()`](https://docs.puppetlabs.com/references/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_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. 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. 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. - -#### `loadyaml` - -Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type. - -For example: - - ~~~ - $myhash = loadyaml('/etc/puppet/data/myhash.yaml') - ~~~ - -The second parameter will be returned if the file was not found or could not be parsed. - -For example: - - ~~~ - $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: - - ~~~ - $myhash = loadjson('/etc/puppet/data/myhash.json') - ~~~ - -The second parameter will be returned if the file was not found or could not be parsed. - -For example: - - ~~~ - $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. - - ~~~ - $metadata = load_module_metadata('archive') - notify { $metadata['author']: } - ~~~ - -If you do not want to fail the catalog compilation when a module's metadata file is absent: - - ~~~ - $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. *Type*: rvalue. - -#### `member` - -This function determines if a variable is a member of an array. The variable can be either a string, array, or 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*: - - ~~~ - $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 "wins." *Type*: rvalue. - -#### `min` - -Returns the lowest value of all arguments. Requires at least one argument. *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. *Type*: rvalue. The optional second argument is returned if the data was not correct. - -#### `parseyaml` - -Converts a string of YAML into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct. - -#### `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. - - ~~~ - $real_jenkins_version = pick($::jenkins_version, '1.449') - ~~~ - -*Type*: rvalue. - -#### `pick_default` - -Returns the first value in a list of values. Contrary to the `pick()` function, the `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` - -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. Should only be used when running `puppet apply` or running a puppet master in the foreground. This requires the `pry` gem to be installed in puppet's rubygems. - -*Examples:* -```puppet -pry() -``` -Once in a pry session, some interesting commands: - -* 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 - -#### `assert_private` - -Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. - -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: - - ~~~ - assert_private("You're not supposed to do that!") - ~~~ - -*Type*: statement. - -#### `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. - -*Type*: rvalue. - -**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. - -#### `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"], and `range("host01", "host10")` returns ["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")` 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. *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. Like `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 double quotes nor in single quotes. This function behaves the same as ruby's `Shellwords.shellescape()` function, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape). - -*Example:* -~~~ -shell_escape('foo b"ar') => 'foo\ b\"ar' -~~~ - -*Type*: rvalue. - -#### `shell_join` - -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, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin). - -*Example:* -~~~ -shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z' -~~~ - -*Type*: rvalue. - -#### `shell_split` - -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, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit). - -*Example:* -~~~ -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. *Type*: rvalue. - -#### `sort` - -Sorts strings and arrays lexically. *Type*: rvalue. - -#### `squeeze` - -Returns a new string where runs of the same character that occur in this set are replaced by a single character. *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. Given any string, this function returns a hex version of a salted-SHA512 password hash, which can be inserted into your Puppet -manifests as a valid password attribute. *Type*: rvalue. - -#### `strftime` - -Returns formatted time. For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date. *Type*: rvalue. - - *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 (e.g. +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 the 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. - -#### `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". Takes a single string value as an argument. *Type*: rvalue. - -#### `try_get_value` - -*Type*: rvalue. - -DEPRECATED: replaced by `dig()`. - -Retrieves a value within multiple layers of hashes and arrays via a string containing a path. The path is a string of hash keys or array indexes starting with zero, separated by the path separator character (default "/"). 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. The last argument can set the path separator character. - -~~~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 *'/'*) - -#### `type3x` - -Returns a string description of the type when passed a value. Type can be a string, array, hash, float, integer, or boolean. This function will be removed when Puppet 3 support is dropped and the new type system can be used. *Type*: rvalue. - -#### `type_of` - -This function is provided for backwards compatibility but is generally not preferred over the built-in [type() function](https://docs.puppet.com/puppet/latest/reference/function.html#type) provided by Puppet. - -Returns the literal type when passed a value. Requires the new parser. 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 the given string. Very useful when using a File resource with a cross-platform template. *Type*: rvalue. - -~~~ -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 that respond to upcase to uppercase. For example, `upcase('abcd')` returns 'ABCD'. *Type*: rvalue. - -#### `uriescape` - -URLEncodes a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue. - -#### `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: - -~~~ -$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 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) -~~~ - -*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. Aborts catalog compilation if any value fails this check. - -The following values pass: - -~~~ -$my_array = [ 'one', 'two' ] -validate_array($my_array) -~~~ - -The following values fail, causing compilation to abort: - -~~~ -validate_array(true) -validate_array('some_string') -$undefined = undef -validate_array($undefined) -~~~ - -*Type*: statement. - -#### `validate_augeas` - -Performs validation of a string using an Augeas lens. The first argument of this function should be the 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 aborts with a parse error. - -A third optional argument lists 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, to make sure your $passwdcontent never contains user `foo`: - -~~~ -validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) -~~~ - -To ensure that no users use the '/bin/barsh' shell: - -~~~ -validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] -~~~ - -You can pass a fourth argument as the error message raised and shown to the user: - -~~~ -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. Aborts 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) -~~~ - -*Type*: statement. - -#### `validate_cmd` - -Performs 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 of the command if no % placeholder given). If the command is launched against a tempfile containing the passed string, or 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. - -~~~ -# 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') -~~~ - -*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. Aborts 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) - ~~~ - -*Type*: statement. - -#### `validate_integer` - -**Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).** - -Validates that the first argument is an integer (or an array of integers). Aborts 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 fail, causing compilation to abort: - - ~~~ - 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 it is an IPv4 or an IPv6 -address. It also validates IP address with netmask. The argument must be given as a string. - -The following values will pass: - - ~~~ - 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 abort: - - ~~~ - 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. - -Accepts arguments for: -* 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: - -``` -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 could sometimes be 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 '<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(<function>) expected <type> value, got <actual type>_`: 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(<function>) expected <type> value, got <actual type>`: 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: - -~~~ -class example($value) { - validate_numeric($value) -~~~ - -the resulting validation code looks like this: - -~~~ -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 that the first argument is a numeric value (or an array or string of numeric values). Aborts 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. - -*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. The first argument of this function should be the 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 aborts with a parse error. - - You can pass a third argument as the error message raised and shown to the user. - - The following strings validate against the regular expressions: - - ~~~ - validate_re('one', '^one$') - validate_re('one', [ '^one', '^two' ]) - ~~~ - - The following string fails to validate, causing compilation to abort: - - ~~~ - validate_re('one', [ '^two', '^three' ]) - ~~~ - - To set the error message: - - ~~~ - validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') - ~~~ - - Note: Compilation terminates if the first argument is not a string. Always use quotes to force stringification: - - ~~~ - 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 the first argument is a string (or an array of strings), and is less than or equal to the length of the second argument. It fails if the first argument is not a string or array of strings, or if the second argument is not convertable to a number. Optionally, a minimum string length can be given as the third argument. - - The following values pass: - - ~~~ - validate_slength("discombobulate",17) - validate_slength(["discombobulate","moo"],17) - validate_slength(["discombobulate","moo"],17,3) - ~~~ - - The following values fail: - - ~~~ - 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: - - ~~~ - $my_string = "one two" - validate_string($my_string, 'three') - ~~~ - - The following values 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('...') - } - ~~~ - -*Type*: statement. - -#### `validate_x509_rsa_key_pair` - -Validates a PEM-formatted X.509 certificate and private key using OpenSSL. -Verifies that the certficate's signature was created from the supplied key. - -Fails catalog compilation if any value fails this check. - -Takes two arguments, the first argument must be a X.509 certificate and the -second must be an RSA private key: - - ~~~ - 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. The first argument is the array you want to analyze, and the second argument 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 - - For example, `values_at(['a','b','c'], 2)` returns ['c']; `values_at(['a','b','c'], ["0-1"])` returns ['a','b']; and `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). diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b6a64b --- /dev/null +++ b/README.md @@ -0,0 +1,2506 @@ +# 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 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: + +```puppet +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: + +```puppet +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: + +```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. A regex comparison is performed against the line value, and if it does not match, an exception is raised. + +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`, an exception is raised if more than one line matches. + +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. 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`. + +### 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::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::Windowspath` + +Matches paths on Windows operating systems. + +Acceptable input example: + +```shell +C:\\WINDOWS\\System32 + +C:\\ + +\\\\host\\windows +``` + +Unacceptable input example: + +```shell +/usr2/username/bin:/usr/local/bin:/usr/bin:. +``` + +### 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. + +#### `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 (e.g. +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 '<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(<function>) expected <type> value, got <actual type>_`: 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(<function>) expected <type> value, got <actual type>`: 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). @@ -1,10 +1,9 @@ -require 'puppet_blacksmith/rake_tasks' -require 'puppet-lint/tasks/puppet-lint' require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' +require 'puppet_blacksmith/rake_tasks' if Bundler.rubygems.find_name('puppet-blacksmith').any? +PuppetLint.configuration.fail_on_warnings = true PuppetLint.configuration.send('relative') -PuppetLint.configuration.send('disable_documentation') -PuppetLint.configuration.send('disable_single_quote_string_with_variables') desc 'Generate pooler nodesets' task :gen_nodeset do diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..7e05880 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,52 @@ +version: 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: + - PUPPET_GEM_VERSION: ~> 4.0 + RUBY_VER: 21 + - PUPPET_GEM_VERSION: ~> 4.0 + RUBY_VER: 21-x64 + - PUPPET_GEM_VERSION: ~> 5.0 + RUBY_VER: 24 + - PUPPET_GEM_VERSION: ~> 5.0 + RUBY_VER: 24-x64 + - PUPPET_GEM_VERSION: 4.7.1 + RUBY_VER: 21-x64 +matrix: + fast_finish: true +install: +- SET PATH=C:\Ruby%RUBY_VER%\bin;%PATH% +- ps: | + # AppVeyor appears to have OpenSSL headers available already + # which msys2 would normally install with: + # pacman -S mingw-w64-x86_64-openssl --noconfirm + # + if ( $(ruby --version) -match "^ruby\s+2\.4" ) { + Write-Output "Building OpenSSL gem ~> 2.0.4 to fix Ruby 2.4 / AppVeyor issue" + gem install openssl --version '~> 2.0.4' --no-ri --no-rdoc + } + + gem list openssl + ruby -ropenssl -e 'puts \"OpenSSL Version - #{OpenSSL::OPENSSL_VERSION}\"; puts \"OpenSSL Library Version - #{OpenSSL::OPENSSL_LIBRARY_VERSION}\"' +- bundle install --jobs 4 --retry 2 --without system_tests +- type Gemfile.lock +build: off +test_script: +- bundle exec puppet -V +- ruby -v +- bundle exec rake spec SPEC_OPTS='--format documentation' +notifications: +- provider: Email + to: + - nobody@nowhere.com + on_build_success: false + on_build_failure: false + on_build_status_changed: false diff --git a/examples/file_line.pp b/examples/file_line.pp index 85b1325..e628bea 100644 --- a/examples/file_line.pp +++ b/examples/file_line.pp @@ -2,8 +2,8 @@ # of the file_line resource type. file { '/tmp/dansfile': ensure => file, -} -> -file_line { 'dans_line': +} +-> file_line { 'dans_line': line => 'dan is awesome', path => '/tmp/dansfile', } diff --git a/lib/puppet/functions/fact.rb b/lib/puppet/functions/fact.rb new file mode 100644 index 0000000..dfb048b --- /dev/null +++ b/lib/puppet/functions/fact.rb @@ -0,0 +1,58 @@ +# 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 do |string| + string.include?('.') ? %Q{"#{string}"} : string + end.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(/([^."]+)|(?:")([^"]+)(?:")/).map {|x| x.compact.first } + + walked_path = [] + path.reduce(facts) do |d, k| + return nil if d.nil? || k.nil? + + case + when d.is_a?(Array) + begin + result = d[Integer(k)] + rescue ArgumentError => e + Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'") + result = nil + end + when 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 diff --git a/lib/puppet/functions/length.rb b/lib/puppet/functions/length.rb new file mode 100644 index 0000000..5ebd455 --- /dev/null +++ b/lib/puppet/functions/length.rb @@ -0,0 +1,14 @@ +#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 + return result + end +end diff --git a/lib/puppet/functions/to_json.rb b/lib/puppet/functions/to_json.rb new file mode 100644 index 0000000..782d695 --- /dev/null +++ b/lib/puppet/functions/to_json.rb @@ -0,0 +1,21 @@ +# 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 diff --git a/lib/puppet/functions/to_json_pretty.rb b/lib/puppet/functions/to_json_pretty.rb new file mode 100644 index 0000000..4c28539 --- /dev/null +++ b/lib/puppet/functions/to_json_pretty.rb @@ -0,0 +1,21 @@ +# 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), +# } +# +# +require 'json' + +Puppet::Functions.create_function(:to_json_pretty) do + dispatch :to_json_pretty do + param 'Variant[Hash, Array]', :data + end + + def to_json_pretty(data) + JSON.pretty_generate(data) + end +end diff --git a/lib/puppet/functions/to_yaml.rb b/lib/puppet/functions/to_yaml.rb new file mode 100644 index 0000000..fdd7370 --- /dev/null +++ b/lib/puppet/functions/to_yaml.rb @@ -0,0 +1,21 @@ +# 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 diff --git a/lib/puppet/parser/functions/abs.rb b/lib/puppet/parser/functions/abs.rb index 11d2d7f..222a902 100644 --- a/lib/puppet/parser/functions/abs.rb +++ b/lib/puppet/parser/functions/abs.rb @@ -9,8 +9,7 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "abs(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "abs(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] @@ -21,8 +20,7 @@ module Puppet::Parser::Functions elsif value.match(/^-?\d+$/) value = value.to_i else - raise(Puppet::ParseError, 'abs(): Requires float or ' + - 'integer to work with') + raise(Puppet::ParseError, 'abs(): Requires float or integer to work with') end end diff --git a/lib/puppet/parser/functions/any2bool.rb b/lib/puppet/parser/functions/any2bool.rb index f0f8f83..17612bf 100644 --- a/lib/puppet/parser/functions/any2bool.rb +++ b/lib/puppet/parser/functions/any2bool.rb @@ -15,8 +15,7 @@ This converts 'anything' to a boolean. In practise it does the following: EOS ) do |arguments| - raise(Puppet::ParseError, "any2bool(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 # If argument is already Boolean, return it if !!arguments[0] == arguments[0] diff --git a/lib/puppet/parser/functions/assert_private.rb b/lib/puppet/parser/functions/assert_private.rb index 66c79cc..62e2c6b 100644 --- a/lib/puppet/parser/functions/assert_private.rb +++ b/lib/puppet/parser/functions/assert_private.rb @@ -9,8 +9,7 @@ module Puppet::Parser::Functions EOS ) do |args| - raise(Puppet::ParseError, "assert_private(): Wrong number of arguments "+ - "given (#{args.size}}) for 0 or 1)") if args.size > 1 + 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') diff --git a/lib/puppet/parser/functions/base64.rb b/lib/puppet/parser/functions/base64.rb index a8998f2..d610146 100644 --- a/lib/puppet/parser/functions/base64.rb +++ b/lib/puppet/parser/functions/base64.rb @@ -1,3 +1,6 @@ + +# 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 => <<-'ENDHEREDOC') do |args| diff --git a/lib/puppet/parser/functions/bool2num.rb b/lib/puppet/parser/functions/bool2num.rb index 6ad6cf4..92e4dde 100644 --- a/lib/puppet/parser/functions/bool2num.rb +++ b/lib/puppet/parser/functions/bool2num.rb @@ -11,8 +11,7 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "bool2num(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = function_str2bool([arguments[0]]) diff --git a/lib/puppet/parser/functions/bool2str.rb b/lib/puppet/parser/functions/bool2str.rb index 7e36474..37d4a4e 100644 --- a/lib/puppet/parser/functions/bool2str.rb +++ b/lib/puppet/parser/functions/bool2str.rb @@ -20,8 +20,7 @@ module Puppet::Parser::Functions ) do |arguments| unless arguments.size == 1 or arguments.size == 3 - raise(Puppet::ParseError, "bool2str(): Wrong number of arguments " + - "given (#{arguments.size} for 3)") + raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)") end value = arguments[0] diff --git a/lib/puppet/parser/functions/camelcase.rb b/lib/puppet/parser/functions/camelcase.rb index d7f43f7..085b3c6 100644 --- a/lib/puppet/parser/functions/camelcase.rb +++ b/lib/puppet/parser/functions/camelcase.rb @@ -1,5 +1,6 @@ # # 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 @@ -8,15 +9,13 @@ Converts the case of a string or all strings in an array to camel case. EOS ) do |arguments| - raise(Puppet::ParseError, "camelcase(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) - raise(Puppet::ParseError, 'camelcase(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'camelcase(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/capitalize.rb b/lib/puppet/parser/functions/capitalize.rb index 98b2d16..096bc5d 100644 --- a/lib/puppet/parser/functions/capitalize.rb +++ b/lib/puppet/parser/functions/capitalize.rb @@ -1,5 +1,6 @@ # # 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 @@ -9,14 +10,12 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "capitalize(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'capitalize(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'capitalize(): Requires either array or string to work with') end if value.is_a?(Array) @@ -29,5 +28,3 @@ module Puppet::Parser::Functions return result end end - -# vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/ceiling.rb b/lib/puppet/parser/functions/ceiling.rb index 5f3b10b..bec4266 100644 --- a/lib/puppet/parser/functions/ceiling.rb +++ b/lib/puppet/parser/functions/ceiling.rb @@ -5,18 +5,15 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "ceiling(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + 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)") + 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 + raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.ceil end diff --git a/lib/puppet/parser/functions/chomp.rb b/lib/puppet/parser/functions/chomp.rb index c55841e..f9da50f 100644 --- a/lib/puppet/parser/functions/chomp.rb +++ b/lib/puppet/parser/functions/chomp.rb @@ -10,14 +10,12 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "chomp(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'chomp(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'chomp(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/chop.rb b/lib/puppet/parser/functions/chop.rb index b24ab78..809349d 100644 --- a/lib/puppet/parser/functions/chop.rb +++ b/lib/puppet/parser/functions/chop.rb @@ -12,14 +12,12 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "chop(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 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') + raise(Puppet::ParseError, 'chop(): Requires either an array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/clamp.rb b/lib/puppet/parser/functions/clamp.rb index 432c7c1..c4503fe 100644 --- a/lib/puppet/parser/functions/clamp.rb +++ b/lib/puppet/parser/functions/clamp.rb @@ -10,8 +10,7 @@ module Puppet::Parser::Functions args.flatten! - raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, ' + - 'need three to clamp') if args.size != 3 + raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3 # check values out args.each do |value| diff --git a/lib/puppet/parser/functions/concat.rb b/lib/puppet/parser/functions/concat.rb index 91edb4e..0a49cfe 100644 --- a/lib/puppet/parser/functions/concat.rb +++ b/lib/puppet/parser/functions/concat.rb @@ -17,8 +17,7 @@ Would result in: ) 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 + raise(Puppet::ParseError, "concat(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 a = arguments[0] diff --git a/lib/puppet/parser/functions/count.rb b/lib/puppet/parser/functions/count.rb index 52de1b8..cef2637 100644 --- a/lib/puppet/parser/functions/count.rb +++ b/lib/puppet/parser/functions/count.rb @@ -7,8 +7,7 @@ If called with only an array it counts the number of elements that are not nil/u ) do |args| if (args.size > 2) then - raise(ArgumentError, "count(): Wrong number of arguments "+ - "given #{args.size} for 1 or 2.") + raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.") end collection, item = args diff --git a/lib/puppet/parser/functions/defined_with_params.rb b/lib/puppet/parser/functions/defined_with_params.rb index 99687ae..c45a9df 100644 --- a/lib/puppet/parser/functions/defined_with_params.rb +++ b/lib/puppet/parser/functions/defined_with_params.rb @@ -24,7 +24,25 @@ ENDOFDOC params = {} end ret = false - if resource = findresource(reference.to_s) + + 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 + + if resource = findresource(type, title) matches = params.collect do |key, value| # eql? avoids bugs caused by monkeypatching in puppet resource_is_undef = resource[key].eql?(:undef) || resource[key].nil? diff --git a/lib/puppet/parser/functions/delete.rb b/lib/puppet/parser/functions/delete.rb index 466c55c..9dd5164 100644 --- a/lib/puppet/parser/functions/delete.rb +++ b/lib/puppet/parser/functions/delete.rb @@ -23,8 +23,7 @@ string, or key from a hash. EOS ) do |arguments| - raise(Puppet::ParseError, "delete(): Wrong number of arguments "+ - "given #{arguments.size} for 2") unless arguments.size == 2 + 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| @@ -34,8 +33,7 @@ string, or key from a hash. 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}.") + raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.") end end collection diff --git a/lib/puppet/parser/functions/delete_at.rb b/lib/puppet/parser/functions/delete_at.rb index 3eb4b53..daf3721 100644 --- a/lib/puppet/parser/functions/delete_at.rb +++ b/lib/puppet/parser/functions/delete_at.rb @@ -14,8 +14,7 @@ Would return: ['a','c'] EOS ) do |arguments| - raise(Puppet::ParseError, "delete_at(): Wrong number of arguments " + - "given (#{arguments.size} for 2)") if arguments.size < 2 + raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] @@ -26,8 +25,7 @@ Would return: ['a','c'] index = arguments[1] if index.is_a?(String) and not index.match(/^\d+$/) - raise(Puppet::ParseError, 'delete_at(): You must provide ' + - 'non-negative numeric index') + raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index') end result = array.clone @@ -36,8 +34,7 @@ Would return: ['a','c'] 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') + raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given') end result.delete_at(index) # We ignore the element that got deleted ... diff --git a/lib/puppet/parser/functions/delete_regex.rb b/lib/puppet/parser/functions/delete_regex.rb index d72b3e9..e5dc1fd 100644 --- a/lib/puppet/parser/functions/delete_regex.rb +++ b/lib/puppet/parser/functions/delete_regex.rb @@ -1,5 +1,6 @@ # -# delete_regex.rb +# 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 @@ -12,7 +13,7 @@ to be matched as an OR. delete_regex(['a','b','c','b'], 'b') Would return: ['a','c'] - + delete_regex(['a','b','c','b'], ['b', 'c']) Would return: ['a'] @@ -25,8 +26,7 @@ to be matched as an OR. EOS ) do |arguments| - raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments "+ - "given #{arguments.size} for 2") unless arguments.size == 2 + 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| @@ -34,8 +34,7 @@ to be matched as an OR. 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}.") + raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.") end end collection diff --git a/lib/puppet/parser/functions/delete_undef_values.rb b/lib/puppet/parser/functions/delete_undef_values.rb index f94d4da..00bd252 100644 --- a/lib/puppet/parser/functions/delete_undef_values.rb +++ b/lib/puppet/parser/functions/delete_undef_values.rb @@ -15,13 +15,10 @@ Would return: ['A','',false] EOS ) do |args| - raise(Puppet::ParseError, - "delete_undef_values(): Wrong number of arguments given " + - "(#{args.size})") if args.size < 1 + raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.size < 1 unless args[0].is_a? Array or args[0].is_a? Hash - raise(Puppet::ParseError, - "delete_undef_values(): expected an array or hash, got #{args[0]} type #{args[0].class} ") + 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) diff --git a/lib/puppet/parser/functions/delete_values.rb b/lib/puppet/parser/functions/delete_values.rb index f6c8c0e..e799aef 100644 --- a/lib/puppet/parser/functions/delete_values.rb +++ b/lib/puppet/parser/functions/delete_values.rb @@ -11,15 +11,12 @@ Would return: {'a'=>'A','c'=>'C','B'=>'D'} EOS ) do |arguments| - raise(Puppet::ParseError, - "delete_values(): Wrong number of arguments given " + - "(#{arguments.size} of 2)") if arguments.size != 2 + raise(Puppet::ParseError, "delete_values(): Wrong number of arguments given (#{arguments.size} of 2)") if arguments.size != 2 hash, item = arguments if not hash.is_a?(Hash) - raise(TypeError, "delete_values(): First argument must be a Hash. " + \ - "Given an argument of class #{hash.class}.") + 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 diff --git a/lib/puppet/parser/functions/deprecation.rb b/lib/puppet/parser/functions/deprecation.rb index cd64fe2..39d306a 100644 --- a/lib/puppet/parser/functions/deprecation.rb +++ b/lib/puppet/parser/functions/deprecation.rb @@ -4,8 +4,7 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "deprecation: Wrong number of arguments " + - "given (#{arguments.size} for 2)") unless arguments.size == 2 + raise(Puppet::ParseError, "deprecation: Wrong number of arguments given (#{arguments.size} for 2)") unless arguments.size == 2 key = arguments[0] message = arguments[1] diff --git a/lib/puppet/parser/functions/difference.rb b/lib/puppet/parser/functions/difference.rb index cd258f7..c9ac478 100644 --- a/lib/puppet/parser/functions/difference.rb +++ b/lib/puppet/parser/functions/difference.rb @@ -17,8 +17,7 @@ Would return: ["a"] ) do |arguments| # Two arguments are required - raise(Puppet::ParseError, "difference(): Wrong number of arguments " + - "given (#{arguments.size} for 2)") if arguments.size != 2 + raise(Puppet::ParseError, "difference(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] diff --git a/lib/puppet/parser/functions/dig44.rb b/lib/puppet/parser/functions/dig44.rb index 1e7c318..21c0a8c 100644 --- a/lib/puppet/parser/functions/dig44.rb +++ b/lib/puppet/parser/functions/dig44.rb @@ -42,19 +42,16 @@ missing. And the fourth argument can set a variable path separator. eos ) 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 + raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2 data, path, default = *arguments unless data.is_a?(Hash) or data.is_a?(Array) - raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, " << - "given #{data.class.name}") + raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") end unless path.is_a? Array - raise(Puppet::ParseError, "dig44(): second argument must be an array, " << - "given #{path.class.name}") + raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") end value = path.reduce(data) do |structure, key| diff --git a/lib/puppet/parser/functions/downcase.rb b/lib/puppet/parser/functions/downcase.rb index 040b84f..ab04f8a 100644 --- a/lib/puppet/parser/functions/downcase.rb +++ b/lib/puppet/parser/functions/downcase.rb @@ -1,5 +1,6 @@ # # 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 @@ -8,14 +9,12 @@ Converts the case of a string or all strings in an array to lower case. EOS ) do |arguments| - raise(Puppet::ParseError, "downcase(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "downcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'downcase(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'downcase(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/empty.rb b/lib/puppet/parser/functions/empty.rb index b5a3cde..4f77ad3 100644 --- a/lib/puppet/parser/functions/empty.rb +++ b/lib/puppet/parser/functions/empty.rb @@ -8,14 +8,12 @@ Returns true if the variable is empty. EOS ) do |arguments| - raise(Puppet::ParseError, "empty(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "empty(): 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.is_a?(String) || value.is_a?(Numeric) - raise(Puppet::ParseError, 'empty(): Requires either ' + - 'array, hash, string or integer to work with') + raise(Puppet::ParseError, 'empty(): Requires either array, hash, string or integer to work with') end if value.is_a?(Numeric) diff --git a/lib/puppet/parser/functions/enclose_ipv6.rb b/lib/puppet/parser/functions/enclose_ipv6.rb index 80ffc3a..1f8a454 100644 --- a/lib/puppet/parser/functions/enclose_ipv6.rb +++ b/lib/puppet/parser/functions/enclose_ipv6.rb @@ -16,12 +16,10 @@ Takes an array of ip addresses and encloses the ipv6 addresses with square brack end if (arguments.size != 1) then - raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments given #{arguments.size} for 1") end unless arguments[0].is_a?(String) or arguments[0].is_a?(Array) then - raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type "+ - "given #{arguments[0].class} expected String or Array") + raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type given #{arguments[0].class} expected String or Array") end input = [arguments[0]].flatten.compact @@ -32,8 +30,7 @@ Takes an array of ip addresses and encloses the ipv6 addresses with square brack begin ip = IPAddr.new(val) rescue *rescuable_exceptions - raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument "+ - "given #{val} is not an ip address.") + raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument given #{val} is not an ip address.") end val = "[#{ip.to_s}]" if ip.ipv6? end diff --git a/lib/puppet/parser/functions/ensure_packages.rb b/lib/puppet/parser/functions/ensure_packages.rb index 439af1e..1bf8bf1 100644 --- a/lib/puppet/parser/functions/ensure_packages.rb +++ b/lib/puppet/parser/functions/ensure_packages.rb @@ -11,15 +11,17 @@ third argument to the ensure_resource() function. ) do |arguments| if arguments.size > 2 or arguments.size == 0 - raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments " + - "given (#{arguments.size} for 1 or 2)") - elsif arguments.size == 2 and !arguments[1].is_a?(Hash) + raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments given (#{arguments.size} for 1 or 2)") + elsif arguments.size == 2 and !arguments[1].is_a?(Hash) raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') end 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 @@ -31,13 +33,19 @@ third argument to the ensure_resource() function. 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 { |package_name| + raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.length == 0 + if !findresource("Package[#{package_name}]") function_ensure_resource(['package', package_name, defaults ]) + end } end end diff --git a/lib/puppet/parser/functions/flatten.rb b/lib/puppet/parser/functions/flatten.rb index a1ed183..4401bdb 100644 --- a/lib/puppet/parser/functions/flatten.rb +++ b/lib/puppet/parser/functions/flatten.rb @@ -15,8 +15,7 @@ Would return: ['a','b','c'] EOS ) do |arguments| - raise(Puppet::ParseError, "flatten(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "flatten(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] diff --git a/lib/puppet/parser/functions/floor.rb b/lib/puppet/parser/functions/floor.rb index 9a6f014..9e4b504 100644 --- a/lib/puppet/parser/functions/floor.rb +++ b/lib/puppet/parser/functions/floor.rb @@ -5,18 +5,15 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "floor(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + 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)") + 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 + raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.floor end diff --git a/lib/puppet/parser/functions/fqdn_rotate.rb b/lib/puppet/parser/functions/fqdn_rotate.rb index b66431d..05bdcc7 100644 --- a/lib/puppet/parser/functions/fqdn_rotate.rb +++ b/lib/puppet/parser/functions/fqdn_rotate.rb @@ -15,15 +15,13 @@ Puppet::Parser::Functions.newfunction( 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.size < 1 + raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.size < 1 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') + raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with') end result = value.clone diff --git a/lib/puppet/parser/functions/glob.rb b/lib/puppet/parser/functions/glob.rb new file mode 100644 index 0000000..54cdda6 --- /dev/null +++ b/lib/puppet/parser/functions/glob.rb @@ -0,0 +1,22 @@ +# +# glob.rb +# + +module Puppet::Parser::Functions + newfunction(:glob, :type => :rvalue, :doc => <<-'EOS' + Returns an Array of file entries of a directory or an Array of directories. + Uses same patterns as Dir#glob + EOS + ) do |arguments| + + raise(Puppet::ParseError, "glob(): Wrong number of arguments given " + + "(#{arguments.size} for 1)") unless arguments.size == 1 + + pattern = arguments[0] + + raise(Puppet::ParseError, 'glob(): Requires either array or string ' + + 'to work') unless pattern.is_a?(String) || pattern.is_a?(Array) + + Dir.glob(pattern) + end +end diff --git a/lib/puppet/parser/functions/grep.rb b/lib/puppet/parser/functions/grep.rb index ceba9ec..c611a7e 100644 --- a/lib/puppet/parser/functions/grep.rb +++ b/lib/puppet/parser/functions/grep.rb @@ -18,8 +18,7 @@ Would return: ) do |arguments| if (arguments.size != 2) then - raise(Puppet::ParseError, "grep(): Wrong number of arguments "+ - "given #{arguments.size} for 2") + raise(Puppet::ParseError, "grep(): Wrong number of arguments given #{arguments.size} for 2") end a = arguments[0] diff --git a/lib/puppet/parser/functions/has_interface_with.rb b/lib/puppet/parser/functions/has_interface_with.rb index e762798..f6cb74b 100644 --- a/lib/puppet/parser/functions/has_interface_with.rb +++ b/lib/puppet/parser/functions/has_interface_with.rb @@ -19,8 +19,7 @@ has_interface_with("lo") => true EOS ) do |args| - raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments " + - "given (#{args.size} for 1 or 2)") if args.size < 1 or args.size > 2 + raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments given (#{args.size} for 1 or 2)") if args.size < 1 or args.size > 2 interfaces = lookupvar('interfaces') diff --git a/lib/puppet/parser/functions/has_ip_address.rb b/lib/puppet/parser/functions/has_ip_address.rb index 842c8ec..a0071c8 100644 --- a/lib/puppet/parser/functions/has_ip_address.rb +++ b/lib/puppet/parser/functions/has_ip_address.rb @@ -11,8 +11,7 @@ This function iterates through the 'interfaces' fact and checks the EOS ) do |args| - raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments " + - "given (#{args.size} for 1)") if args.size != 1 + 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) diff --git a/lib/puppet/parser/functions/has_ip_network.rb b/lib/puppet/parser/functions/has_ip_network.rb index 9ccf902..b02c0c0 100644 --- a/lib/puppet/parser/functions/has_ip_network.rb +++ b/lib/puppet/parser/functions/has_ip_network.rb @@ -11,8 +11,7 @@ This function iterates through the 'interfaces' fact and checks the EOS ) do |args| - raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments " + - "given (#{args.size} for 1)") if args.size != 1 + 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) diff --git a/lib/puppet/parser/functions/hash.rb b/lib/puppet/parser/functions/hash.rb index 89d0e07..22763f3 100644 --- a/lib/puppet/parser/functions/hash.rb +++ b/lib/puppet/parser/functions/hash.rb @@ -14,8 +14,7 @@ Would return: {'a'=>1,'b'=>2,'c'=>3} EOS ) do |arguments| - raise(Puppet::ParseError, "hash(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] @@ -30,8 +29,7 @@ Would return: {'a'=>1,'b'=>2,'c'=>3} array = array.flatten result = Hash[*array] rescue StandardError - raise(Puppet::ParseError, 'hash(): Unable to compute ' + - 'hash from array given') + raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given') end return result diff --git a/lib/puppet/parser/functions/intersection.rb b/lib/puppet/parser/functions/intersection.rb index bfbb4ba..8a438f4 100644 --- a/lib/puppet/parser/functions/intersection.rb +++ b/lib/puppet/parser/functions/intersection.rb @@ -15,8 +15,7 @@ This function returns an array of the intersection of two. ) do |arguments| # Two arguments are required - raise(Puppet::ParseError, "intersection(): Wrong number of arguments " + - "given (#{arguments.size} for 2)") if arguments.size != 2 + raise(Puppet::ParseError, "intersection(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 first = arguments[0] second = arguments[1] diff --git a/lib/puppet/parser/functions/is_array.rb b/lib/puppet/parser/functions/is_array.rb index 1d2c0fa..a33afe4 100644 --- a/lib/puppet/parser/functions/is_array.rb +++ b/lib/puppet/parser/functions/is_array.rb @@ -10,8 +10,7 @@ Returns true if the variable passed to this function is an array. 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.size < 1 + raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 type = arguments[0] diff --git a/lib/puppet/parser/functions/is_bool.rb b/lib/puppet/parser/functions/is_bool.rb index 83d2ebe..2ebe430 100644 --- a/lib/puppet/parser/functions/is_bool.rb +++ b/lib/puppet/parser/functions/is_bool.rb @@ -10,8 +10,7 @@ Returns true if the variable passed to this function is a boolean. 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 + raise(Puppet::ParseError, "is_bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] diff --git a/lib/puppet/parser/functions/is_domain_name.rb b/lib/puppet/parser/functions/is_domain_name.rb index 90ede32..247db3b 100644 --- a/lib/puppet/parser/functions/is_domain_name.rb +++ b/lib/puppet/parser/functions/is_domain_name.rb @@ -9,8 +9,7 @@ Returns true if the string passed to this function is a syntactically correct do ) do |arguments| if (arguments.size != 1) then - raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow string types diff --git a/lib/puppet/parser/functions/is_email_address.rb b/lib/puppet/parser/functions/is_email_address.rb index 4fb0229..bcd7921 100644 --- a/lib/puppet/parser/functions/is_email_address.rb +++ b/lib/puppet/parser/functions/is_email_address.rb @@ -8,8 +8,7 @@ Returns true if the string passed to this function is a valid email address. EOS ) do |arguments| if arguments.size != 1 - raise(Puppet::ParseError, 'is_email_address(): Wrong number of arguments '\ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_email_address(): Wrong number of arguments given #{arguments.size} for 1") end # Taken from http://emailregex.com/ (simpler regex) diff --git a/lib/puppet/parser/functions/is_float.rb b/lib/puppet/parser/functions/is_float.rb index 1186458..aa84a2b 100644 --- a/lib/puppet/parser/functions/is_float.rb +++ b/lib/puppet/parser/functions/is_float.rb @@ -11,8 +11,7 @@ Returns true if the variable passed to this function is a float. 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) then - raise(Puppet::ParseError, "is_float(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_float(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] diff --git a/lib/puppet/parser/functions/is_function_available.rb b/lib/puppet/parser/functions/is_function_available.rb index 6da82c8..50cd5e1 100644 --- a/lib/puppet/parser/functions/is_function_available.rb +++ b/lib/puppet/parser/functions/is_function_available.rb @@ -11,8 +11,7 @@ true if the function exists, false if not. ) do |arguments| if (arguments.size != 1) then - raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow String types diff --git a/lib/puppet/parser/functions/is_hash.rb b/lib/puppet/parser/functions/is_hash.rb index ad907f0..3162f7d 100644 --- a/lib/puppet/parser/functions/is_hash.rb +++ b/lib/puppet/parser/functions/is_hash.rb @@ -8,8 +8,7 @@ Returns true if the variable passed to this function is a hash. EOS ) do |arguments| - raise(Puppet::ParseError, "is_hash(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "is_hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] diff --git a/lib/puppet/parser/functions/is_integer.rb b/lib/puppet/parser/functions/is_integer.rb index e04fd1f..8965b15 100644 --- a/lib/puppet/parser/functions/is_integer.rb +++ b/lib/puppet/parser/functions/is_integer.rb @@ -16,8 +16,7 @@ If given any other argument `false` is returned. 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) then - raise(Puppet::ParseError, "is_integer(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_integer(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] diff --git a/lib/puppet/parser/functions/is_ip_address.rb b/lib/puppet/parser/functions/is_ip_address.rb index 5f1d765..79ddb98 100644 --- a/lib/puppet/parser/functions/is_ip_address.rb +++ b/lib/puppet/parser/functions/is_ip_address.rb @@ -13,8 +13,7 @@ Returns true if the string passed to this function is a valid IP address. 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) then - raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1") end begin diff --git a/lib/puppet/parser/functions/is_ipv4_address.rb b/lib/puppet/parser/functions/is_ipv4_address.rb index 1764e61..91869b6 100644 --- a/lib/puppet/parser/functions/is_ipv4_address.rb +++ b/lib/puppet/parser/functions/is_ipv4_address.rb @@ -13,8 +13,7 @@ Returns true if the string passed to this function is a valid IPv4 address. 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) then - raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments given #{arguments.size} for 1") end begin diff --git a/lib/puppet/parser/functions/is_ipv6_address.rb b/lib/puppet/parser/functions/is_ipv6_address.rb index 7ca4997..4d96202 100644 --- a/lib/puppet/parser/functions/is_ipv6_address.rb +++ b/lib/puppet/parser/functions/is_ipv6_address.rb @@ -13,8 +13,7 @@ Returns true if the string passed to this function is a valid IPv6 address. require 'ipaddr' if (arguments.size != 1) then - raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments given #{arguments.size} for 1") end begin diff --git a/lib/puppet/parser/functions/is_mac_address.rb b/lib/puppet/parser/functions/is_mac_address.rb index 2619d44..5993ed2 100644 --- a/lib/puppet/parser/functions/is_mac_address.rb +++ b/lib/puppet/parser/functions/is_mac_address.rb @@ -9,8 +9,7 @@ Returns true if the string passed to this function is a valid mac address. ) do |arguments| if (arguments.size != 1) then - raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments given #{arguments.size} for 1") end mac = arguments[0] diff --git a/lib/puppet/parser/functions/is_numeric.rb b/lib/puppet/parser/functions/is_numeric.rb index 4a55225..7800edd 100644 --- a/lib/puppet/parser/functions/is_numeric.rb +++ b/lib/puppet/parser/functions/is_numeric.rb @@ -27,8 +27,7 @@ Valid examples: 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) then - raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] diff --git a/lib/puppet/parser/functions/is_string.rb b/lib/puppet/parser/functions/is_string.rb index 31ee91e..0ed6aec 100644 --- a/lib/puppet/parser/functions/is_string.rb +++ b/lib/puppet/parser/functions/is_string.rb @@ -10,8 +10,7 @@ Returns true if the variable passed to this function is a string. 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.size < 1 + raise(Puppet::ParseError, "is_string(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 type = arguments[0] diff --git a/lib/puppet/parser/functions/join.rb b/lib/puppet/parser/functions/join.rb index 6c0a6ba..1c17997 100644 --- a/lib/puppet/parser/functions/join.rb +++ b/lib/puppet/parser/functions/join.rb @@ -15,8 +15,7 @@ Would result in: "a,b,c" ) 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.size < 1 + raise(Puppet::ParseError, "join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] diff --git a/lib/puppet/parser/functions/join_keys_to_values.rb b/lib/puppet/parser/functions/join_keys_to_values.rb index e3baf9f..d8966ba 100644 --- a/lib/puppet/parser/functions/join_keys_to_values.rb +++ b/lib/puppet/parser/functions/join_keys_to_values.rb @@ -23,22 +23,19 @@ Would result in: ["a is 1","b is 2","b is 3"] # Validate the number of arguments. if arguments.size != 2 - raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two " + - "arguments, but #{arguments.size} given.") + raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.") end # Validate the first argument. hash = arguments[0] if not hash.is_a?(Hash) - raise(TypeError, "join_keys_to_values(): The first argument must be a " + - "hash, but a #{hash.class} was given.") + 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] if not separator.is_a?(String) - raise(TypeError, "join_keys_to_values(): The second argument must be a " + - "string, but a #{separator.class} was given.") + 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. diff --git a/lib/puppet/parser/functions/keys.rb b/lib/puppet/parser/functions/keys.rb index f0d13b6..199e319 100644 --- a/lib/puppet/parser/functions/keys.rb +++ b/lib/puppet/parser/functions/keys.rb @@ -8,8 +8,7 @@ Returns the keys of a hash as an array. EOS ) do |arguments| - raise(Puppet::ParseError, "keys(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 hash = arguments[0] diff --git a/lib/puppet/parser/functions/lstrip.rb b/lib/puppet/parser/functions/lstrip.rb index 624e4c8..9a9ee29 100644 --- a/lib/puppet/parser/functions/lstrip.rb +++ b/lib/puppet/parser/functions/lstrip.rb @@ -8,14 +8,12 @@ Strips leading spaces to the left of a string. EOS ) do |arguments| - raise(Puppet::ParseError, "lstrip(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "lstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'lstrip(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'lstrip(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/max.rb b/lib/puppet/parser/functions/max.rb index 60fb94a..758c42c 100644 --- a/lib/puppet/parser/functions/max.rb +++ b/lib/puppet/parser/functions/max.rb @@ -5,8 +5,7 @@ module Puppet::Parser::Functions EOS ) do |args| - raise(Puppet::ParseError, "max(): Wrong number of arguments " + - "need at least one") if args.size == 0 + raise(Puppet::ParseError, "max(): Wrong number of arguments need at least one") if args.size == 0 # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible diff --git a/lib/puppet/parser/functions/member.rb b/lib/puppet/parser/functions/member.rb index 1e5b3de..fb93452 100644 --- a/lib/puppet/parser/functions/member.rb +++ b/lib/puppet/parser/functions/member.rb @@ -30,8 +30,7 @@ would return: false EOS ) do |arguments| - raise(Puppet::ParseError, "member(): Wrong number of arguments " + - "given (#{arguments.size} for 2)") if arguments.size < 2 + raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] @@ -50,8 +49,7 @@ would return: false end - raise(Puppet::ParseError, 'member(): You must provide item ' + - 'to search for within array given') if item.respond_to?('empty?') && item.empty? + 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? diff --git a/lib/puppet/parser/functions/min.rb b/lib/puppet/parser/functions/min.rb index 6bd6ebf..f10a2b2 100644 --- a/lib/puppet/parser/functions/min.rb +++ b/lib/puppet/parser/functions/min.rb @@ -5,8 +5,7 @@ module Puppet::Parser::Functions EOS ) do |args| - raise(Puppet::ParseError, "min(): Wrong number of arguments " + - "need at least one") if args.size == 0 + raise(Puppet::ParseError, "min(): Wrong number of arguments need at least one") if args.size == 0 # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible diff --git a/lib/puppet/parser/functions/num2bool.rb b/lib/puppet/parser/functions/num2bool.rb index af0e6ed..9ad59b2 100644 --- a/lib/puppet/parser/functions/num2bool.rb +++ b/lib/puppet/parser/functions/num2bool.rb @@ -10,8 +10,7 @@ become true. EOS ) do |arguments| - raise(Puppet::ParseError, "num2bool(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "num2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 number = arguments[0] diff --git a/lib/puppet/parser/functions/prefix.rb b/lib/puppet/parser/functions/prefix.rb index ac1c58a..b1c1e35 100644 --- a/lib/puppet/parser/functions/prefix.rb +++ b/lib/puppet/parser/functions/prefix.rb @@ -15,8 +15,7 @@ Will return: ['pa','pb','pc'] ) 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.size < 1 + raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 enumerable = arguments[0] diff --git a/lib/puppet/parser/functions/pw_hash.rb b/lib/puppet/parser/functions/pw_hash.rb index 41d4223..adcc719 100644 --- a/lib/puppet/parser/functions/pw_hash.rb +++ b/lib/puppet/parser/functions/pw_hash.rb @@ -1,3 +1,6 @@ + +# 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, @@ -24,6 +27,13 @@ Puppet::Parser::Functions::newfunction( 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 or args[0].nil? raise ArgumentError, "pw_hash(): second argument must be a string" unless args[1].is_a? String hashes = { 'md5' => '1', diff --git a/lib/puppet/parser/functions/range.rb b/lib/puppet/parser/functions/range.rb index d690df7..72c373a 100644 --- a/lib/puppet/parser/functions/range.rb +++ b/lib/puppet/parser/functions/range.rb @@ -37,8 +37,7 @@ Will return: [0,2,4,6,8] EOS ) do |arguments| - raise(Puppet::ParseError, 'range(): Wrong number of ' + - 'arguments given (0 for 1)') if arguments.size == 0 + raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.size == 0 if arguments.size > 1 start = arguments[0] @@ -57,8 +56,7 @@ Will return: [0,2,4,6,8] type = m[2] step = 1 elsif value.match(/^.+$/) - raise(Puppet::ParseError, "range(): Unable to compute range " + - "from the value: #{value}") + raise(Puppet::ParseError, "range(): Unable to compute range from the value: #{value}") else raise(Puppet::ParseError, "range(): Unknown range format: #{value}") end diff --git a/lib/puppet/parser/functions/regexpescape.rb b/lib/puppet/parser/functions/regexpescape.rb index 477ee87..2cfa3bb 100644 --- a/lib/puppet/parser/functions/regexpescape.rb +++ b/lib/puppet/parser/functions/regexpescape.rb @@ -7,14 +7,12 @@ module Puppet::Parser::Functions Requires either a single string or an array as an input. EOS ) do |arguments| # rubocop:disable Style/ClosingParenthesisIndentation - raise(Puppet::ParseError, 'regexpescape(): Wrong number of arguments ' \ - "given (#{arguments.size} for 1)") if arguments.empty? + 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') + raise(Puppet::ParseError, 'regexpescape(): Requires either array or string to work with') end result = if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/reverse.rb b/lib/puppet/parser/functions/reverse.rb index 7f1018f..aca98ce 100644 --- a/lib/puppet/parser/functions/reverse.rb +++ b/lib/puppet/parser/functions/reverse.rb @@ -8,14 +8,12 @@ Reverses the order of a string or array. EOS ) do |arguments| - raise(Puppet::ParseError, "reverse(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "reverse(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'reverse(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'reverse(): Requires either array or string to work with') end result = value.reverse diff --git a/lib/puppet/parser/functions/round.rb b/lib/puppet/parser/functions/round.rb new file mode 100644 index 0000000..489c301 --- /dev/null +++ b/lib/puppet/parser/functions/round.rb @@ -0,0 +1,33 @@ +# +# round.rb +# + +module Puppet::Parser::Functions + newfunction(:round, :type => :rvalue, :doc => <<-EOS + Rounds a number to the nearest integer + + *Examples:* + + round(2.9) + + returns: 3 + + round(2.4) + + returns: 2 + + EOS + ) 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 diff --git a/lib/puppet/parser/functions/rstrip.rb b/lib/puppet/parser/functions/rstrip.rb index 0cf8d22..e24abd5 100644 --- a/lib/puppet/parser/functions/rstrip.rb +++ b/lib/puppet/parser/functions/rstrip.rb @@ -8,14 +8,12 @@ Strips leading spaces to the right of the string. EOS ) do |arguments| - raise(Puppet::ParseError, "rstrip(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "rstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'rstrip(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'rstrip(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/shell_escape.rb b/lib/puppet/parser/functions/shell_escape.rb index 447fe35..7306b7c 100644 --- a/lib/puppet/parser/functions/shell_escape.rb +++ b/lib/puppet/parser/functions/shell_escape.rb @@ -15,8 +15,7 @@ This function behaves the same as ruby's Shellwords.shellescape() function. EOS ) do |arguments| - raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + 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 diff --git a/lib/puppet/parser/functions/shell_join.rb b/lib/puppet/parser/functions/shell_join.rb index 05aeb95..682ed8d 100644 --- a/lib/puppet/parser/functions/shell_join.rb +++ b/lib/puppet/parser/functions/shell_join.rb @@ -13,8 +13,7 @@ This function behaves the same as ruby's Shellwords.shelljoin() function EOS ) do |arguments| - raise(Puppet::ParseError, "shell_join(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "shell_join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] diff --git a/lib/puppet/parser/functions/shell_split.rb b/lib/puppet/parser/functions/shell_split.rb index 0446448..09e6e78 100644 --- a/lib/puppet/parser/functions/shell_split.rb +++ b/lib/puppet/parser/functions/shell_split.rb @@ -12,8 +12,7 @@ This function behaves the same as ruby's Shellwords.shellsplit() function EOS ) do |arguments| - raise(Puppet::ParseError, "shell_split(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "shell_split(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 string = arguments[0].to_s diff --git a/lib/puppet/parser/functions/shuffle.rb b/lib/puppet/parser/functions/shuffle.rb index 30c663d..942cbce 100644 --- a/lib/puppet/parser/functions/shuffle.rb +++ b/lib/puppet/parser/functions/shuffle.rb @@ -8,14 +8,12 @@ Randomizes the order of a string or array elements. EOS ) do |arguments| - raise(Puppet::ParseError, "shuffle(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'shuffle(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with') end result = value.clone diff --git a/lib/puppet/parser/functions/size.rb b/lib/puppet/parser/functions/size.rb index 0d6cc96..b503aa0 100644 --- a/lib/puppet/parser/functions/size.rb +++ b/lib/puppet/parser/functions/size.rb @@ -8,11 +8,12 @@ Returns the number of elements in a string, an array or a hash EOS ) do |arguments| - raise(Puppet::ParseError, "size(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 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 @@ -26,8 +27,7 @@ Returns the number of elements in a string, an array or a hash # Float(item) - raise(Puppet::ParseError, 'size(): Requires either ' + - 'string, array or hash to work with') + raise(Puppet::ParseError, 'size(): Requires either string, array or hash to work with') rescue ArgumentError result = item.size diff --git a/lib/puppet/parser/functions/sort.rb b/lib/puppet/parser/functions/sort.rb index cefbe54..d7792f5 100644 --- a/lib/puppet/parser/functions/sort.rb +++ b/lib/puppet/parser/functions/sort.rb @@ -1,5 +1,6 @@ # -# sort.rb +# 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 @@ -9,8 +10,7 @@ Sorts strings and arrays lexically. ) do |arguments| if (arguments.size != 1) then - raise(Puppet::ParseError, "sort(): Wrong number of arguments "+ - "given #{arguments.size} for 1") + raise(Puppet::ParseError, "sort(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] diff --git a/lib/puppet/parser/functions/squeeze.rb b/lib/puppet/parser/functions/squeeze.rb index 81fadfd..f5757d1 100644 --- a/lib/puppet/parser/functions/squeeze.rb +++ b/lib/puppet/parser/functions/squeeze.rb @@ -9,8 +9,7 @@ Returns a new string where runs of the same character that occur in this set are ) do |arguments| if ((arguments.size != 2) and (arguments.size != 1)) then - raise(Puppet::ParseError, "squeeze(): Wrong number of arguments "+ - "given #{arguments.size} for 2 or 1") + raise(Puppet::ParseError, "squeeze(): Wrong number of arguments given #{arguments.size} for 2 or 1") end item = arguments[0] diff --git a/lib/puppet/parser/functions/str2bool.rb b/lib/puppet/parser/functions/str2bool.rb index 472506d..38ad1ce 100644 --- a/lib/puppet/parser/functions/str2bool.rb +++ b/lib/puppet/parser/functions/str2bool.rb @@ -10,8 +10,7 @@ like: 0, F,f, N,n, false, FALSE, no to 'false'. EOS ) do |arguments| - raise(Puppet::ParseError, "str2bool(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 string = arguments[0] @@ -21,8 +20,7 @@ like: 0, F,f, N,n, false, FALSE, no to 'false'. end unless string.is_a?(String) - raise(Puppet::ParseError, 'str2bool(): Requires ' + - 'string to work with') + raise(Puppet::ParseError, 'str2bool(): Requires string to work with') end # We consider all the yes, no, y, n and so on too ... diff --git a/lib/puppet/parser/functions/str2saltedsha512.rb b/lib/puppet/parser/functions/str2saltedsha512.rb index 7fe7b01..0410c62 100644 --- a/lib/puppet/parser/functions/str2saltedsha512.rb +++ b/lib/puppet/parser/functions/str2saltedsha512.rb @@ -1,5 +1,6 @@ # -# str2saltedsha512.rb +# 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 @@ -12,14 +13,12 @@ manifests as a valid password attribute. ) do |arguments| require 'digest/sha2' - raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments " + - "passed (#{arguments.size} but we require 1)") if arguments.size != 1 + 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}") + raise(Puppet::ParseError, "str2saltedsha512(): Requires a String argument, you passed: #{password.class}") end seedint = rand(2**31 - 1) diff --git a/lib/puppet/parser/functions/strftime.rb b/lib/puppet/parser/functions/strftime.rb index 0b52ade..deae329 100644 --- a/lib/puppet/parser/functions/strftime.rb +++ b/lib/puppet/parser/functions/strftime.rb @@ -1,5 +1,6 @@ # -# strftime.rb +# 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 @@ -71,13 +72,11 @@ To return the date: ) 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.size < 1 + raise(Puppet::ParseError, "strftime(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 format = arguments[0] - raise(Puppet::ParseError, 'strftime(): You must provide ' + - 'format for evaluation') if format.empty? + 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] diff --git a/lib/puppet/parser/functions/strip.rb b/lib/puppet/parser/functions/strip.rb index 3fac47d..9e8366f 100644 --- a/lib/puppet/parser/functions/strip.rb +++ b/lib/puppet/parser/functions/strip.rb @@ -15,14 +15,12 @@ Would result in: "aaa" EOS ) do |arguments| - raise(Puppet::ParseError, "strip(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "strip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'strip(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'strip(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/suffix.rb b/lib/puppet/parser/functions/suffix.rb index 2908434..7c5057d 100644 --- a/lib/puppet/parser/functions/suffix.rb +++ b/lib/puppet/parser/functions/suffix.rb @@ -16,8 +16,7 @@ Will return: ['ap','bp','cp'] ) 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.size < 1 + raise(Puppet::ParseError, "suffix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 enumerable = arguments[0] diff --git a/lib/puppet/parser/functions/swapcase.rb b/lib/puppet/parser/functions/swapcase.rb index eb7fe13..f3276fb 100644 --- a/lib/puppet/parser/functions/swapcase.rb +++ b/lib/puppet/parser/functions/swapcase.rb @@ -1,5 +1,6 @@ # # 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 @@ -14,14 +15,12 @@ Would result in: "AbCd" EOS ) do |arguments| - raise(Puppet::ParseError, "swapcase(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "swapcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'swapcase(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'swapcase(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/time.rb b/lib/puppet/parser/functions/time.rb index c574747..d7780c8 100644 --- a/lib/puppet/parser/functions/time.rb +++ b/lib/puppet/parser/functions/time.rb @@ -18,8 +18,7 @@ Will return something like: 1311972653 time_zone = arguments[0] if arguments[0] if (arguments.size != 0) and (arguments.size != 1) then - raise(Puppet::ParseError, "time(): Wrong number of arguments "+ - "given #{arguments.size} for 0 or 1") + raise(Puppet::ParseError, "time(): Wrong number of arguments given #{arguments.size} for 0 or 1") end time = Time.new diff --git a/lib/puppet/parser/functions/to_bytes.rb b/lib/puppet/parser/functions/to_bytes.rb index df490ea..bf72503 100644 --- a/lib/puppet/parser/functions/to_bytes.rb +++ b/lib/puppet/parser/functions/to_bytes.rb @@ -7,8 +7,7 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] diff --git a/lib/puppet/parser/functions/type3x.rb b/lib/puppet/parser/functions/type3x.rb index 0800b4a..b17380e 100644 --- a/lib/puppet/parser/functions/type3x.rb +++ b/lib/puppet/parser/functions/type3x.rb @@ -16,8 +16,7 @@ Returns the type when passed a value. Type can be one of: * boolean EOS ) do |args| - raise(Puppet::ParseError, "type3x(): Wrong number of arguments " + - "given (#{args.size} for 1)") if args.size < 1 + raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") if args.size < 1 value = args[0] diff --git a/lib/puppet/parser/functions/union.rb b/lib/puppet/parser/functions/union.rb index 6c5bb83..abe2dc8 100644 --- a/lib/puppet/parser/functions/union.rb +++ b/lib/puppet/parser/functions/union.rb @@ -15,8 +15,7 @@ Would return: ["a","b","c","d"] ) 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 + 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) diff --git a/lib/puppet/parser/functions/unique.rb b/lib/puppet/parser/functions/unique.rb index cf770f3..1e2a895 100644 --- a/lib/puppet/parser/functions/unique.rb +++ b/lib/puppet/parser/functions/unique.rb @@ -24,14 +24,16 @@ This returns: EOS ) do |arguments| - raise(Puppet::ParseError, "unique(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + 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.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'unique(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'unique(): Requires either array or string to work with') end result = value.clone diff --git a/lib/puppet/parser/functions/upcase.rb b/lib/puppet/parser/functions/upcase.rb index 44b3bcd..e847e51 100644 --- a/lib/puppet/parser/functions/upcase.rb +++ b/lib/puppet/parser/functions/upcase.rb @@ -1,5 +1,6 @@ # -# upcase.rb +# 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 @@ -16,14 +17,12 @@ Will return: EOS ) do |arguments| - raise(Puppet::ParseError, "upcase(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size != 1 + 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') + raise(Puppet::ParseError, 'upcase(): Requires an array, hash or object that responds to upcase in order to work') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/uriescape.rb b/lib/puppet/parser/functions/uriescape.rb index 45bbed2..4c5c400 100644 --- a/lib/puppet/parser/functions/uriescape.rb +++ b/lib/puppet/parser/functions/uriescape.rb @@ -1,5 +1,6 @@ # # 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. # require 'uri' @@ -10,14 +11,12 @@ module Puppet::Parser::Functions EOS ) do |arguments| - raise(Puppet::ParseError, "uriescape(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "uriescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'uriescape(): Requires either ' + - 'array or string to work with') + raise(Puppet::ParseError, 'uriescape(): Requires either array or string to work with') end if value.is_a?(Array) diff --git a/lib/puppet/parser/functions/validate_domain_name.rb b/lib/puppet/parser/functions/validate_domain_name.rb new file mode 100644 index 0000000..c3fad78 --- /dev/null +++ b/lib/puppet/parser/functions/validate_domain_name.rb @@ -0,0 +1,39 @@ +module Puppet::Parser::Functions + newfunction(:validate_domain_name, :doc => <<-ENDHEREDOC + 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') + + ENDHEREDOC + ) 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 diff --git a/lib/puppet/parser/functions/values.rb b/lib/puppet/parser/functions/values.rb index 1606756..0ca236c 100644 --- a/lib/puppet/parser/functions/values.rb +++ b/lib/puppet/parser/functions/values.rb @@ -21,8 +21,7 @@ This example would return: EOS ) do |arguments| - raise(Puppet::ParseError, "values(): Wrong number of arguments " + - "given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 hash = arguments[0] diff --git a/lib/puppet/parser/functions/values_at.rb b/lib/puppet/parser/functions/values_at.rb index f350f53..04a3d1a 100644 --- a/lib/puppet/parser/functions/values_at.rb +++ b/lib/puppet/parser/functions/values_at.rb @@ -29,8 +29,7 @@ Would return ['a','c','d']. EOS ) do |arguments| - raise(Puppet::ParseError, "values_at(): Wrong number of " + - "arguments given (#{arguments.size} for 2)") if arguments.size < 2 + raise(Puppet::ParseError, "values_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments.shift @@ -41,8 +40,7 @@ Would return ['a','c','d']. indices = [arguments.shift].flatten() # Get them all ... Pokemon ... if not indices or indices.empty? - raise(Puppet::ParseError, 'values_at(): You must provide ' + - 'at least one positive index to collect') + raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect') end result = [] @@ -57,11 +55,9 @@ Would return ['a','c','d']. type = m[2] if start > stop - raise(Puppet::ParseError, 'values_at(): Stop index in ' + - 'given indices range is smaller than the start index') + raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index') elsif stop > array.size - 1 # First element is at index 0 is it not? - raise(Puppet::ParseError, 'values_at(): Stop index in ' + - 'given indices range exceeds array size') + raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size') end range = case type @@ -73,16 +69,14 @@ Would return ['a','c','d']. else # Only positive numbers allowed in this case ... if not i.match(/^\d+$/) - raise(Puppet::ParseError, 'values_at(): Unknown format ' + - 'of given index') + 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') + raise(Puppet::ParseError, 'values_at(): Given index exceeds array size') end indices_list << i diff --git a/lib/puppet/parser/functions/zip.rb b/lib/puppet/parser/functions/zip.rb index 3074f28..13e24b6 100644 --- a/lib/puppet/parser/functions/zip.rb +++ b/lib/puppet/parser/functions/zip.rb @@ -17,8 +17,7 @@ Would result in: ) 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 + raise(Puppet::ParseError, "zip(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 a = arguments[0] b = arguments[1] diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb index beeb430..16f2709 100644 --- a/lib/puppet/provider/file_line/ruby.rb +++ b/lib/puppet/provider/file_line/ruby.rb @@ -1,32 +1,42 @@ Puppet::Type.type(:file_line).provide(:ruby) do def exists? - if resource[:replace].to_s != 'true' and count_matches(match_regex) > 0 - true + found = false + lines_count = 0 + lines.each do |line| + found = line.chomp == resource[:line] + if found + lines_count += 1 + end + end + if resource[:match] == nil + found = lines_count > 0 else - lines.find do |line| - if resource[:ensure].to_s == 'absent' and resource[:match_for_absence].to_s == 'true' - line.chomp =~ Regexp.new(resource[:match]) - else - line.chomp == resource[:line].chomp - end + match_count = count_matches(new_match_regex) + if resource[:append_on_no_match].to_s == 'false' + found = true + elsif resource[:replace].to_s == 'true' + found = lines_count > 0 && lines_count == match_count + else + found = match_count > 0 end end + found end def create - unless resource[:replace].to_s != 'true' and count_matches(match_regex) > 0 + unless 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 - append_line + handle_append_line end end end def destroy - if resource[:match_for_absence].to_s == 'true' and resource[:match] + if resource[:match_for_absence].to_s == 'true' && resource[:match] handle_destroy_with_match else handle_destroy_line @@ -34,34 +44,49 @@ Puppet::Type.type(:file_line).provide(:ruby) do 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]) + begin + @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 end - def match_regex + 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| line.match(regex) }.size + end + def handle_create_with_match() - regex_after = resource[:after] ? Regexp.new(resource[:after]) : nil - match_count = count_matches(match_regex) + 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 |l| - fh.puts(match_regex.match(l) ? resource[:line] : l) - if (match_count == 0 and regex_after) - if regex_after.match(l) + lines.each do |line| + fh.puts(match_regex.match(line) ? resource[:line] : line) + if match_count == 0 && 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. + match_count += 1 # Increment match_count to indicate that the new line has been inserted. end end end @@ -73,32 +98,29 @@ Puppet::Type.type(:file_line).provide(:ruby) do end def handle_create_with_after - regex = Regexp.new(resource[:after]) - count = count_matches(regex) + after_regex = new_after_regex + after_count = count_matches(after_regex) - if count > 1 && resource[:multiple].to_s != 'true' - raise Puppet::Error, "#{count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." + 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 |l| - fh.puts(l) - if regex.match(l) then + 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 - end - if (count == 0) # append the line to the end of the file - append_line + if (after_count == 0) + fh.puts(resource[:line]) + end end end - def count_matches(regex) - lines.select{|l| l.match(regex)}.size - 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]}'" @@ -106,27 +128,23 @@ Puppet::Type.type(:file_line).provide(:ruby) do local_lines = lines File.open(resource[:path],'w') do |fh| - fh.write(local_lines.reject{|l| match_regex.match(l) }.join('')) + 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{|l| l.chomp == resource[:line] }.join('')) + fh.write(local_lines.reject{ |line| line.chomp == resource[:line] }.join('')) end end - ## - # append the line to the file. - # - # @api private - def append_line - File.open(resource[:path], 'w') do |fh| - lines.each do |l| - fh.puts(l) + def handle_append_line + File.open(resource[:path],'w') do |fh| + lines.each do |line| + fh.puts(line) end - fh.puts resource[:line] + fh.puts(resource[:line]) end end end diff --git a/lib/puppet/type/file_line.rb b/lib/puppet/type/file_line.rb index 7b7d44e..06be552 100644 --- a/lib/puppet/type/file_line.rb +++ b/lib/puppet/type/file_line.rb @@ -34,12 +34,16 @@ Puppet::Type.newtype(:file_line) do 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. - Match Example With `ensure => absent`: + 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', - line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } @@ -48,6 +52,38 @@ Puppet::Type.newtype(:file_line) do 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. EOT @@ -88,8 +124,16 @@ Puppet::Type.newtype(:file_line) do ' This is also takes a regex.' end - newparam(:line) do + # 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 @@ -107,6 +151,17 @@ Puppet::Type.newtype(:file_line) do defaultto true 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] diff --git a/locales/config.yaml b/locales/config.yaml new file mode 100644 index 0000000..66abac1 --- /dev/null +++ b/locales/config.yaml @@ -0,0 +1,26 @@ +--- +# 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 <project_name>.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 + # <project_name> + 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' + diff --git a/locales/ja/puppetlabs-stdlib.po b/locales/ja/puppetlabs-stdlib.po new file mode 100644 index 0000000..c154c2f --- /dev/null +++ b/locales/ja/puppetlabs-stdlib.po @@ -0,0 +1,26 @@ +# +#, 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: 梅田智世 <c-umeda@nifty.com>, 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 モジュールの標準ライブラリ" diff --git a/locales/puppetlabs-stdlib.pot b/locales/puppetlabs-stdlib.pot new file mode 100644 index 0000000..2608675 --- /dev/null +++ b/locales/puppetlabs-stdlib.pot @@ -0,0 +1,23 @@ +#, 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 <EMAIL@ADDRESS>\n" +"Language-Team: LANGUAGE <LL@li.org>\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 "" diff --git a/metadata.json b/metadata.json index 82078bf..f1f9562 100644 --- a/metadata.json +++ b/metadata.json @@ -1,6 +1,6 @@ { "name": "puppetlabs-stdlib", - "version": "4.13.1", + "version": "4.20.0", "author": "puppetlabs", "summary": "Standard library of resources for Puppet modules.", "license": "Apache-2.0", @@ -55,7 +55,6 @@ { "operatingsystem": "Debian", "operatingsystemrelease": [ - "6", "7", "8" ] @@ -63,18 +62,15 @@ { "operatingsystem": "Ubuntu", "operatingsystemrelease": [ - "10.04", - "12.04", "14.04", - "16.06" + "16.04" ] }, { "operatingsystem": "Solaris", "operatingsystemrelease": [ "10", - "11", - "12" + "11" ] }, { @@ -102,7 +98,7 @@ "requirements": [ { "name": "puppet", - "version_requirement": ">=2.7.20 <5.0.0" + "version_requirement": ">=2.7.20 < 6.0.0" } ], "description": "Standard Library for Puppet Modules", diff --git a/readmes/README_ja_JP.md b/readmes/README_ja_JP.md new file mode 100644 index 0000000..013b74c --- /dev/null +++ b/readmes/README_ja_JP.md @@ -0,0 +1,2480 @@ +# 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'と続く行が探され、その行が行内の値に置き換えられます。 + +マッチ例: + + 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`を用いたマッチ例: + +```puppet +file_line { 'bashrc_proxy': + ensure => absent, + path => '/etc/bashrc', + line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + match => '^export\ HTTP_PROXY\=', + match_for_absence => true, +} +``` + +上の例では、`match`により、'export'で始まり'HTTP_PROXY'と続く行が探され、その行が削除されます。複数の行がマッチし、`multiple => true`パラメータが設定されていない場合は、エラーが生じます。 + +エンコード例: + +```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`に設定すると、複数の行がマッチする場合に例外が発生します。 + +値: `true`、`false` + +デフォルト値: `false` + + +##### `name` + +リソースの名称として使用する名前を指定します。リソースのnamevarをリソースの規定の`title`と異なるものにしたい場合は、`name`で名前を指定します。 + +値: 文字列 + +デフォルト値: タイトルの値 + +##### `path` + +**必須** + +`line`で指定された行を確保するファイルを指定します。 + +値: 当該ファイルの絶対パスを指定する文字列 + +##### `replace` + +`match`パラメータとマッチする既存の行を上書きするかどうかを指定します。`false`に設定すると、`match`パラメータにマッチする行が見つかった場合、その行はファイルに配置されません。 + +ブーリアン + +デフォルト値: `true` + +### データタイプ + +#### `Stdlib::Absolutepath` + +厳密な絶対パスタイプ。UnixpathタイプおよびWindowspathタイプの異形を使用します。 + +使用可能なインプット例: + +```shell +/var/log +``` + +```shell +/usr2/username/bin:/usr/local/bin:/usr/bin:. +``` + +```shell +C:\\WINDOWS\\System32 +``` + +使用不可能なインプット例: + +```shell +../relative_path +``` + +#### `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::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`関数を使用してください。 + +*タイプ*: 右辺値 + +#### `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 '<type>'`: このメッセージは、情報提供の目的のみで表示されるものです。使用している値は、新形式で許可されていますが、旧確認関数では無効となります。 +* `Warning: This method is deprecated, please use the stdlib validate_legacy function`: モジュールがまだ`validate_legacy`にアップグレードされていません。[deprecation](#deprecation)オプションを使用してさしあたり警告を解除するか、モジュールの開発者によりフィックスを提出してください。この問題の解決方法については、以下の[モジュール開発者へ](#モジュール開発者へ)を参照してください。 +* `Warning: validate_legacy(<function>) expected <type> value, got <actual type>_`: コードが渡す値は、Puppet 3形式の確認では認められますが、次バージョンのモジュールでは認められません。ほとんどの場合、数字またはブーリアンからクォートを削除すれば、この問題を解決することができます。 +* `Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, validate_legacy(<function>) expected <type> value, got <actual type>`: コードの渡す値は、新形式の確認でも旧形式の確認でも認められません。 + +##### モジュール開発者へ + +`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)で見ることができます。
\ No newline at end of file diff --git a/spec/acceptance/abs_spec.rb b/spec/acceptance/abs_spec.rb index 6e41e2f..5af436f 100755 --- a/spec/acceptance/abs_spec.rb +++ b/spec/acceptance/abs_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'abs function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'abs function' do describe 'success' do it 'should accept a string' do pp = <<-EOS diff --git a/spec/acceptance/anchor_spec.rb b/spec/acceptance/anchor_spec.rb index 5bc2bbb..24a9064 100755 --- a/spec/acceptance/anchor_spec.rb +++ b/spec/acceptance/anchor_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper_acceptance' -describe 'anchor type', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'anchor type' do describe 'success' do it 'should effect proper chaining of resources' do pp = <<-EOS diff --git a/spec/acceptance/any2array_spec.rb b/spec/acceptance/any2array_spec.rb index 18ea4cd..8a13911 100755 --- a/spec/acceptance/any2array_spec.rb +++ b/spec/acceptance/any2array_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'any2array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'any2array function' do describe 'success' do it 'should create an empty array' do pp = <<-EOS diff --git a/spec/acceptance/base64_spec.rb b/spec/acceptance/base64_spec.rb index 97e1738..e9096a7 100755 --- a/spec/acceptance/base64_spec.rb +++ b/spec/acceptance/base64_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'base64 function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'base64 function' do describe 'success' do it 'should encode then decode a string' do pp = <<-EOS diff --git a/spec/acceptance/bool2num_spec.rb b/spec/acceptance/bool2num_spec.rb index 52ff75b..c69acc6 100755 --- a/spec/acceptance/bool2num_spec.rb +++ b/spec/acceptance/bool2num_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'bool2num function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'bool2num function' do describe 'success' do ['false', 'f', '0', 'n', 'no'].each do |bool| it "should convert a given boolean, #{bool}, to 0" do diff --git a/spec/acceptance/capitalize_spec.rb b/spec/acceptance/capitalize_spec.rb index e5e7b7b..03d01a8 100755 --- a/spec/acceptance/capitalize_spec.rb +++ b/spec/acceptance/capitalize_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'capitalize function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'capitalize function' do describe 'success' do it 'should capitalize the first letter of a string' do pp = <<-EOS diff --git a/spec/acceptance/ceiling_spec.rb b/spec/acceptance/ceiling_spec.rb index 557986e..895e4a0 100755 --- a/spec/acceptance/ceiling_spec.rb +++ b/spec/acceptance/ceiling_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'ceiling function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'ceiling function' do describe 'success' do it 'ceilings floats' do pp = <<-EOS diff --git a/spec/acceptance/chomp_spec.rb b/spec/acceptance/chomp_spec.rb index f6c1595..56e0876 100755 --- a/spec/acceptance/chomp_spec.rb +++ b/spec/acceptance/chomp_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'chomp function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'chomp function' do describe 'success' do it 'should eat the newline' do pp = <<-EOS diff --git a/spec/acceptance/chop_spec.rb b/spec/acceptance/chop_spec.rb index a16a710..0993806 100755 --- a/spec/acceptance/chop_spec.rb +++ b/spec/acceptance/chop_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'chop function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'chop function' do describe 'success' do it 'should eat the last character' do pp = <<-EOS diff --git a/spec/acceptance/clamp_spec.rb b/spec/acceptance/clamp_spec.rb index 0189258..e8ccb96 100755 --- a/spec/acceptance/clamp_spec.rb +++ b/spec/acceptance/clamp_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'clamp function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'clamp function' do describe 'success' do it 'clamps list of values' do pp = <<-EOS diff --git a/spec/acceptance/concat_spec.rb b/spec/acceptance/concat_spec.rb index c472db6..8d184d1 100755 --- a/spec/acceptance/concat_spec.rb +++ b/spec/acceptance/concat_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'concat function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'concat function' do describe 'success' do it 'should concat one array to another' do pp = <<-EOS diff --git a/spec/acceptance/count_spec.rb b/spec/acceptance/count_spec.rb index fe7ca9d..18c039d 100755 --- a/spec/acceptance/count_spec.rb +++ b/spec/acceptance/count_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'count function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'count function' do describe 'success' do it 'should count elements in an array' do pp = <<-EOS diff --git a/spec/acceptance/deep_merge_spec.rb b/spec/acceptance/deep_merge_spec.rb index c0f9b12..8222f24 100755 --- a/spec/acceptance/deep_merge_spec.rb +++ b/spec/acceptance/deep_merge_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'deep_merge function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'deep_merge function' do describe 'success' do it 'should deep merge two hashes' do pp = <<-EOS diff --git a/spec/acceptance/defined_with_params_spec.rb b/spec/acceptance/defined_with_params_spec.rb index fc54450..a332bd6 100755 --- a/spec/acceptance/defined_with_params_spec.rb +++ b/spec/acceptance/defined_with_params_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'defined_with_params function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'defined_with_params function' do describe 'success' do it 'should successfully notify' do pp = <<-EOS diff --git a/spec/acceptance/delete_at_spec.rb b/spec/acceptance/delete_at_spec.rb index db0c01f..d4f852a 100755 --- a/spec/acceptance/delete_at_spec.rb +++ b/spec/acceptance/delete_at_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'delete_at function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'delete_at function' do describe 'success' do it 'should delete elements of the array' do pp = <<-EOS diff --git a/spec/acceptance/delete_spec.rb b/spec/acceptance/delete_spec.rb index a28604c..f85b093 100755 --- a/spec/acceptance/delete_spec.rb +++ b/spec/acceptance/delete_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'delete function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'delete function' do describe 'success' do it 'should delete elements of the array' do pp = <<-EOS diff --git a/spec/acceptance/delete_undef_values_spec.rb b/spec/acceptance/delete_undef_values_spec.rb index b7eda19..af45a92 100755 --- a/spec/acceptance/delete_undef_values_spec.rb +++ b/spec/acceptance/delete_undef_values_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'delete_undef_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'delete_undef_values function' do describe 'success' do it 'should delete elements of the array' do pp = <<-EOS diff --git a/spec/acceptance/delete_values_spec.rb b/spec/acceptance/delete_values_spec.rb index 6d2369c..04b6920 100755 --- a/spec/acceptance/delete_values_spec.rb +++ b/spec/acceptance/delete_values_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'delete_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'delete_values function' do describe 'success' do it 'should delete elements of the hash' do pp = <<-EOS diff --git a/spec/acceptance/difference_spec.rb b/spec/acceptance/difference_spec.rb index 2fae5c4..68f6bbe 100755 --- a/spec/acceptance/difference_spec.rb +++ b/spec/acceptance/difference_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'difference function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'difference function' do describe 'success' do it 'returns non-duplicates in the first array' do pp = <<-EOS diff --git a/spec/acceptance/dirname_spec.rb b/spec/acceptance/dirname_spec.rb index 97913dd..db83f0f 100755 --- a/spec/acceptance/dirname_spec.rb +++ b/spec/acceptance/dirname_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'dirname function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'dirname function' do describe 'success' do context 'absolute path' do it 'returns the dirname' do diff --git a/spec/acceptance/downcase_spec.rb b/spec/acceptance/downcase_spec.rb index bc4e706..300bcfa 100755 --- a/spec/acceptance/downcase_spec.rb +++ b/spec/acceptance/downcase_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'downcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'downcase function' do describe 'success' do it 'returns the downcase' do pp = <<-EOS diff --git a/spec/acceptance/empty_spec.rb b/spec/acceptance/empty_spec.rb index 2d4df90..97b7333 100755 --- a/spec/acceptance/empty_spec.rb +++ b/spec/acceptance/empty_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'empty function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'empty function' do describe 'success' do it 'recognizes empty strings' do pp = <<-EOS diff --git a/spec/acceptance/flatten_spec.rb b/spec/acceptance/flatten_spec.rb index c4d66e0..289eec9 100755 --- a/spec/acceptance/flatten_spec.rb +++ b/spec/acceptance/flatten_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'flatten function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'flatten function' do describe 'success' do it 'flattens arrays' do pp = <<-EOS diff --git a/spec/acceptance/floor_spec.rb b/spec/acceptance/floor_spec.rb index 0dcdad9..8259d2a 100755 --- a/spec/acceptance/floor_spec.rb +++ b/spec/acceptance/floor_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'floor function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'floor function' do describe 'success' do it 'floors floats' do pp = <<-EOS diff --git a/spec/acceptance/fqdn_rand_string_spec.rb b/spec/acceptance/fqdn_rand_string_spec.rb index 065a517..af1b2a9 100644 --- a/spec/acceptance/fqdn_rand_string_spec.rb +++ b/spec/acceptance/fqdn_rand_string_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'fqdn_rand_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'fqdn_rand_string function' do describe 'success' do include_context "with faked facts" context "when the FQDN is 'fakehost.localdomain'" do diff --git a/spec/acceptance/fqdn_rotate_spec.rb b/spec/acceptance/fqdn_rotate_spec.rb index 404351f..66e94a9 100755 --- a/spec/acceptance/fqdn_rotate_spec.rb +++ b/spec/acceptance/fqdn_rotate_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'fqdn_rotate function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'fqdn_rotate function' do describe 'success' do include_context "with faked facts" context "when the FQDN is 'fakehost.localdomain'" do diff --git a/spec/acceptance/get_module_path_spec.rb b/spec/acceptance/get_module_path_spec.rb index 6ac690c..3d10251 100755 --- a/spec/acceptance/get_module_path_spec.rb +++ b/spec/acceptance/get_module_path_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'get_module_path function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'get_module_path function' do describe 'success' do it 'get_module_paths dne' do pp = <<-EOS diff --git a/spec/acceptance/getparam_spec.rb b/spec/acceptance/getparam_spec.rb index b1a677e..bd12154 100755 --- a/spec/acceptance/getparam_spec.rb +++ b/spec/acceptance/getparam_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'getparam function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'getparam function' do describe 'success' do it 'getparam a notify' do pp = <<-EOS diff --git a/spec/acceptance/getvar_spec.rb b/spec/acceptance/getvar_spec.rb index 333c467..605cdce 100755 --- a/spec/acceptance/getvar_spec.rb +++ b/spec/acceptance/getvar_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'getvar function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'getvar function' do describe 'success' do it 'getvars from classes' do pp = <<-EOS diff --git a/spec/acceptance/grep_spec.rb b/spec/acceptance/grep_spec.rb index b39d48e..7c35ee4 100755 --- a/spec/acceptance/grep_spec.rb +++ b/spec/acceptance/grep_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'grep function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'grep function' do describe 'success' do it 'greps arrays' do pp = <<-EOS diff --git a/spec/acceptance/has_interface_with_spec.rb b/spec/acceptance/has_interface_with_spec.rb index 9590193..fd33af5 100755 --- a/spec/acceptance/has_interface_with_spec.rb +++ b/spec/acceptance/has_interface_with_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_interface_with function', :unless => ((UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem'))) or (fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_interface_with function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do describe 'success' do it 'has_interface_with existing ipaddress' do pp = <<-EOS diff --git a/spec/acceptance/has_ip_address_spec.rb b/spec/acceptance/has_ip_address_spec.rb index 149a10d..878d921 100755 --- a/spec/acceptance/has_ip_address_spec.rb +++ b/spec/acceptance/has_ip_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_ip_address function', :unless => ((UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem'))) or (fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_ip_address function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do describe 'success' do it 'has_ip_address existing ipaddress' do pp = <<-EOS diff --git a/spec/acceptance/has_ip_network_spec.rb b/spec/acceptance/has_ip_network_spec.rb index 7d2f34e..f7a7d35 100755 --- a/spec/acceptance/has_ip_network_spec.rb +++ b/spec/acceptance/has_ip_network_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_ip_network function', :unless => ((UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem'))) or (fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_ip_network function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do describe 'success' do it 'has_ip_network existing ipaddress' do pp = <<-EOS diff --git a/spec/acceptance/has_key_spec.rb b/spec/acceptance/has_key_spec.rb index c8557cb..661c122 100755 --- a/spec/acceptance/has_key_spec.rb +++ b/spec/acceptance/has_key_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_key function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'has_key function' do describe 'success' do it 'has_keys in hashes' do pp = <<-EOS diff --git a/spec/acceptance/hash_spec.rb b/spec/acceptance/hash_spec.rb index ed53834..85da50b 100755 --- a/spec/acceptance/hash_spec.rb +++ b/spec/acceptance/hash_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'hash function' do describe 'success' do it 'hashs arrays' do pp = <<-EOS diff --git a/spec/acceptance/intersection_spec.rb b/spec/acceptance/intersection_spec.rb index 66b8652..02d4e7d 100755 --- a/spec/acceptance/intersection_spec.rb +++ b/spec/acceptance/intersection_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'intersection function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'intersection function' do describe 'success' do it 'intersections arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_a_spec.rb b/spec/acceptance/is_a_spec.rb index 355fd83..fb0019a 100644 --- a/spec/acceptance/is_a_spec.rb +++ b/spec/acceptance/is_a_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper_acceptance' if get_puppet_version =~ /^4/ - describe 'is_a function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'is_a function' do it 'should match a string' do pp = <<-EOS if 'hello world'.is_a(String) { diff --git a/spec/acceptance/is_array_spec.rb b/spec/acceptance/is_array_spec.rb index 9c6bad7..1a83417 100755 --- a/spec/acceptance/is_array_spec.rb +++ b/spec/acceptance/is_array_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_array function' do describe 'success' do it 'is_arrays arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_bool_spec.rb b/spec/acceptance/is_bool_spec.rb index 60079f9..823cb46 100755 --- a/spec/acceptance/is_bool_spec.rb +++ b/spec/acceptance/is_bool_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_bool function' do describe 'success' do it 'is_bools arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_domain_name_spec.rb b/spec/acceptance/is_domain_name_spec.rb index e0f03fa..884b0bc 100755 --- a/spec/acceptance/is_domain_name_spec.rb +++ b/spec/acceptance/is_domain_name_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_domain_name function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_domain_name function' do describe 'success' do it 'is_domain_names arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_float_spec.rb b/spec/acceptance/is_float_spec.rb index 338ba58..0b38d94 100755 --- a/spec/acceptance/is_float_spec.rb +++ b/spec/acceptance/is_float_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_float function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_float function' do describe 'success' do it 'is_floats arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_function_available_spec.rb b/spec/acceptance/is_function_available_spec.rb index 2b5dd6d..f8191ee 100755 --- a/spec/acceptance/is_function_available_spec.rb +++ b/spec/acceptance/is_function_available_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_function_available function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_function_available function' do describe 'success' do it 'is_function_availables arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_hash_spec.rb b/spec/acceptance/is_hash_spec.rb index 2ef310a..64f016c 100755 --- a/spec/acceptance/is_hash_spec.rb +++ b/spec/acceptance/is_hash_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_hash function' do describe 'success' do it 'is_hashs arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_integer_spec.rb b/spec/acceptance/is_integer_spec.rb index bf6902b..7333687 100755 --- a/spec/acceptance/is_integer_spec.rb +++ b/spec/acceptance/is_integer_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_integer function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_integer function' do describe 'success' do it 'is_integers arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_ip_address_spec.rb b/spec/acceptance/is_ip_address_spec.rb index ed7a854..2c62c77 100755 --- a/spec/acceptance/is_ip_address_spec.rb +++ b/spec/acceptance/is_ip_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_ip_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_ip_address function' do describe 'success' do it 'is_ip_addresss ipv4' do pp = <<-EOS diff --git a/spec/acceptance/is_ipv4_address_spec.rb b/spec/acceptance/is_ipv4_address_spec.rb index 5dc6bf5..abe26d8 100755 --- a/spec/acceptance/is_ipv4_address_spec.rb +++ b/spec/acceptance/is_ipv4_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_ipv4_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_ipv4_address function' do describe 'success' do it 'is_ipv4_addresss' do pp = <<-EOS diff --git a/spec/acceptance/is_ipv6_address_spec.rb b/spec/acceptance/is_ipv6_address_spec.rb index 1e88be8..73a3fa4 100755 --- a/spec/acceptance/is_ipv6_address_spec.rb +++ b/spec/acceptance/is_ipv6_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_ipv6_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_ipv6_address function' do describe 'success' do it 'is_ipv6_addresss' do pp = <<-EOS diff --git a/spec/acceptance/is_mac_address_spec.rb b/spec/acceptance/is_mac_address_spec.rb index a2c892f..617bef6 100755 --- a/spec/acceptance/is_mac_address_spec.rb +++ b/spec/acceptance/is_mac_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_mac_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_mac_address function' do describe 'success' do it 'is_mac_addresss a mac' do pp = <<-EOS diff --git a/spec/acceptance/is_numeric_spec.rb b/spec/acceptance/is_numeric_spec.rb index 21c8988..7e65384 100755 --- a/spec/acceptance/is_numeric_spec.rb +++ b/spec/acceptance/is_numeric_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_numeric function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_numeric function' do describe 'success' do it 'is_numerics arrays' do pp = <<-EOS diff --git a/spec/acceptance/is_string_spec.rb b/spec/acceptance/is_string_spec.rb index f526888..bee5e01 100755 --- a/spec/acceptance/is_string_spec.rb +++ b/spec/acceptance/is_string_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'is_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'is_string function' do describe 'success' do it 'is_strings arrays' do pp = <<-EOS diff --git a/spec/acceptance/join_keys_to_values_spec.rb b/spec/acceptance/join_keys_to_values_spec.rb index 70493fd..ae6947e 100755 --- a/spec/acceptance/join_keys_to_values_spec.rb +++ b/spec/acceptance/join_keys_to_values_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'join_keys_to_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'join_keys_to_values function' do describe 'success' do it 'join_keys_to_valuess hashes' do pp = <<-EOS diff --git a/spec/acceptance/join_spec.rb b/spec/acceptance/join_spec.rb index 5397ce2..75b88d8 100755 --- a/spec/acceptance/join_spec.rb +++ b/spec/acceptance/join_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'join function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'join function' do describe 'success' do it 'joins arrays' do pp = <<-EOS diff --git a/spec/acceptance/keys_spec.rb b/spec/acceptance/keys_spec.rb index 176918e..65bfe28 100755 --- a/spec/acceptance/keys_spec.rb +++ b/spec/acceptance/keys_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'keys function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'keys function' do describe 'success' do it 'keyss hashes' do pp = <<-EOS diff --git a/spec/acceptance/loadjson_spec.rb b/spec/acceptance/loadjson_spec.rb index 2992c37..ebd5307 100644 --- a/spec/acceptance/loadjson_spec.rb +++ b/spec/acceptance/loadjson_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') -describe 'loadjson function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'loadjson function' do describe 'success' do it 'loadjsons array of values' do shell("echo '{\"aaa\":1,\"bbb\":2,\"ccc\":3,\"ddd\":4}' > #{tmpdir}/testjson.json") diff --git a/spec/acceptance/loadyaml_spec.rb b/spec/acceptance/loadyaml_spec.rb index ba3f0b7..57fb8cb 100644 --- a/spec/acceptance/loadyaml_spec.rb +++ b/spec/acceptance/loadyaml_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') -describe 'loadyaml function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'loadyaml function' do describe 'success' do it 'loadyamls array of values' do shell("echo '--- diff --git a/spec/acceptance/lstrip_spec.rb b/spec/acceptance/lstrip_spec.rb index 3dc952f..eba5d0d 100755 --- a/spec/acceptance/lstrip_spec.rb +++ b/spec/acceptance/lstrip_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'lstrip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'lstrip function' do describe 'success' do it 'lstrips arrays' do pp = <<-EOS diff --git a/spec/acceptance/max_spec.rb b/spec/acceptance/max_spec.rb index f04e3d2..3caa813 100755 --- a/spec/acceptance/max_spec.rb +++ b/spec/acceptance/max_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'max function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'max function' do describe 'success' do it 'maxs arrays' do pp = <<-EOS diff --git a/spec/acceptance/member_spec.rb b/spec/acceptance/member_spec.rb index fe75a07..2bcadd3 100755 --- a/spec/acceptance/member_spec.rb +++ b/spec/acceptance/member_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'member function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'member function' do shared_examples 'item found' do it 'should output correctly' do apply_manifest(pp, :catch_failures => true) do |r| diff --git a/spec/acceptance/merge_spec.rb b/spec/acceptance/merge_spec.rb index 227b994..814db4e 100755 --- a/spec/acceptance/merge_spec.rb +++ b/spec/acceptance/merge_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'merge function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'merge function' do describe 'success' do it 'should merge two hashes' do pp = <<-EOS diff --git a/spec/acceptance/min_spec.rb b/spec/acceptance/min_spec.rb index 509092d..7b18fac 100755 --- a/spec/acceptance/min_spec.rb +++ b/spec/acceptance/min_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'min function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'min function' do describe 'success' do it 'mins arrays' do pp = <<-EOS diff --git a/spec/acceptance/num2bool_spec.rb b/spec/acceptance/num2bool_spec.rb index 1d99ba0..00d0ddc 100755 --- a/spec/acceptance/num2bool_spec.rb +++ b/spec/acceptance/num2bool_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'num2bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'num2bool function' do describe 'success' do it 'bools positive numbers and numeric strings as true' do pp = <<-EOS diff --git a/spec/acceptance/parsejson_spec.rb b/spec/acceptance/parsejson_spec.rb index d0e3de8..52133e4 100755 --- a/spec/acceptance/parsejson_spec.rb +++ b/spec/acceptance/parsejson_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'parsejson function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'parsejson function' do describe 'success' do it 'parses valid json' do pp = <<-EOS diff --git a/spec/acceptance/parseyaml_spec.rb b/spec/acceptance/parseyaml_spec.rb index 64511f1..acbda46 100755 --- a/spec/acceptance/parseyaml_spec.rb +++ b/spec/acceptance/parseyaml_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'parseyaml function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'parseyaml function' do describe 'success' do it 'parses valid yaml' do pp = <<-EOS diff --git a/spec/acceptance/pick_default_spec.rb b/spec/acceptance/pick_default_spec.rb index a663f54..e7e25ab 100755 --- a/spec/acceptance/pick_default_spec.rb +++ b/spec/acceptance/pick_default_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'pick_default function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'pick_default function' do describe 'success' do it 'pick_defaults a default value' do pp = <<-EOS diff --git a/spec/acceptance/pick_spec.rb b/spec/acceptance/pick_spec.rb index 46cf63f..c70b2d9 100755 --- a/spec/acceptance/pick_spec.rb +++ b/spec/acceptance/pick_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'pick function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'pick function' do describe 'success' do it 'picks a default value' do pp = <<-EOS diff --git a/spec/acceptance/prefix_spec.rb b/spec/acceptance/prefix_spec.rb index de55530..58c691d 100755 --- a/spec/acceptance/prefix_spec.rb +++ b/spec/acceptance/prefix_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'prefix function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'prefix function' do describe 'success' do it 'prefixes array of values' do pp = <<-EOS diff --git a/spec/acceptance/pw_hash_spec.rb b/spec/acceptance/pw_hash_spec.rb index cd4cb87..829d087 100644 --- a/spec/acceptance/pw_hash_spec.rb +++ b/spec/acceptance/pw_hash_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper_acceptance' # Windows and OS X do not have useful implementations of crypt(3) -describe 'pw_hash function', :unless => (UNSUPPORTED_PLATFORMS + ['windows', 'Darwin', 'SLES']).include?(fact('operatingsystem')) do +describe 'pw_hash function', :unless => (['windows', 'Darwin', 'SLES']).include?(fact('operatingsystem')) do describe 'success' do it 'hashes passwords' do pp = <<-EOS diff --git a/spec/acceptance/range_spec.rb b/spec/acceptance/range_spec.rb index a3ccd33..f57f884 100755 --- a/spec/acceptance/range_spec.rb +++ b/spec/acceptance/range_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'range function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'range function' do describe 'success' do it 'ranges letters' do pp = <<-EOS diff --git a/spec/acceptance/reject_spec.rb b/spec/acceptance/reject_spec.rb index 7f16a00..ce4342d 100755 --- a/spec/acceptance/reject_spec.rb +++ b/spec/acceptance/reject_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'reject function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'reject function' do describe 'success' do it 'rejects array of values' do pp = <<-EOS diff --git a/spec/acceptance/reverse_spec.rb b/spec/acceptance/reverse_spec.rb index c3f0156..3b5dfad 100755 --- a/spec/acceptance/reverse_spec.rb +++ b/spec/acceptance/reverse_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'reverse function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'reverse function' do describe 'success' do it 'reverses strings' do pp = <<-EOS diff --git a/spec/acceptance/rstrip_spec.rb b/spec/acceptance/rstrip_spec.rb index b57a8b0..150dac1 100755 --- a/spec/acceptance/rstrip_spec.rb +++ b/spec/acceptance/rstrip_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'rstrip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'rstrip function' do describe 'success' do it 'rstrips arrays' do pp = <<-EOS diff --git a/spec/acceptance/shuffle_spec.rb b/spec/acceptance/shuffle_spec.rb index b840d1f..0738383 100755 --- a/spec/acceptance/shuffle_spec.rb +++ b/spec/acceptance/shuffle_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'shuffle function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'shuffle function' do describe 'success' do it 'shuffles arrays' do pp = <<-EOS diff --git a/spec/acceptance/size_spec.rb b/spec/acceptance/size_spec.rb index a52b778..6390c20 100755 --- a/spec/acceptance/size_spec.rb +++ b/spec/acceptance/size_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'size function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'size function' do describe 'success' do it 'single string size' do pp = <<-EOS diff --git a/spec/acceptance/sort_spec.rb b/spec/acceptance/sort_spec.rb index c85bfab..e7ff7f7 100755 --- a/spec/acceptance/sort_spec.rb +++ b/spec/acceptance/sort_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'sort function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'sort function' do describe 'success' do it 'sorts arrays' do pp = <<-EOS diff --git a/spec/acceptance/squeeze_spec.rb b/spec/acceptance/squeeze_spec.rb index 400a458..3324691 100755 --- a/spec/acceptance/squeeze_spec.rb +++ b/spec/acceptance/squeeze_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'squeeze function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'squeeze function' do describe 'success' do it 'squeezes arrays' do pp = <<-EOS diff --git a/spec/acceptance/str2bool_spec.rb b/spec/acceptance/str2bool_spec.rb index cf549da..9a8c06c 100755 --- a/spec/acceptance/str2bool_spec.rb +++ b/spec/acceptance/str2bool_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'str2bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'str2bool function' do describe 'success' do it 'works with "y"' do pp = <<-EOS diff --git a/spec/acceptance/str2saltedsha512_spec.rb b/spec/acceptance/str2saltedsha512_spec.rb index 993e63b..5f03924 100755 --- a/spec/acceptance/str2saltedsha512_spec.rb +++ b/spec/acceptance/str2saltedsha512_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'str2saltedsha512 function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'str2saltedsha512 function' do describe 'success' do it 'works with "y"' do pp = <<-EOS diff --git a/spec/acceptance/strftime_spec.rb b/spec/acceptance/strftime_spec.rb index 53b7f90..38521b0 100755 --- a/spec/acceptance/strftime_spec.rb +++ b/spec/acceptance/strftime_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'strftime function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'strftime function' do describe 'success' do it 'gives the Century' do pp = <<-EOS diff --git a/spec/acceptance/strip_spec.rb b/spec/acceptance/strip_spec.rb index 906fd7a..05cd395 100755 --- a/spec/acceptance/strip_spec.rb +++ b/spec/acceptance/strip_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'strip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'strip function' do describe 'success' do it 'strips arrays' do pp = <<-EOS diff --git a/spec/acceptance/suffix_spec.rb b/spec/acceptance/suffix_spec.rb index 630f866..60a6264 100755 --- a/spec/acceptance/suffix_spec.rb +++ b/spec/acceptance/suffix_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'suffix function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'suffix function' do describe 'success' do it 'suffixes array of values' do pp = <<-EOS diff --git a/spec/acceptance/swapcase_spec.rb b/spec/acceptance/swapcase_spec.rb index b7894fb..9f94c0d 100755 --- a/spec/acceptance/swapcase_spec.rb +++ b/spec/acceptance/swapcase_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'swapcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'swapcase function' do describe 'success' do it 'works with strings' do pp = <<-EOS diff --git a/spec/acceptance/time_spec.rb b/spec/acceptance/time_spec.rb index cdb2960..dae1166 100755 --- a/spec/acceptance/time_spec.rb +++ b/spec/acceptance/time_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'time function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'time function' do describe 'success' do it 'gives the time' do pp = <<-EOS diff --git a/spec/acceptance/to_bytes_spec.rb b/spec/acceptance/to_bytes_spec.rb index 2b4c61f..b1015a3 100755 --- a/spec/acceptance/to_bytes_spec.rb +++ b/spec/acceptance/to_bytes_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'to_bytes function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'to_bytes function' do describe 'success' do it 'converts kB to B' do pp = <<-EOS diff --git a/spec/acceptance/try_get_value_spec.rb b/spec/acceptance/try_get_value_spec.rb index c0bf38a..716241c 100755 --- a/spec/acceptance/try_get_value_spec.rb +++ b/spec/acceptance/try_get_value_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'try_get_value function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'try_get_value function' do describe 'success' do it 'gets a value' do pp = <<-EOS diff --git a/spec/acceptance/type_spec.rb b/spec/acceptance/type_spec.rb index 67e3248..5cc9470 100755 --- a/spec/acceptance/type_spec.rb +++ b/spec/acceptance/type_spec.rb @@ -1,29 +1,29 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'type function', :unless => (UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) || is_future_parser_enabled?) do +describe 'type function' do describe 'success' do it 'types arrays' do pp = <<-EOS $a = ["the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = type($a) - notice(inline_template('type is <%= @o.inspect %>')) + notice(inline_template('type is <%= @o.to_s %>')) EOS apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/type is "array"/) + expect(r.stdout).to match(/type is Tuple\[String.*, String.*, String.*, String.*\]/) end end it 'types strings' do pp = <<-EOS $a = "blowzy night-frumps vex'd jack q" $o = type($a) - notice(inline_template('type is <%= @o.inspect %>')) + notice(inline_template('type is <%= @o.to_s %>')) EOS apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/type is "string"/) + expect(r.stdout).to match(/type is String/) end end it 'types hashes' diff --git a/spec/acceptance/union_spec.rb b/spec/acceptance/union_spec.rb index 160fd7b..7229bf5 100755 --- a/spec/acceptance/union_spec.rb +++ b/spec/acceptance/union_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'union function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'union function' do describe 'success' do it 'unions arrays' do pp = <<-EOS diff --git a/spec/acceptance/unique_spec.rb b/spec/acceptance/unique_spec.rb index bfadad1..7fb5eca 100755 --- a/spec/acceptance/unique_spec.rb +++ b/spec/acceptance/unique_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'unique function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'unique function' do describe 'success' do it 'uniques arrays' do pp = <<-EOS diff --git a/spec/acceptance/unsupported_spec.rb b/spec/acceptance/unsupported_spec.rb deleted file mode 100755 index 1c559f6..0000000 --- a/spec/acceptance/unsupported_spec.rb +++ /dev/null @@ -1,11 +0,0 @@ -#! /usr/bin/env ruby -S rspec -require 'spec_helper_acceptance' - -describe 'unsupported distributions and OSes', :if => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do - it 'should fail' do - pp = <<-EOS - class { 'mysql::server': } - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/unsupported osfamily/i) - end -end diff --git a/spec/acceptance/upcase_spec.rb b/spec/acceptance/upcase_spec.rb index 3d2906d..1782309 100755 --- a/spec/acceptance/upcase_spec.rb +++ b/spec/acceptance/upcase_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'upcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'upcase function' do describe 'success' do it 'upcases arrays' do pp = <<-EOS diff --git a/spec/acceptance/uriescape_spec.rb b/spec/acceptance/uriescape_spec.rb index 7e30205..e123425 100755 --- a/spec/acceptance/uriescape_spec.rb +++ b/spec/acceptance/uriescape_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'uriescape function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'uriescape function' do describe 'success' do it 'uriescape strings' do pp = <<-EOS diff --git a/spec/acceptance/validate_absolute_path_spec.rb b/spec/acceptance/validate_absolute_path_spec.rb index 7082e84..880850d 100755 --- a/spec/acceptance/validate_absolute_path_spec.rb +++ b/spec/acceptance/validate_absolute_path_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_absolute_path function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_absolute_path function' do describe 'success' do %w{ C:/ diff --git a/spec/acceptance/validate_array_spec.rb b/spec/acceptance/validate_array_spec.rb index 2f549d5..a76321d 100755 --- a/spec/acceptance/validate_array_spec.rb +++ b/spec/acceptance/validate_array_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_array function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/validate_augeas_spec.rb b/spec/acceptance/validate_augeas_spec.rb index 71a4c84..be213d3 100755 --- a/spec/acceptance/validate_augeas_spec.rb +++ b/spec/acceptance/validate_augeas_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_augeas function', :unless => ((UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem'))) or (fact('osfamily') == 'windows')) do +describe 'validate_augeas function', :unless => (fact('osfamily') == 'windows') do describe 'prep' do it 'installs augeas for tests' end diff --git a/spec/acceptance/validate_bool_spec.rb b/spec/acceptance/validate_bool_spec.rb index 5c52d0f..993f9ef 100755 --- a/spec/acceptance/validate_bool_spec.rb +++ b/spec/acceptance/validate_bool_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_bool function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/validate_cmd_spec.rb b/spec/acceptance/validate_cmd_spec.rb index 5ac66fd..5fc7b94 100755 --- a/spec/acceptance/validate_cmd_spec.rb +++ b/spec/acceptance/validate_cmd_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_cmd function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_cmd function' do describe 'success' do it 'validates a true command' do pp = <<-EOS diff --git a/spec/acceptance/validate_hash_spec.rb b/spec/acceptance/validate_hash_spec.rb index 637df0a..fc0f079 100755 --- a/spec/acceptance/validate_hash_spec.rb +++ b/spec/acceptance/validate_hash_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_hash function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/validate_ipv4_address_spec.rb b/spec/acceptance/validate_ipv4_address_spec.rb index 64841c3..67d3139 100755 --- a/spec/acceptance/validate_ipv4_address_spec.rb +++ b/spec/acceptance/validate_ipv4_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_ipv4_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_ipv4_address function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/validate_ipv6_address_spec.rb b/spec/acceptance/validate_ipv6_address_spec.rb index 6426d1a..eaa845d 100755 --- a/spec/acceptance/validate_ipv6_address_spec.rb +++ b/spec/acceptance/validate_ipv6_address_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_ipv6_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_ipv6_address function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/validate_re_spec.rb b/spec/acceptance/validate_re_spec.rb index 22f6d47..eefb286 100755 --- a/spec/acceptance/validate_re_spec.rb +++ b/spec/acceptance/validate_re_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_re function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_re function' do describe 'success' do it 'validates a string' do pp = <<-EOS diff --git a/spec/acceptance/validate_slength_spec.rb b/spec/acceptance/validate_slength_spec.rb index 1ab2bb9..c29fd23 100755 --- a/spec/acceptance/validate_slength_spec.rb +++ b/spec/acceptance/validate_slength_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_slength function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_slength function' do describe 'success' do it 'validates a single string max' do pp = <<-EOS diff --git a/spec/acceptance/validate_string_spec.rb b/spec/acceptance/validate_string_spec.rb index ae3468f..f04608d 100755 --- a/spec/acceptance/validate_string_spec.rb +++ b/spec/acceptance/validate_string_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'validate_string function' do describe 'success' do it 'validates a single argument' do pp = <<-EOS diff --git a/spec/acceptance/values_at_spec.rb b/spec/acceptance/values_at_spec.rb index da63cf3..eb0bf4f 100755 --- a/spec/acceptance/values_at_spec.rb +++ b/spec/acceptance/values_at_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'values_at function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'values_at function' do describe 'success' do it 'returns a specific value' do pp = <<-EOS diff --git a/spec/acceptance/values_spec.rb b/spec/acceptance/values_spec.rb index a2eff32..cef1c9d 100755 --- a/spec/acceptance/values_spec.rb +++ b/spec/acceptance/values_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'values function' do describe 'success' do it 'returns an array of values' do pp = <<-EOS @@ -13,12 +13,7 @@ describe 'values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('oper $output = values($arg) notice(inline_template('<%= @output.sort.inspect %>')) EOS - if is_future_parser_enabled? - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 2, 3\]/) - else - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["1", "2", "3"\]/) - end - + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 2, 3\]/) end end describe 'failure' do diff --git a/spec/acceptance/zip_spec.rb b/spec/acceptance/zip_spec.rb index 139079e..ae22896 100755 --- a/spec/acceptance/zip_spec.rb +++ b/spec/acceptance/zip_spec.rb @@ -1,8 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -require 'puppet' -describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do +describe 'zip function' do describe 'success' do it 'zips two arrays of numbers together' do pp = <<-EOS @@ -11,11 +10,7 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) EOS - if is_future_parser_enabled? - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\], \[3, 7\], \[4, 8\]\]/) - else - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", "5"\], \["2", "6"\], \["3", "7"\], \["4", "8"\]\]/) - end + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\], \[3, 7\], \[4, 8\]\]/) end it 'zips two arrays of numbers & bools together' do pp = <<-EOS @@ -24,11 +19,7 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) EOS - if is_future_parser_enabled? - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, true\], \[2, true\], \["three", false\], \[4, false\]\]/) - else - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", true\], \["2", true\], \["three", false\], \["4", false\]\]/) - end + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, true\], \[2, true\], \["three", false\], \[4, false\]\]/) end it 'zips two arrays of numbers together and flattens them' do # XXX This only tests the argument `true`, even though the following are valid: @@ -41,11 +32,7 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one,$two,true) notice(inline_template('<%= @output.inspect %>')) EOS - if is_future_parser_enabled? - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 5, 2, 6, 3, 7, 4, 8\]/) - else - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["1", "5", "2", "6", "3", "7", "4", "8"\]/) - end + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 5, 2, 6, 3, 7, 4, 8\]/) end it 'handles unmatched length' do # XXX Is this expected behavior? @@ -55,11 +42,7 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) EOS - if is_future_parser_enabled? - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\]\]/) - else - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", "5"\], \["2", "6"\]\]/) - end + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\]\]/) end end describe 'failure' do @@ -69,7 +52,6 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one) notice(inline_template('<%= @output.inspect %>')) EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Wrong number of arguments/) end it 'handles improper argument types' do @@ -79,7 +61,6 @@ describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operati $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Requires array/) end end diff --git a/spec/aliases/absolute_path_spec.rb b/spec/aliases/absolute_path_spec.rb index 3fb9d12..308a3aa 100644 --- a/spec/aliases/absolute_path_spec.rb +++ b/spec/aliases/absolute_path_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::absolute_path', type: :class do describe 'valid paths handling' do %w{ @@ -15,6 +15,9 @@ if Puppet.version.to_f >= 4.5 / /var/tmp /var/opt/../lib/puppet + /var/opt//lib/puppet + /var/ůťƒ8 + /var/ネット }.each do |value| describe value.inspect do let(:params) {{ value: value }} @@ -50,6 +53,8 @@ if Puppet.version.to_f >= 4.5 etc/puppetlabs/puppet opt/puppet/bin relative\\windows + \var\ůťƒ8 + \var\ネット }.each do |value| describe value.inspect do let(:params) {{ value: value }} diff --git a/spec/aliases/absolutepath_spec.rb b/spec/aliases/absolutepath_spec.rb deleted file mode 100644 index aa435d7..0000000 --- a/spec/aliases/absolutepath_spec.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'spec_helper' - -if Puppet.version.to_f >= 4.5 - describe 'test::absolutepath', type: :class do - describe 'valid handling' do - %w{ - /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 - let(:params) {{ value: value }} - it { is_expected.to compile } - 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" - ].each do |value| - describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Variant/) } - end - end - end - - end - end -end diff --git a/spec/aliases/array_spec.rb b/spec/aliases/array_spec.rb index d0f9877..89cc2af 100644 --- a/spec/aliases/array_spec.rb +++ b/spec/aliases/array_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::array', type: :class do describe 'accepts arrays' do [ diff --git a/spec/aliases/bool_spec.rb b/spec/aliases/bool_spec.rb index 78c57fc..b84ab51 100644 --- a/spec/aliases/bool_spec.rb +++ b/spec/aliases/bool_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::bool', type: :class do describe 'accepts booleans' do [ diff --git a/spec/aliases/float_spec.rb b/spec/aliases/float_spec.rb index cc20758..84e1934 100644 --- a/spec/aliases/float_spec.rb +++ b/spec/aliases/float_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::float', type: :class do describe 'accepts floats' do [ @@ -20,7 +20,7 @@ if Puppet.version.to_f >= 4.5 [ 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 let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a value of type Float or Pattern(\[.*\]+)?/) } + it { is_expected.to compile.and_raise_error(/parameter 'value' expects.*Float.*Pattern/) } end end end diff --git a/spec/aliases/hash_spec.rb b/spec/aliases/hash_spec.rb new file mode 100644 index 0000000..6e5060d --- /dev/null +++ b/spec/aliases/hash_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' + +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 + describe 'test::hash', type: :class do + describe 'accepts hashes' do + [ + {}, + {'one' => "two"}, + {'wan' => 3}, + {'001' => "helly"}, + ].each do |value| + describe value.inspect do + let(:params) {{ value: value }} + it { is_expected.to compile } + end + end + end + describe 'rejects other values' do + [ + '', + 'one', + '1', + [], + ].each do |value| + describe value.inspect do + let(:params) {{ value: value }} + it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Hash/) } + end + end + end + end +end diff --git a/spec/aliases/httpsurl_spec.rb b/spec/aliases/httpsurl_spec.rb index 97ae006..3e51118 100644 --- a/spec/aliases/httpsurl_spec.rb +++ b/spec/aliases/httpsurl_spec.rb @@ -1,12 +1,14 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::httpsurl', type: :class 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 let(:params) {{ value: value }} @@ -26,7 +28,9 @@ if Puppet.version.to_f >= 4.5 '', "httds://notquiteright.org", "hptts:/nah", - "https;//notrightbutclose.org" + "https;//notrightbutclose.org", + "http://graphemica.com/❤", + "http://graphemica.com/緩" ].each do |value| describe value.inspect do let(:params) {{ value: value }} diff --git a/spec/aliases/httpurl_spec.rb b/spec/aliases/httpurl_spec.rb index 8bd57ca..fd49a47 100644 --- a/spec/aliases/httpurl_spec.rb +++ b/spec/aliases/httpurl_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::httpurl', type: :class do describe 'valid handling' do %w{ @@ -10,6 +10,8 @@ if Puppet.version.to_f >= 4.5 http://anhttp.com http://runningoutofideas.gov http:// + http://graphemica.com/❤ + http://graphemica.com/緩 }.each do |value| describe value.inspect do let(:params) {{ value: value }} @@ -29,7 +31,9 @@ if Puppet.version.to_f >= 4.5 '', "httds://notquiteright.org", "hptts:/nah", - "https;//notrightbutclose.org" + "https;//notrightbutclose.org", + "hts://graphemica.com/❤", + "https:graphemica.com/緩" ].each do |value| describe value.inspect do let(:params) {{ value: value }} diff --git a/spec/aliases/integer_spec.rb b/spec/aliases/integer_spec.rb index 260090a..9cf0357 100644 --- a/spec/aliases/integer_spec.rb +++ b/spec/aliases/integer_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::integer', type: :class do describe 'accepts integers' do [ @@ -8,6 +8,8 @@ if Puppet.version.to_f >= 4.5 '3', -3, '-3', + "123\nfoo", + "foo\n123", ].each do |value| describe value.inspect do let(:params) {{ value: value }} @@ -17,10 +19,14 @@ if Puppet.version.to_f >= 4.5 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.7, '3.7',-3.7, '-342.2315e-12' ].each do |value| + [ "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 let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a value of type Integer, Pattern(\[.*\]+)?, or Array/) } + if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 + it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Integer = Variant\[Integer, Pattern\[.*\], Array\[.*\]\] value/) } + else + it { is_expected.to compile.and_raise_error(/parameter 'value' expects a value of type Integer, Pattern(\[.*\]+)?, or Array/) } + end end end end diff --git a/spec/aliases/ip_address.rb b/spec/aliases/ip_address.rb index 664bf24..67a555c 100644 --- a/spec/aliases/ip_address.rb +++ b/spec/aliases/ip_address.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::ip_address', type: :class do describe 'accepts ipv4 and ipv6 addresses' do [ diff --git a/spec/aliases/ipv4_spec.rb b/spec/aliases/ipv4_spec.rb index 210b4b1..6a503ad 100644 --- a/spec/aliases/ipv4_spec.rb +++ b/spec/aliases/ipv4_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::ipv4', type: :class do describe 'accepts ipv4 addresses' do SharedData::IPV4_PATTERNS.each do |value| diff --git a/spec/aliases/ipv6_spec.rb b/spec/aliases/ipv6_spec.rb index 13d7c3e..ae90f42 100644 --- a/spec/aliases/ipv6_spec.rb +++ b/spec/aliases/ipv6_spec.rb @@ -1,11 +1,18 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::ipv6', type: :class do describe 'accepts ipv6 addresses' do [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', - 'fa76:8765:34ac:0823:ab76:eee9:0987:1111' + '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 let(:params) {{ value: value }} @@ -18,7 +25,10 @@ if Puppet.version.to_f >= 4.5 'nope', '77', '4.4.4', - '2000:7334' + '2000:7334', + '::ffff:2.3.4', + '::ffff:257.1.2.3', + '::ffff:12345678901234567890.1.26', ].each do |value| describe value.inspect do let(:params) {{ value: value }} diff --git a/spec/aliases/numeric_spec.rb b/spec/aliases/numeric_spec.rb index 0e98bee..09c28ec 100644 --- a/spec/aliases/numeric_spec.rb +++ b/spec/aliases/numeric_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::numeric', type: :class do describe 'accepts numerics' do [ @@ -24,7 +24,7 @@ if Puppet.version.to_f >= 4.5 [ 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 let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a value of type Numeric, Pattern(\[.*\]+)?, or Array/) } + it { is_expected.to compile.and_raise_error(/parameter 'value' expects.*Numeric.*Pattern.*Array/) } end end end diff --git a/spec/aliases/string_spec.rb b/spec/aliases/string_spec.rb index 8a93585..4fc8ce6 100644 --- a/spec/aliases/string_spec.rb +++ b/spec/aliases/string_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::string', type: :class do describe 'accepts strings' do [ @@ -24,7 +24,7 @@ if Puppet.version.to_f >= 4.5 ].each do |value| describe value.inspect do let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a String/) } + it { is_expected.to compile.and_raise_error(/parameter 'value' expects a (?:value of type Undef or )?.*String/) } end end end diff --git a/spec/aliases/unixpath_spec.rb b/spec/aliases/unixpath_spec.rb index aee161d..6aecfe7 100644 --- a/spec/aliases/unixpath_spec.rb +++ b/spec/aliases/unixpath_spec.rb @@ -1,12 +1,16 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::unixpath', type: :class 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 let(:params) {{ value: value }} @@ -27,7 +31,9 @@ if Puppet.version.to_f >= 4.5 "C:/whatever", "\\var\\tmp", "\\Users/hc/wksp/stdlib", - "*/Users//nope" + "*/Users//nope", + "var\ůťƒ8", + "var\ネット" ].each do |value| describe value.inspect do let(:params) {{ value: value }} diff --git a/spec/aliases/windowspath_spec.rb b/spec/aliases/windowspath_spec.rb index c13794e..c20e373 100644 --- a/spec/aliases/windowspath_spec.rb +++ b/spec/aliases/windowspath_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.5 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::windowspath', type: :class do describe 'valid handling' do %w{ @@ -10,6 +10,8 @@ if Puppet.version.to_f >= 4.5 X:/foo/bar X:\\foo\\bar \\\\host\\windows + X:/var/ůťƒ8 + X:/var/ネット }.each do |value| describe value.inspect do let(:params) {{ value: value }} @@ -30,7 +32,9 @@ if Puppet.version.to_f >= 4.5 "httds://notquiteright.org", "/usr2/username/bin:/usr/local/bin:/usr/bin:.", "C;//notright/here", - "C:noslashes" + "C:noslashes", + "C:ネット", + "C:ůťƒ8" ].each do |value| describe value.inspect do let(:params) {{ value: value }} @@ -38,7 +42,6 @@ if Puppet.version.to_f >= 4.5 end end end - end end end diff --git a/spec/fixtures/test/manifests/deftype.pp b/spec/fixtures/test/manifests/deftype.pp new file mode 100644 index 0000000..825f8fe --- /dev/null +++ b/spec/fixtures/test/manifests/deftype.pp @@ -0,0 +1,3 @@ +define test::deftype($param = 'foo') { + notify { "deftype: $title": } +} diff --git a/spec/fixtures/test/manifests/hash.pp b/spec/fixtures/test/manifests/hash.pp new file mode 100644 index 0000000..c243570 --- /dev/null +++ b/spec/fixtures/test/manifests/hash.pp @@ -0,0 +1,8 @@ +# Class to test the Stdlib::Compat::Hash type alias +class test::hash( + Stdlib::Compat::Hash $value, + ) { + + notice("Success") + +} diff --git a/spec/functions/any2array_spec.rb b/spec/functions/any2array_spec.rb index 70121f1..631657f 100755 --- a/spec/functions/any2array_spec.rb +++ b/spec/functions/any2array_spec.rb @@ -12,4 +12,10 @@ describe "any2array" do 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' }).and_return(['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 diff --git a/spec/functions/basename_spec.rb b/spec/functions/basename_spec.rb index c84e192..3e02b01 100755 --- a/spec/functions/basename_spec.rb +++ b/spec/functions/basename_spec.rb @@ -11,4 +11,9 @@ describe 'basename' do 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 'should run 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 diff --git a/spec/functions/chomp_spec.rb b/spec/functions/chomp_spec.rb index 6878742..56bd9b1 100755 --- a/spec/functions/chomp_spec.rb +++ b/spec/functions/chomp_spec.rb @@ -17,4 +17,9 @@ describe 'chomp' do 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(["one", "two", "three"]) } + + context 'should run 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 diff --git a/spec/functions/chop_spec.rb b/spec/functions/chop_spec.rb index db7d18b..b70fc37 100755 --- a/spec/functions/chop_spec.rb +++ b/spec/functions/chop_spec.rb @@ -17,4 +17,9 @@ describe 'chop' do 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(["one", "tw", "three"]) } + + context 'should run 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 diff --git a/spec/functions/concat_spec.rb b/spec/functions/concat_spec.rb index eb76233..6ab1b6e 100755 --- a/spec/functions/concat_spec.rb +++ b/spec/functions/concat_spec.rb @@ -11,7 +11,11 @@ describe 'concat' do it { is_expected.to run.with_params(['1','2','3'],[['4','5'],'6']).and_return(['1','2','3',['4','5'],'6']) } it { is_expected.to run.with_params(['1','2'],['3','4'],['5','6']).and_return(['1','2','3','4','5','6']) } it { is_expected.to run.with_params(['1','2'],'3','4',['5','6']).and_return(['1','2','3','4','5','6']) } + +context 'should run 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(['ấ','β','©'],['đ','ể','文字列']).and_return(['ấ','β','©','đ','ể','文字列']) } +end it "should leave the original array intact" do argument1 = ['1','2','3'] diff --git a/spec/functions/count_spec.rb b/spec/functions/count_spec.rb index c8d1960..3854cb8 100755 --- a/spec/functions/count_spec.rb +++ b/spec/functions/count_spec.rb @@ -15,4 +15,9 @@ describe 'count' do 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 diff --git a/spec/functions/deep_merge_spec.rb b/spec/functions/deep_merge_spec.rb index 397e048..819e025 100755 --- a/spec/functions/deep_merge_spec.rb +++ b/spec/functions/deep_merge_spec.rb @@ -4,7 +4,7 @@ describe 'deep_merge' do it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } it { is_expected.to run.with_params({ 'key' => 'value' }).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } it { is_expected.to run.with_params({}, '2').and_raise_error(Puppet::ParseError, /unexpected argument type String/) } - it { is_expected.to run.with_params({}, 2).and_raise_error(Puppet::ParseError, /unexpected argument type Fixnum/) } + it { is_expected.to run.with_params({}, 2).and_raise_error(Puppet::ParseError, /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({}) } @@ -52,4 +52,8 @@ describe 'deep_merge' do expect(argument1).to eq(original1) expect(argument2).to eq(original2) end + + context 'should run with UTF8 and double byte characters' do + it { is_expected.to run.with_params({'ĸέỹ1' => 'ϋǻļủë1'}, {'この文字列' => '万' }).and_return({'ĸέỹ1' => 'ϋǻļủë1', 'この文字列' => '万'}) } + end end diff --git a/spec/functions/defined_with_params_spec.rb b/spec/functions/defined_with_params_spec.rb index e2f3abe..491a03b 100755 --- a/spec/functions/defined_with_params_spec.rb +++ b/spec/functions/defined_with_params_spec.rb @@ -11,6 +11,11 @@ describe 'defined_with_params' do 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 'should run 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 @@ -32,4 +37,32 @@ describe 'defined_with_params' do 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 '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 'array' do + it 'fails' do + expect { + subject.call([['User[dan]'], {}]) + }.to raise_error ArgumentError, /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 diff --git a/spec/functions/delete_at_spec.rb b/spec/functions/delete_at_spec.rb index 0e19472..0471039 100755 --- a/spec/functions/delete_at_spec.rb +++ b/spec/functions/delete_at_spec.rb @@ -18,6 +18,8 @@ describe 'delete_at' do 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(["ƒờở", "βāř", "ьầż"], 1).and_return(["ƒờở", "ьầż"]) } + it "should leave the original array intact" do argument = [1, 2, 3] diff --git a/spec/functions/delete_spec.rb b/spec/functions/delete_spec.rb index b44accf..4e37865 100755 --- a/spec/functions/delete_spec.rb +++ b/spec/functions/delete_spec.rb @@ -19,6 +19,7 @@ describe 'delete' do it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['one', 'three']) } it { is_expected.to run.with_params(['two', 'one', 'two', 'three', 'two'], 'two').and_return(['one', 'three']) } it { is_expected.to run.with_params(['one', 'two', 'three', 'two'], ['one', 'two']).and_return(['three']) } + it { is_expected.to run.with_params(['ồאּẻ', 'ŧẅơ', 'ŧңŗё℮', 'ŧẅơ'], ['ồאּẻ', 'ŧẅơ']).and_return(['ŧңŗё℮']) } end describe 'deleting from a string' do @@ -30,7 +31,8 @@ describe 'delete' do 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', ['foo', 'bar']).and_return('baz') } - # this is so sick + it { is_expected.to run.with_params('ƒōōβậяβậβậяź', ['ƒōō', 'βậя']).and_return('βậź') } + it { is_expected.to run.with_params('barfoobar', ['barbar', 'foo']).and_return('barbar') } it { is_expected.to run.with_params('barfoobar', ['foo', 'barbar']).and_return('') } end @@ -47,6 +49,10 @@ describe 'delete' do .with_params({'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}, ['key1', 'key2']) \ .and_return( {'key3' => 'value3'}) } + it { is_expected.to run \ + .with_params({'ĸəұ1' => 'νãŀủĕ1', 'ĸəұ2' => 'νãŀủĕ2', 'ĸəұ3' => 'νãŀủĕ3'}, ['ĸəұ1', 'ĸəұ2']) \ + .and_return( {'ĸəұ3' => 'νãŀủĕ3'}) + } end it "should leave the original array intact" do diff --git a/spec/functions/delete_undef_values_spec.rb b/spec/functions/delete_undef_values_spec.rb index ec9fb9c..c20cee2 100755 --- a/spec/functions/delete_undef_values_spec.rb +++ b/spec/functions/delete_undef_values_spec.rb @@ -16,6 +16,7 @@ describe 'delete_undef_values' do 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(['one','two','three']) } + it { is_expected.to run.with_params(['ớņέ',undef_value,'ŧשּׁō','ŧħґëə']).and_return(['ớņέ','ŧשּׁō','ŧħґëə']) } end it "should leave the original argument intact" do diff --git a/spec/functions/delete_values_spec.rb b/spec/functions/delete_values_spec.rb index 12907d4..329fa0b 100755 --- a/spec/functions/delete_values_spec.rb +++ b/spec/functions/delete_values_spec.rb @@ -19,7 +19,11 @@ describe 'delete_values' do .and_return({'key1' => 'value1'}) } it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value to delete'}, 'value to delete') \ + .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 \ diff --git a/spec/functions/deprecation_spec.rb b/spec/functions/deprecation_spec.rb index cee4f1c..bde4e89 100644 --- a/spec/functions/deprecation_spec.rb +++ b/spec/functions/deprecation_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.0 +if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'deprecation' do before(:each) { # this is to reset the strict variable to default @@ -40,7 +40,7 @@ if Puppet.version.to_f >= 4.0 Puppet.settings[:strict] = :warning } end -else +elsif Puppet.version.to_f < 4.0 # Puppet version < 4 will use these tests. describe 'deprecation' do after(:all) do diff --git a/spec/functions/difference_spec.rb b/spec/functions/difference_spec.rb index d5e983d..0ae3689 100755 --- a/spec/functions/difference_spec.rb +++ b/spec/functions/difference_spec.rb @@ -12,8 +12,10 @@ describe 'difference' do 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(['one', 'two', 'three'], ['two', 'three']).and_return(['one']) } + it { is_expected.to run.with_params(['ớņέ', 'ŧשּׁō', 'ŧħґëə', 2], ['ŧשּׁō', 'ŧħґëə']).and_return(['ớņέ', 2]) } it { is_expected.to run.with_params(['one', 'two', 'two', 'three'], ['two', 'three']).and_return(['one']) } it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['one']) } it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three', 'four']).and_return(['one']) } diff --git a/spec/functions/dig44_spec.rb b/spec/functions/dig44_spec.rb index 4f7408d..a7b8a3d 100644 --- a/spec/functions/dig44_spec.rb +++ b/spec/functions/dig44_spec.rb @@ -25,6 +25,18 @@ describe 'dig44' do } end + let(:utf8_data) do + { + 'ẵ' => { + 'в' => [ + '©', + 'ĝ', + 'に', + ] + } + } + end + context 'single values' do it 'should exist' do is_expected.not_to be_nil @@ -100,6 +112,20 @@ describe 'dig44' do it 'should return "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 'Internationalization (i18N) values' do + + it 'should be able to return a unicode character' do + is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 0]).and_return('©') + end + it 'should be able to return a utf8 character' do + is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 1]).and_return('ĝ') + end + + it 'should be able to return a double byte character' do + is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 2]).and_return('に') + end end end diff --git a/spec/functions/dirname_spec.rb b/spec/functions/dirname_spec.rb index 46c4c35..c494915 100755 --- a/spec/functions/dirname_spec.rb +++ b/spec/functions/dirname_spec.rb @@ -10,4 +10,9 @@ describe 'dirname' do 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 'should run 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 diff --git a/spec/functions/dos2unix_spec.rb b/spec/functions/dos2unix_spec.rb index 9c84703..97abae7 100644 --- a/spec/functions/dos2unix_spec.rb +++ b/spec/functions/dos2unix_spec.rb @@ -29,12 +29,19 @@ describe 'dos2unix' do end end - context 'Converting from unix to unix format' do - sample_text = "Hello\nWorld\n" - desired_output = "Hello\nWorld\n" + context 'Internationalization (i18N) values' do + sample_text_utf8 = "Ħ℮ļłǿ\r\nשׁөŕłđ\r\n" + desired_output_utf8 = "Ħ℮ļłǿ\nשׁөŕłđ\n" - it 'should output unix format' do - should run.with_params(sample_text).and_return(desired_output) + sample_text_doublebyte = "こんにちは\r\n世界\r\n" + desired_output_doublebyte = "こんにちは\n世界\n" + + it 'should output uft8 string' do + should run.with_params(sample_text_utf8).and_return(desired_output_utf8) + end + + it 'should output double byte string' do + should run.with_params(sample_text_doublebyte).and_return(desired_output_doublebyte) end end end diff --git a/spec/functions/ensure_packages_spec.rb b/spec/functions/ensure_packages_spec.rb index 5d97684..190e580 100755 --- a/spec/functions/ensure_packages_spec.rb +++ b/spec/functions/ensure_packages_spec.rb @@ -34,11 +34,38 @@ describe 'ensure_packages' do end end + context '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, /Empty String provided/) } + end + end + context 'given hash of packages' do before { subject.call([{"foo" => { "provider" => "rpm" }, "bar" => { "provider" => "gem" }}, { "ensure" => "present"}]) } + before { subject.call([{"パッケージ" => { "ensure" => "absent"}}]) } + before { subject.call([{"ρǻ¢κầģẻ" => { "ensure" => "absent"}}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(lambda { catalogue }).to contain_package('foo').with({'provider' => 'rpm', 'ensure' => 'present'}) } it { expect(lambda { catalogue }).to contain_package('bar').with({'provider' => 'gem', 'ensure' => 'present'}) } + + context 'should run with UTF8 and double byte characters' do + it { expect(lambda { catalogue }).to contain_package('パッケージ').with({'ensure' => 'absent'}) } + it { expect(lambda { catalogue }).to contain_package('ρǻ¢κầģẻ').with({'ensure' => 'absent'}) } + end end + + context '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 { subject.call(['puppet', { "ensure" => "installed" }]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_package('puppet').with_ensure('present') } + end + end + end diff --git a/spec/functions/ensure_resource_spec.rb b/spec/functions/ensure_resource_spec.rb index d552f4e..c847bf7 100755 --- a/spec/functions/ensure_resource_spec.rb +++ b/spec/functions/ensure_resource_spec.rb @@ -4,7 +4,7 @@ describe 'ensure_resource' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params().and_raise_error(ArgumentError, /Must specify a type/) } it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, /Must specify a title/) } - if Puppet.version.to_f >= 4.6 + 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) } @@ -39,6 +39,37 @@ describe 'ensure_resource' do it { expect(lambda { catalogue }).to contain_user('username1').without_gid } end + describe 'after running ensure_resource("test::deftype", "foo", {})' do + before { subject.call(['test::deftype', 'foo', {}]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_test__deftype('foo').without_ensure } + end + end + + context 'given a catalog with UTF8 chars' do + describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", {})' do + before { subject.call(['User', 'Şắოрŀễ Ţëם', {}]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } + end + + describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { gid => undef })' do + before { subject.call(['User', 'Şắოрŀễ Ţëם', { 'gid' => :undef }]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } + it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } + end + + describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { ensure => present, gid => undef })' do + before { subject.call(['User', 'Şắოрŀễ Ţëם', { 'ensure' => 'present', 'gid' => :undef }]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').with_ensure('present') } + it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } + end end context 'given a catalog with "user { username1: ensure => present }"' do @@ -90,4 +121,15 @@ describe 'ensure_resource' do } end end + + context 'given a catalog with "test::deftype { foo: }"' do + let(:pre_condition) { 'test::deftype { "foo": }' } + + describe 'after running ensure_resource("test::deftype", "foo", {})' do + before { subject.call(['test::deftype', 'foo', {}]) } + + # this lambda is required due to strangeness within rspec-puppet's expectation handling + it { expect(lambda { catalogue }).to contain_test__deftype('foo').without_ensure } + end + end end diff --git a/spec/functions/ensure_resources_spec.rb b/spec/functions/ensure_resources_spec.rb new file mode 100644 index 0000000..7cca671 --- /dev/null +++ b/spec/functions/ensure_resources_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper' + +describe 'ensure_resources' do + it { is_expected.not_to eq(nil) } + it { is_expected.to run.with_params().and_raise_error(ArgumentError, /Must specify a type/) } + it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, /Must specify a title/) } + + describe 'given a title hash of multiple resources' do + before { 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(lambda { catalogue }).to contain_user('dan').with_ensure('present') } + it { expect(lambda { catalogue }).to contain_user('alex').with_ensure('present') } + it { expect(lambda { catalogue }).to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600'}) } + it { expect(lambda { catalogue }).to contain_user('alex').with({ 'gid' => 'mygroup', 'uid' => '700'}) } + end + + describe 'given a title hash of a single resource' do + before { 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(lambda { catalogue }).to contain_user('dan').with_ensure('present') } + it { expect(lambda { catalogue }).to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600'}) } + end +end diff --git a/spec/functions/flatten_spec.rb b/spec/functions/flatten_spec.rb index a4338be..b80f3c5 100755 --- a/spec/functions/flatten_spec.rb +++ b/spec/functions/flatten_spec.rb @@ -11,4 +11,5 @@ describe 'flatten' do it { is_expected.to run.with_params([['one']]).and_return(['one']) } it { is_expected.to run.with_params(["a","b","c","d","e","f","g"]).and_return(["a","b","c","d","e","f","g"]) } it { is_expected.to run.with_params([["a","b",["c",["d","e"],"f","g"]]]).and_return(["a","b","c","d","e","f","g"]) } + it { is_expected.to run.with_params(["ã","β",["ĉ",["đ","ẽ","ƒ","ġ"]]]).and_return(["ã","β","ĉ","đ","ẽ","ƒ","ġ"]) } end diff --git a/spec/functions/fqdn_rand_string_spec.rb b/spec/functions/fqdn_rand_string_spec.rb index e407084..861a59e 100644 --- a/spec/functions/fqdn_rand_string_spec.rb +++ b/spec/functions/fqdn_rand_string_spec.rb @@ -20,6 +20,7 @@ describe 'fqdn_rand_string' do it { is_expected.to run.with_params(100, '').and_return(default_charset) } it { is_expected.to run.with_params(100, 'a').and_return(/\Aa{100}\z/) } it { is_expected.to run.with_params(100, 'ab').and_return(/\A[ab]{100}\z/) } + it { is_expected.to run.with_params(100, 'ãβ').and_return(/\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)) diff --git a/spec/functions/fqdn_rotate_spec.rb b/spec/functions/fqdn_rotate_spec.rb index db7a717..7c1038a 100755 --- a/spec/functions/fqdn_rotate_spec.rb +++ b/spec/functions/fqdn_rotate_spec.rb @@ -7,6 +7,7 @@ describe 'fqdn_rotate' do it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /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']) } diff --git a/spec/functions/fqdn_uuid_spec.rb b/spec/functions/fqdn_uuid_spec.rb index a2d1618..d0c30d6 100644 --- a/spec/functions/fqdn_uuid_spec.rb +++ b/spec/functions/fqdn_uuid_spec.rb @@ -10,5 +10,4 @@ describe 'fqdn_uuid' do it { should run.with_params('puppetlabs.com').and_return('9c70320f-6815-5fc5-ab0f-debe68bf764c') } it { should run.with_params('google.com').and_return('64ee70a4-8cc1-5d25-abf2-dea6c79a09c8') } end - end diff --git a/spec/functions/getparam_spec.rb b/spec/functions/getparam_spec.rb index e4ef9e6..522ed3b 100755 --- a/spec/functions/getparam_spec.rb +++ b/spec/functions/getparam_spec.rb @@ -24,4 +24,12 @@ describe 'getparam' do 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 diff --git a/spec/functions/getvar_spec.rb b/spec/functions/getvar_spec.rb index 54f1842..55789d8 100755 --- a/spec/functions/getvar_spec.rb +++ b/spec/functions/getvar_spec.rb @@ -20,4 +20,19 @@ describe 'getvar' do 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 'given variables in namespaces' do + let(:pre_condition) { + <<-'ENDofPUPPETcode' + class site::info { $lock = 'ŧҺîš íš ắ śţřĭŋĝ' } + class site::new { $item = '万Ü€‰' } + include site::info + include site::new + ENDofPUPPETcode + } + + 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 + diff --git a/spec/functions/glob_spec.rb b/spec/functions/glob_spec.rb new file mode 100755 index 0000000..06439da --- /dev/null +++ b/spec/functions/glob_spec.rb @@ -0,0 +1,11 @@ +require '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 diff --git a/spec/functions/grep_spec.rb b/spec/functions/grep_spec.rb index 6e0bd6e..d2152b1 100755 --- a/spec/functions/grep_spec.rb +++ b/spec/functions/grep_spec.rb @@ -16,4 +16,5 @@ describe 'grep' do it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['two']) } it { is_expected.to run.with_params(['one', 'two', 'three'], 't(wo|hree)').and_return(['two', 'three']) } + it { is_expected.to run.with_params(['ờאּê', 'ţשּׂỡ', 'ţһŗəè'], 'ţ(שּׂỡ|һŗəè)').and_return(['ţשּׂỡ', 'ţһŗəè']) } end diff --git a/spec/functions/has_ip_network_spec.rb b/spec/functions/has_ip_network_spec.rb index 7b5fe66..57cf613 100755 --- a/spec/functions/has_ip_network_spec.rb +++ b/spec/functions/has_ip_network_spec.rb @@ -9,7 +9,6 @@ describe 'has_ip_network' do let(:facts) do { :interfaces => 'eth0,lo', - :network => :undefined, :network_lo => '127.0.0.0', :network_eth0 => '10.0.0.0', } diff --git a/spec/functions/has_key_spec.rb b/spec/functions/has_key_spec.rb index 965d5a6..0e0e1cc 100755 --- a/spec/functions/has_key_spec.rb +++ b/spec/functions/has_key_spec.rb @@ -12,4 +12,9 @@ describe 'has_key' do 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 'should run 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 diff --git a/spec/functions/hash_spec.rb b/spec/functions/hash_spec.rb index 4fe99ce..092474b 100755 --- a/spec/functions/hash_spec.rb +++ b/spec/functions/hash_spec.rb @@ -10,5 +10,6 @@ describe 'hash' do it { is_expected.to run.with_params(['one']).and_raise_error(Puppet::ParseError, /Unable to compute/) } it { is_expected.to run.with_params([]).and_return({}) } it { is_expected.to run.with_params(['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(['key1', 'value1', 'key2', 'value2']).and_return({ 'key1' => 'value1', 'key2' => 'value2' }) } end diff --git a/spec/functions/intersection_spec.rb b/spec/functions/intersection_spec.rb index c0f6086..ec368a5 100755 --- a/spec/functions/intersection_spec.rb +++ b/spec/functions/intersection_spec.rb @@ -14,6 +14,7 @@ describe 'intersection' do 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(['one', 'two', 'three'], ['two', 'three']).and_return(['two', 'three']) } + it { is_expected.to run.with_params(['ōŋể', 'ŧשợ', 'ţђŕẽё'], ['ŧשợ', 'ţђŕẽё']).and_return(['ŧשợ', 'ţђŕẽё']) } it { is_expected.to run.with_params(['one', 'two', 'two', 'three'], ['two', 'three']).and_return(['two', 'three']) } it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['two', 'three']) } it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three', 'four']).and_return(['two', 'three']) } diff --git a/spec/functions/is_a_spec.rb b/spec/functions/is_a_spec.rb index 8dec13f..2d6cb46 100644 --- a/spec/functions/is_a_spec.rb +++ b/spec/functions/is_a_spec.rb @@ -21,5 +21,10 @@ if Puppet.version.to_f >= 4.0 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 + is_expected.to run.with_params('このテキスト', String).and_return(true) + is_expected.to run.with_params('ŧћịś ŧêχŧ', String).and_return(true) + end end end diff --git a/spec/functions/is_function_available.rb b/spec/functions/is_function_available_spec.rb index 44f08c0..44f08c0 100755 --- a/spec/functions/is_function_available.rb +++ b/spec/functions/is_function_available_spec.rb diff --git a/spec/functions/is_integer_spec.rb b/spec/functions/is_integer_spec.rb index b296830..8118ef4 100755 --- a/spec/functions/is_integer_spec.rb +++ b/spec/functions/is_integer_spec.rb @@ -11,6 +11,8 @@ describe 'is_integer' do 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) } @@ -24,6 +26,7 @@ describe 'is_integer' do 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 'Checking for deprecation warning' do after(:all) do diff --git a/spec/functions/is_mac_address_spec.rb b/spec/functions/is_mac_address_spec.rb index 5f76a91..c1e33b8 100755 --- a/spec/functions/is_mac_address_spec.rb +++ b/spec/functions/is_mac_address_spec.rb @@ -9,6 +9,12 @@ describe 'is_mac_address' do 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 'function can handle 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) diff --git a/spec/functions/join_keys_to_values_spec.rb b/spec/functions/join_keys_to_values_spec.rb index c2bae5b..0a2a50c 100755 --- a/spec/functions/join_keys_to_values_spec.rb +++ b/spec/functions/join_keys_to_values_spec.rb @@ -11,6 +11,12 @@ describe 'join_keys_to_values' do 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 'should run 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 'should run join_keys_to_values(<hash with multiple keys>, ":") and return the proper array' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }, ':']) @@ -21,3 +27,4 @@ describe 'join_keys_to_values' do expect(result.sort).to eq(['key1 value1', 'key2 value2', 'key2 value3'].sort) end end + diff --git a/spec/functions/join_spec.rb b/spec/functions/join_spec.rb index a300571..98852d5 100755 --- a/spec/functions/join_spec.rb +++ b/spec/functions/join_spec.rb @@ -16,4 +16,5 @@ describe 'join' do it { is_expected.to run.with_params(['one'], ':').and_return('one') } it { is_expected.to run.with_params(['one', 'two', 'three']).and_return('onetwothree') } it { is_expected.to run.with_params(['one', 'two', 'three'], ':').and_return('one:two:three') } + it { is_expected.to run.with_params(['ōŋể', 'ŧשợ', 'ţђŕẽё'], ':').and_return('ōŋể:ŧשợ:ţђŕẽё') } end diff --git a/spec/functions/keys_spec.rb b/spec/functions/keys_spec.rb index 2e009dc..fc7d6d8 100755 --- a/spec/functions/keys_spec.rb +++ b/spec/functions/keys_spec.rb @@ -16,4 +16,9 @@ describe 'keys' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }]) expect(result).to match_array(['key1', 'key2']) end + + it 'should run with UTF8 and double byte characters' do + result = subject.call([{ 'ҝểү' => '√ẳŀμệ', 'キー' => '値' }]) + expect(result).to match_array(['ҝểү', 'キー']) + end end diff --git a/spec/functions/length_spec.rb b/spec/functions/length_spec.rb new file mode 100755 index 0000000..487cf21 --- /dev/null +++ b/spec/functions/length_spec.rb @@ -0,0 +1,31 @@ +require 'spec_helper' + +describe 'length' do + it { is_expected.not_to eq(nil) } + it { is_expected.to run.with_params().and_raise_error(ArgumentError, /'length' expects 1 argument, got none/) } + it { is_expected.to run.with_params([], 'extra').and_raise_error(ArgumentError, /'length' expects 1 argument, got 2/) } + it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, /expects a value of type String, Array, or Hash, got Integer/) } + it { is_expected.to run.with_params(true).and_raise_error(ArgumentError, /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(['one', 'two', 'three']).and_return(3) } + it { is_expected.to run.with_params(['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 diff --git a/spec/functions/load_module_metadata_spec.rb b/spec/functions/load_module_metadata_spec.rb index 1a61e2c..9496fcb 100755 --- a/spec/functions/load_module_metadata_spec.rb +++ b/spec/functions/load_module_metadata_spec.rb @@ -7,32 +7,55 @@ describe 'load_module_metadata' do describe "when calling with valid arguments" do before :each do - if RSpec.configuration.puppet_future - allow(File).to receive(:read).with(/\/stdlib\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') - else - allow(File).to receive(:read).with(/\/stdlib\/metadata.json/).and_return('{"name": "puppetlabs-stdlib"}') - end + allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(/\/(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(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - +この文字"}') + allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - +この文字"}') + end + it "should json parse the file" do - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(true) - allow(File).to receive(:read).with('/path/to/module/metadata.json').and_return('{"name": "spencer-science"}') + if Puppet::Util::Platform.windows? + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') + allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(true) + allow(File).to receive(:read).with('C:/path/to/module/metadata.json').and_return('{"name": "spencer-science"}') + else + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') + allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(true) + allow(File).to receive(:read).with('/path/to/module/metadata.json').and_return('{"name": "spencer-science"}') + end result = subject.call(['science']) expect(result['name']).to eq('spencer-science') end it "should fail by default if there is no metadata.json" do - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + if Puppet::Util::Platform.windows? + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') + allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(false) + else + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') + allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + end expect {subject.call(['science'])}.to raise_error(Puppet::ParseError) end it "should return nil if user allows empty metadata.json" do - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + if Puppet::Util::Platform.windows? + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') + allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(false) + else + allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') + allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + end result = subject.call(['science', true]) expect(result).to eq({}) end + end end end diff --git a/spec/functions/loadjson_spec.rb b/spec/functions/loadjson_spec.rb index a00dff9..dbef805 100644 --- a/spec/functions/loadjson_spec.rb +++ b/spec/functions/loadjson_spec.rb @@ -6,26 +6,37 @@ describe 'loadjson' do describe "when calling with valid arguments" do before :each do - if RSpec.configuration.puppet_future - allow(File).to receive(:read).with(/\/stdlib\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') - else - allow(File).to receive(:read).with(/\/stdlib\/metadata.json/).and_return('{"name": "puppetlabs-stdlib"}') - end + allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/).and_return('{"name": "puppetlabs-stdlib"}') end context 'when a non-existing file is specified' do - let(:filename) { '/tmp/doesnotexist' } + let(:filename) { + if Puppet::Util::Platform.windows? + 'C:/tmp/doesnotexist' + else + '/tmp/doesnotexist' + end + } before { allow(File).to receive(:exists?).with(filename).and_return(false).once allow(PSON).to receive(:load).never } 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' } } - let(:json) { '{"key":"value"}' } + let(:filename) { + if Puppet::Util::Platform.windows? + 'C:/tmp/doesexist' + else + '/tmp/doesexist' + end + } + let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'} } + let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } before { allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once @@ -36,7 +47,13 @@ describe 'loadjson' do end context 'when the file could not be parsed' do - let(:filename) { '/tmp/doesexist' } + let(:filename) { + if Puppet::Util::Platform.windows? + 'C:/tmp/doesexist' + else + '/tmp/doesexist' + end + } let(:json) { '{"key":"value"}' } before { allow(File).to receive(:exists?).with(filename).and_return(true).once diff --git a/spec/functions/loadyaml_spec.rb b/spec/functions/loadyaml_spec.rb index 9f16a1a..e9428e3 100755 --- a/spec/functions/loadyaml_spec.rb +++ b/spec/functions/loadyaml_spec.rb @@ -11,11 +11,13 @@ describe 'loadyaml' do YAML.expects(:load_file).never } 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' } } + let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'} } before { File.expects(:exists?).with(filename).returns(true).once YAML.expects(:load_file).with(filename).returns(data).once diff --git a/spec/functions/lstrip_spec.rb b/spec/functions/lstrip_spec.rb index 981794e..a5a09ed 100755 --- a/spec/functions/lstrip_spec.rb +++ b/spec/functions/lstrip_spec.rb @@ -22,6 +22,7 @@ describe 'lstrip' do 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") } diff --git a/spec/functions/member_spec.rb b/spec/functions/member_spec.rb index 527f887..8988632 100755 --- a/spec/functions/member_spec.rb +++ b/spec/functions/member_spec.rb @@ -17,5 +17,7 @@ describe 'member' do 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(['one', 'two', 'three', 'four'], ['four', 'two']).and_return(true) } + it { is_expected.to run.with_params(['ọאּẹ', 'ŧẅồ', 'ţҺŗęē', 'ƒơџŕ'], ['ƒơџŕ', 'ŧẅồ']).and_return(true) } it { is_expected.to run.with_params(['one', 'two', 'three', 'four'], ['four', 'five']).and_return(false) } + it { is_expected.to run.with_params(['ọאּẹ', 'ŧẅồ', 'ţҺŗęē', 'ƒơџŕ'], ['ƒơџŕ', 'ƒί√ə']).and_return(false) } end diff --git a/spec/functions/merge_spec.rb b/spec/functions/merge_spec.rb index 7b53363..3b2e3ef 100755 --- a/spec/functions/merge_spec.rb +++ b/spec/functions/merge_spec.rb @@ -4,7 +4,7 @@ describe 'merge' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } it { is_expected.to run.with_params({}, 'two').and_raise_error(Puppet::ParseError, /unexpected argument type String/) } - it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, /unexpected argument type Fixnum/) } + it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, /unexpected argument type (Fixnum|Integer)/) } it { pending 'should not special case this' is_expected.to run.with_params({}).and_return({}) diff --git a/spec/functions/parsejson_spec.rb b/spec/functions/parsejson_spec.rb index a01f1f6..7b07e49 100755 --- a/spec/functions/parsejson_spec.rb +++ b/spec/functions/parsejson_spec.rb @@ -12,12 +12,12 @@ describe 'parsejson' do context 'with correct JSON data' do - it 'should be able to parse a JSON data with a Hash' do + it 'should be 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 'should be able to parse a JSON data with an Array' do + it 'should be able to parse JSON data with an Array' do is_expected.to run.with_params('["a","b","c"]'). and_return(['a', 'b', 'c']) end @@ -29,11 +29,16 @@ describe 'parsejson' do and_return({}) end - it 'should be able to parse a JSON data with a mixed structure' do + it 'should be 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 'should be able to parse JSON data with a UTF8 and double byte characters' do + is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}'). + and_return({'×' =>'これ', 'ý' => '記号', 'です' => { '©' => ['Á', 'ß'] } }) + end + it 'should 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'}) diff --git a/spec/functions/parseyaml_spec.rb b/spec/functions/parseyaml_spec.rb index fa947ca..c2a138c 100755 --- a/spec/functions/parseyaml_spec.rb +++ b/spec/functions/parseyaml_spec.rb @@ -18,21 +18,26 @@ describe 'parseyaml' do and_return('just a string') end - it 'should be able to parse a YAML data with a Hash' do + it 'should be 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 'should be able to parse a YAML data with an Array' do + it 'should be able to parse YAML data with an Array' do is_expected.to run.with_params("---\n- a\n- b\n- c\n"). and_return(['a', 'b', 'c']) end - it 'should be able to parse a YAML data with a mixed structure' do + it 'should be 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 'should be 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"=>"×", "これ"=>"記号", "です"=>{"©"=>["Á", "ß"]} }) + end + it 'should 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'}) diff --git a/spec/functions/pick_default_spec.rb b/spec/functions/pick_default_spec.rb index e2fc64a..a7ffc86 100755 --- a/spec/functions/pick_default_spec.rb +++ b/spec/functions/pick_default_spec.rb @@ -5,6 +5,7 @@ describe 'pick_default' do it { is_expected.to run.with_params().and_raise_error(Puppet::Error, /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') } @@ -13,6 +14,7 @@ describe 'pick_default' do [ '', :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) } diff --git a/spec/functions/pick_spec.rb b/spec/functions/pick_spec.rb index 2c7caa8..438553b 100755 --- a/spec/functions/pick_spec.rb +++ b/spec/functions/pick_spec.rb @@ -9,4 +9,9 @@ describe 'pick' do 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 'should run 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 diff --git a/spec/functions/prefix_spec.rb b/spec/functions/prefix_spec.rb index 3761022..5510c58 100755 --- a/spec/functions/prefix_spec.rb +++ b/spec/functions/prefix_spec.rb @@ -11,6 +11,7 @@ describe 'prefix' do it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, /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(['one', '2']) } + it { is_expected.to run.with_params(['ớņệ', 2]).and_return(['ớņệ', '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']) } diff --git a/spec/functions/pw_hash_spec.rb b/spec/functions/pw_hash_spec.rb index df5348c..9e03464 100644 --- a/spec/functions/pw_hash_spec.rb +++ b/spec/functions/pw_hash_spec.rb @@ -65,5 +65,13 @@ describe 'pw_hash' do 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 diff --git a/spec/functions/range_spec.rb b/spec/functions/range_spec.rb index 492cad4..ca569d5 100755 --- a/spec/functions/range_spec.rb +++ b/spec/functions/range_spec.rb @@ -79,6 +79,14 @@ describe 'range' do 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(['ħөŝŧ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(['ホスト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]) } diff --git a/spec/functions/regexpescape_spec.rb b/spec/functions/regexpescape_spec.rb index 6efa847..36dbe70 100644 --- a/spec/functions/regexpescape_spec.rb +++ b/spec/functions/regexpescape_spec.rb @@ -32,5 +32,10 @@ describe 'regexpescape' 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 'should run 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 diff --git a/spec/functions/reject_spec.rb b/spec/functions/reject_spec.rb index 4863050..86db7c7 100755 --- a/spec/functions/reject_spec.rb +++ b/spec/functions/reject_spec.rb @@ -16,4 +16,5 @@ describe 'reject' do it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['one', 'three']) } it { is_expected.to run.with_params(['one', 'two', 'three'], 't(wo|hree)').and_return(['one']) } + it { is_expected.to run.with_params(['όʼnệ', 'ţщồ', 'ţңяέέ'], 'ţ(щồ|ңяέέ)').and_return(['όʼnệ']) } end diff --git a/spec/functions/reverse_spec.rb b/spec/functions/reverse_spec.rb index e00dee9..79bc0ad 100755 --- a/spec/functions/reverse_spec.rb +++ b/spec/functions/reverse_spec.rb @@ -15,11 +15,13 @@ describe 'reverse' do it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(['three', 'two', 'one']) } it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(['four', 'three', 'two', 'one']) } + 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 { 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 'should call its reverse method' do diff --git a/spec/functions/round_spec.rb b/spec/functions/round_spec.rb new file mode 100755 index 0000000..8b13478 --- /dev/null +++ b/spec/functions/round_spec.rb @@ -0,0 +1,14 @@ +require '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 diff --git a/spec/functions/rstrip_spec.rb b/spec/functions/rstrip_spec.rb index d2efac8..a7663e2 100755 --- a/spec/functions/rstrip_spec.rb +++ b/spec/functions/rstrip_spec.rb @@ -22,6 +22,7 @@ describe 'rstrip' do 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') } diff --git a/spec/functions/seeded_rand_spec.rb b/spec/functions/seeded_rand_spec.rb index 38e134e..ac108f4 100644 --- a/spec/functions/seeded_rand_spec.rb +++ b/spec/functions/seeded_rand_spec.rb @@ -50,4 +50,9 @@ describe 'seeded_rand' do scope.function_seeded_rand([max, seed]) end + + context 'should run 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 diff --git a/spec/functions/shell_escape_spec.rb b/spec/functions/shell_escape_spec.rb index 3061dec..77917dd 100644 --- a/spec/functions/shell_escape_spec.rb +++ b/spec/functions/shell_escape_spec.rb @@ -19,4 +19,9 @@ describe 'shell_escape' do it { is_expected.to run.with_params('~`!@#$%^&*()_+-=[]\{}|;\':",./<>?') .and_return('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') } end + + context 'should run 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 diff --git a/spec/functions/shell_join_spec.rb b/spec/functions/shell_join_spec.rb index 6815f7c..46305bf 100644 --- a/spec/functions/shell_join_spec.rb +++ b/spec/functions/shell_join_spec.rb @@ -15,6 +15,11 @@ describe 'shell_join' do 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 'should run 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 end describe 'stringification' do diff --git a/spec/functions/shell_split_spec.rb b/spec/functions/shell_split_spec.rb index beeb977..f8f9c90 100644 --- a/spec/functions/shell_split_spec.rb +++ b/spec/functions/shell_split_spec.rb @@ -20,5 +20,10 @@ describe 'shell_split' do .and_return(['~`!@#$%^&*()_+-=[]\{}|;\':",./<>?']) } it { is_expected.to run.with_params('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') .and_return(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) } + + context 'should run 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 end end diff --git a/spec/functions/shuffle_spec.rb b/spec/functions/shuffle_spec.rb index ebc3a73..4673daa 100755 --- a/spec/functions/shuffle_spec.rb +++ b/spec/functions/shuffle_spec.rb @@ -26,6 +26,11 @@ describe 'shuffle' do it { is_expected.to run.with_params('abc').and_return('bac') } it { is_expected.to run.with_params('abcd').and_return('dcba') } + context 'should run 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 diff --git a/spec/functions/size_spec.rb b/spec/functions/size_spec.rb index c0047ee..2047423 100755 --- a/spec/functions/size_spec.rb +++ b/spec/functions/size_spec.rb @@ -19,11 +19,14 @@ describe 'size' do 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 'should call its size method' do diff --git a/spec/functions/squeeze_spec.rb b/spec/functions/squeeze_spec.rb index 7f09c30..b267d9a 100755 --- a/spec/functions/squeeze_spec.rb +++ b/spec/functions/squeeze_spec.rb @@ -16,6 +16,12 @@ describe 'squeeze' do it { is_expected.to run.with_params('aaaaaaaaabbbbbbbbbbcccccccccc', 'b-c').and_return('aaaaaaaaabc') } end + context 'should run 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 \ diff --git a/spec/functions/strftime_spec.rb b/spec/functions/strftime_spec.rb index e76774a..41cda6a 100755 --- a/spec/functions/strftime_spec.rb +++ b/spec/functions/strftime_spec.rb @@ -14,9 +14,9 @@ describe 'strftime' do expect(result.to_i).to(be > 1311953157) end - it "using %s should be lower then 1.5 trillion" do + it "using %s should be greater than 1.5 trillion" do result = scope.function_strftime(["%s"]) - expect(result.to_i).to(be < 1500000000) + expect(result.to_i).to(be > 1500000000) end it "should return a date when given %Y-%m-%d" do diff --git a/spec/functions/strip_spec.rb b/spec/functions/strip_spec.rb index 689b6dd..18e943d 100755 --- a/spec/functions/strip_spec.rb +++ b/spec/functions/strip_spec.rb @@ -30,5 +30,6 @@ describe 'strip' do 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 diff --git a/spec/functions/suffix_spec.rb b/spec/functions/suffix_spec.rb index efba4ab..e0eafb1 100755 --- a/spec/functions/suffix_spec.rb +++ b/spec/functions/suffix_spec.rb @@ -15,6 +15,8 @@ describe 'suffix' do 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(['one', 'two', 'three'], 'post').and_return(['onepost', 'twopost', 'threepost']) } + it { is_expected.to run.with_params(['ỗńέ', 'ťשׂǿ', 'ŧҺř℮ə'], 'рổŝţ').and_return(['ỗńέрổŝţ', 'ťשׂǿрổŝţ', 'ŧҺř℮əрổŝţ']) } + it { is_expected.to run.with_params({}).and_return({}) } diff --git a/spec/functions/to_json_pretty_spec.rb b/spec/functions/to_json_pretty_spec.rb new file mode 100755 index 0000000..abbcc2c --- /dev/null +++ b/spec/functions/to_json_pretty_spec.rb @@ -0,0 +1,11 @@ +require '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]") } + it { is_expected.to run.with_params(['one']).and_return("[\n \"one\"\n]") } + it { is_expected.to run.with_params(['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("{\n \"key\": \"value\"\n}") } + it { is_expected.to run.with_params({"one" => {"oneA" => "A","oneB" => {"oneB1" => "1","oneB2" => "2"}},"two" => ["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}") } +end diff --git a/spec/functions/to_json_spec.rb b/spec/functions/to_json_spec.rb new file mode 100755 index 0000000..925523c --- /dev/null +++ b/spec/functions/to_json_spec.rb @@ -0,0 +1,19 @@ +require '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(['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" => ["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 diff --git a/spec/functions/to_yaml_spec.rb b/spec/functions/to_yaml_spec.rb new file mode 100755 index 0000000..3f69a70 --- /dev/null +++ b/spec/functions/to_yaml_spec.rb @@ -0,0 +1,17 @@ +require '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(['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" => ["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 diff --git a/spec/functions/union_spec.rb b/spec/functions/union_spec.rb index cfd38b6..3f36f24 100755 --- a/spec/functions/union_spec.rb +++ b/spec/functions/union_spec.rb @@ -20,5 +20,6 @@ describe 'union' do it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['one', 'two', 'three']) } it { is_expected.to run.with_params(['one', 'two'], ['two', 'three'], ['one', 'three']).and_return(['one', 'two', 'three']) } it { is_expected.to run.with_params(['one', 'two'], ['three', 'four'], ['one', 'two', 'three'], ['four']).and_return(['one', 'two', 'three', 'four']) } + it { is_expected.to run.with_params(['ốńə', 'ţשׂợ'], ['ŧĥяếệ', 'ƒởųŗ'], ['ốńə', 'ţשׂợ', 'ŧĥяếệ'], ['ƒởųŗ']).and_return(['ốńə', 'ţשׂợ', 'ŧĥяếệ', 'ƒởųŗ']) } it 'should not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return(['1', '2', '3', 1, 2]) end end diff --git a/spec/functions/unique_spec.rb b/spec/functions/unique_spec.rb index 24257a0..76932ec 100755 --- a/spec/functions/unique_spec.rb +++ b/spec/functions/unique_spec.rb @@ -1,27 +1,31 @@ require 'spec_helper' describe 'unique' do - describe 'signature validation' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /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, /wrong number of arguments/i) - } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - end + 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, /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, /wrong number of arguments/i) + } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /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(['a', 'b', 'a']).and_return(['a', 'b']) } - 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(['a', 'b', 'a']).and_return(['a', 'b']) } + it { is_expected.to run.with_params(['ã', 'ъ', 'ã']).and_return(['ã', 'ъ']) } + 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') } + 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 diff --git a/spec/functions/validate_cmd_spec.rb b/spec/functions/validate_cmd_spec.rb index ab0cbc9..c6559e8 100755 --- a/spec/functions/validate_cmd_spec.rb +++ b/spec/functions/validate_cmd_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe 'validate_cmd' do +describe 'validate_cmd', :unless => Puppet::Util::Platform.windows? do let(:touch) { File.exists?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' } describe 'signature validation' do diff --git a/spec/functions/validate_domain_name_spec.rb b/spec/functions/validate_domain_name_spec.rb new file mode 100644 index 0000000..69fcae4 --- /dev/null +++ b/spec/functions/validate_domain_name_spec.rb @@ -0,0 +1,35 @@ +require '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, /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, /is not a string/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } + + it { is_expected.to run.with_params('foo.example.com', []).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params('foo.example.com', {}).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params('foo.example.com', 1).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params('foo.example.com', true).and_raise_error(Puppet::ParseError, /is not a string/) } + + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + it { is_expected.to run.with_params('invalid domain').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + it { is_expected.to run.with_params('-foo.example.com').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + it { is_expected.to run.with_params('www.example.2com').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + it { is_expected.to run.with_params('192.168.1.1').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + end +end diff --git a/spec/functions/validate_ipv6_address_spec.rb b/spec/functions/validate_ipv6_address_spec.rb index 78810d4..137db36 100755 --- a/spec/functions/validate_ipv6_address_spec.rb +++ b/spec/functions/validate_ipv6_address_spec.rb @@ -29,6 +29,13 @@ describe 'validate_ipv6_address' do 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 @@ -38,6 +45,9 @@ describe 'validate_ipv6_address' do it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } + it { is_expected.to run.with_params('::ffff:2.3.4').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } + it { is_expected.to run.with_params('::ffff:257.1.2.3').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } + it { is_expected.to run.with_params('::ffff:12345678901234567890.1.26').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } it { is_expected.to run.with_params('affe:beef').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, /is not a string/) } it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, /is not a string/) } diff --git a/spec/functions/validate_legacy_spec.rb b/spec/functions/validate_legacy_spec.rb index 50cb317..7b48f12 100644 --- a/spec/functions/validate_legacy_spec.rb +++ b/spec/functions/validate_legacy_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if Puppet.version.to_f >= 4.0 +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) } diff --git a/spec/functions/values_at_spec.rb b/spec/functions/values_at_spec.rb index a8348f3..681c101 100755 --- a/spec/functions/values_at_spec.rb +++ b/spec/functions/values_at_spec.rb @@ -30,6 +30,11 @@ describe 'values_at' do it { is_expected.to run.with_params([0, 1, 2], 3).and_raise_error(Puppet::ParseError, /index exceeds array size/) } end + context 'when requesting a single item using UTF8 and double byte characters' do + it { is_expected.to run.with_params(['ẩ', 'β', 'с', 'ď'], 0).and_return(['ẩ']) } + it { is_expected.to run.with_params(['文', '字', 'の', '値'], 2).and_return(['の']) } + end + context 'when requesting multiple items' do it { is_expected.to run.with_params([0, 1, 2], [1, -1]).and_raise_error(Puppet::ParseError, /Unknown format of given index/) } it { is_expected.to run.with_params([0, 1, 2], [0, 2]).and_return([0, 2]) } diff --git a/spec/functions/values_spec.rb b/spec/functions/values_spec.rb index 4abf0bd..26c6dfb 100755 --- a/spec/functions/values_spec.rb +++ b/spec/functions/values_spec.rb @@ -16,4 +16,9 @@ describe 'values' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2', 'duplicate_value_key' => 'value2' }]) expect(result).to match_array(['value1', 'value2', 'value2']) end + + it 'should run with UTF8 and double byte characters' do + result = subject.call([{ 'かぎ' => '使用', 'ҝĕұ' => '√ẩŀứệ', 'ҝĕұďŭрļǐçằťè' => '√ẩŀứệ' }]) + expect(result).to match_array(['使用', '√ẩŀứệ', '√ẩŀứệ']) + end end diff --git a/spec/functions/zip_spec.rb b/spec/functions/zip_spec.rb index abca7ee..e1ae8ee 100755 --- a/spec/functions/zip_spec.rb +++ b/spec/functions/zip_spec.rb @@ -12,4 +12,10 @@ describe 'zip' do 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 'should run 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 end + diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 8a1907f..4d85e7d 100755 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -1,36 +1,21 @@ #! /usr/bin/env ruby -S rspec +require 'puppet' require 'beaker-rspec' require 'beaker/puppet_install_helper' - -UNSUPPORTED_PLATFORMS = [] +require 'beaker/module_install_helper' run_puppet_install_helper +install_ca_certs unless ENV['PUPPET_INSTALL_TYPE'] =~ /pe/i +install_module_on(hosts) +install_module_dependencies_on(hosts) RSpec.configure do |c| - # Project root - proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do - if ENV['FUTURE_PARSER'] == 'yes' - default[:default_apply_opts] ||= {} - default[:default_apply_opts].merge!({:parser => 'future'}) - end - - copy_root_module_to(default, :source => proj_root, :module_name => 'stdlib') - end -end - -def is_future_parser_enabled? - if default[:type] == 'aio' || ENV['PUPPET_INSTALL_TYPE'] == 'agent' - return true - elsif default[:default_apply_opts] - return default[:default_apply_opts][:parser] == 'future' end - return false end def get_puppet_version diff --git a/spec/unit/ensure_resources_spec.rb b/spec/unit/ensure_resources_spec.rb deleted file mode 100644 index aea723e..0000000 --- a/spec/unit/ensure_resources_spec.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'spec_helper' - -describe 'test::ensure_resources', type: :class do - let(:params) {{ resource_type: 'user', title_hash: title_param, attributes_hash: {'ensure' => 'present'} }} - - describe 'given a title hash of multiple resources' do - - let(:title_param) { {'dan' => { 'gid' => 'mygroup', 'uid' => '600' }, 'alex' => { 'gid' => 'mygroup', 'uid' => '700'}} } - - it { is_expected.to compile } - it { is_expected.to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600', 'ensure' => 'present'}) } - it { is_expected.to contain_user('alex').with({ 'gid' => 'mygroup', 'uid' => '700', 'ensure' => 'present'}) } - end - - describe 'given a title hash of a single resource' do - - let(:title_param) { {'dan' => { 'gid' => 'mygroup', 'uid' => '600' }} } - - it { is_expected.to compile } - it { is_expected.to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600', 'ensure' => 'present'}) } - end -end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec.rb b/spec/unit/puppet/provider/file_line/ruby_spec.rb index 1f41f62..4ec9bae 100755 --- a/spec/unit/puppet/provider/file_line/ruby_spec.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec.rb @@ -2,7 +2,8 @@ require 'spec_helper' require 'tempfile' provider_class = Puppet::Type.type(:file_line).provider(:ruby) -describe provider_class do +# 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 context "when adding" do let :tmpfile do tmp = Tempfile.new('tmp') @@ -29,7 +30,7 @@ describe provider_class do File.open(tmpfile, 'w') do |fh| fh.write('foo1') end - expect(provider.exists?).to be_nil + expect(provider.exists?).to eql (false) end it 'should append to an existing file when creating' do provider.create @@ -69,7 +70,7 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo2") end - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql (false) @provider.create expect(File.read(@tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar") end @@ -112,7 +113,7 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") end - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql(false) expect { @provider.create }.to raise_error(Puppet::Error, /More than one line.*matches/) expect(File.read(@tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz") end @@ -131,11 +132,30 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") end - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql(false) @provider.create expect(File.read(@tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar") end + it 'should replace 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') do |fh| + fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") + end + expect(@provider.exists?).to eql(false) + @provider.create + expect(File.read(@tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0") + end + it 'should raise an error with invalid values' do expect { @resource = Puppet::Type::File_line.new( @@ -154,7 +174,7 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo=blah\nfoo2") end - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql(false) @provider.create expect(File.read(@tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end @@ -162,7 +182,7 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo2") end - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql(false) @provider.create expect(File.read(@tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n") end @@ -170,10 +190,28 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo = bar\nfoo2") end - expect(@provider.exists?).to be_truthy + expect(@provider.exists?).to eql(true) @provider.create expect(File.read(@tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") end + + it 'should 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') do |fh| + fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") + end + expect(@provider.exists?).to be true + expect(File.read(@tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") + end end describe 'using after' do @@ -274,7 +312,7 @@ describe provider_class do } ) @provider = provider_class.new(@resource) - expect(@provider.exists?).to be_nil + expect(@provider.exists?).to eql (false) @provider.create expect(File.read(@tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz") end @@ -299,7 +337,7 @@ describe provider_class do end end - context "when removing" do + 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: @@ -340,6 +378,23 @@ describe provider_class do @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') do |fh| + fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") + end + @provider.destroy + expect(File.read(@tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + end end context "when removing with a match" do @@ -367,7 +422,7 @@ describe provider_class do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo\nfoo2") end - expect(@provider.exists?).to be_truthy + expect(@provider.exists?).to eql (true) end it 'should remove one line if it matches' do @@ -378,6 +433,41 @@ describe provider_class do 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, + } + ) + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo\nfoo2") + end + @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, + } + ) + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo\nfoo2") + end + @provider.destroy + expect(File.read(@tmpfile)).to eql("foo1\nfoo2") + end + it 'should raise an error if more than one line matches' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") @@ -442,6 +532,41 @@ describe provider_class do expect(File.read(@tmpfile)).to eql("foo1\nfoo\n") end - 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') do |fh| + fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") + end + @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') do |fh| + fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") + end + @provider.destroy + expect(File.read(@tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + end + end end diff --git a/spec/unit/puppet/type/file_line_spec.rb b/spec/unit/puppet/type/file_line_spec.rb index 48e2670..db07352 100755 --- a/spec/unit/puppet/type/file_line_spec.rb +++ b/spec/unit/puppet/type/file_line_spec.rb @@ -2,14 +2,28 @@ require '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') + Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => tmp_path) end it 'should accept a line and path' do file_line[:line] = 'my_line' expect(file_line[:line]).to eq('my_line') - file_line[:path] = '/my/path' - expect(file_line[:path]).to eq('/my/path') + file_line[:path] = my_path + expect(file_line[:path]).to eq(my_path) end it 'should accept a match regex' do file_line[:match] = '^foo.*$' @@ -19,7 +33,7 @@ describe Puppet::Type.type(:file_line) do expect { Puppet::Type.type(:file_line).new( :name => 'foo', - :path => '/my/path', + :path => my_path, :line => 'foo=bar', :match => '^bar=blah$' )}.not_to raise_error @@ -28,23 +42,44 @@ describe Puppet::Type.type(:file_line) do expect { Puppet::Type.type(:file_line).new( :name => 'foo', - :path => '/my/path', + :path => my_path, :line => 'foo=bar', :match => '^\s*foo=.*$' )}.not_to raise_error end + it 'should accept utf8 characters' do + expect { + Puppet::Type.type(:file_line).new( + :name => 'ƒồỗ', + :path => my_path, + :line => 'ƒồỗ=ьåя', + :match => '^ьåя=βļάħ$' + )}.not_to raise_error + end + it 'should accept double byte characters' do + expect { + Puppet::Type.type(:file_line).new( + :name => 'フーバー', + :path => my_path, + :line => 'この=それ', + :match => '^この=ああ$' + )}.not_to raise_error + end it 'should accept posix filenames' do - file_line[:path] = '/tmp/path' - expect(file_line[:path]).to eq('/tmp/path') + file_line[:path] = tmp_path + expect(file_line[:path]).to eq(tmp_path) end it 'should not accept unqualified path' do expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, /File paths must be fully qualified/) end it 'should require that a line is specified' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => '/tmp/file') }.to raise_error(Puppet::Error, /line is a required attribute/) + expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path) }.to raise_error(Puppet::Error, /line is a required attribute/) end it 'should not require that a line is specified when matching for absence' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => '/tmp/file', :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error + expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error + 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 end it 'should require that a file is specified' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, /path is a required attribute/) @@ -55,15 +90,20 @@ describe Puppet::Type.type(:file_line) do it 'should default to replace => true' do expect(file_line[:replace]).to eq :true end - + it 'should default to encoding => UTF-8' do + expect(file_line[:encoding]).to eq 'UTF-8' + end + it 'should accept 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 "should autorequire the file it manages" do catalog = Puppet::Resource::Catalog.new - file = Puppet::Type.type(:file).new(:name => "/tmp/path") + 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]") and (rel.target.to_s == file_line.to_s) + (rel.source.to_s == "File[#{tmp_path}]") and (rel.target.to_s == file_line.to_s) end expect(relationship).to be_a Puppet::Relationship end diff --git a/types/compat/hash.pp b/types/compat/hash.pp new file mode 100644 index 0000000..e84a10b --- /dev/null +++ b/types/compat/hash.pp @@ -0,0 +1,2 @@ +# Emulate the is_hash and validate_hash functions +type Stdlib::Compat::Hash = Hash[Any, Any] diff --git a/types/compat/ipv6.pp b/types/compat/ipv6.pp index 18b148d..8b82f1a 100644 --- a/types/compat/ipv6.pp +++ b/types/compat/ipv6.pp @@ -1 +1 @@ -type Stdlib::Compat::Ipv6 = Pattern[/^(?:(?:[\da-f]{1,4}:){7}[\da-f]{1,4}|((?:[\da-f]{1,4}:){6})(\d+)\.(\d+)\.(\d+)\.(\d+))$/] +type 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*$/] diff --git a/types/mac.pp b/types/mac.pp new file mode 100644 index 0000000..4103574 --- /dev/null +++ b/types/mac.pp @@ -0,0 +1,2 @@ +# A type for a MAC address +type Stdlib::MAC = Pattern[/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/] diff --git a/types/unixpath.pp b/types/unixpath.pp index 76f2c17..4cd6f01 100644 --- a/types/unixpath.pp +++ b/types/unixpath.pp @@ -1,2 +1,2 @@ # this regex rejects any path component that is a / or a NUL -type Stdlib::Unixpath = Pattern[/^\/([^\/\0]+(\/)?)+$/] +type Stdlib::Unixpath = Pattern[/^\/([^\/\0]+\/*)*$/] |