1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

modules g*: use f-strings (#10958)

* modules g*: use f-strings

* add changelog frag

* remove extraneous to_native()
This commit is contained in:
Alexei Znamensky 2025-10-25 11:54:38 +13:00 committed by GitHub
parent a3987c9844
commit b67e7c83cf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 250 additions and 245 deletions

View file

@ -0,0 +1,31 @@
minor_changes:
- gconftool2 - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gem - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- git_config - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- git_config_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_deploy_key - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_issue - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_key - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_release - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_repo - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_webhook - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- github_webhook_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_branch - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_deploy_key - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_group - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_group_access_token - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_group_members - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_hook - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_issue - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_label - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_merge_request - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_milestone - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_project - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_project_access_token - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_project_badge - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_project_members - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_protected_branch - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_runner - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gitlab_user - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- grove - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).
- gunicorn - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10958).

View file

@ -145,7 +145,7 @@ class GConftool(StateModuleHelper):
def _make_process(self, fail_on_err):
def process(rc, out, err):
if err and fail_on_err:
self.do_raise('gconftool-2 failed with error:\n%s' % err.strip())
self.do_raise(f'gconftool-2 failed with error:\n{err.strip()}')
out = out.rstrip()
self.vars.value = None if out == "" else out
return self.vars.value

View file

@ -182,7 +182,7 @@ def get_installed_versions(module, remote=False):
if module.params['repository']:
cmd.extend(['--source', module.params['repository']])
cmd.append('-n')
cmd.append('^%s$' % module.params['name'])
cmd.append(f"^{module.params['name']}$")
environ = get_rubygems_environ(module)
(rc, out, err) = module.run_command(cmd, environ_update=environ, check_rc=True)
@ -337,10 +337,10 @@ def main():
rc, out, err = command_output
module.fail_json(
msg=(
"Failed to uninstall gem '%s': it is still present after 'gem uninstall'. "
f"Failed to uninstall gem '{module.params['name']}': it is still present after 'gem uninstall'. "
"This usually happens with default or system gems provided by the OS, "
"which cannot be removed with the gem command."
) % module.params['name'],
),
rc=rc,
stdout=out,
stderr=err

View file

@ -183,7 +183,7 @@ def main():
base_args.append('-f')
base_args.append(params['file'])
elif scope:
base_args.append("--" + scope)
base_args.append(f"--{scope}")
list_args = list(base_args)
@ -210,7 +210,7 @@ def main():
set_args.append("--unset-all")
set_args.append(name)
else:
set_args.append("--" + add_mode)
set_args.append(f"--{add_mode}")
set_args.append(name)
set_args.append(new_value)
@ -248,7 +248,7 @@ def build_diff_value(value):
if not value:
return "\n"
if len(value) == 1:
return value[0] + "\n"
return f"{value[0]}\n"
return value

View file

@ -154,7 +154,7 @@ def main():
def build_args(module, name, path, scope):
git_path = module.get_bin_path("git", True)
args = [git_path, "config", "--includes", "--null", "--" + scope]
args = [git_path, "config", "--includes", "--null", f"--{scope}"]
if scope == "file":
args.append(path)

View file

@ -203,7 +203,7 @@ class GithubDeployKey(object):
def url(self):
owner = self.module.params['owner']
repo = self.module.params['repo']
return "{0}/repos/{1}/{2}/keys".format(self.github_url, owner, repo)
return f"{self.github_url}/repos/{owner}/{repo}/keys"
@property
def headers(self):
@ -214,7 +214,7 @@ class GithubDeployKey(object):
if self.otp is not None:
return {"X-GitHub-OTP": self.otp}
elif self.token is not None:
return {"Authorization": "token {0}".format(self.token)}
return {"Authorization": f"token {self.token}"}
else:
return None
@ -267,7 +267,7 @@ class GithubDeployKey(object):
self.handle_error(method="POST", info=info)
def remove_existing_key(self, key_id):
resp, info = fetch_url(self.module, "{0}/{1}".format(self.url, key_id), headers=self.headers, method="DELETE")
resp, info = fetch_url(self.module, f"{self.url}/{key_id}", headers=self.headers, method="DELETE")
status_code = info["status"]
@ -286,7 +286,7 @@ class GithubDeployKey(object):
err = None
if status_code == 401:
self.module.fail_json(msg="Failed to connect to {0} due to invalid credentials".format(self.github_url), http_status_code=status_code, error=err)
self.module.fail_json(msg=f"Failed to connect to {self.github_url} due to invalid credentials", http_status_code=status_code, error=err)
elif status_code == 404:
self.module.fail_json(msg="GitHub repository does not exist", http_status_code=status_code, error=err)
else:

View file

@ -99,13 +99,13 @@ def main():
'Accept': 'application/vnd.github.v3+json',
}
url = "https://api.github.com/repos/%s/%s/issues/%s" % (organization, repo, issue)
url = f"https://api.github.com/repos/{organization}/{repo}/issues/{issue}"
response, info = fetch_url(module, url, headers=headers)
if not (200 <= info['status'] < 400):
if info['status'] == 404:
module.fail_json(msg="Failed to find issue %s" % issue)
module.fail_json(msg="Failed to send request to %s: %s" % (url, info['msg']))
module.fail_json(msg=f"Failed to find issue {issue}")
module.fail_json(msg=f"Failed to send request to {url}: {info['msg']}")
gh_obj = json.loads(response.read())

View file

@ -166,7 +166,7 @@ class GitHubSession(object):
def request(self, method, url, data=None):
headers = {
'Authorization': 'token %s' % self.token,
'Authorization': f'token {self.token}',
'Content-Type': 'application/json',
'Accept': 'application/vnd.github.v3+json',
}
@ -174,13 +174,12 @@ class GitHubSession(object):
self.module, url, method=method, data=data, headers=headers)
if not (200 <= info['status'] < 400):
self.module.fail_json(
msg=(" failed to send request %s to %s: %s"
% (method, url, info['msg'])))
msg=f" failed to send request {method} to {url}: {info['msg']}")
return GitHubResponse(response, info)
def get_all_keys(session):
url = session.api_url + '/user/keys'
url = f"{session.api_url}/user/keys"
result = []
while url:
r = session.request('GET', url)
@ -204,7 +203,7 @@ def create_key(session, name, pubkey, check_mode):
else:
return session.request(
'POST',
session.api_url + '/user/keys',
f"{session.api_url}/user/keys",
data=json.dumps({'title': name, 'key': pubkey})).json()
@ -213,7 +212,7 @@ def delete_keys(session, to_delete, check_mode):
return
for key in to_delete:
session.request('DELETE', session.api_url + '/user/keys/%s' % key["id"])
session.request('DELETE', f"{session.api_url}/user/keys/{key['id']}")
def ensure_key_absent(session, name, check_mode):
@ -233,9 +232,7 @@ def ensure_key_present(module, session, name, pubkey, force, check_mode):
for key in all_keys:
existing_signature = key['key'].split(' ')[1]
if new_signature == existing_signature and key['title'] != name:
module.fail_json(msg=(
"another key with the same content is already registered "
"under the name |{0}|").format(key['title']))
module.fail_json(msg=f"another key with the same content is already registered under the name |{key['title']}|")
if matching_keys and force and matching_keys[0]['key'].split(' ')[1] != new_signature:
delete_keys(session, matching_keys, check_mode=check_mode)

View file

