Skip to content

Commit

Permalink
Add systemd::escape function
Browse files Browse the repository at this point in the history
Add a systemd escape function.

```puppet
systemd::escape('/foo/bar')
```
returns `-foo-bar`

while the path escape can be executed as

```puppet
systemd::escape('/foo/bar',true)
```

to return 'foo-bar'
  • Loading branch information
traylenator committed Sep 6, 2021
1 parent b0dee23 commit 1abd7f9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions functions/escape.pp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
function systemd::escape(String $input, Boolean $path = false) >> String {
# Escape method is defined
# https://www.freedesktop.org/software/systemd/man/systemd.unit.html
$_output = $input.map |$_i, $_token | {
case $_token {
'/': {
if $path and ($_i != 0 ) and $input[$_i-1] == '/' {
$_escaped = ''
} elsif $path and ($_i == 0 or $_i == ($input.length - 1) ) {
$_escaped = ''
} else {
$_escaped = '-'
}
}
',': { $_escaped = '\x2c' }
default: { $_escaped = $_token }
}
$_escaped
}.join

return $_output
}
17 changes: 17 additions & 0 deletions spec/functions/escape_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
require 'spec_helper'

describe 'systemd::escape' do
context 'with path false' do
it { is_expected.to run.with_params('foo', false).and_return('foo') }
it { is_expected.to run.with_params('/foo/bar/', false).and_return('-foo-bar-') }
it { is_expected.to run.with_params('//foo//bar//', false).and_return('--foo--bar--') }
it { is_expected.to run.with_params('//foo:bar,foo_bar.//', false).and_return('--foo:bar\x2cfoo_bar.--') }
end

context 'with path true' do
it { is_expected.to run.with_params('foo', true).and_return('foo') }
it { is_expected.to run.with_params('/foo/bar/', true).and_return('foo-bar') }
it { is_expected.to run.with_params('//foo//bar//', true).and_return('foo-bar') }
it { is_expected.to run.with_params('//foo:bar,foo_bar.//', true).and_return('foo:bar\x2cfoo_bar.') }
end
end

0 comments on commit 1abd7f9

Please sign in to comment.