Merge pull request #532 from rjeffman/pylint_fixes

Add partial support for Pylint.
This commit is contained in:
Thomas Woerner
2021-05-26 10:10:08 +02:00
committed by GitHub
24 changed files with 176 additions and 150 deletions

View File

@@ -31,3 +31,8 @@ jobs:
- name: Run Python linters - name: Run Python linters
uses: rjeffman/python-lint-action@v2 uses: rjeffman/python-lint-action@v2
- name: Run pylint
run: |
pip install pylint==2.8.2
pylint plugins --disable=import-error

View File

@@ -21,6 +21,13 @@ repos:
rev: 5.1.1 rev: 5.1.1
hooks: hooks:
- id: pydocstyle - id: pydocstyle
- repo: https://github.com/pycqa/pylint
rev: v2.8.2
hooks:
- id: pylint
args:
- --disable=import-error
files: \.py$
- repo: local - repo: local
hooks: hooks:
- id: ansible-doc-test - id: ansible-doc-test

View File

@@ -57,7 +57,7 @@ else:
# FreeIPA releases. # FreeIPA releases.
import re import re
class version: class version: # pylint: disable=invalid-name, too-few-public-methods
@staticmethod @staticmethod
def parse(version_str): def parse(version_str):
""" """
@@ -65,7 +65,7 @@ else:
This will not work for `rc`, `dev` or similar version string. This will not work for `rc`, `dev` or similar version string.
""" """
return tuple(re.split("[-_\.]", version_str)) # noqa: W605 return tuple(re.split("[-_.]", version_str)) # noqa: W605
from ipalib import api from ipalib import api
from ipalib import errors as ipalib_errors # noqa from ipalib import errors as ipalib_errors # noqa
@@ -202,11 +202,11 @@ else:
if not backend.isconnected(): if not backend.isconnected():
backend.connect(ccache=os.environ.get('KRB5CCNAME', None)) backend.connect(ccache=os.environ.get('KRB5CCNAME', None))
def api_command(module, command, name, args): def api_command(_module, command, name, args):
"""Call ipa.Command.""" """Call ipa.Command."""
return api.Command[command](name, **args) return api.Command[command](name, **args)
def api_command_no_name(module, command, args): def api_command_no_name(_module, command, args):
"""Call ipa.Command without a name.""" """Call ipa.Command without a name."""
return api.Command[command](**args) return api.Command[command](**args)
@@ -233,7 +233,7 @@ else:
"!=": operator.ne, "!=": operator.ne,
} }
operation = oper_map.get(oper) operation = oper_map.get(oper)
if not(operation): if not operation:
raise NotImplementedError("Invalid operator: %s" % oper) raise NotImplementedError("Invalid operator: %s" % oper)
return operation(version.parse(VERSION), return operation(version.parse(VERSION),
version.parse(requested_version)) version.parse(requested_version))
@@ -258,6 +258,8 @@ else:
finally: finally:
temp_kdestroy(ccache_dir, ccache_name) temp_kdestroy(ccache_dir, ccache_name)
# fix pylint inconsistent return
return None
def date_format(value): def date_format(value):
accepted_date_formats = [ accepted_date_formats = [
@@ -269,9 +271,9 @@ else:
'%Y-%m-%d %H:%MZ', # non-ISO 8601, minute precision '%Y-%m-%d %H:%MZ', # non-ISO 8601, minute precision
] ]
for date_format in accepted_date_formats: for _date_format in accepted_date_formats:
try: try:
return datetime.strptime(value, date_format) return datetime.strptime(value, _date_format)
except ValueError: except ValueError:
pass pass
raise ValueError("Invalid date '%s'" % value) raise ValueError("Invalid date '%s'" % value)
@@ -292,16 +294,8 @@ else:
# If both args and ipa are None, return there's no difference. # If both args and ipa are None, return there's no difference.
# If only one is None, return there is a difference. # If only one is None, return there is a difference.
# This tests avoid unecessary invalid access to attributes. # This tests avoid unecessary invalid access to attributes.
if args is None and ipa is None:
return True
if args is None or ipa is None: if args is None or ipa is None:
module.debug( return args is None and ipa is None
base_debug_msg + "args is%s None an ipa is%s None" % (
"" if args is None else " not",
"" if ipa is None else " not",
)
)
return False
# Fail if args or ipa are not dicts. # Fail if args or ipa are not dicts.
if not (isinstance(args, dict) and isinstance(ipa, dict)): if not (isinstance(args, dict) and isinstance(ipa, dict)):
@@ -313,7 +307,7 @@ else:
filtered_args = [key for key in args if key not in ignore] filtered_args = [key for key in args if key not in ignore]
for key in filtered_args: for key in filtered_args:
if key not in ipa: if key not in ipa: # pylint: disable=no-else-return
module.debug( module.debug(
base_debug_msg + "Command key not present in IPA: %s" % key base_debug_msg + "Command key not present in IPA: %s" % key
) )
@@ -365,15 +359,13 @@ else:
if value is not None: if value is not None:
if isinstance(value, list): if isinstance(value, list):
return [_afm_convert(x) for x in value] return [_afm_convert(x) for x in value]
elif isinstance(value, dict): if isinstance(value, dict):
return {_afm_convert(k): _afm_convert(v) return {_afm_convert(k): _afm_convert(v)
for k, v in value.items()} for k, v in value.items()}
elif isinstance(value, str): if isinstance(value, str):
return to_text(value) return to_text(value)
else:
return value return value
else:
return value
def module_params_get(module, name): def module_params_get(module, name):
return _afm_convert(module.params.get(name)) return _afm_convert(module.params.get(name))
@@ -460,14 +452,13 @@ else:
cert = load_certificate(cert.encode('utf-8')) cert = load_certificate(cert.encode('utf-8'))
return cert return cert
def DN_x500_text(text): def DN_x500_text(text): # pylint: disable=invalid-name
if hasattr(DN, "x500_text"): if hasattr(DN, "x500_text"):
return DN(text).x500_text() return DN(text).x500_text()
else: # Emulate x500_text
# Emulate x500_text dn = DN(text)
dn = DN(text) dn.rdns = reversed(dn.rdns)
dn.rdns = reversed(dn.rdns) return str(dn)
return str(dn)
def is_valid_port(port): def is_valid_port(port):
if not isinstance(port, int): if not isinstance(port, int):
@@ -536,8 +527,9 @@ else:
def __getitem__(self, key): def __getitem__(self, key):
param = self.mapping[key] param = self.mapping[key]
if param is not None: if param is None:
return _afm_convert(param) return None
return _afm_convert(param)
def __iter__(self): def __iter__(self):
return iter(self.mapping) return iter(self.mapping)
@@ -622,6 +614,7 @@ else:
ipa_param_mapping = None ipa_param_mapping = None
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
# pylint: disable=super-with-arguments
super(FreeIPABaseModule, self).__init__(*args, **kwargs) super(FreeIPABaseModule, self).__init__(*args, **kwargs)
# Attributes to store kerberos credentials (if needed) # Attributes to store kerberos credentials (if needed)
@@ -700,7 +693,7 @@ else:
def check_ipa_params(self): def check_ipa_params(self):
"""Validate ipa_params before command is called.""" """Validate ipa_params before command is called."""
pass pass # pylint: disable=unnecessary-pass
def define_ipa_commands(self): def define_ipa_commands(self):
"""Define commands that will be run in IPA server.""" """Define commands that will be run in IPA server."""
@@ -785,7 +778,7 @@ else:
) )
if len(errors) > 0: if len(errors) > 0:
self.fail_json(", ".join("errors")) self.fail_json(", ".join("errors")) # pylint: disable=E1121
def add_ipa_command(self, command, name=None, args=None): def add_ipa_command(self, command, name=None, args=None):
"""Add a command to the list of commands to be executed.""" """Add a command to the list of commands to be executed."""
@@ -805,7 +798,7 @@ else:
self.process_command_result(name, command, args, result) self.process_command_result(name, command, args, result)
self.get_command_errors(command, result) self.get_command_errors(command, result)
def process_command_result(self, name, command, args, result): def process_command_result(self, _name, _command, _args, result):
""" """
Process an API command result. Process an API command result.

