Debian Codegraph @

Tools/build/update_file.py

raw
1 """
2 A script that replaces an old file with a new one, only if the contents
3 actually changed. If not, the new file is simply deleted.
4
5 This avoids wholesale rebuilds when a code (re)generation phase does not
6 actually change the in-tree generated code.
7 """
8
9 from __future__ import annotations
10
11 import contextlib
12 import os
13 import os.path
14 import sys
15
16 TYPE_CHECKING = False
17 if TYPE_CHECKING:
18 import typing
19 from collections.abc import Iterator
20 from io import TextIOWrapper
21
22 _Outcome: typing.TypeAlias = typing.Literal['created', 'updated', 'same']
23
24
25 @contextlib.contextmanager
26 def updating_file_with_tmpfile(
27 filename: str,
28 tmpfile: str | None = None,
29 ) -> Iterator[tuple[TextIOWrapper, TextIOWrapper]]:
30 """A context manager for updating a file via a temp file.
31
32 The context manager provides two open files: the source file open
33 for reading, and the temp file, open for writing.
34
35 Upon exiting: both files are closed, and the source file is replaced
36 with the temp file.
37 """
38 # XXX Optionally use tempfile.TemporaryFile?
39 if not tmpfile:
40 tmpfile = filename + '.tmp'
41 elif os.path.isdir(tmpfile):
42 tmpfile = os.path.join(tmpfile, filename + '.tmp')
43
44 with open(filename, 'rb') as infile:
45 line = infile.readline()
46
47 if line.endswith(b'\r\n'):
48 newline = "\r\n"
49 elif line.endswith(b'\r'):
50 newline = "\r"
51 elif line.endswith(b'\n'):
52 newline = "\n"
53 else:
54 raise ValueError(f"unknown end of line: {filename}: {line!a}")
55
56 with open(tmpfile, 'w', newline=newline) as outfile:
57 with open(filename) as infile:
58 yield infile, outfile
59 update_file_with_tmpfile(filename, tmpfile)
60
61
62 def update_file_with_tmpfile(
63 filename: str,
64 tmpfile: str,
65 *,
66 create: bool = False,
67 ) -> _Outcome:
68 try:
69 targetfile = open(filename, 'rb')
70 except FileNotFoundError:
71 if not create:
72 raise # re-raise
73 outcome: _Outcome = 'created'
74 os.replace(tmpfile, filename)
75 else:
76 with targetfile:
77 old_contents = targetfile.read()
78 with open(tmpfile, 'rb') as f:
79 new_contents = f.read()
80 # Now compare!
81 if old_contents != new_contents:
82 outcome = 'updated'
83 os.replace(tmpfile, filename)
84 else:
85 outcome = 'same'
86 os.unlink(tmpfile)
87 return outcome
88
89
90 if __name__ == '__main__':
91 import argparse
92 parser = argparse.ArgumentParser()
93 parser.add_argument('--create', action='store_true')
94 parser.add_argument('--exitcode', action='store_true')
95 parser.add_argument('filename', help='path to be updated')
96 parser.add_argument('tmpfile', help='path with new contents')
97 args = parser.parse_args()
98 kwargs = vars(args)
99 setexitcode = kwargs.pop('exitcode')
100
101 outcome = update_file_with_tmpfile(**kwargs)
102 if setexitcode:
103 if outcome == 'same':
104 sys.exit(0)
105 elif outcome == 'updated':
106 sys.exit(1)
107 elif outcome == 'created':
108 sys.exit(2)
109 else:
110 raise NotImplementedError