@ -130,7 +130,6 @@ except ImportError:
HAS_GITHUB_API = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def main():
@ -196,18 +195,16 @@ def main():
if password or (login_token and not any(login_token.startswith(prefix) for prefix in SKIPPED_TOKEN_PREFIXES)):
gh_obj.me()
except github3.exceptions.AuthenticationFailed as e:
module.fail_json(msg='Failed to connect to GitHub: %s' % to_native(e),
details="Please check username and password or token "
"for repository %s" % repo)
module.fail_json(msg=f'Failed to connect to GitHub: {e}',
details=f"Please check username and password or token for repository {repo}")
except github3.exceptions.GitHubError as e:
module.fail_json(msg='GitHub API error: %s' % to_native(e),
details="Please check username and password or token "
"for repository %s" % repo)
module.fail_json(msg=f'GitHub API error: {e}',
details=f"Please check username and password or token for repository {repo}")
repository = gh_obj.repository(user, repo)
if not repository:
module.fail_json(msg="Repository %s/%s doesn't exist" % (user, repo))
module.fail_json(msg=f"Repository {user}/{repo} doesn't exist")
if action == 'latest_release':
release = repository.latest_release()
@ -219,7 +216,7 @@ def main():
if action == 'create_release':
release_exists = repository.release_from_tag(tag)
if release_exists:
module.exit_json(changed=False, msg="Release for tag %s already exists." % tag)
module.exit_json(changed=False, msg=f"Release for tag {tag} already exists.")
release = repository.create_release(
tag, target, name, body, draft, prerelease)

View file

@ -269,9 +269,9 @@ def main():
result = run_module(module.params, module.check_mode)
module.exit_json(**result)
except GithubException as e:
module.fail_json(msg="Github error. {0}".format(repr(e)))
module.fail_json(msg=f"Github error. {e}")
except Exception as e:
module.fail_json(msg="Unexpected error. {0}".format(repr(e)))
module.fail_json(msg=f"Unexpected error. {e}")
if __name__ == '__main__':

View file

@ -149,7 +149,6 @@ except ImportError:
HAS_GITHUB = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def _create_hook_config(module):
@ -175,8 +174,7 @@ def create_hook(repo, module):
events=module.params["events"],
active=module.params["active"])
except github.GithubException as err:
module.fail_json(msg="Unable to create hook for repository %s: %s" % (
repo.full_name, to_native(err)))
module.fail_json(msg=f"Unable to create hook for repository {repo.full_name}: {err}")
data = {"hook_id": hook.id}
return True, data
@ -194,8 +192,7 @@ def update_hook(repo, hook, module):
changed = hook.update()
except github.GithubException as err:
module.fail_json(msg="Unable to modify hook for repository %s: %s" % (
repo.full_name, to_native(err)))
module.fail_json(msg=f"Unable to modify hook for repository {repo.full_name}: {err}")
data = {"hook_id": hook.id}
return changed, data
@ -231,24 +228,18 @@ def main():
module.params.get("password") or module.params.get("token"),
base_url=module.params["github_url"])
except github.GithubException as err:
module.fail_json(msg="Could not connect to GitHub at %s: %s" % (
module.params["github_url"], to_native(err)))
module.fail_json(msg=f"Could not connect to GitHub at {module.params['github_url']}: {err}")
try:
repo = github_conn.get_repo(module.params["repository"])
except github.BadCredentialsException as err:
module.fail_json(msg="Could not authenticate to GitHub at %s: %s" % (
module.params["github_url"], to_native(err)))
module.fail_json(msg=f"Could not authenticate to GitHub at {module.params['github_url']}: {err}")
except github.UnknownObjectException as err:
module.fail_json(
msg="Could not find repository %s in GitHub at %s: %s" % (
module.params["repository"], module.params["github_url"],
to_native(err)))
msg=f"Could not find repository {module.params['repository']} in GitHub at {module.params['github_url']}: {err}")
except Exception as err:
module.fail_json(
msg="Could not fetch repository %s from GitHub at %s: %s" %
(module.params["repository"], module.params["github_url"],
to_native(err)),
msg=f"Could not fetch repository {module.params['repository']} from GitHub at {module.params['github_url']}: {err}",
exception=traceback.format_exc())
hook = None
@ -259,8 +250,7 @@ def main():
else:
hook = None
except github.GithubException as err:
module.fail_json(msg="Unable to get hooks from repository %s: %s" % (
module.params["repository"], to_native(err)))
module.fail_json(msg=f"Unable to get hooks from repository {module.params['repository']}: {err}")
changed = False
data = {}
@ -271,8 +261,7 @@ def main():
hook.delete()
except github.GithubException as err:
module.fail_json(
msg="Unable to delete hook from repository %s: %s" % (
repo.full_name, to_native(err)))
msg=f"Unable to delete hook from repository {repo.full_name}: {err}")
else:
changed = True
elif hook is not None and module.params["state"] == "present":

View file

@ -98,7 +98,6 @@ except ImportError:
HAS_GITHUB = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def _munge_hook(hook_obj):
@ -140,32 +139,25 @@ def main():
module.params.get("password") or module.params.get("token"),
base_url=module.params["github_url"])
except github.GithubException as err:
module.fail_json(msg="Could not connect to GitHub at %s: %s" % (
module.params["github_url"], to_native(err)))
module.fail_json(msg=f"Could not connect to GitHub at {module.params['github_url']}: {err}")
try:
repo = github_conn.get_repo(module.params["repository"])
except github.BadCredentialsException as err:
module.fail_json(msg="Could not authenticate to GitHub at %s: %s" % (
module.params["github_url"], to_native(err)))
module.fail_json(msg=f"Could not authenticate to GitHub at {module.params['github_url']}: {err}")
except github.UnknownObjectException as err:
module.fail_json(
msg="Could not find repository %s in GitHub at %s: %s" % (
module.params["repository"], module.params["github_url"],
to_native(err)))
msg=f"Could not find repository {module.params['repository']} in GitHub at {module.params['github_url']}: {err}")
except Exception as err:
module.fail_json(
msg="Could not fetch repository %s from GitHub at %s: %s" %
(module.params["repository"], module.params["github_url"],
to_native(err)),
msg=f"Could not fetch repository {module.params['repository']} from GitHub at {module.params['github_url']}: {err}",
exception=traceback.format_exc())
try:
hooks = [_munge_hook(h) for h in repo.get_hooks()]
except github.GithubException as err:
module.fail_json(
msg="Unable to get hooks from repository %s: %s" %
(module.params["repository"], to_native(err)),
msg=f"Unable to get hooks from repository {module.params['repository']}: {err}",
exception=traceback.format_exc())
module.exit_json(changed=False, hooks=hooks)

View file

@ -151,8 +151,10 @@ def main():
gitlab_version = gitlab.__version__
if LooseVersion(gitlab_version) < LooseVersion('2.3.0'):
module.fail_json(msg="community.general.gitlab_proteched_branch requires python-gitlab Python module >= 2.3.0 (installed version: [%s])."
" Please upgrade python-gitlab to version 2.3.0 or above." % gitlab_version)
module.fail_json(
msg=f"community.general.gitlab_branch requires python-gitlab Python module >= 2.3.0 (installed version: [{gitlab_version}])."
" Please upgrade python-gitlab to version 2.3.0 or above."
)
this_gitlab = GitlabBranch(module=module, project=project, gitlab_instance=gitlab_instance)
@ -161,15 +163,15 @@ def main():
if not this_branch and state == "present":
r_branch = this_gitlab.get_branch(ref_branch)
if not r_branch:
module.fail_json(msg="Ref branch {b} not exist.".format(b=ref_branch))
module.fail_json(msg=f"Ref branch {ref_branch} not exist.")
this_gitlab.create_branch(branch, ref_branch)
module.exit_json(changed=True, msg="Created the branch {b}.".format(b=branch))
module.exit_json(changed=True, msg=f"Created the branch {branch}.")
elif this_branch and state == "present":
module.exit_json(changed=False, msg="Branch {b} already exist".format(b=branch))
module.exit_json(changed=False, msg=f"Branch {branch} already exist")
elif this_branch and state == "absent":
try:
this_gitlab.delete_branch(this_branch)
module.exit_json(changed=True, msg="Branch {b} deleted.".format(b=branch))
module.exit_json(changed=True, msg=f"Branch {branch} deleted.")
except Exception as e:
module.fail_json(msg="Error delete branch.", exception=traceback.format_exc())
else:

View file

@ -114,7 +114,6 @@ deploy_key:
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_project, gitlab_authentication, gitlab, list_all_kwargs
@ -160,12 +159,12 @@ class GitLabDeployKey(object):
self.deploy_key_object = deploy_key
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title)
self._module.exit_json(changed=True, msg=f"Successfully created or updated the deploy key {key_title}")
try:
deploy_key.save()
except Exception as e:
self._module.fail_json(msg="Failed to update deploy key: %s " % e)
self._module.fail_json(msg=f"Failed to update deploy key: {e} ")
return True
else:
return False
@ -181,7 +180,7 @@ class GitLabDeployKey(object):
try:
deploy_key = project.keys.create(arguments)
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create deploy key: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create deploy key: {e} ")
return deploy_key
@ -271,24 +270,24 @@ def main():
project = find_project(gitlab_instance, project_identifier)
if project is None:
module.fail_json(msg="Failed to create deploy key: project %s doesn't exists" % project_identifier)
module.fail_json(msg=f"Failed to create deploy key: project {project_identifier} doesn't exists")
deploy_key_exists = gitlab_deploy_key.exists_deploy_key(project, key_title)
if state == 'absent':
if deploy_key_exists:
gitlab_deploy_key.delete_deploy_key()
module.exit_json(changed=True, msg="Successfully deleted deploy key %s" % key_title)
module.exit_json(changed=True, msg=f"Successfully deleted deploy key {key_title}")
else:
module.exit_json(changed=False, msg="Deploy key deleted or does not exists")
if state == 'present':
if gitlab_deploy_key.create_or_update_deploy_key(project, key_title, key_keyfile, {'can_push': key_can_push}):
module.exit_json(changed=True, msg="Successfully created or updated the deploy key %s" % key_title,
module.exit_json(changed=True, msg=f"Successfully created or updated the deploy key {key_title}",
deploy_key=gitlab_deploy_key.deploy_key_object._attrs)
else:
module.exit_json(changed=False, msg="No need to update the deploy key %s" % key_title,
module.exit_json(changed=False, msg=f"No need to update the deploy key {key_title}",
deploy_key=gitlab_deploy_key.deploy_key_object._attrs)

View file

@ -246,7 +246,6 @@ group:
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_group, gitlab_authentication, gitlab
@ -314,7 +313,7 @@ class GitLabGroup(object):
try:
group.avatar = open(options['avatar_path'], 'rb')
except IOError as e:
self._module.fail_json(msg='Cannot open {0}: {1}'.format(options['avatar_path'], e))
self._module.fail_json(msg=f"Cannot open {options['avatar_path']}: {e}")
changed = True
else:
changed, group = self.update_group(self.group_object, payload)
@ -322,12 +321,12 @@ class GitLabGroup(object):
self.group_object = group
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created or updated the group %s" % name)
self._module.exit_json(changed=True, msg=f"Successfully created or updated the group {name}")
try:
group.save()
except Exception as e:
self._module.fail_json(msg="Failed to update group: %s " % e)
self._module.fail_json(msg=f"Failed to update group: {e} ")
return True
else:
return False
@ -345,7 +344,7 @@ class GitLabGroup(object):
group = self._gitlab.groups.create(filtered)
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create group: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create group: {e} ")
return group
@ -383,7 +382,7 @@ class GitLabGroup(object):
try:
group.delete()
except Exception as e:
self._module.fail_json(msg="Failed to delete group: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to delete group: {e} ")
'''
@param name Name of the group
@ -488,14 +487,14 @@ def main():
if not parent_group:
module.fail_json(msg="Failed to create GitLab group: Parent group doesn't exist")
group_exists = gitlab_group.exists_group(parent_group.full_path + '/' + group_path)
group_exists = gitlab_group.exists_group(f"{parent_group.full_path}/{group_path}")
else:
group_exists = gitlab_group.exists_group(group_path)
if state == 'absent':
if group_exists:
gitlab_group.delete_group(force=force_delete)
module.exit_json(changed=True, msg="Successfully deleted group %s" % group_name)
module.exit_json(changed=True, msg=f"Successfully deleted group {group_name}")
else:
module.exit_json(changed=False, msg="Group deleted or does not exist")
@ -523,9 +522,9 @@ def main():
"visibility": group_visibility,
"wiki_access_level": wiki_access_level,
}):
module.exit_json(changed=True, msg="Successfully created or updated the group %s" % group_name, group=gitlab_group.group_object._attrs)
module.exit_json(changed=True, msg=f"Successfully created or updated the group {group_name}", group=gitlab_group.group_object._attrs)
else:
module.exit_json(changed=False, msg="No need to update the group %s" % group_name, group=gitlab_group.group_object._attrs)
module.exit_json(changed=False, msg=f"No need to update the group {group_name}", group=gitlab_group.group_object._attrs)
if __name__ == '__main__':

View file

@ -158,7 +158,6 @@ from datetime import datetime
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_group, gitlab_authentication, gitlab
@ -187,7 +186,7 @@ class GitLabGroupAccessToken(object):
self.access_token_object = group.access_tokens.create(arguments)
changed = True
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create access token: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create access token: {e} ")
return changed
@ -213,7 +212,7 @@ class GitLabGroupAccessToken(object):
self.access_token_object.delete()
changed = True
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to revoke access token: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to revoke access token: {e} ")
return changed
@ -297,7 +296,7 @@ def main():
group = find_group(gitlab_instance, group_identifier)
if group is None:
module.fail_json(msg="Failed to create access token: group %s does not exists" % group_identifier)
module.fail_json(msg=f"Failed to create access token: group {group_identifier} does not exists")
gitlab_access_token_exists = False
gitlab_access_token.find_access_token(group, name)
@ -307,7 +306,7 @@ def main():
if state == 'absent':
if gitlab_access_token_exists:
gitlab_access_token.revoke_access_token()
module.exit_json(changed=True, msg="Successfully deleted access token %s" % name)
module.exit_json(changed=True, msg=f"Successfully deleted access token {name}")
else:
module.exit_json(changed=False, msg="Access token does not exists")

View file

@ -300,7 +300,7 @@ def main():
# group doesn't exist
if not gitlab_group_id:
module.fail_json(msg="group '%s' not found." % gitlab_group)
module.fail_json(msg=f"group '{gitlab_group}' not found.")
members = []
if module.params['gitlab_user'] is not None:
@ -336,14 +336,14 @@ def main():
# user doesn't exist
if not gitlab_user_id:
if state == 'absent':
changed_users.append("user '%s' not found, and thus also not part of the group" % gitlab_user['name'])
changed_users.append(f"user '{gitlab_user['name']}' not found, and thus also not part of the group")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "user '%s' not found, and thus also not part of the group" % gitlab_user['name']})
'msg': f"user '{gitlab_user['name']}' not found, and thus also not part of the group"})
else:
error = True
changed_users.append("user '%s' not found." % gitlab_user['name'])
changed_users.append(f"user '{gitlab_user['name']}' not found.")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "user '%s' not found." % gitlab_user['name']})
'msg': f"user '{gitlab_user['name']}' not found."})
continue
is_user_a_member = group.is_user_a_member(members, gitlab_user_id)
@ -356,56 +356,56 @@ def main():
if not module.check_mode:
group.add_member_to_group(gitlab_user_id, gitlab_group_id, gitlab_user['access_level'])
changed = True
changed_users.append("Successfully added user '%s' to group" % gitlab_user['name'])
changed_users.append(f"Successfully added user '{gitlab_user['name']}' to group")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully added user '%s' to group" % gitlab_user['name']})
'msg': f"Successfully added user '{gitlab_user['name']}' to group"})
except (gitlab.exceptions.GitlabCreateError) as e:
error = True
changed_users.append("Failed to updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Failed to updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Not allowed to add the access level for the member, %s: %s" % (gitlab_user['name'], e)})
'msg': f"Not allowed to add the access level for the member, {gitlab_user['name']}: {e}"})
# state as absent
else:
changed_users.append("User, '%s', is not a member in the group. No change to report" % gitlab_user['name'])
changed_users.append(f"User, '{gitlab_user['name']}', is not a member in the group. No change to report")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "User, '%s', is not a member in the group. No change to report" % gitlab_user['name']})
'msg': f"User, '{gitlab_user['name']}', is not a member in the group. No change to report"})
# in case that a user is a member
else:
if state == 'present':
# compare the access level
user_access_level = group.get_user_access_level(members, gitlab_user_id)
if user_access_level == gitlab_user['access_level']:
changed_users.append("User, '%s', is already a member in the group. No change to report" % gitlab_user['name'])
changed_users.append(f"User, '{gitlab_user['name']}', is already a member in the group. No change to report")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "User, '%s', is already a member in the group. No change to report" % gitlab_user['name']})
'msg': f"User, '{gitlab_user['name']}', is already a member in the group. No change to report"})
else:
# update the access level for the user
try:
if not module.check_mode:
group.update_user_access_level(members, gitlab_user_id, gitlab_user['access_level'])
changed = True
changed_users.append("Successfully updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Successfully updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully updated the access level for the user, '%s'" % gitlab_user['name']})
'msg': f"Successfully updated the access level for the user, '{gitlab_user['name']}'"})
except (gitlab.exceptions.GitlabUpdateError) as e:
error = True
changed_users.append("Failed to updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Failed to updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Not allowed to update the access level for the member, %s: %s" % (gitlab_user['name'], e)})
'msg': f"Not allowed to update the access level for the member, {gitlab_user['name']}: {e}"})
else:
# remove the user from the group
try:
if not module.check_mode:
group.remove_user_from_group(gitlab_user_id, gitlab_group_id)
changed = True
changed_users.append("Successfully removed user, '%s', from the group" % gitlab_user['name'])
changed_users.append(f"Successfully removed user, '{gitlab_user['name']}', from the group")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully removed user, '%s', from the group" % gitlab_user['name']})
'msg': f"Successfully removed user, '{gitlab_user['name']}', from the group"})
except (gitlab.exceptions.GitlabDeleteError) as e:
error = True
changed_users.append("Failed to removed user, '%s', from the group" % gitlab_user['name'])
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the group")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Failed to remove user, '%s' from the group: %s" % (gitlab_user['name'], e)})
'msg': f"Failed to remove user, '{gitlab_user['name']}' from the group: {e}"})
# if state = present and purge_users set delete users which are in members having give access level but not in gitlab_users
if state == 'present' and purge_users:
@ -419,18 +419,18 @@ def main():
if not module.check_mode:
group.remove_user_from_group(member.id, gitlab_group_id)
changed = True
changed_users.append("Successfully removed user '%s', from group. Was not in given list" % member.username)
changed_users.append(f"Successfully removed user '{member.username}', from group. Was not in given list")
changed_data.append({'gitlab_user': member.username, 'result': 'CHANGED',
'msg': "Successfully removed user '%s', from group. Was not in given list" % member.username})
'msg': f"Successfully removed user '{member.username}', from group. Was not in given list"})
except (gitlab.exceptions.GitlabDeleteError) as e:
error = True
changed_users.append("Failed to removed user, '%s', from the group" % gitlab_user['name'])
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the group")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Failed to remove user, '%s' from the group: %s" % (gitlab_user['name'], e)})
'msg': f"Failed to remove user, '{gitlab_user['name']}' from the group: {e}"})
if len(gitlab_users_access) == 1 and error:
# if single user given and an error occurred return error for list errors will be per user
module.fail_json(msg="FAILED: '%s '" % changed_users[0], result_data=changed_data)
module.fail_json(msg=f"FAILED: '{changed_users[0]} '", result_data=changed_data)
elif error:
module.fail_json(msg='FAILED: At least one given user/permission could not be set', result_data=changed_data)

View file

@ -227,12 +227,12 @@ class GitLabHook(object):
self.hook_object = hook
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url)
self._module.exit_json(changed=True, msg=f"Successfully created or updated the hook {hook_url}")
try:
hook.save()
except Exception as e:
self._module.fail_json(msg="Failed to update hook: %s " % e)
self._module.fail_json(msg=f"Failed to update hook: {e} ")
return changed
@ -352,14 +352,14 @@ def main():
project = find_project(gitlab_instance, project_identifier)
if project is None:
module.fail_json(msg="Failed to create hook: project %s doesn't exists" % project_identifier)
module.fail_json(msg=f"Failed to create hook: project {project_identifier} doesn't exists")
hook_exists = gitlab_hook.exists_hook(project, hook_url)
if state == 'absent':
if hook_exists:
gitlab_hook.delete_hook()
module.exit_json(changed=True, msg="Successfully deleted hook %s" % hook_url)
module.exit_json(changed=True, msg=f"Successfully deleted hook {hook_url}")
else:
module.exit_json(changed=False, msg="Hook deleted or does not exists")
@ -379,9 +379,9 @@ def main():
"token": hook_token,
}):
module.exit_json(changed=True, msg="Successfully created or updated the hook %s" % hook_url, hook=gitlab_hook.hook_object._attrs)
module.exit_json(changed=True, msg=f"Successfully created or updated the hook {hook_url}", hook=gitlab_hook.hook_object._attrs)
else:
module.exit_json(changed=False, msg="No need to update the hook %s" % hook_url, hook=gitlab_hook.hook_object._attrs)
module.exit_json(changed=False, msg=f"No need to update the hook {hook_url}", hook=gitlab_hook.hook_object._attrs)
if __name__ == '__main__':

View file

@ -139,7 +139,7 @@ issue:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, gitlab_authentication, gitlab, find_project, find_group
@ -161,7 +161,7 @@ class GitlabIssue(object):
try:
milestones = group.milestones.list(search=milestone_id)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to list the Milestones: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to list the Milestones: {e}")
if len(milestones) > 1:
self._module.fail_json(msg="Multiple Milestones matched search criteria.")
@ -171,7 +171,7 @@ class GitlabIssue(object):
try:
return group.milestones.get(id=milestones[0].id)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to get the Milestones: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to get the Milestones: {e}")
'''
@param title Title of the Issue
@ -182,7 +182,7 @@ class GitlabIssue(object):
try:
issues = self.project.issues.list(query_parameters={"search": title, "in": "title", "state": state_filter})
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to list the Issues: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to list the Issues: {e}")
if len(issues) > 1:
self._module.fail_json(msg="Multiple Issues matched search criteria.")
@ -190,7 +190,7 @@ class GitlabIssue(object):
try:
return self.project.issues.get(id=issues[0].iid)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to get the Issue: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to get the Issue: {e}")
'''
@param username Name of the user
@ -200,7 +200,7 @@ class GitlabIssue(object):
try:
users = [user for user in self.project.users.list(username=username, all=True) if user.username == username]
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to list the users: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to list the users: {e}")
if len(users) > 1:
self._module.fail_json(msg="Multiple Users matched search criteria.")
@ -220,24 +220,24 @@ class GitlabIssue(object):
'''
def create_issue(self, options):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created Issue '%s'." % options["title"])
self._module.exit_json(changed=True, msg=f"Successfully created Issue '{options['title']}'.")
try:
return self.project.issues.create(options)
except gitlab.exceptions.GitlabCreateError as e:
self._module.fail_json(msg="Failed to create Issue: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create Issue: {e}")
'''
@param issue Issue object to delete
'''
def delete_issue(self, issue):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully deleted Issue '%s'." % issue["title"])
self._module.exit_json(changed=True, msg=f"Successfully deleted Issue '{issue['title']}'.")
try:
return issue.delete()
except gitlab.exceptions.GitlabDeleteError as e:
self._module.fail_json(msg="Failed to delete Issue: '%s'." % to_native(e))
self._module.fail_json(msg=f"Failed to delete Issue: '{e}'.")
'''
@param issue Issue object to update
@ -245,12 +245,12 @@ class GitlabIssue(object):
'''
def update_issue(self, issue, options):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully updated Issue '%s'." % issue["title"])
self._module.exit_json(changed=True, msg=f"Successfully updated Issue '{issue['title']}'.")
try:
return self.project.issues.update(issue.iid, options)
except gitlab.exceptions.GitlabUpdateError as e:
self._module.fail_json(msg="Failed to update Issue %s." % to_native(e))
self._module.fail_json(msg=f"Failed to update Issue {e}.")
'''
@param issue Issue object to evaluate
@ -332,14 +332,14 @@ def main():
this_project = find_project(gitlab_instance, project)
if this_project is None:
module.fail_json(msg="Failed to get the project: %s" % project)
module.fail_json(msg=f"Failed to get the project: {project}")
this_gitlab = GitlabIssue(module=module, project=this_project, gitlab_instance=gitlab_instance)
if milestone_id and milestone_group_id:
this_group = find_group(gitlab_instance, milestone_group_id)
if this_group is None:
module.fail_json(msg="Failed to get the group: %s" % milestone_group_id)
module.fail_json(msg=f"Failed to get the group: {milestone_group_id}")
milestone_id = this_gitlab.get_milestone(milestone_id, this_group).id
@ -351,7 +351,7 @@ def main():
with open(description_path, 'rb') as f:
description = to_text(f.read(), errors='surrogate_or_strict')
except IOError as e:
module.fail_json(msg='Cannot open {0}: {1}'.format(description_path, e))
module.fail_json(msg=f'Cannot open {description_path}: {e}')
# sorting necessary in order to properly detect changes, as we don't want to get false positive
# results due to differences in ids ordering;
@ -370,28 +370,28 @@ def main():
if not this_issue:
issue = this_gitlab.create_issue(options)
module.exit_json(
changed=True, msg="Created Issue '{t}'.".format(t=title),
changed=True, msg=f"Created Issue '{title}'.",
issue=issue.asdict()
)
else:
if this_gitlab.issue_has_changed(this_issue, options):
issue = this_gitlab.update_issue(this_issue, options)
module.exit_json(
changed=True, msg="Updated Issue '{t}'.".format(t=title),
changed=True, msg=f"Updated Issue '{title}'.",
issue=issue
)
else:
module.exit_json(
changed=False, msg="Issue '{t}' already exists".format(t=title),
changed=False, msg=f"Issue '{title}' already exists",
issue=this_issue.asdict()
)
elif state == "absent":
if not this_issue:
module.exit_json(changed=False, msg="Issue '{t}' does not exist or has already been deleted.".format(t=title))
module.exit_json(changed=False, msg=f"Issue '{title}' does not exist or has already been deleted.")
else:
issue = this_gitlab.delete_issue(this_issue)
module.exit_json(
changed=True, msg="Issue '{t}' deleted.".format(t=title),
changed=True, msg=f"Issue '{title}' deleted.",
issue=issue
)

View file

@ -460,9 +460,9 @@ def main():
# if both not found, module must exist
if not gitlab_project_id and not gitlab_group_id:
if gitlab_project and not gitlab_project_id:
module.fail_json(msg="project '%s' not found." % gitlab_project)
module.fail_json(msg=f"project '{gitlab_project}' not found.")
if gitlab_group and not gitlab_group_id:
module.fail_json(msg="group '%s' not found." % gitlab_group)
module.fail_json(msg=f"group '{gitlab_group}' not found.")
this_gitlab = GitlabLabels(module=module, gitlab_instance=gitlab_instance, group_id=gitlab_group_id,
project_id=gitlab_project_id)

View file

@ -144,7 +144,7 @@ mr:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
from ansible_collections.community.general.plugins.module_utils.gitlab import (
@ -166,7 +166,7 @@ class GitlabMergeRequest(object):
try:
return self.project.branches.get(branch)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to get the branch: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to get the branch: {e}")
'''
@param title Title of the Merge Request
@ -179,7 +179,7 @@ class GitlabMergeRequest(object):
try:
mrs = self.project.mergerequests.list(search=title, source_branch=source_branch, target_branch=target_branch, state=state_filter)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to list the Merge Request: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to list the Merge Request: {e}")
if len(mrs) > 1:
self._module.fail_json(msg="Multiple Merge Requests matched search criteria.")
@ -187,7 +187,7 @@ class GitlabMergeRequest(object):
try:
return self.project.mergerequests.get(id=mrs[0].iid)
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to get the Merge Request: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to get the Merge Request: {e}")
'''
@param username Name of the user
@ -197,7 +197,7 @@ class GitlabMergeRequest(object):
try:
users = [user for user in self.project.users.list(username=username, all=True) if user.username == username]
except gitlab.exceptions.GitlabGetError as e:
self._module.fail_json(msg="Failed to list the users: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to list the users: {e}")
if len(users) > 1:
self._module.fail_json(msg="Multiple Users matched search criteria.")
@ -217,36 +217,36 @@ class GitlabMergeRequest(object):
'''
def create_mr(self, options):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created the Merge Request %s" % options["title"])
self._module.exit_json(changed=True, msg=f"Successfully created the Merge Request {options['title']}")
try:
return self.project.mergerequests.create(options)
except gitlab.exceptions.GitlabCreateError as e:
self._module.fail_json(msg="Failed to create Merge Request: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create Merge Request: {e}")
'''
@param mr Merge Request object to delete
'''
def delete_mr(self, mr):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully deleted the Merge Request %s" % mr["title"])
self._module.exit_json(changed=True, msg=f"Successfully deleted the Merge Request {mr['title']}")
try:
return mr.delete()
except gitlab.exceptions.GitlabDeleteError as e:
self._module.fail_json(msg="Failed to delete Merge Request: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to delete Merge Request: {e}")
'''
@param mr Merge Request object to update
'''
def update_mr(self, mr, options):
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully updated the Merge Request %s" % mr["title"])
self._module.exit_json(changed=True, msg=f"Successfully updated the Merge Request {mr['title']}")
try:
return self.project.mergerequests.update(mr.iid, options)
except gitlab.exceptions.GitlabUpdateError as e:
self._module.fail_json(msg="Failed to update Merge Request: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to update Merge Request: {e}")
'''
@param mr Merge Request object to evaluate
@ -336,22 +336,24 @@ def main():
gitlab_version = gitlab.__version__
if LooseVersion(gitlab_version) < LooseVersion('2.3.0'):
module.fail_json(msg="community.general.gitlab_merge_request requires python-gitlab Python module >= 2.3.0 (installed version: [%s])."
" Please upgrade python-gitlab to version 2.3.0 or above." % gitlab_version)
module.fail_json(
msg=f"community.general.gitlab_merge_request requires python-gitlab Python module >= 2.3.0 (installed version: [{gitlab_version}])."
" Please upgrade python-gitlab to version 2.3.0 or above."
)
this_project = find_project(gitlab_instance, project)
if this_project is None:
module.fail_json(msg="Failed to get the project: %s" % project)
module.fail_json(msg=f"Failed to get the project: {project}")
this_gitlab = GitlabMergeRequest(module=module, project=this_project, gitlab_instance=gitlab_instance)
r_source_branch = this_gitlab.get_branch(source_branch)
if not r_source_branch:
module.fail_json(msg="Source branch {b} not exist.".format(b=r_source_branch))
module.fail_json(msg=f"Source branch {r_source_branch} not exist.")
r_target_branch = this_gitlab.get_branch(target_branch)
if not r_target_branch:
module.fail_json(msg="Destination branch {b} not exist.".format(b=r_target_branch))
module.fail_json(msg=f"Destination branch {r_target_branch} not exist.")
this_mr = this_gitlab.get_mr(title, source_branch, target_branch, state_filter)
@ -361,7 +363,7 @@ def main():
with open(description_path, 'rb') as f:
description = to_text(f.read(), errors='surrogate_or_strict')
except IOError as e:
module.fail_json(msg='Cannot open {0}: {1}'.format(description_path, e))
module.fail_json(msg=f'Cannot open {description_path}: {e}')
# sorting necessary in order to properly detect changes, as we don't want to get false positive
# results due to differences in ids ordering; see `mr_has_changed()`
@ -384,25 +386,25 @@ def main():
mr = this_gitlab.create_mr(options)
module.exit_json(
changed=True, msg="Created the Merge Request {t} from branch {s} to branch {d}.".format(t=title, d=target_branch, s=source_branch),
changed=True, msg=f"Created the Merge Request {title} from branch {source_branch} to branch {target_branch}.",
mr=mr.asdict()
)
else:
if this_gitlab.mr_has_changed(this_mr, options):
mr = this_gitlab.update_mr(this_mr, options)
module.exit_json(
changed=True, msg="Merge Request {t} from branch {s} to branch {d} updated.".format(t=title, d=target_branch, s=source_branch),
changed=True, msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} updated.",
mr=mr
)
else:
module.exit_json(
changed=False, msg="Merge Request {t} from branch {s} to branch {d} already exist".format(t=title, d=target_branch, s=source_branch),
changed=False, msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} already exist",
mr=this_mr.asdict()
)
elif this_mr and state == "absent":
mr = this_gitlab.delete_mr(this_mr)
module.exit_json(
changed=True, msg="Merge Request {t} from branch {s} to branch {d} deleted.".format(t=title, d=target_branch, s=source_branch),
changed=True, msg=f"Merge Request {title} from branch {source_branch} to branch {target_branch} deleted.",
mr=mr
)
else:

View file

@ -272,13 +272,13 @@ class GitlabMilestones(object):
if _found:
return _found[0].id
else:
self._module.fail_json(msg="milestone '%s' not found." % _title)
self._module.fail_json(msg=f"milestone '{_title}' not found.")
def check_date(self, _date):
try:
datetime.strptime(_date, '%Y-%m-%d')
except ValueError:
self._module.fail_json(msg="milestone's date '%s' not in correct format." % _date)
self._module.fail_json(msg=f"milestone's date '{_date}' not in correct format.")
return _date
def delete_milestone(self, var_obj):
@ -460,9 +460,9 @@ def main():
# if both not found, module must exist
if not gitlab_project_id and not gitlab_group_id:
if gitlab_project and not gitlab_project_id:
module.fail_json(msg="project '%s' not found." % gitlab_project)
module.fail_json(msg=f"project '{gitlab_project}' not found.")
if gitlab_group and not gitlab_group_id:
module.fail_json(msg="group '%s' not found." % gitlab_group)
module.fail_json(msg=f"group '{gitlab_group}' not found.")
this_gitlab = GitlabMilestones(module=module, gitlab_instance=gitlab_instance, group_id=gitlab_group_id,
project_id=gitlab_project_id)

View file

@ -409,7 +409,6 @@ project:
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_group, find_project, gitlab_authentication, gitlab
@ -495,7 +494,7 @@ class GitLabProject(object):
try:
project.avatar = open(options['avatar_path'], 'rb')
except IOError as e:
self._module.fail_json(msg='Cannot open {0}: {1}'.format(options['avatar_path'], e))
self._module.fail_json(msg=f"Cannot open {options['avatar_path']}: {e}")
changed = True
else:
@ -506,12 +505,12 @@ class GitLabProject(object):
self.project_object = project
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name)
self._module.exit_json(changed=True, msg=f"Successfully created or updated the project {project_name}")
try:
project.save()
except Exception as e:
self._module.fail_json(msg="Failed to update project: %s " % e)
self._module.fail_json(msg=f"Failed to update project: {e} ")
return True
return False
@ -529,7 +528,7 @@ class GitLabProject(object):
try:
project = self._gitlab.projects.create(arguments)
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create project: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create project: {e} ")
return project
@ -582,7 +581,7 @@ class GitLabProject(object):
'''
def exists_project(self, namespace, path):
# When project exists, object will be stored in self.project_object.
project = find_project(self._gitlab, namespace.full_path + '/' + path)
project = find_project(self._gitlab, f"{namespace.full_path}/{path}")
if project:
self.project_object = project
return True
@ -721,7 +720,7 @@ def main():
if group_identifier:
group = find_group(gitlab_instance, group_identifier)
if group is None:
module.fail_json(msg="Failed to create project: group %s doesn't exist" % group_identifier)
module.fail_json(msg=f"Failed to create project: group {group_identifier} doesn't exist")
namespace_id = group.id
else:
@ -737,7 +736,7 @@ def main():
try:
namespace = gitlab_instance.namespaces.get(namespace_id)
except gitlab.exceptions.GitlabGetError as e:
module.fail_json(msg="Failed to find the namespace for the given user: %s" % to_native(e))
module.fail_json(msg=f"Failed to find the namespace for the given user: {e}")
if not namespace:
module.fail_json(msg="Failed to find the namespace for the project")
@ -746,7 +745,7 @@ def main():
if state == 'absent':
if project_exists:
gitlab_project.delete_project()
module.exit_json(changed=True, msg="Successfully deleted project %s" % project_name)
module.exit_json(changed=True, msg=f"Successfully deleted project {project_name}")
module.exit_json(changed=False, msg="Project deleted or does not exist")
if state == 'present':
@ -792,8 +791,8 @@ def main():
"wiki_enabled": wiki_enabled,
}):
module.exit_json(changed=True, msg="Successfully created or updated the project %s" % project_name, project=gitlab_project.project_object._attrs)
module.exit_json(changed=False, msg="No need to update the project %s" % project_name, project=gitlab_project.project_object._attrs)
module.exit_json(changed=True, msg=f"Successfully created or updated the project {project_name}", project=gitlab_project.project_object._attrs)
module.exit_json(changed=False, msg=f"No need to update the project {project_name}", project=gitlab_project.project_object._attrs)
if __name__ == '__main__':