View File

@@ -264,10 +264,7 @@ def config_show(module):
def gen_args(params): def gen_args(params):
_args = {} _args = {k: v for k, v in params.items() if v is not None}
for k, v in params.items():
if v is not None:
_args[k] = v
return _args return _args
@@ -368,7 +365,7 @@ def main():
reverse_field_map = {v: k for k, v in field_map.items()} reverse_field_map = {v: k for k, v in field_map.items()}
params = {} params = {}
for x in field_map.keys(): for x in field_map:
val = module_params_get(ansible_module, x) val = module_params_get(ansible_module, x)
if val is not None: if val is not None:
@@ -402,11 +399,11 @@ def main():
("ipasearchrecordslimit", -1, 2147483647), ("ipasearchrecordslimit", -1, 2147483647),
("ipapwdexpadvnotify", 0, 2147483647), ("ipapwdexpadvnotify", 0, 2147483647),
] ]
for arg, min, max in args_with_limits: for arg, minimum, maximum in args_with_limits:
if arg in params and (params[arg] > max or params[arg] < min): if arg in params and (params[arg] > maximum or params[arg] < minimum):
ansible_module.fail_json( ansible_module.fail_json(
msg="Argument '%s' must be between %d and %d." msg="Argument '%s' must be between %d and %d."
% (arg, min, max)) % (arg, minimum, maximum))
changed = False changed = False
exit_args = {} exit_args = {}
@@ -434,7 +431,7 @@ def main():
rawresult = api_command_no_name(ansible_module, "config_show", {}) rawresult = api_command_no_name(ansible_module, "config_show", {})
result = rawresult['result'] result = rawresult['result']
del result['dn'] del result['dn']
for key, v in result.items(): for key, value in result.items():
k = reverse_field_map.get(key, key) k = reverse_field_map.get(key, key)
if ansible_module.argument_spec.get(k): if ansible_module.argument_spec.get(k):
if k == 'ipaselinuxusermaporder': if k == 'ipaselinuxusermaporder':
@@ -449,20 +446,20 @@ def main():
elif k == 'groupsearch': elif k == 'groupsearch':
exit_args['groupsearch'] = \ exit_args['groupsearch'] = \
result.get(key)[0].split(',') result.get(key)[0].split(',')
elif isinstance(v, str) and \ elif isinstance(value, str) and \
ansible_module.argument_spec[k]['type'] == "list": ansible_module.argument_spec[k]['type'] == "list":
exit_args[k] = [v] exit_args[k] = [value]
elif isinstance(v, list) and \ elif isinstance(value, list) and \
ansible_module.argument_spec[k]['type'] == "str": ansible_module.argument_spec[k]['type'] == "str":
exit_args[k] = ",".join(v) exit_args[k] = ",".join(value)
elif isinstance(v, list) and \ elif isinstance(value, list) and \
ansible_module.argument_spec[k]['type'] == "int": ansible_module.argument_spec[k]['type'] == "int":
exit_args[k] = ",".join(v) exit_args[k] = ",".join(value)
elif isinstance(v, list) and \ elif isinstance(value, list) and \
ansible_module.argument_spec[k]['type'] == "bool": ansible_module.argument_spec[k]['type'] == "bool":
exit_args[k] = (v[0] == "TRUE") exit_args[k] = (value[0] == "TRUE")
else: else:
exit_args[k] = v exit_args[k] = value
except ipalib_errors.EmptyModlist: except ipalib_errors.EmptyModlist:
changed = False changed = False
except Exception as e: except Exception as e:

View File

@@ -114,8 +114,8 @@ def find_dnsconfig(module):
if _result["result"].get('idnsforwarders', None) is None: if _result["result"].get('idnsforwarders', None) is None:
_result["result"]['idnsforwarders'] = [''] _result["result"]['idnsforwarders'] = ['']
return _result["result"] return _result["result"]
else:
module.fail_json(msg="Could not retrieve current DNS configuration.") module.fail_json(msg="Could not retrieve current DNS configuration.")
return None return None

View File

@@ -135,8 +135,8 @@ def find_dnsforwardzone(module, name):
msg="There is more than one dnsforwardzone '%s'" % (name)) msg="There is more than one dnsforwardzone '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(forwarders, forwardpolicy, skip_overlap_check): def gen_args(forwarders, forwardpolicy, skip_overlap_check):
@@ -386,8 +386,8 @@ def main():
**exit_args) **exit_args)
# Execute commands # Execute commands
for name, command, args in commands: for _name, command, args in commands:
api_command(ansible_module, command, name, args) api_command(ansible_module, command, _name, args)
changed = True changed = True
except Exception as e: except Exception as e:

View File

@@ -1377,7 +1377,7 @@ def define_commands_for_present_state(module, zone_name, entry, res_find):
_args['idnsname'] = name _args['idnsname'] = name
_commands.append([zone_name, 'dnsrecord_add', _args]) _commands.append([zone_name, 'dnsrecord_add', _args])
# clean used fields from args # clean used fields from args
for f in part_fields: for f in part_fields: # pylint: disable=invalid-name
if f in args: if f in args:
del args[f] del args[f]
else: else:

