diff --git a/changelogs/fragments/1916-add-version-sort-filter.yml b/changelogs/fragments/1916-add-version-sort-filter.yml new file mode 100644 index 0000000000..a06b464e55 --- /dev/null +++ b/changelogs/fragments/1916-add-version-sort-filter.yml @@ -0,0 +1,3 @@ +add plugin.filter: + - name: version_sort + description: Sort a list according to version order instead of pure alphabetical one diff --git a/plugins/filter/version_sort.py b/plugins/filter/version_sort.py new file mode 100644 index 0000000000..598b8f2088 --- /dev/null +++ b/plugins/filter/version_sort.py @@ -0,0 +1,21 @@ +# Copyright (C) 2021 Eric Lavarde +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +from distutils.version import LooseVersion + + +def version_sort(value, reverse=False): + '''Sort a list according to loose versions so that e.g. 2.9 is smaller than 2.10''' + return sorted(value, key=LooseVersion, reverse=reverse) + + +class FilterModule(object): + ''' Version sort filter ''' + + def filters(self): + return { + 'version_sort': version_sort + } diff --git a/tests/integration/targets/filter_version_sort/aliases b/tests/integration/targets/filter_version_sort/aliases new file mode 100644 index 0000000000..f04737b845 --- /dev/null +++ b/tests/integration/targets/filter_version_sort/aliases @@ -0,0 +1,2 @@ +shippable/posix/group2 +skip/python2.6 # filters are controller only, and we no longer support Python 2.6 on the controller diff --git a/tests/integration/targets/filter_version_sort/tasks/main.yml b/tests/integration/targets/filter_version_sort/tasks/main.yml new file mode 100644 index 0000000000..2edca18c9c --- /dev/null +++ b/tests/integration/targets/filter_version_sort/tasks/main.yml @@ -0,0 +1,10 @@ +--- +#################################################################### +# WARNING: These are designed specifically for Ansible tests # +# and should not be used as examples of how to write Ansible roles # +#################################################################### + +- name: validate that versions are properly sorted in a stable way + assert: + that: + - "['a-1.9.rpm', 'a-1.10-1.rpm', 'a-1.09.rpm', 'b-1.01.rpm', 'a-2.1-0.rpm', 'a-1.10-0.rpm'] | community.general.version_sort == ['a-1.9.rpm', 'a-1.09.rpm', 'a-1.10-0.rpm', 'a-1.10-1.rpm', 'a-2.1-0.rpm', 'b-1.01.rpm']"