Skip to content

Commit

Permalink
Merge pull request #54216 from cdalvaro/improve_macOS_homebrew_cask_s…
Browse files Browse the repository at this point in the history
…upport

Improve macOS homebrew cask support
  • Loading branch information
dwoz committed Dec 24, 2019
2 parents 84d699f + ff8d8a3 commit 81cccd8
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 4 deletions.
56 changes: 55 additions & 1 deletion salt/modules/mac_brew_pkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import copy
import functools
import logging
import re

# Import salt libs
import salt.utils.data
Expand Down Expand Up @@ -149,7 +150,19 @@ def list_pkgs(versions_as_list=False, **kwargs):
for line in out.splitlines():
try:
name_and_versions = line.split(' ')
name = '/'.join(('caskroom/cask', name_and_versions[0]))
pkg_name = name_and_versions[0]

# Get cask namespace
info_cmd = 'cask info {}'.format(pkg_name)
match = re.search(r'^From: .*/(.+?)/homebrew-(.+?)/.*$',
_call_brew(info_cmd)['stdout'], re.MULTILINE)
if match:
namespace = '/'.join((match.group(1).lower(),
match.group(2).lower()))
else:
namespace = 'homebrew/cask'

name = '/'.join((namespace, pkg_name))
installed_versions = name_and_versions[1:]
key_func = functools.cmp_to_key(salt.utils.versions.version_cmp)
newest_version = sorted(installed_versions, key=key_func).pop()
Expand Down Expand Up @@ -245,6 +258,7 @@ def remove(name=None, pkgs=None, **kwargs):
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
name, pkgs = _fix_cask_namespace(name, pkgs)
pkg_params = __salt__['pkg_resource.parse_targets'](
name, pkgs, **kwargs
)[0]
Expand Down Expand Up @@ -384,6 +398,7 @@ def install(name=None, pkgs=None, taps=None, options=None, **kwargs):
salt '*' pkg.install 'package package package'
'''
try:
name, pkgs = _fix_cask_namespace(name, pkgs)
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, kwargs.get('sources', {})
)
Expand Down Expand Up @@ -534,3 +549,42 @@ def info_installed(*names):
salt '*' pkg.info_installed <package1> <package2> <package3> ...
'''
return _info(*names)


def _fix_cask_namespace(name=None, pkgs=None):
"""
Check if provided packages contains the old version of brew-cask namespace
and replace it by the new one.
This function also warns about the correct namespace for this packages
and it will stop working with the release of Sodium.
:param name: The name of the package to check
:param pkgs: A list of packages to check
:return: name and pkgs with the mocked namespace
"""

show_warning = False

if name and name.startswith('caskroom/cask/'):
show_warning = True
name = name.replace("caskroom/cask/", "homebrew/cask/")

if pkgs:
pkgs_ = []
for pkg in pkgs:
if pkg.startswith('caskroom/cask/'):
show_warning = True
pkg = pkg.replace("caskroom/cask/", "homebrew/cask/")
pkgs_.append(pkg)
pkgs = pkgs_

if show_warning:
salt.utils.versions.warn_until(
'Sodium',
'The \'caskroom/cask/\' namespace for brew-cask packages '
'is deprecated. Use \'homebrew/cask/\' instead.'
)

return name, pkgs
64 changes: 61 additions & 3 deletions tests/unit/modules/test_mac_brew_pkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class BrewTestCase(TestCase, LoaderModuleMockMixin):
'''
TestCase for salt.modules.mac_brew module
'''

def setup_loader_modules(self):
return {mac_brew: {'__opts__': {'user': MagicMock(return_value='bar')}}}

