File 0012-implement-version_cmp-for-zypper.patch of Package salt.3314

From 82a9f07f27cf95a7dcff32c8434af9b5d7cf55ad Mon Sep 17 00:00:00 2001
From: Michael Calmer <mc@suse.de>
Date: Wed, 10 Feb 2016 11:47:12 +0100
Subject: [PATCH 12/22] implement version_cmp for zypper

---
 salt/modules/zypper.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 65 insertions(+)

diff --git a/salt/modules/zypper.py b/salt/modules/zypper.py
index 56d9ffb..bd9c30a 100644
--- a/salt/modules/zypper.py
+++ b/salt/modules/zypper.py
@@ -11,6 +11,7 @@ import copy
 import logging
 import re
 import os
+import rpm
 
 # Import 3rd-party libs
 # pylint: disable=import-error,redefined-builtin,no-name-in-module
@@ -288,6 +289,70 @@ def version(*names, **kwargs):
     '''
     return __salt__['pkg_resource.version'](*names, **kwargs) or {}
 
+def _stringToEVR(verstring):
+    '''
+    Split the version string into epoch, version and release and
+    return this as tuple.
+
+    epoch is always not empty.
+    version and release can be an empty string if such a component
+    could not be found in the version string.
+
+    "2:1.0-1.2" => ('2', '1.0', '1.2)
+    "1.0" => ('0', '1.0', '')
+    "" => ('0', '', '')
+    '''
+    if verstring in [None, '']:
+        return ('0', '', '')
+    i = verstring.find(':')
+    if i != -1:
+        try:
+            epoch = str(long(verstring[:i]))
+        except ValueError:
+            # look, garbage in the epoch field, how fun, kill it
+            epoch = '0' # this is our fallback, deal
+    else:
+        epoch = '0'
+    j = verstring.find('-')
+    if j != -1:
+        version = verstring[i + 1:j]
+        release = verstring[j + 1:]
+    else:
+        version = verstring[i + 1:]
+        release = ''
+    return (epoch, version, release)
+
+def version_cmp(ver1, ver2):
+    '''
+    .. versionadded:: 2015.5.4
+
+    Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
+    ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
+    making the comparison.
+
+    CLI Example:
+
+    .. code-block:: bash
+
+        salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
+    '''
+    try:
+        cmp_result = rpm.labelCompare(
+            _stringToEVR(ver1),
+            _stringToEVR(ver2)
+        )
+        if cmp_result not in (-1, 0, 1):
+            raise Exception(
+                'cmp result \'{0}\' is invalid'.format(cmp_result)
+            )
+        return cmp_result
+    except Exception as exc:
+        log.warning(
+            'Failed to compare version \'{0}\' to \'{1}\' using '
+            'rpmUtils: {2}'.format(ver1, ver2, exc)
+        )
+    return salt.utils.version_cmp(ver1, ver2)
+
 
 def list_pkgs(versions_as_list=False, **kwargs):
     '''
-- 
2.1.4

openSUSE Build Service is sponsored by