Puppet Function: systemd::escape

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

Summary

Escape strings as systemd-escape does.

Overview

systemd::escape(String[1] $input, Boolean $path = false)String

Examples:

Escaping a string

$result = systemd::escape('foo::bar')

Escaping a path

$result = systemd::escape('/mnt/foobar',true)

Parameters:

  • input (String[1])

    Input string

  • path (Boolean) (defaults to: false)

    Use path (-p) ornon-path style escaping.

Returns:

  • (String)

    String



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'functions/escape.pp', line 9

function systemd::escape(String[1] $input, Boolean $path = false) >> String {
  # Escape method is defined
  # https://www.freedesktop.org/software/systemd/man/systemd.unit.html

  # fail path if . on end.
  if $path and $input[-1] == '.' {
    fail('A path can not end in a \'.\'')
  }

  # De-duplicate any `/` and prefix,suffix `/` if file
  if $path {
    $_chomped = $input.regsubst('/+$','').regsubst('^/+','').regsubst('//+','/')
  } else {
    $_chomped = $input
  }

  # Docs talk of escaping `:` also but seems not to be the case in reality.
  #
  $_output = $_chomped.map |$_i, $_token | {
    case $_token {
      '.': {
        $_escaped = $_i ? {
          0       => '\x2e',
          default => $_token,
        }
      }
      '/': { $_escaped = '-' }
      ',': { $_escaped = '\x2c' }
      '-': { $_escaped = '\x2d' }
      default: { $_escaped = $_token }
    }
    $_escaped
  }.join

  return $_output
}