Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_acme/io.py

raw
1 # Copyright (c) 2013, Romeo Theriault <romeot () hawaii.edu>
2 # Copyright (c) 2016 Michael Gruener <[email protected]>
3 # Copyright (c) 2021 Felix Fontein <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
8 # Do not use this from other collections or standalone plugins/modules!
9
10 from __future__ import annotations
11
12 import os
13 import shutil
14 import tempfile
15 import traceback
16 import typing as t
17
18 from ansible_collections.community.crypto.plugins.module_utils._acme.errors import (
19 ModuleFailException,
20 )
21
22 if t.TYPE_CHECKING:
23 from ansible.module_utils.basic import AnsibleModule # pragma: no cover
24
25
26 def read_file(fn: str | os.PathLike) -> bytes:
27 try:
28 with open(fn, "rb") as f:
29 return f.read()
30 except Exception as e:
31 raise ModuleFailException(f'Error while reading file "{fn}": {e}') from e
32
33
34 # This function was adapted from an earlier version of https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/uri.py
35 def write_file(
36 *, module: AnsibleModule, dest: str | os.PathLike[str], content: bytes
37 ) -> bool:
38 """
39 Write content to destination file dest, only if the content
40 has changed.
41 """
42 changed = False
43 # create a tempfile
44 fd, tmpsrc = tempfile.mkstemp(text=False)
45 f = os.fdopen(fd, "wb")
46 try:
47 f.write(content)
48 except Exception as err:
49 try:
50 f.close()
51 except Exception:
52 pass
53 os.remove(tmpsrc)
54 raise ModuleFailException(
55 f"failed to create temporary content file: {err}",
56 exception=traceback.format_exc(),
57 ) from err
58 f.close()
59 checksum_src = None
60 checksum_dest = None
61 # raise an error if there is no tmpsrc file
62 if not os.path.exists(tmpsrc):
63 try:
64 os.remove(tmpsrc)
65 except Exception:
66 pass
67 raise ModuleFailException(f"Source {tmpsrc} does not exist")
68 if not os.access(tmpsrc, os.R_OK):
69 os.remove(tmpsrc)
70 raise ModuleFailException(f"Source {tmpsrc} not readable")
71 checksum_src = module.sha1(tmpsrc)
72 # check if there is no dest file
73 if os.path.exists(dest):
74 # raise an error if copy has no permission on dest
75 if not os.access(dest, os.W_OK):
76 os.remove(tmpsrc)
77 raise ModuleFailException(f"Destination {dest} not writable")
78 if not os.access(dest, os.R_OK):
79 os.remove(tmpsrc)
80 raise ModuleFailException(f"Destination {dest} not readable")
81 checksum_dest = module.sha1(str(dest))
82 else:
83 dirname = os.path.dirname(dest) or "."
84 if not os.access(dirname, os.W_OK):
85 os.remove(tmpsrc)
86 raise ModuleFailException(f"Destination dir {dirname} not writable")
87 if checksum_src != checksum_dest:
88 try:
89 shutil.copyfile(tmpsrc, dest)
90 changed = True
91 except Exception as err:
92 os.remove(tmpsrc)
93 raise ModuleFailException(
94 f"failed to copy {tmpsrc} to {dest}: {err}",
95 exception=traceback.format_exc(),
96 ) from err
97 os.remove(tmpsrc)
98 return changed
99
100
101 __all__ = ("read_file", "write_file")