mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-04-15 16:31:30 +00:00
Reformat everything.
This commit is contained in:
parent
3f2213791a
commit
340ff8586d
1008 changed files with 61301 additions and 58309 deletions
|
|
@ -107,91 +107,87 @@ import os
|
|||
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
|
||||
|
||||
import platform
|
||||
NOT_WORKING_MAC_VERSION_MAS_ACCOUNT = '12.0'
|
||||
|
||||
NOT_WORKING_MAC_VERSION_MAS_ACCOUNT = "12.0"
|
||||
|
||||
|
||||
class Mas:
|
||||
|
||||
def __init__(self, module):
|
||||
self.module = module
|
||||
|
||||
# Initialize data properties
|
||||
self.mas_path = self.module.get_bin_path('mas')
|
||||
self.mas_path = self.module.get_bin_path("mas")
|
||||
self._checked_signin = False
|
||||
self._mac_version = platform.mac_ver()[0] or '0.0'
|
||||
self._mac_version = platform.mac_ver()[0] or "0.0"
|
||||
self._installed = None # Populated only if needed
|
||||
self._outdated = None # Populated only if needed
|
||||
self._outdated = None # Populated only if needed
|
||||
self.count_install = 0
|
||||
self.count_upgrade = 0
|
||||
self.count_uninstall = 0
|
||||
self.result = {
|
||||
'changed': False
|
||||
}
|
||||
self.result = {"changed": False}
|
||||
|
||||
self.check_mas_tool()
|
||||
|
||||
def app_command(self, command, id):
|
||||
''' Runs a `mas` command on a given app; command can be 'install', 'upgrade' or 'uninstall' '''
|
||||
"""Runs a `mas` command on a given app; command can be 'install', 'upgrade' or 'uninstall'"""
|
||||
|
||||
if not self.module.check_mode:
|
||||
if command != 'uninstall':
|
||||
if command != "uninstall":
|
||||
self.check_signin()
|
||||
|
||||
rc, out, err = self.run([command, str(id)])
|
||||
if rc != 0:
|
||||
self.module.fail_json(
|
||||
msg=f"Error running command '{command}' on app '{id}': {out.rstrip()}"
|
||||
)
|
||||
self.module.fail_json(msg=f"Error running command '{command}' on app '{id}': {out.rstrip()}")
|
||||
|
||||
# No error or dry run
|
||||
self.__dict__[f"count_{command}"] += 1
|
||||
|
||||
def check_mas_tool(self):
|
||||
''' Verifies that the `mas` tool is available in a recent version '''
|
||||
"""Verifies that the `mas` tool is available in a recent version"""
|
||||
|
||||
# Is the `mas` tool available at all?
|
||||
if not self.mas_path:
|
||||
self.module.fail_json(msg='Required `mas` tool is not installed')
|
||||
self.module.fail_json(msg="Required `mas` tool is not installed")
|
||||
|
||||
# Is the version recent enough?
|
||||
rc, out, err = self.run(['version'])
|
||||
if rc != 0 or not out.strip() or LooseVersion(out.strip()) < LooseVersion('1.5.0'):
|
||||
rc, out, err = self.run(["version"])
|
||||
if rc != 0 or not out.strip() or LooseVersion(out.strip()) < LooseVersion("1.5.0"):
|
||||
self.module.fail_json(msg=f"`mas` tool in version 1.5.0+ needed, got {out.strip()}")
|
||||
|
||||
def check_signin(self):
|
||||
''' Verifies that the user is signed in to the Mac App Store '''
|
||||
"""Verifies that the user is signed in to the Mac App Store"""
|
||||
# Only check this once per execution
|
||||
if self._checked_signin:
|
||||
return
|
||||
if LooseVersion(self._mac_version) >= LooseVersion(NOT_WORKING_MAC_VERSION_MAS_ACCOUNT):
|
||||
# Checking if user is signed-in is disabled due to https://github.com/mas-cli/mas/issues/417
|
||||
self.module.log('WARNING: You must be signed in via the Mac App Store GUI beforehand else error will occur')
|
||||
self.module.log("WARNING: You must be signed in via the Mac App Store GUI beforehand else error will occur")
|
||||
else:
|
||||
rc, out, err = self.run(['account'])
|
||||
if out.split("\n", 1)[0].rstrip() == 'Not signed in':
|
||||
self.module.fail_json(msg='You must be signed in to the Mac App Store')
|
||||
rc, out, err = self.run(["account"])
|
||||
if out.split("\n", 1)[0].rstrip() == "Not signed in":
|
||||
self.module.fail_json(msg="You must be signed in to the Mac App Store")
|
||||
|
||||
self._checked_signin = True
|
||||
|
||||
def exit(self):
|
||||
''' Exit with the data we have collected over time '''
|
||||
"""Exit with the data we have collected over time"""
|
||||
|
||||
msgs = []
|
||||
if self.count_install > 0:
|
||||
msgs.append(f'Installed {self.count_install} app(s)')
|
||||
msgs.append(f"Installed {self.count_install} app(s)")
|
||||
if self.count_upgrade > 0:
|
||||
msgs.append(f'Upgraded {self.count_upgrade} app(s)')
|
||||
msgs.append(f"Upgraded {self.count_upgrade} app(s)")
|
||||
if self.count_uninstall > 0:
|
||||
msgs.append(f'Uninstalled {self.count_uninstall} app(s)')
|
||||
msgs.append(f"Uninstalled {self.count_uninstall} app(s)")
|
||||
|
||||
if msgs:
|
||||
self.result['changed'] = True
|
||||
self.result['msg'] = ', '.join(msgs)
|
||||
self.result["changed"] = True
|
||||
self.result["msg"] = ", ".join(msgs)
|
||||
|
||||
self.module.exit_json(**self.result)
|
||||
|
||||
def get_current_state(self, command):
|
||||
''' Returns the list of all app IDs; command can either be 'list' or 'outdated' '''
|
||||
"""Returns the list of all app IDs; command can either be 'list' or 'outdated'"""
|
||||
|
||||
rc, raw_apps, err = self.run([command])
|
||||
rows = raw_apps.split("\n")
|
||||
|
|
@ -200,55 +196,55 @@ class Mas:
|
|||
apps = []
|
||||
for r in rows:
|
||||
# Format: "123456789 App Name"
|
||||
r = r.split(' ', 1)
|
||||
r = r.split(" ", 1)
|
||||
if len(r) == 2:
|
||||
apps.append(int(r[0]))
|
||||
|
||||
return apps
|
||||
|
||||
def installed(self):
|
||||
''' Returns the list of installed apps '''
|
||||
"""Returns the list of installed apps"""
|
||||
|
||||
# Populate cache if not already done
|
||||
if self._installed is None:
|
||||
self._installed = self.get_current_state('list')
|
||||
self._installed = self.get_current_state("list")
|
||||
|
||||
return self._installed
|
||||
|
||||
def is_installed(self, id):
|
||||
''' Checks whether the given app is installed '''
|
||||
"""Checks whether the given app is installed"""
|
||||
|
||||
return int(id) in self.installed()
|
||||
|
||||
def is_outdated(self, id):
|
||||
''' Checks whether the given app is installed, but outdated '''
|
||||
"""Checks whether the given app is installed, but outdated"""
|
||||
|
||||
return int(id) in self.outdated()
|
||||
|
||||
def outdated(self):
|
||||
''' Returns the list of installed, but outdated apps '''
|
||||
"""Returns the list of installed, but outdated apps"""
|
||||
|
||||
# Populate cache if not already done
|
||||
if self._outdated is None:
|
||||
self._outdated = self.get_current_state('outdated')
|
||||
self._outdated = self.get_current_state("outdated")
|
||||
|
||||
return self._outdated
|
||||
|
||||
def run(self, cmd):
|
||||
''' Runs a command of the `mas` tool '''
|
||||
"""Runs a command of the `mas` tool"""
|
||||
|
||||
cmd.insert(0, self.mas_path)
|
||||
return self.module.run_command(cmd, False)
|
||||
|
||||
def upgrade_all(self):
|
||||
''' Upgrades all installed apps and sets the correct result data '''
|
||||
"""Upgrades all installed apps and sets the correct result data"""
|
||||
|
||||
outdated = self.outdated()
|
||||
|
||||
if not self.module.check_mode:
|
||||
self.check_signin()
|
||||
|
||||
rc, out, err = self.run(['upgrade'])
|
||||
rc, out, err = self.run(["upgrade"])
|
||||
if rc != 0:
|
||||
self.module.fail_json(msg=f"Could not upgrade all apps: {out.rstrip()}")
|
||||
|
||||
|
|
@ -258,41 +254,41 @@ class Mas:
|
|||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
id=dict(type='list', elements='int'),
|
||||
state=dict(type='str', default='present', choices=['absent', 'latest', 'present']),
|
||||
upgrade_all=dict(type='bool', default=False, aliases=['upgrade']),
|
||||
id=dict(type="list", elements="int"),
|
||||
state=dict(type="str", default="present", choices=["absent", "latest", "present"]),
|
||||
upgrade_all=dict(type="bool", default=False, aliases=["upgrade"]),
|
||||
),
|
||||
supports_check_mode=True
|
||||
supports_check_mode=True,
|
||||
)
|
||||
mas = Mas(module)
|
||||
|
||||
if module.params['id']:
|
||||
apps = module.params['id']
|
||||
if module.params["id"]:
|
||||
apps = module.params["id"]
|
||||
else:
|
||||
apps = []
|
||||
|
||||
state = module.params['state']
|
||||
upgrade = module.params['upgrade_all']
|
||||
state = module.params["state"]
|
||||
upgrade = module.params["upgrade_all"]
|
||||
|
||||
# Run operations on the given app IDs
|
||||
for app in sorted(set(apps)):
|
||||
if state == 'present':
|
||||
if state == "present":
|
||||
if not mas.is_installed(app):
|
||||
mas.app_command('install', app)
|
||||
mas.app_command("install", app)
|
||||
|
||||
elif state == 'absent':
|
||||
elif state == "absent":
|
||||
if mas.is_installed(app):
|
||||
# Ensure we are root
|
||||
if os.getuid() != 0:
|
||||
module.fail_json(msg="Uninstalling apps requires root permissions ('become: true')")
|
||||
|
||||
mas.app_command('uninstall', app)
|
||||
mas.app_command("uninstall", app)
|
||||
|
||||
elif state == 'latest':
|
||||
elif state == "latest":
|
||||
if not mas.is_installed(app):
|
||||
mas.app_command('install', app)
|
||||
mas.app_command("install", app)
|
||||
elif mas.is_outdated(app):
|
||||
mas.app_command('upgrade', app)
|
||||
mas.app_command("upgrade", app)
|
||||
|
||||
# Upgrade all apps if requested
|
||||
mas._outdated = None # Clear cache
|
||||
|
|
@ -303,5 +299,5 @@ def main():
|
|||
mas.exit()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue