From 49d9a6aa45201413304db6f9b538ef4f08d30905 Mon Sep 17 00:00:00 2001 From: Erik Johnson Date: Wed, 5 Feb 2014 21:44:11 -0600 Subject: [PATCH] freebsdpkg: add with_origin option to list_pkgs() This adds a new option to list_pkgs() which, if True, will return a more complex data structure containing both the origin and version for each package. --- salt/modules/freebsdpkg.py | 45 ++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/salt/modules/freebsdpkg.py b/salt/modules/freebsdpkg.py index bb10bb3d4b..7a9cee3e2a 100644 --- a/salt/modules/freebsdpkg.py +++ b/salt/modules/freebsdpkg.py @@ -70,6 +70,7 @@ variables, if set, but these values can also be overridden in several ways: # Import python libs import copy import logging +import re # Import salt libs import salt.utils @@ -211,12 +212,18 @@ def refresh_db(): return True -def list_pkgs(versions_as_list=False, **kwargs): +def list_pkgs(versions_as_list=False, with_origin=False, **kwargs): ''' List the packages currently installed as a dict:: {'': ''} + with_origin : False + Return a nested dictionary containing both the origin name and version + for each installed package. + + .. versionadded:: 2014.1.0 (Hydrogen) + CLI Example: .. code-block:: bash @@ -229,28 +236,42 @@ def list_pkgs(versions_as_list=False, **kwargs): return {} if 'pkg.list_pkgs' in __context__: - if versions_as_list: - return __context__['pkg.list_pkgs'] - else: - ret = copy.deepcopy(__context__['pkg.list_pkgs']) + ret = copy.deepcopy(__context__['pkg.list_pkgs']) + if not versions_as_list: __salt__['pkg_resource.stringify'](ret) - return ret + if salt.utils.is_true(with_origin): + origins = __context__.get('pkg.origin', {}) + return dict([ + (x, {'origin': origins.get(x, ''), 'version': y}) + for x, y in ret.iteritems() + ]) + return ret + ret = {} - out = __salt__['cmd.run_stdout']('pkg_info', output_loglevel='debug') - for line in out.splitlines(): - if not line: + origins = {} + out = __salt__['cmd.run_stdout']('pkg_info -ao', output_loglevel='debug') + pkgs_re = re.compile(r'Information for ([^:]+):\s*Origin:\n([^\n]+)') + for pkg, origin in pkgs_re.findall(out): + if not pkg: continue try: - pkg, ver = line.split()[0].rsplit('-', 1) - except (IndexError, ValueError): + pkgname, pkgver = pkg.rsplit('-', 1) + except ValueError: continue - __salt__['pkg_resource.add_pkg'](ret, pkg, ver) + __salt__['pkg_resource.add_pkg'](ret, pkgname, pkgver) + origins[pkgname] = origin __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) + __context__['pkg.origin'] = origins if not versions_as_list: __salt__['pkg_resource.stringify'](ret) + if salt.utils.is_true(with_origin): + return dict([ + (x, {'origin': origins.get(x, ''), 'version': y}) + for x, y in ret.iteritems() + ]) return ret