View File

@@ -263,22 +263,18 @@ class DNSZoneModule(FreeIPABaseModule):
if any(invalid_ips): if any(invalid_ips):
self.fail_json(msg=error_msg % invalid_ips) self.fail_json(msg=error_msg % invalid_ips)
def is_valid_nsec3param_rec(self, nsec3param_rec): def is_valid_nsec3param_rec(self, nsec3param_rec): # pylint: disable=R0201
try: try:
part1, part2, part3, part4 = nsec3param_rec.split(" ") part1, part2, part3, part4 = nsec3param_rec.split(" ")
except ValueError: except ValueError:
return False return False
if not all([part1.isdigit(), part2.isdigit(), part3.isdigit()]): if (
return False not all([part1.isdigit(), part2.isdigit(), part3.isdigit()])
or not 0 <= int(part1) <= 255
if not 0 <= int(part1) <= 255: or not 0 <= int(part2) <= 255
return False or not 0 <= int(part3) <= 65535
):
if not 0 <= int(part2) <= 255:
return False
if not 0 <= int(part3) <= 65535:
return False return False
try: try:
@@ -298,7 +294,7 @@ class DNSZoneModule(FreeIPABaseModule):
return True return True
def get_ipa_nsec3paramrecord(self, **kwargs): def get_ipa_nsec3paramrecord(self, **_kwargs): # pylint: disable=R1710
nsec3param_rec = self.ipa_params.nsec3param_rec nsec3param_rec = self.ipa_params.nsec3param_rec
if nsec3param_rec is not None: if nsec3param_rec is not None:
error_msg = ( error_msg = (
@@ -310,12 +306,12 @@ class DNSZoneModule(FreeIPABaseModule):
self.fail_json(msg=error_msg) self.fail_json(msg=error_msg)
return nsec3param_rec return nsec3param_rec
def get_ipa_idnsforwarders(self, **kwargs): def get_ipa_idnsforwarders(self, **_kwargs): # pylint: disable=R1710
if self.ipa_params.forwarders is not None: if self.ipa_params.forwarders is not None:
forwarders = [] forwarders = []
for forwarder in self.ipa_params.forwarders: for forwarder in self.ipa_params.forwarders:
ip_address = forwarder.get("ip_address") ip_address = forwarder.get("ip_address")
if not (is_ip_address(ip_address)): if not is_ip_address(ip_address):
self.fail_json( self.fail_json(
msg="Invalid IP for DNS forwarder: %s" % ip_address msg="Invalid IP for DNS forwarder: %s" % ip_address
) )
@@ -334,14 +330,14 @@ class DNSZoneModule(FreeIPABaseModule):
return forwarders return forwarders
def get_ipa_idnsallowtransfer(self, **kwargs): def get_ipa_idnsallowtransfer(self, **_kwargs): # pylint: disable=R1710
if self.ipa_params.allow_transfer is not None: if self.ipa_params.allow_transfer is not None:
error_msg = "Invalid ip_address for DNS allow_transfer: %s" error_msg = "Invalid ip_address for DNS allow_transfer: %s"
self.validate_ips(self.ipa_params.allow_transfer, error_msg) self.validate_ips(self.ipa_params.allow_transfer, error_msg)
return (";".join(self.ipa_params.allow_transfer) or "none") + ";" return (";".join(self.ipa_params.allow_transfer) or "none") + ";"
def get_ipa_idnsallowquery(self, **kwargs): def get_ipa_idnsallowquery(self, **_kwargs): # pylint: disable=R1710
if self.ipa_params.allow_query is not None: if self.ipa_params.allow_query is not None:
error_msg = "Invalid ip_address for DNS allow_query: %s" error_msg = "Invalid ip_address for DNS allow_query: %s"
self.validate_ips(self.ipa_params.allow_query, error_msg) self.validate_ips(self.ipa_params.allow_query, error_msg)
@@ -364,27 +360,27 @@ class DNSZoneModule(FreeIPABaseModule):
return ".".join((name, domain)) return ".".join((name, domain))
def get_ipa_idnssoarname(self, **kwargs): def get_ipa_idnssoarname(self, **_kwargs): # pylint: disable=R1710
if self.ipa_params.admin_email is not None: if self.ipa_params.admin_email is not None:
return DNSName( return DNSName(
self._replace_at_symbol_in_rname(self.ipa_params.admin_email) self._replace_at_symbol_in_rname(self.ipa_params.admin_email)
) )
def get_ipa_idnssoamname(self, **kwargs): def get_ipa_idnssoamname(self, **_kwargs): # pylint: disable=R1710
if self.ipa_params.name_server is not None: if self.ipa_params.name_server is not None:
return DNSName(self.ipa_params.name_server) return DNSName(self.ipa_params.name_server)
def get_ipa_skip_overlap_check(self, **kwargs): def get_ipa_skip_overlap_check(self, **kwargs): # pylint: disable=R1710
zone = kwargs.get('zone') zone = kwargs.get('zone')
if not zone and self.ipa_params.skip_overlap_check is not None: if not zone and self.ipa_params.skip_overlap_check is not None:
return self.ipa_params.skip_overlap_check return self.ipa_params.skip_overlap_check
def get_ipa_skip_nameserver_check(self, **kwargs): def get_ipa_skip_nameserver_check(self, **kwargs): # pylint: disable=R1710
zone = kwargs.get('zone') zone = kwargs.get('zone')
if not zone and self.ipa_params.skip_nameserver_check is not None: if not zone and self.ipa_params.skip_nameserver_check is not None:
return self.ipa_params.skip_nameserver_check return self.ipa_params.skip_nameserver_check
def __reverse_zone_name(self, ipaddress): def __reverse_zone_name(self, ipaddress): # pylint: disable=R1710
""" """
Infer reverse zone name from an ip address. Infer reverse zone name from an ip address.
@@ -404,10 +400,9 @@ class DNSZoneModule(FreeIPABaseModule):
ip_version = ip.version ip_version = ip.version
if ip_version == 4: if ip_version == 4:
return u'.'.join(items[4 - prefixlen // 8:]) return u'.'.join(items[4 - prefixlen // 8:])
elif ip_version == 6: if ip_version == 6:
return u'.'.join(items[32 - prefixlen // 4:]) return u'.'.join(items[32 - prefixlen // 4:])
else: self.fail_json(msg="Invalid IP version for reverse zone.")
self.fail_json(msg="Invalid IP version for reverse zone.")
def get_zone(self, zone_name): def get_zone(self, zone_name):
get_zone_args = {"idnsname": zone_name, "all": True} get_zone_args = {"idnsname": zone_name, "all": True}
@@ -505,6 +500,7 @@ class DNSZoneModule(FreeIPABaseModule):
self.add_ipa_command("dnszone_mod", zone_name, args) self.add_ipa_command("dnszone_mod", zone_name, args)
def process_command_result(self, name, command, args, result): def process_command_result(self, name, command, args, result):
# pylint: disable=super-with-arguments
super(DNSZoneModule, self).process_command_result( super(DNSZoneModule, self).process_command_result(
name, command, args, result name, command, args, result
) )

View File

@@ -201,8 +201,8 @@ def find_group(module, name):
msg="There is more than one group '%s'" % (name)) msg="There is more than one group '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description, gid, nomembers): def gen_args(description, gid, nomembers):

View File

@@ -175,8 +175,8 @@ def find_hbacrule(module, name):
msg="There is more than one hbacrule '%s'" % (name)) msg="There is more than one hbacrule '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description, usercategory, hostcategory, servicecategory, def gen_args(description, usercategory, hostcategory, servicecategory,

View File

@@ -89,8 +89,8 @@ def find_hbacsvc(module, name):
msg="There is more than one hbacsvc '%s'" % (name)) msg="There is more than one hbacsvc '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description): def gen_args(description):

View File

@@ -121,8 +121,8 @@ def find_hbacsvcgroup(module, name):
msg="There is more than one hbacsvcgroup '%s'" % (name)) msg="There is more than one hbacsvcgroup '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description, nomembers): def gen_args(description, nomembers):

View File

@@ -466,7 +466,7 @@ def show_host(module, name):
def gen_args(description, locality, location, platform, os, password, random, def gen_args(description, locality, location, platform, os, password, random,
mac_address, sshpubkey, userclass, auth_ind, requires_pre_auth, mac_address, sshpubkey, userclass, auth_ind, requires_pre_auth,
ok_as_delegate, ok_to_auth_as_delegate, force, reverse, ok_as_delegate, ok_to_auth_as_delegate, force, _reverse,
ip_address, update_dns): ip_address, update_dns):
# certificate, managedby_host, principal, create_keytab_* and # certificate, managedby_host, principal, create_keytab_* and
# allow_retrieve_keytab_* are not handled here # allow_retrieve_keytab_* are not handled here
@@ -529,7 +529,7 @@ def gen_dnsrecord_args(module, ip_address, reverse):
return _args return _args
def check_parameters( def check_parameters( # pylint: disable=unused-argument
module, state, action, module, state, action,
description, locality, location, platform, os, password, random, description, locality, location, platform, os, password, random,
certificate, managedby_host, principal, allow_create_keytab_user, certificate, managedby_host, principal, allow_create_keytab_user,
@@ -862,7 +862,7 @@ def main():
ok_to_auth_as_delegate, force, reverse, ip_address, ok_to_auth_as_delegate, force, reverse, ip_address,
update_dns, update_password) update_dns, update_password)
elif isinstance(host, str) or isinstance(host, unicode): elif isinstance(host, (str, unicode)):
name = host name = host
else: else:
ansible_module.fail_json(msg="Host '%s' is not valid" % ansible_module.fail_json(msg="Host '%s' is not valid" %

View File

@@ -157,8 +157,8 @@ def find_hostgroup(module, name):
msg="There is more than one hostgroup '%s'" % (name)) msg="There is more than one hostgroup '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description, nomembers, rename): def gen_args(description, nomembers, rename):

View File

@@ -130,8 +130,8 @@ def find_pwpolicy(module, name):
msg="There is more than one pwpolicy '%s'" % (name)) msg="There is more than one pwpolicy '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(maxlife, minlife, history, minclasses, minlength, priority, def gen_args(maxlife, minlife, history, minclasses, minlength, priority,

View File

@@ -250,8 +250,8 @@ def find_service(module, name):
_res["usercertificate"] = [encode_certificate(cert) for _res["usercertificate"] = [encode_certificate(cert) for
cert in certs] cert in certs]
return _res return _res
else:
return None return None
def gen_args(pac_type, auth_ind, skip_host_check, force, requires_pre_auth, def gen_args(pac_type, auth_ind, skip_host_check, force, requires_pre_auth,
@@ -771,7 +771,7 @@ def main():
elif state == "absent": elif state == "absent":
if action == "service": if action == "service":
if res_find is not None: if res_find is not None:
args = {'continue': True if delete_continue else False} args = {'continue': delete_continue}
commands.append([name, 'service_del', args]) commands.append([name, 'service_del', args])
elif action == "member": elif action == "member":

View File

@@ -90,8 +90,8 @@ def find_sudocmd(module, name):
msg="There is more than one sudocmd '%s'" % (name)) msg="There is more than one sudocmd '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description): def gen_args(description):

View File

@@ -206,8 +206,8 @@ def find_sudorule(module, name):
msg="There is more than one sudorule '%s'" % (name)) msg="There is more than one sudorule '%s'" % (name))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def gen_args(description, usercat, hostcat, cmdcat, runasusercat, def gen_args(description, usercat, hostcat, cmdcat, runasusercat,

View File

@@ -132,8 +132,8 @@ def find_left_right(module, suffix, left, right):
"not unique for suffix '%s'" % (left, right, suffix)) "not unique for suffix '%s'" % (left, right, suffix))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def find_cn(module, suffix, name): def find_cn(module, suffix, name):
@@ -147,8 +147,8 @@ def find_cn(module, suffix, name):
msg="CN '%s' is not unique for suffix '%s'" % (name, suffix)) msg="CN '%s' is not unique for suffix '%s'" % (name, suffix))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def find_left_right_cn(module, suffix, left, right, name): def find_left_right_cn(module, suffix, left, right, name):

