Debian Codegraph @

test/lib/ansible_test/_internal/io.py

raw
1 """Functions for disk IO."""
2
3 from __future__ import annotations
4
5 import io
6 import json
7 import os
8 import typing as t
9
10 from .encoding import (
11 ENCODING,
12 to_bytes,
13 to_text,
14 )
15
16
17 def read_json_file(path: str) -> t.Any:
18 """Parse and return the json content from the specified path."""
19 return json.loads(read_text_file(path))
20
21
22 def read_text_file(path: str) -> str:
23 """Return the contents of the specified path as text."""
24 return to_text(read_binary_file(path))
25
26
27 def read_binary_file(path: str) -> bytes:
28 """Return the contents of the specified path as bytes."""
29 with open_binary_file(path) as file_obj:
30 return file_obj.read()
31
32
33 def make_dirs(path: str) -> None:
34 """Create a directory at path, including any necessary parent directories."""
35 os.makedirs(to_bytes(path), exist_ok=True)
36
37
38 def write_json_file(
39 path: str,
40 content: t.Any,
41 create_directories: bool = False,
42 formatted: bool = True,
43 encoder: t.Optional[t.Type[json.JSONEncoder]] = None,
44 ) -> str:
45 """Write the given json content to the specified path, optionally creating missing directories."""
46 text_content = json.dumps(content,
47 sort_keys=formatted,
48 indent=4 if formatted else None,
49 separators=(', ', ': ') if formatted else (',', ':'),
50 cls=encoder,
51 ) + '\n'
52
53 write_text_file(path, text_content, create_directories=create_directories)
54
55 return text_content
56
57
58 def write_text_file(path: str, content: str, create_directories: bool = False) -> None:
59 """Write the given text content to the specified path, optionally creating missing directories."""
60 if create_directories:
61 make_dirs(os.path.dirname(path))
62
63 with open_binary_file(path, 'wb') as file_obj:
64 file_obj.write(to_bytes(content))
65
66
67 def open_text_file(path: str, mode: str = 'r') -> t.IO[str]:
68 """Open the given path for text access."""
69 if 'b' in mode:
70 raise Exception('mode cannot include "b" for text files: %s' % mode)
71
72 return io.open(to_bytes(path), mode, encoding=ENCODING) # pylint: disable=consider-using-with
73
74
75 def open_binary_file(path: str, mode: str = 'rb') -> t.IO[bytes]:
76 """Open the given path for binary access."""
77 if 'b' not in mode:
78 raise Exception('mode must include "b" for binary files: %s' % mode)
79
80 return io.open(to_bytes(path), mode) # pylint: disable=consider-using-with
81
82
83 class SortedSetEncoder(json.JSONEncoder):
84 """Encode sets as sorted lists."""
85
86 def default(self, o: t.Any) -> t.Any:
87 """Return a serialized version of the `o` object."""
88 if isinstance(o, set):
89 return sorted(o)
90
91 return json.JSONEncoder.default(self, o)