View file

@ -156,7 +156,6 @@ from datetime import datetime
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_project, gitlab_authentication, gitlab
@ -184,7 +183,7 @@ class GitLabProjectAccessToken(object):
self.access_token_object = project.access_tokens.create(arguments)
changed = True
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create access token: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create access token: {e}")
return changed
@ -209,7 +208,7 @@ class GitLabProjectAccessToken(object):
self.access_token_object.delete()
changed = True
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to revoke access token: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to revoke access token: {e}")
return changed
@ -291,7 +290,7 @@ def main():
project = find_project(gitlab_instance, project_identifier)
if project is None:
module.fail_json(msg="Failed to create access token: project %s does not exists" % project_identifier)
module.fail_json(msg=f"Failed to create access token: project {project_identifier} does not exists")
gitlab_access_token_exists = False
gitlab_access_token.find_access_token(project, name)
@ -301,7 +300,7 @@ def main():
if state == 'absent':
if gitlab_access_token_exists:
gitlab_access_token.revoke_access_token()
module.exit_json(changed=True, msg="Successfully deleted access token %s" % name)
module.exit_json(changed=True, msg=f"Successfully deleted access token {name}")
else:
module.exit_json(changed=False, msg="Access token does not exists")

View file

@ -165,7 +165,7 @@ def core(module):
project = find_project(gl, gitlab_project)
# project doesn't exist
if not project:
module.fail_json(msg="project '%s' not found." % gitlab_project)
module.fail_json(msg=f"project '{gitlab_project}' not found.")
wished_badge = {
"link_url": module.params["link_url"],

View file

@ -304,7 +304,7 @@ def main():
# project doesn't exist
if not gitlab_project_id:
module.fail_json(msg="project '%s' not found." % gitlab_project)
module.fail_json(msg=f"project '{gitlab_project}' not found.")
members = []
if module.params['gitlab_user'] is not None:
@ -342,14 +342,14 @@ def main():
# user doesn't exist
if not gitlab_user_id:
if state == 'absent':
changed_users.append("user '%s' not found, and thus also not part of the project" % gitlab_user['name'])
changed_users.append(f"user '{gitlab_user['name']}' not found, and thus also not part of the project")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "user '%s' not found, and thus also not part of the project" % gitlab_user['name']})
'msg': f"user '{gitlab_user['name']}' not found, and thus also not part of the project"})
else:
error = True
changed_users.append("user '%s' not found." % gitlab_user['name'])
changed_users.append(f"user '{gitlab_user['name']}' not found.")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "user '%s' not found." % gitlab_user['name']})
'msg': f"user '{gitlab_user['name']}' not found."})
continue
is_user_a_member = project.is_user_a_member(members, gitlab_user_id)
@ -362,56 +362,56 @@ def main():
if not module.check_mode:
project.add_member_to_project(gitlab_user_id, gitlab_project_id, gitlab_user['access_level'])
changed = True
changed_users.append("Successfully added user '%s' to project" % gitlab_user['name'])
changed_users.append(f"Successfully added user '{gitlab_user['name']}' to project")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully added user '%s' to project" % gitlab_user['name']})
'msg': f"Successfully added user '{gitlab_user['name']}' to project"})
except (gitlab.exceptions.GitlabCreateError) as e:
error = True
changed_users.append("Failed to updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Failed to updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Not allowed to add the access level for the member, %s: %s" % (gitlab_user['name'], e)})
'msg': f"Not allowed to add the access level for the member, {gitlab_user['name']}: {e}"})
# state as absent
else:
changed_users.append("User, '%s', is not a member in the project. No change to report" % gitlab_user['name'])
changed_users.append(f"User, '{gitlab_user['name']}', is not a member in the project. No change to report")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "User, '%s', is not a member in the project. No change to report" % gitlab_user['name']})
'msg': f"User, '{gitlab_user['name']}', is not a member in the project. No change to report"})
# in case that a user is a member
else:
if state == 'present':
# compare the access level
user_access_level = project.get_user_access_level(members, gitlab_user_id)
if user_access_level == gitlab_user['access_level']:
changed_users.append("User, '%s', is already a member in the project. No change to report" % gitlab_user['name'])
changed_users.append(f"User, '{gitlab_user['name']}', is already a member in the project. No change to report")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'OK',
'msg': "User, '%s', is already a member in the project. No change to report" % gitlab_user['name']})
'msg': f"User, '{gitlab_user['name']}', is already a member in the project. No change to report"})
else:
# update the access level for the user
try:
if not module.check_mode:
project.update_user_access_level(members, gitlab_user_id, gitlab_user['access_level'])
changed = True
changed_users.append("Successfully updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Successfully updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully updated the access level for the user, '%s'" % gitlab_user['name']})
'msg': f"Successfully updated the access level for the user, '{gitlab_user['name']}'"})
except (gitlab.exceptions.GitlabUpdateError) as e:
error = True
changed_users.append("Failed to updated the access level for the user, '%s'" % gitlab_user['name'])
changed_users.append(f"Failed to updated the access level for the user, '{gitlab_user['name']}'")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Not allowed to update the access level for the member, %s: %s" % (gitlab_user['name'], e)})
'msg': f"Not allowed to update the access level for the member, {gitlab_user['name']}: {e}"})
else:
# remove the user from the project
try:
if not module.check_mode:
project.remove_user_from_project(gitlab_user_id, gitlab_project_id)
changed = True
changed_users.append("Successfully removed user, '%s', from the project" % gitlab_user['name'])
changed_users.append(f"Successfully removed user, '{gitlab_user['name']}', from the project")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'CHANGED',
'msg': "Successfully removed user, '%s', from the project" % gitlab_user['name']})
'msg': f"Successfully removed user, '{gitlab_user['name']}', from the project"})
except (gitlab.exceptions.GitlabDeleteError) as e:
error = True
changed_users.append("Failed to removed user, '%s', from the project" % gitlab_user['name'])
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the project")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Failed to remove user, '%s' from the project: %s" % (gitlab_user['name'], e)})
'msg': f"Failed to remove user, '{gitlab_user['name']}' from the project: {e}"})
# if state = present and purge_users set delete users which are in members having give access level but not in gitlab_users
if state == 'present' and purge_users:
@ -425,18 +425,18 @@ def main():
if not module.check_mode:
project.remove_user_from_project(member.id, gitlab_project_id)
changed = True
changed_users.append("Successfully removed user '%s', from project. Was not in given list" % member.username)
changed_users.append(f"Successfully removed user '{member.username}', from project. Was not in given list")
changed_data.append({'gitlab_user': member.username, 'result': 'CHANGED',
'msg': "Successfully removed user '%s', from project. Was not in given list" % member.username})
'msg': f"Successfully removed user '{member.username}', from project. Was not in given list"})
except (gitlab.exceptions.GitlabDeleteError) as e:
error = True
changed_users.append("Failed to removed user, '%s', from the project" % gitlab_user['name'])
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the project")
changed_data.append({'gitlab_user': gitlab_user['name'], 'result': 'FAILED',
'msg': "Failed to remove user, '%s' from the project: %s" % (gitlab_user['name'], e)})
'msg': f"Failed to remove user, '{gitlab_user['name']}' from the project: {e}"})
if len(gitlab_users_access) == 1 and error:
# if single user given and an error occurred return error for list errors will be per user
module.fail_json(msg="FAILED: '%s '" % changed_users[0], result_data=changed_data)
module.fail_json(msg=f"FAILED: '{changed_users[0]} '", result_data=changed_data)
elif error:
module.fail_json(
msg='FAILED: At least one given user/permission could not be set', result_data=changed_data)