Expand Down Expand Up @@ -62,8 +63,8 @@ def test_tap_failure(self):
mock_user = MagicMock(return_value='foo')
mock_cmd = MagicMock(return_value='')
with patch.dict(mac_brew.__salt__, {'cmd.run_all': mock_failure,
'file.get_user': mock_user,
'cmd.run': mock_cmd}), \
'file.get_user': mock_user,
'cmd.run': mock_cmd}), \
patch('salt.modules.mac_brew_pkg._list_taps', MagicMock(return_value={})):
self.assertFalse(mac_brew._tap('homebrew/test'))

Expand Down Expand Up @@ -109,6 +110,63 @@ def test_list_pkgs_versions_true(self):
self.assertEqual(mac_brew.list_pkgs(versions_as_list=True),
mock_context)

def test_list_pkgs_homebrew_cask_pakages(self):
'''
Tests if pkg.list_pkgs list properly homebrew cask packages
'''

def custom_call_brew(cmd, failhard=True):
result = dict()
if cmd == 'info --json=v1 --installed':
result = {'stdout': '[{"name":"zsh","full_name":"zsh","oldname":null,'
'"aliases":[],"homepage":"https://www.zsh.org/",'
'"versions":{"stable":"5.7.1","devel":null,"head":"HEAD","bottle":true},'
'"installed":[{"version":"5.7.1","used_options":[],'
'"built_as_bottle":true,"poured_from_bottle":true,'
'"runtime_dependencies":[{"full_name":"ncurses","version":"6.1"},'
'{"full_name":"pcre","version":"8.42"}],'
'"installed_as_dependency":false,"installed_on_request":true}]}]',
'stderr': '',
'retcode': 0}
elif cmd == 'cask list --versions':
result = {'stdout': 'macvim 8.1.151\nfont-firacode-nerd-font 2.0.0',
'stderr': '',
'retcode': 0}
elif cmd == 'cask info macvim':
result = {'stdout': 'macvim: 8.1.1517,156 (auto_updates)\n'
'https://github.com/macvim-dev/macvim\n'
'/usr/local/Caskroom/macvim/8.1.151 (64B)\n'
'From: https://github.com/Homebrew/homebrew-cask/blob/master/Casks/macvim.rb\n'
'==> Name\n'
'MacVim',
'stderr': '',
'retcode': 0}
elif cmd == 'cask info font-firacode-nerd-font':
result = {'stdout': 'font-firacode-nerd-font: 2.0.0\n'
'https://github.com/ryanoasis/nerd-fonts\n'
'/usr/local/Caskroom/font-firacode-nerd-font/2.0.0 (35 files, 64.8MB)\n'
'From: https://github.com/Homebrew/homebrew-cask-fonts/blob/master/Casks/font-firacode-nerd-font.rb\n'
'==> Name\n'
'FuraCode Nerd Font (FiraCode)',
'stderr': '',
'retcode': ''}

return result

def custom_add_pkg(ret, name, newest_version):
ret[name] = newest_version
return ret

expected_pkgs = {'zsh': '5.7.1',
'homebrew/cask/macvim': '8.1.151',
'homebrew/cask-fonts/font-firacode-nerd-font': '2.0.0'}

with patch('salt.modules.mac_brew_pkg._call_brew', custom_call_brew),\
patch.dict(mac_brew.__salt__, {'pkg_resource.add_pkg': custom_add_pkg,
'pkg_resource.sort_pkglist': MagicMock()}):
self.assertEqual(mac_brew.list_pkgs(versions_as_list=True),
expected_pkgs)

# 'version' function tests: 1

def test_version(self):
Expand Down Expand Up @@ -159,7 +217,7 @@ def test_refresh_db(self):
mock_user = MagicMock(return_value='foo')
mock_success = MagicMock(return_value={'retcode': 0})
with patch.dict(mac_brew.__salt__, {'file.get_user': mock_user,
'cmd.run_all': mock_success}), \
'cmd.run_all': mock_success}), \
patch('salt.modules.mac_brew_pkg._homebrew_bin',
MagicMock(return_value=HOMEBREW_BIN)):
with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
Expand Down

0 comments on commit 81cccd8

Please sign in to comment.