Puppet Function: firewalld::safe_filename

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

Summary

Returns a string that is safe for firewalld filenames

Overview

firewalld::safe_filename(String[1] $filename, Struct[ { 'replacement_string' => Pattern[/^[\w-]+$/], 'file_extension' => Optional[String[1]] } ] $options = { 'replacement_string' => '_' })String

Examples:

Regular Filename

$filename = 'B@d Characters!'
firewalld::safe_filename($orig_string)

Result => 'B_d_Characters_'

Filename with Options

$filename = 'B@d Characters!.txt'
firewalld::safe_filename(
  $filename,
  {
    'replacement_string' => '--',
    'file_extension'     => '.txt'
  }
)

Result => 'B--d--Characters--.txt'

Parameters:

  • filename (String[1])

    The String to process

  • options (Struct[ { 'replacement_string' => Pattern[/^[\w-]+$/], 'file_extension' => Optional[String[1]] } ]) (defaults to: { 'replacement_string' => '_' })

    Various processing options

  • options (String[1]) (defaults to: { 'replacement_string' => '_' })

    replacement_string The String to use when replacing invalid characters

Options Hash (options):

  • file_extension (String[1])

    This will be stripped from the end of the string prior to processing and re-added afterwards

Returns:

  • (String)

    Processed string



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'functions/safe_filename.pp', line 37

function firewalld::safe_filename(
  String[1] $filename,
  Struct[
    {
      'replacement_string' => Pattern[/^[\w-]+$/],
      'file_extension'     => Optional[String[1]]
    }
  ]         $options  = { 'replacement_string' => '_' }
) {
  $_badchar_regex = '[^\w-]'

  # If we have an extension defined
  if $options['file_extension'] {
    # See if the string ends with the extension
    $_extension_length = length($options['file_extension'])
    if $filename[-($_extension_length), -1] == $options['file_extension'] {
      # And extract the base filename
      $_basename = $filename[0, -($_extension_length) - 1]
    }
  }

  # If we extraced a base filename substitute on that and re-add the file extension
  if defined('$_basename') {
    sprintf('%s%s',
      regsubst($_basename, $_badchar_regex, $options['replacement_string'], 'G'),
      $options['file_extension']
    )
  }
  # Otherwise, just substitute on the original filename
  else {
    regsubst($filename, $_badchar_regex, $options['replacement_string'], 'G')
  }
}