View file

@ -200,8 +200,10 @@ def main():
gitlab_version = gitlab.__version__
if LooseVersion(gitlab_version) < LooseVersion('2.3.0'):
module.fail_json(msg="community.general.gitlab_protected_branch requires python-gitlab Python module >= 2.3.0 (installed version: [%s])."
" Please upgrade python-gitlab to version 2.3.0 or above." % gitlab_version)
module.fail_json(
msg=f"community.general.gitlab_protected_branch requires python-gitlab Python module >= 2.3.0 (installed version: [{gitlab_version}])."
" Please upgrade python-gitlab to version 2.3.0 or above."
)
this_gitlab = GitlabProtectedBranch(module=module, project=project, gitlab_instance=gitlab_instance)

View file

@ -259,7 +259,6 @@ runner:
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, gitlab_authentication, gitlab, list_all_kwargs
@ -328,12 +327,12 @@ class GitLabRunner(object):
changed, runner = self.update_runner(self.runner_object, arguments)
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully updated the runner %s" % description)
self._module.exit_json(changed=True, msg=f"Successfully updated the runner {description}")
try:
runner.save()
except Exception as e:
self._module.fail_json(msg="Failed to update runner: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to update runner: {e} ")
self.runner_object = runner
return changed
@ -356,7 +355,7 @@ class GitLabRunner(object):
else:
runner = self._gitlab.user.runners.create(arguments)
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create runner: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create runner: {e}")
return runner
@ -486,12 +485,12 @@ def main():
try:
gitlab_project = gitlab_instance.projects.get(project)
except gitlab.exceptions.GitlabGetError as e:
module.fail_json(msg='No such a project %s' % project, exception=to_native(e))
module.fail_json(msg=f'No such a project {project}', exception=e)
elif group:
try:
gitlab_group = gitlab_instance.groups.get(group)
except gitlab.exceptions.GitlabGetError as e:
module.fail_json(msg='No such a group %s' % group, exception=to_native(e))
module.fail_json(msg=f'No such a group {group}', exception=e)
gitlab_runner = GitLabRunner(module, gitlab_instance, gitlab_group, gitlab_project)
runner_exists = gitlab_runner.exists_runner(runner_description)
@ -499,7 +498,7 @@ def main():
if state == 'absent':
if runner_exists:
gitlab_runner.delete_runner()
module.exit_json(changed=True, msg="Successfully deleted runner %s" % runner_description)
module.exit_json(changed=True, msg=f"Successfully deleted runner {runner_description}")
else:
module.exit_json(changed=False, msg="Runner deleted or does not exists")
@ -520,10 +519,10 @@ def main():
runner_values["paused"] = runner_paused
if gitlab_runner.create_or_update_runner(runner_description, runner_values):
module.exit_json(changed=True, runner=gitlab_runner.runner_object._attrs,
msg="Successfully created or updated the runner %s" % runner_description)
msg=f"Successfully created or updated the runner {runner_description}")
else:
module.exit_json(changed=False, runner=gitlab_runner.runner_object._attrs,
msg="No need to update the runner %s" % runner_description)
msg=f"No need to update the runner {runner_description}")
if __name__ == '__main__':

