diff --git a/examples/tree.yaml b/examples/tree.yaml new file mode 100644 index 0000000..028e54e --- /dev/null +++ b/examples/tree.yaml @@ -0,0 +1,35 @@ +--- + +# This playbook example contains simple use cases that illustrate the basics functionality of join filter. + +- name: Tree + gather_facts: false + hosts: localhost + vars: + path: /tmp + tree: + - path: foo + - path: foo/bar + content: | + Bar + - path: foo/baz + template: template.j2 + - path: qux + state: absent + tasks: + + - name: Tree with simple path + manala.path.path: + path: "{{ item.path }}" + state: "{{ item.state | default(omit) }}" + content: "{{ item.content | default(omit) }}" + template: "{{ item.template | default(omit) }}" + loop: "{{ tree | manala.path.join(path) }}" + + - name: Tree with multiple paths + manala.path.path: + path: "{{ item.path }}" + state: "{{ item.state | default(omit) }}" + content: "{{ item.content | default(omit) }}" + template: "{{ item.template | default(omit) }}" + loop: "{{ tree | manala.path.join(path, 'service') }}" diff --git a/plugins/filter/join.py b/plugins/filter/join.py new file mode 100644 index 0000000..570e002 --- /dev/null +++ b/plugins/filter/join.py @@ -0,0 +1,27 @@ +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +import os.path + +from ansible.errors import AnsibleFilterError + + +def join(elements, *paths): + if not isinstance(elements, list): + raise AnsibleFilterError('join first parameter expects a list of dictionary but was given a %s' % type(elements)) + + for element in elements: + element['path'] = os.path.join(*(*paths, element['path'])) + + return elements + + +class FilterModule(object): + ''' Manala join jinja2 filters ''' + + def filters(self): + filters = { + 'join': join, + } + + return filters diff --git a/tests/unit/plugins/filter/test_join.py b/tests/unit/plugins/filter/test_join.py new file mode 100644 index 0000000..830a03c --- /dev/null +++ b/tests/unit/plugins/filter/test_join.py @@ -0,0 +1,33 @@ +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import unittest +from plugins.filter.join import join + +from ansible.errors import AnsibleFilterError + + +class TestJoin(unittest.TestCase): + + def test_uncorrect_first_parameter(self): + with self.assertRaises(AnsibleFilterError) as error: + join("NotGood", "/tmp") + self.assertEqual("join first parameter expects a list of dictionary but was given a ", str(error.exception)) + + def test_path(self): + self.assertEqual([ + {"path": "/tmp/foo"}, + {"path": "/tmp/foo/bar"} + ], join([ + {"path": "foo"}, + {"path": "foo/bar"} + ], "/tmp")) + + def test_paths(self): + self.assertEqual([ + {"path": "/tmp/service/foo"}, + {"path": "/tmp/service/foo/bar"} + ], join([ + {"path": "foo"}, + {"path": "foo/bar"} + ], "/tmp", "service"))