1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (c) 2022 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import json
17import os
18import subprocess
19import hashlib
20
21
22# Read json file data
23def read_json_file(input_file):
24    if not os.path.exists(input_file):
25        print("file '{}' doesn't exist.".format(input_file))
26        return None
27
28    data = None
29    try:
30        with open(input_file, 'r') as input_f:
31            data = json.load(input_f)
32    except json.decoder.JSONDecodeError:
33        print("The file '{}' format is incorrect.".format(input_file))
34        raise
35    except:  # noqa E722
36        print("read file '{}' failed.".format(input_file))
37        raise
38    return data
39
40
41# Read file by line
42def read_file(input_file):
43    if not os.path.exists(input_file):
44        print("file '{}' doesn't exist.".format(input_file))
45        return None
46
47    data = []
48    try:
49        with open(input_file, 'r') as file_obj:
50            for line in file_obj.readlines():
51                data.append(line.rstrip('\n'))
52    except:  # noqa E722
53        print("read file '{}' failed".format(input_file))
54        raise
55    return data
56
57
58# Write json file data
59def write_json_file(output_file, content, check_changes=False):
60    file_dir = os.path.dirname(os.path.abspath(output_file))
61    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
62    modes = stat.S_IWUSR | stat.S_IRUSR
63    if not os.path.exists(file_dir):
64        os.makedirs(file_dir, exist_ok=True)
65
66    if check_changes is True:
67        changed = __check_changes(output_file, content)
68    else:
69        changed = True
70    if changed is True:
71        with os.fdopen(os.open(output_file, flags, modes), 'w') as output_f:
72            json.dump(content, output_f, sort_keys=True, indent=2)
73
74
75def __check_changes(output_file, content):
76    if os.path.exists(output_file) and os.path.isfile(output_file):
77        # file content md5 val
78        sha256_obj = hashlib.sha256()
79        sha256_obj.update(str(read_json_file(output_file)).encode())
80        hash_value = sha256_obj.hexdigest()
81        # new content md5 val
82        sha256_obj_new = hashlib.sha256()
83        sha256_obj_new.update(str(content).encode())
84        hash_value_new = sha256_obj_new.hexdigest()
85        if hash_value_new == hash_value:
86            return False
87    return True
88
89
90# Write file data
91def write_file(output_file, content):
92    file_dir = os.path.dirname(os.path.abspath(output_file))
93    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
94    modes = stat.S_IWUSR | stat.S_IRUSR
95    if not os.path.exists(file_dir):
96        os.makedirs(file_dir, exist_ok=True)
97
98    with os.fdopen(os.open(output_file, flags, modes), 'w') as output_f:
99        output_f.write(content)
100    if output_file.endswith('.gni') or output_file.endswith('.gn'):
101        # Call gn format to make the output gn file prettier.
102        cmd = ['gn', 'format']
103        cmd.append(output_file)
104        subprocess.check_output(cmd)
105