View file

@ -219,7 +219,6 @@ user:
from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils.gitlab import (
auth_argument_spec, find_group, gitlab_authentication, gitlab, list_all_kwargs
@ -315,11 +314,11 @@ class GitLabUser(object):
try:
user.save()
except Exception as e:
self._module.fail_json(msg="Failed to update user: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to update user: {e} ")
if changed:
if self._module.check_mode:
self._module.exit_json(changed=True, msg="Successfully created or updated the user %s" % username)
self._module.exit_json(changed=True, msg=f"Successfully created or updated the user {username}")
return True
else:
return False
@ -360,7 +359,7 @@ class GitLabUser(object):
parameter['expires_at'] = sshkey['expires_at']
user.keys.create(parameter)
except gitlab.exceptions.GitlabCreateError as e:
self._module.fail_json(msg="Failed to assign sshkey to user: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to assign sshkey to user: {e}")
return True
return False
@ -420,7 +419,7 @@ class GitLabUser(object):
'user_id': self.get_user_id(user),
'access_level': self.ACCESS_LEVEL[access_level]})
except gitlab.exceptions.GitlabCreateError as e:
self._module.fail_json(msg="Failed to assign user to group: %s" % to_native(e))
self._module.fail_json(msg=f"Failed to assign user to group: {e}")
return True
return False
@ -468,7 +467,7 @@ class GitLabUser(object):
self.add_identities(user, identities)
except (gitlab.exceptions.GitlabCreateError) as e:
self._module.fail_json(msg="Failed to create user: %s " % to_native(e))
self._module.fail_json(msg=f"Failed to create user: {e}")
return user
@ -639,21 +638,21 @@ def main():
if state == 'absent':
if user_exists:
gitlab_user.delete_user()
module.exit_json(changed=True, msg="Successfully deleted user %s" % user_username)
module.exit_json(changed=True, msg=f"Successfully deleted user {user_username}")
else:
module.exit_json(changed=False, msg="User deleted or does not exists")
if state == 'blocked':
if user_exists and user_is_active:
gitlab_user.block_user()
module.exit_json(changed=True, msg="Successfully blocked user %s" % user_username)
module.exit_json(changed=True, msg=f"Successfully blocked user {user_username}")
else:
module.exit_json(changed=False, msg="User already blocked or does not exists")
if state == 'unblocked':
if user_exists and not user_is_active:
gitlab_user.unblock_user()
module.exit_json(changed=True, msg="Successfully unblocked user %s" % user_username)
module.exit_json(changed=True, msg=f"Successfully unblocked user {user_username}")
else:
module.exit_json(changed=False, msg="User is not blocked or does not exists")
@ -674,9 +673,9 @@ def main():
"identities": user_identities,
"overwrite_identities": overwrite_identities,
}):
module.exit_json(changed=True, msg="Successfully created or updated the user %s" % user_username, user=gitlab_user.user_object._attrs)
module.exit_json(changed=True, msg=f"Successfully created or updated the user {user_username}", user=gitlab_user.user_object._attrs)
else:
module.exit_json(changed=False, msg="No need to update the user %s" % user_username, user=gitlab_user.user_object._attrs)
module.exit_json(changed=False, msg=f"No need to update the user {user_username}", user=gitlab_user.user_object._attrs)
if __name__ == '__main__':

