Puppet Function: simplib::hash_to_opts

Defined in:
functions/hash_to_opts.pp
Function type:
Puppet Language

Overview

simplib::hash_to_opts(Hash[String,Variant[Array,String,Numeric,Boolean,Undef]] $input, Struct[{ Optional[connector] => String[1], Optional[prefix] => String[1], Optional[repeat] => Enum['comma','repeat'], Optional[delimiter] => String[1], }] $opts = {})String

Turn a hash into a options string, for use in a shell command

Examples:

simplib::hash_to_opts(=> ‘value’)

returns ``--key=value``

simplib::hash_to_opts(=> [‘lo’,7,false])

returns ``--key=lo,7,false``

simplib::hash_to_opts({‘key’ => Undef })

returns ```--key``

simplib::hash_to_opts(=> ‘/tmp/file’, => ‘ ’, ‘prefix’ => ‘-’)

returns ``-f /tmp/file``

Parameters:

  • input (Hash[String,Variant[Array,String,Numeric,Boolean,Undef]])

    Input hash, with Strings as keys and either a String, Array, Numeric, Boolean, or Undef as a value.

  • opts (Struct[{ Optional[connector] => String[1], Optional[prefix] => String[1], Optional[repeat] => Enum['comma','repeat'], Optional[delimiter] => String[1], }]) (defaults to: {})

    Options hash. It only takes 3 keys, none of them required:

    • “connector“: String that joins each key and value pair. Defaults to ‘=’

    • “prefix“: String that prefixes each key value pair. Defaults to ‘–’

    • “delimiter“: When a value is an array, the string that is used to deliminate each item. Defaults to ‘,’

    • “repeat“: Whether to return array values as a deliminated string, or by repeating the option with each unique value

Returns:

  • (String)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'functions/hash_to_opts.pp', line 25

function simplib::hash_to_opts (
  Hash[String,Variant[Array,String,Numeric,Boolean,Undef]] $input,
  Struct[{
    Optional[connector] => String[1],
    Optional[prefix]    => String[1],
    Optional[repeat]    => Enum['comma','repeat'],
    Optional[delimiter] => String[1],
  }] $opts = {}
) {
  $connector = pick($opts['connector'], '=')
  $prefix    = pick($opts['prefix'],    '--')
  $repeat    = pick($opts['repeat'],    'comma')
  $delimiter = pick($opts['delimiter'], ',')

  $out = $input.map |$key, $val| {
    case $val {
      default: { "${prefix}${key}${connector}${String($val).shellquote}" }
      Undef:   { "${prefix}${key}" }
      Array:   {
        # lint:ignore:case_without_default
        case $repeat {
          'comma':  { "${prefix}${key}${connector}${val.join($delimiter).shellquote}" }
          'repeat': { $val.prefix("${prefix}${key}${connector}").shellquote }
        }
        # lint:endignore
      }
    }
  }
  $out.join(' ')
}