View File

@@ -125,8 +125,8 @@ def find_trust(module, realm):
module.fail_json(msg="There is more than one realm '%s'" % (realm)) module.fail_json(msg="There is more than one realm '%s'" % (realm))
elif len(_result["result"]) == 1: elif len(_result["result"]) == 1:
return _result["result"][0] return _result["result"][0]
else:
return None return None
def del_trust(module, realm): def del_trust(module, realm):
@@ -136,8 +136,6 @@ def del_trust(module, realm):
if len(_result["result"]["failed"]) > 0: if len(_result["result"]["failed"]) > 0:
module.fail_json( module.fail_json(
msg="Trust deletion has failed for '%s'" % (realm)) msg="Trust deletion has failed for '%s'" % (realm))
else:
return None
def add_trust(module, realm, args): def add_trust(module, realm, args):
@@ -148,12 +146,10 @@ def add_trust(module, realm, args):
if "cn" not in _result["result"]: if "cn" not in _result["result"]:
module.fail_json( module.fail_json(
msg="Trust add has failed for '%s'" % (realm)) msg="Trust add has failed for '%s'" % (realm))
else:
return None
def gen_args(trust_type, admin, password, server, trust_secret, base_id, def gen_args(trust_type, admin, password, server, trust_secret, base_id,
range_size, range_type, two_way, external): range_size, _range_type, two_way, external):
_args = {} _args = {}
if trust_type is not None: if trust_type is not None:
_args["trust_type"] = trust_type _args["trust_type"] = trust_type