View file

@ -88,7 +88,7 @@ def do_notify_grove(module, channel_token, service, message, url=None, icon_url=
data = urlencode(my_data)
response, info = fetch_url(module, my_url, data=data)
if info['status'] != 200:
module.fail_json(msg="failed to send notification: %s" % info['msg'])
module.fail_json(msg=f"failed to send notification: {info['msg']}")
# ==============================================================
# main

View file

@ -160,7 +160,7 @@ def main():
# use venv path if exists
if venv:
gunicorn_command = "/".join((venv, 'bin', 'gunicorn'))
gunicorn_command = f"{venv}/bin/gunicorn"
else:
gunicorn_command = module.get_bin_path('gunicorn')
@ -207,7 +207,7 @@ def main():
else:
# if user defined own error log, check that
if error_log:
error = 'Please check your {0}'.format(error_log.strip())
error = f'Please check your {error_log.strip()}'
else:
if os.path.isfile(tmp_error_log):
with open(tmp_error_log, 'r') as f:
@ -217,10 +217,10 @@ def main():
else:
error = "Log not found"
module.fail_json(msg='Failed to start gunicorn. {0}'.format(error), error=err)
module.fail_json(msg=f'Failed to start gunicorn. {error}', error=err)
else:
module.fail_json(msg='Failed to start gunicorn {0}'.format(err), error=err)
module.fail_json(msg=f'Failed to start gunicorn {err}', error=err)
if __name__ == '__main__':