1# Copyright (c) 2020 Nordic Semiconductor ASA
2# SPDX-License-Identifier: Apache-2.0
3
4"""
5Helper functions used by gen_kconfig_rest.py and gen_devicetree_rest.py.
6"""
7
8import errno
9
10
11def write_if_updated(path, s):
12    """
13    Writes 's' as the contents of <out_dir>/<filename>, but only if it
14    differs from the current contents of the file. This avoids unnecessary
15    timestamp updates, which trigger documentation rebuilds.
16
17    Returns True if the file was updated, False otherwise.
18    """
19
20    try:
21        with open(path, encoding="utf-8") as f:
22            if s == f.read():
23                return False
24    except OSError as e:
25        if e.errno != errno.ENOENT:
26            raise
27
28    with open(path, "w", encoding="utf-8") as f:
29        f.write(s)
30    return True
31