View File

@@ -512,10 +512,9 @@ def find_user(module, name, preserved=False):
if certs is not None: if certs is not None:
_result["usercertificate"] = [encode_certificate(x) _result["usercertificate"] = [encode_certificate(x)
for x in certs] for x in certs]
return _result return _result
else:
return None return None
def gen_args(first, last, fullname, displayname, initials, homedir, shell, def gen_args(first, last, fullname, displayname, initials, homedir, shell,
@@ -599,17 +598,14 @@ def gen_args(first, last, fullname, displayname, initials, homedir, shell,
return _args return _args
def check_parameters(module, state, action, def check_parameters( # pylint: disable=unused-argument
first, last, fullname, displayname, initials, homedir, module, state, action, first, last, fullname, displayname, initials,
shell, email, principal, principalexpiration, homedir, shell, email, principal, principalexpiration,
passwordexpiration, password, random, uid, gid, city, passwordexpiration, password, random, uid, gid, city, phone, mobile,
phone, mobile, pager, fax, orgunit, title, manager, pager, fax, orgunit, title, manager, carlicense, sshpubkey,
carlicense, sshpubkey, userauthtype, userclass, radius, userauthtype, userclass, radius, radiususer, departmentnumber,
radiususer, departmentnumber, employeenumber, employeenumber, employeetype, preferredlanguage, certificate,
employeetype, preferredlanguage, certificate, certmapdata, noprivate, nomembers, preserve, update_password):
certmapdata, noprivate, nomembers, preserve,
update_password):
if state == "present": if state == "present":
if action == "member": if action == "member":
invalid = ["first", "last", "fullname", "displayname", "initials", invalid = ["first", "last", "fullname", "displayname", "initials",
@@ -715,7 +711,7 @@ def check_certmapdata(data):
return False return False
i = data.find("<I>", 4) i = data.find("<I>", 4)
s = data.find("<S>", i) s = data.find("<S>", i) # pylint: disable=invalid-name
issuer = data[i+3:s] issuer = data[i+3:s]
subject = data[s+3:] subject = data[s+3:]
@@ -1033,7 +1029,7 @@ def main():
email = extend_emails(email, default_email_domain) email = extend_emails(email, default_email_domain)
elif isinstance(user, str) or isinstance(user, unicode): elif isinstance(user, (str, unicode)):
name = user name = user
else: else:
ansible_module.fail_json(msg="User '%s' is not valid" % ansible_module.fail_json(msg="User '%s' is not valid" %

View File

@@ -348,9 +348,9 @@ def find_vault(module, name, username, service, shared):
return None return None
def gen_args(description, username, service, shared, vault_type, salt, def gen_args(
password, password_file, public_key, public_key_file, vault_data, description, username, service, shared, vault_type, salt,
datafile_in, datafile_out): public_key, public_key_file):
_args = {} _args = {}
vault_type = vault_type or to_text("symmetric") vault_type = vault_type or to_text("symmetric")
@@ -443,12 +443,12 @@ def data_storage_args(vault_type, args, data, password, password_file,
return _args return _args
def check_parameters(module, state, action, description, username, service, def check_parameters( # pylint: disable=unused-argument
shared, users, groups, services, owners, ownergroups, module, state, action, description, username, service, shared, users,
ownerservices, vault_type, salt, password, password_file, groups, services, owners, ownergroups, ownerservices, vault_type, salt,
public_key, public_key_file, private_key, password, password_file, public_key, public_key_file, private_key,
private_key_file, vault_data, datafile_in, datafile_out, private_key_file, vault_data, datafile_in, datafile_out, new_password,
new_password, new_password_file): new_password_file):
invalid = [] invalid = []
if state == "present": if state == "present":
invalid = ['datafile_out'] invalid = ['datafile_out']
@@ -491,11 +491,11 @@ def check_parameters(module, state, action, description, username, service,
"action '%s'" % (arg, state, action)) "action '%s'" % (arg, state, action))
def check_encryption_params(module, state, action, vault_type, salt, def check_encryption_params( # pylint: disable=unused-argument
password, password_file, public_key, module, state, action, vault_type, salt, password, password_file,
public_key_file, private_key, private_key_file, public_key, public_key_file, private_key, private_key_file, vault_data,
vault_data, datafile_in, datafile_out, datafile_in, datafile_out, new_password, new_password_file, res_find):
new_password, new_password_file, res_find): """Check parameters used for (de)vault data encryption."""
vault_type_invalid = [] vault_type_invalid = []
existing_type = None existing_type = None
@@ -757,9 +757,7 @@ def main():
# Generate args # Generate args
args = gen_args(description, username, service, shared, vault_type, args = gen_args(description, username, service, shared, vault_type,
salt, password, password_file, public_key, salt, public_key, public_key_file)
public_key_file, vault_data, datafile_in,
datafile_out)
pwdargs = None pwdargs = None
# Create command # Create command

View File

@@ -31,3 +31,40 @@ per-file-ignores =
[pydocstyle] [pydocstyle]
inherit = false inherit = false
ignore = D1,D212,D203 ignore = D1,D212,D203
[pylint.MASTER]
disable =
c-extension-no-member,
missing-module-docstring,
missing-class-docstring,
missing-function-docstring,
wrong-import-order,
ungrouped-imports,
wrong-import-position,
protected-access,
no-name-in-module,
too-many-arguments,
too-many-statements,
too-many-lines,
raise-missing-from,
duplicate-code,
broad-except,
too-many-branches,
too-many-locals,
fixme
[pylint.BASIC]
good-names = ex, i, j, k, Run, _, e, x, dn, cn, ip, os, unicode
[pylint.IMPORTS]
ignored-modules =
ansible.module_utils.ansible_freeipa_module,
ipalib, ipalib.config, ipalib.constants, ipalib.krb_utils, ipalib.errors,
ipapython.ipautil, ipapython.dn, ipapython.version, ipapython.dnsutil,
ipaplatform.paths
[pylint.REFACTORING]
max-nested-blocks = 9
[pylint.FORMAT]
max-line-length = 80

View File

@@ -4,6 +4,7 @@ topdir="`dirname $(dirname $0)`"
flake8 . flake8 .
pydocstyle . pydocstyle .
pylint plugins
ANSIBLE_LIBRARY=${ANSIBLE_LIBRARY:-"${topdir}/plugins/modules"} ANSIBLE_LIBRARY=${ANSIBLE_LIBRARY:-"${topdir}/plugins/modules"}
ANSIBLE_MODULE_UTILS=${ANSIBLE_MODULE_UTILS:-"${topdir}/plugins/module_utils"} ANSIBLE_MODULE_UTILS=${ANSIBLE_MODULE_UTILS:-"${topdir}/plugins/module_utils"}