Skip to content

Commit

Permalink
[PR #9579/0de39a6f backport][stable-10] use open() as context manager (
Browse files Browse the repository at this point in the history
…#9596)

use open() as context manager (#9579)

* use open() as context manager

* add changelog frag

(cherry picked from commit 0de39a6)

Co-authored-by: Alexei Znamensky <[email protected]>
  • Loading branch information
patchback[bot] and russoz authored Jan 21, 2025
1 parent 98d25a3 commit e9b58cf
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 103 deletions.
11 changes: 11 additions & 0 deletions changelogs/fragments/9579-with-open.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
minor_changes:
- known_hosts - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- cloud_init_data_facts - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- cronvar - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- crypttab - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- parted - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- pulp_repo - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- redhat_subscription - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- solaris_zone - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- sorcery - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
- timezone - open file using ``open()`` as a context manager (https://github.com/ansible-collections/community.general/pull/9579).
6 changes: 2 additions & 4 deletions plugins/module_utils/known_hosts.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ def not_in_host_file(self, host):
continue

try:
host_fh = open(hf)
with open(hf) as host_fh:
data = host_fh.read()
except IOError:
hfiles_not_found += 1
continue
else:
data = host_fh.read()
host_fh.close()

for line in data.split("\n"):
if line is None or " " not in line:
Expand Down
5 changes: 2 additions & 3 deletions plugins/modules/cloud_init_data_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,8 @@ def gather_cloud_init_data_facts(module):
json_file = os.path.join(CLOUD_INIT_PATH, i + '.json')

if os.path.exists(json_file):
f = open(json_file, 'rb')
contents = to_text(f.read(), errors='surrogate_or_strict')
f.close()
with open(json_file, 'rb') as f:
contents = to_text(f.read(), errors='surrogate_or_strict')

if contents:
res['cloud_init_data_facts'][i] = module.from_json(contents)
Expand Down
5 changes: 2 additions & 3 deletions plugins/modules/cronvar.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,8 @@ def read(self):
if self.cron_file:
# read the cronfile
try:
f = open(self.cron_file, 'r')
self.lines = f.read().splitlines()
f.close()
with open(self.cron_file, 'r') as f:
self.lines = f.read().splitlines()
except IOError:
# cron file does not exist
return
Expand Down
10 changes: 2 additions & 8 deletions plugins/modules/crypttab.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,8 @@ def main():
changed, reason = existing_line.opts.remove(opts)

if changed and not module.check_mode:
try:
f = open(path, 'wb')
with open(path, 'wb') as f:
f.write(to_bytes(crypttab, errors='surrogate_or_strict'))
finally:
f.close()

module.exit_json(changed=changed, msg=reason, **module.params)

Expand All @@ -173,12 +170,9 @@ def __init__(self, path):
os.makedirs(os.path.dirname(path))
open(path, 'a').close()

try:
f = open(path, 'r')
with open(path, 'r') as f:
for line in f.readlines():
self._lines.append(Line(line))
finally:
f.close()

def add(self, line):
self._lines.append(line)
Expand Down
5 changes: 1 addition & 4 deletions plugins/modules/parted.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,11 +588,8 @@ def read_record(file_path, default=None):
Reads the first line of a file and returns it.
"""
try:
f = open(file_path, 'r')
try:
with open(file_path, 'r') as f:
return f.readline().strip()
finally:
f.close()
except IOError:
return default

Expand Down
15 changes: 3 additions & 12 deletions plugins/modules/pulp_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,29 +583,20 @@ def main():
if importer_ssl_ca_cert is not None:
importer_ssl_ca_cert_file_path = os.path.abspath(importer_ssl_ca_cert)
if os.path.isfile(importer_ssl_ca_cert_file_path):
importer_ssl_ca_cert_file_object = open(importer_ssl_ca_cert_file_path, 'r')
try:
with open(importer_ssl_ca_cert_file_path, 'r') as importer_ssl_ca_cert_file_object:
importer_ssl_ca_cert = importer_ssl_ca_cert_file_object.read()
finally:
importer_ssl_ca_cert_file_object.close()

if importer_ssl_client_cert is not None:
importer_ssl_client_cert_file_path = os.path.abspath(importer_ssl_client_cert)
if os.path.isfile(importer_ssl_client_cert_file_path):
importer_ssl_client_cert_file_object = open(importer_ssl_client_cert_file_path, 'r')
try:
with open(importer_ssl_client_cert_file_path, 'r') as importer_ssl_client_cert_file_object:
importer_ssl_client_cert = importer_ssl_client_cert_file_object.read()
finally:
importer_ssl_client_cert_file_object.close()

if importer_ssl_client_key is not None:
importer_ssl_client_key_file_path = os.path.abspath(importer_ssl_client_key)
if os.path.isfile(importer_ssl_client_key_file_path):
importer_ssl_client_key_file_object = open(importer_ssl_client_key_file_path, 'r')
try:
with open(importer_ssl_client_key_file_path, 'r') as importer_ssl_client_key_file_object:
importer_ssl_client_key = importer_ssl_client_key_file_object.read()
finally:
importer_ssl_client_key_file_object.close()

server = pulp_server(module, pulp_host, repo_type, wait_for_completion=wait_for_completion)
server.set_repo_list()
Expand Down
5 changes: 2 additions & 3 deletions plugins/modules/redhat_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,9 +308,8 @@ def update_plugin_conf(self, plugin, enabled=True):
else:
cfg.set('main', 'enabled', '0')

fd = open(tmpfile, 'w+')
cfg.write(fd)
fd.close()
with open(tmpfile, 'w+') as fd:
cfg.write(fd)
self.module.atomic_move(tmpfile, plugin_conf)

def enable(self):
Expand Down
46 changes: 21 additions & 25 deletions plugins/modules/solaris_zone.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,24 +246,22 @@ def configure_sysid(self):

open('%s/root/noautoshutdown' % self.path, 'w').close()

node = open('%s/root/etc/nodename' % self.path, 'w')
node.write(self.name)
node.close()

id = open('%s/root/etc/.sysIDtool.state' % self.path, 'w')
id.write('1 # System previously configured?\n')
id.write('1 # Bootparams succeeded?\n')
id.write('1 # System is on a network?\n')
id.write('1 # Extended network information gathered?\n')
id.write('0 # Autobinder succeeded?\n')
id.write('1 # Network has subnets?\n')
id.write('1 # root password prompted for?\n')
id.write('1 # locale and term prompted for?\n')
id.write('1 # security policy in place\n')
id.write('1 # NFSv4 domain configured\n')
id.write('0 # Auto Registration Configured\n')
id.write('vt100')
id.close()
with open('%s/root/etc/nodename' % self.path, 'w') as node:
node.write(self.name)

with open('%s/root/etc/.sysIDtool.state' % self.path, 'w') as id:
id.write('1 # System previously configured?\n')
id.write('1 # Bootparams succeeded?\n')
id.write('1 # System is on a network?\n')
id.write('1 # Extended network information gathered?\n')
id.write('0 # Autobinder succeeded?\n')
id.write('1 # Network has subnets?\n')
id.write('1 # root password prompted for?\n')
id.write('1 # locale and term prompted for?\n')
id.write('1 # security policy in place\n')
id.write('1 # NFSv4 domain configured\n')
id.write('0 # Auto Registration Configured\n')
id.write('vt100')

def configure_ssh_keys(self):
rsa_key_file = '%s/root/etc/ssh/ssh_host_rsa_key' % self.path
Expand All @@ -284,20 +282,18 @@ def configure_ssh_keys(self):
def configure_password(self):
shadow = '%s/root/etc/shadow' % self.path
if self.root_password:
f = open(shadow, 'r')
lines = f.readlines()
f.close()
with open(shadow, 'r') as f:
lines = f.readlines()

for i in range(0, len(lines)):
fields = lines[i].split(':')
if fields[0] == 'root':
fields[1] = self.root_password
lines[i] = ':'.join(fields)

f = open(shadow, 'w')
for line in lines:
f.write(line)
f.close()
with open(shadow, 'w') as f:
for line in lines:
f.write(line)

def boot(self):
if not self.module.check_mode:
Expand Down
10 changes: 3 additions & 7 deletions plugins/modules/sorcery.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,15 +460,11 @@ def match_depends(module):

if depends_new:
try:
try:
fl = open(sorcery_depends, 'a')

with open(sorcery_depends, 'a') as fl:
for k in depends_new:
fl.write("%s:%s:%s:optional::\n" % (spell, k, depends[k]))
except IOError:
module.fail_json(msg="I/O error on the depends file")
finally:
fl.close()
except IOError:
module.fail_json(msg="I/O error on the depends file")

depends_ok = False

Expand Down
37 changes: 15 additions & 22 deletions plugins/modules/timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,8 @@ def __init__(self, module):
self.conf_files['name'] = '/etc/sysconfig/clock'
self.conf_files['hwclock'] = '/etc/sysconfig/clock'
try:
f = open(self.conf_files['name'], 'r')
with open(self.conf_files['name'], 'r') as f:
sysconfig_clock = f.read()
except IOError as err:
if self._allow_ioerror(err, 'name'):
# If the config file doesn't exist detect the distribution and set regexps.
Expand All @@ -414,8 +415,6 @@ def __init__(self, module):
# The key for timezone might be `ZONE` or `TIMEZONE`
# (the former is used in RHEL/CentOS and the latter is used in SUSE linux).
# So check the content of /etc/sysconfig/clock and decide which key to use.
sysconfig_clock = f.read()
f.close()
if re.search(r'^TIMEZONE\s*=', sysconfig_clock, re.MULTILINE):
# For SUSE
self.regexps['name'] = self.dist_regexps['SuSE']
Expand Down Expand Up @@ -448,15 +447,13 @@ def _edit_file(self, filename, regexp, value, key):
"""
# Read the file
try:
file = open(filename, 'r')
with open(filename, 'r') as file:
lines = file.readlines()
except IOError as err:
if self._allow_ioerror(err, key):
lines = []
else:
self.abort('tried to configure %s using a file "%s", but could not read it' % (key, filename))
else:
lines = file.readlines()
file.close()
# Find the all matched lines
matched_indices = []
for i, line in enumerate(lines):
Expand All @@ -473,18 +470,17 @@ def _edit_file(self, filename, regexp, value, key):
lines.insert(insert_line, value)
# Write the changes
try:
file = open(filename, 'w')
with open(filename, 'w') as file:
file.writelines(lines)
except IOError:
self.abort('tried to configure %s using a file "%s", but could not write to it' % (key, filename))
else:
file.writelines(lines)
file.close()
self.msg.append('Added 1 line and deleted %s line(s) on %s' % (len(matched_indices), filename))

def _get_value_from_config(self, key, phase):
filename = self.conf_files[key]
try:
file = open(filename, mode='r')
with open(filename, mode='r') as file:
status = file.read()
except IOError as err:
if self._allow_ioerror(err, key):
if key == 'hwclock':
Expand All @@ -496,8 +492,6 @@ def _get_value_from_config(self, key, phase):
else:
self.abort('tried to configure %s using a file "%s", but could not read it' % (key, filename))
else:
status = file.read()
file.close()
try:
value = self.regexps[key].search(status).group(1)
except AttributeError:
Expand Down Expand Up @@ -628,11 +622,11 @@ def get(self, key, phase):
"""
if key == 'name':
try:
f = open('/etc/default/init', 'r')
for line in f:
m = re.match('^TZ=(.*)$', line.strip())
if m:
return m.groups()[0]
with open('/etc/default/init', 'r') as f:
for line in f:
m = re.match('^TZ=(.*)$', line.strip())
if m:
return m.groups()[0]
except Exception:
self.module.fail_json(msg='Failed to read /etc/default/init')
else:
Expand Down Expand Up @@ -811,9 +805,8 @@ def __init__(self, module):
def __get_timezone(self):
""" Return the current value of TZ= in /etc/environment """
try:
f = open('/etc/environment', 'r')
etcenvironment = f.read()
f.close()
with open('/etc/environment', 'r') as f:
etcenvironment = f.read()
except Exception:
self.module.fail_json(msg='Issue reading contents of /etc/environment')

Expand Down
10 changes: 4 additions & 6 deletions tests/unit/plugins/inventory/test_iocage.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,14 @@ def inventory():


def load_txt_data(path):
f = open(path, 'r')
s = f.read()
f.close()
with open(path, 'r') as f:
s = f.read()
return s


def load_yml_data(path):
f = open(path, 'r')
d = yaml.safe_load(f)
f.close()
with open(path, 'r') as f:
d = yaml.safe_load(f)
return d


Expand Down
11 changes: 5 additions & 6 deletions tests/unit/plugins/modules/test_wdc_redfish_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -896,15 +896,14 @@ def generate_temp_bundlefile(self,
bundle_tarfile = tarfile.open(os.path.join(self.tempdir, tar_name), "w")
package_filename = "oobm-{0}.pkg".format(mock_firmware_version)
package_filename_path = os.path.join(self.tempdir, package_filename)
package_file = open(package_filename_path, "w")
package_file.close()
with open(package_filename_path, "w"):
pass
bundle_tarfile.add(os.path.join(self.tempdir, package_filename), arcname=package_filename)
bin_filename = "firmware.bin"
bin_filename_path = os.path.join(self.tempdir, bin_filename)
bin_file = open(bin_filename_path, "wb")
byte_to_write = b'\x80' if is_multi_tenant else b'\xFF'
bin_file.write(byte_to_write * 12)
bin_file.close()
with open(bin_filename_path, "wb") as bin_file:
byte_to_write = b'\x80' if is_multi_tenant else b'\xFF'
bin_file.write(byte_to_write * 12)
for filename in [package_filename, bin_filename]:
bundle_tarfile.add(os.path.join(self.tempdir, filename), arcname=filename)
bundle_tarfile.close()
Expand Down

0 comments on commit e9b58cf

Please sign in to comment.