1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2021 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
20import platform
21
22
23def find_top():
24    cur_dir = os.getcwd()
25    while cur_dir != "/":
26        build_config_file = os.path.join(
27            cur_dir, 'build/config/BUILDCONFIG.gn')
28        if os.path.exists(build_config_file):
29            return cur_dir
30        cur_dir = os.path.dirname(cur_dir)
31
32
33# Read json file data
34def read_json_file(input_file):
35    if not os.path.exists(input_file):
36        print("file '{}' doesn't exist.".format(input_file))
37        return None
38
39    data = None
40    try:
41        with open(input_file, 'r') as input_f:
42            data = json.load(input_f)
43    except json.decoder.JSONDecodeError:
44        print("The file '{}' format is incorrect.".format(input_file))
45        raise
46    except:  # noqa E722
47        print("read file '{}' failed.".format(input_file))
48        raise
49    return data
50
51
52# Read file by line
53def read_file(input_file):
54    if not os.path.exists(input_file):
55        print("file '{}' doesn't exist.".format(input_file))
56        return None
57
58    data = []
59    try:
60        with open(input_file, 'r') as file_obj:
61            for line in file_obj.readlines():
62                data.append(line.rstrip('\n'))
63    except:  # noqa E722
64        print("read file '{}' failed".format(input_file))
65        raise
66    return data
67
68
69# Write json file data
70def write_json_file(output_file, content, check_changes=False):
71    file_dir = os.path.dirname(os.path.abspath(output_file))
72    if not os.path.exists(file_dir):
73        os.makedirs(file_dir, exist_ok=True)
74
75    if check_changes is True:
76        changed = __check_changes(output_file, content)
77    else:
78        changed = True
79    if changed is True:
80        with open(output_file, 'w') as output_f:
81            json.dump(content, output_f, sort_keys=True, indent=2)
82
83
84def __check_changes(output_file, content):
85    if os.path.exists(output_file) and os.path.isfile(output_file):
86        # file content md5 val
87        sha256_obj = hashlib.sha256()
88        sha256_obj.update(str(read_json_file(output_file)).encode())
89        hash_value = sha256_obj.hexdigest()
90        # new content md5 val
91        sha256_obj_new = hashlib.sha256()
92        sha256_obj_new.update(str(content).encode())
93        hash_value_new = sha256_obj_new.hexdigest()
94        if hash_value_new == hash_value:
95            return False
96    return True
97
98
99# Write file data
100def write_file(output_file, content):
101    code_dir = find_top()
102    os_name = platform.system().lower()
103    gn_exe = os.path.join(code_dir, f'prebuilts/build-tools/{os_name}-x86/bin/gn')
104    file_dir = os.path.dirname(os.path.abspath(output_file))
105    if not os.path.exists(file_dir):
106        os.makedirs(file_dir, exist_ok=True)
107
108    with open(output_file, 'w') as output_f:
109        output_f.write(content)
110    if output_file.endswith('.gni') or output_file.endswith('.gn'):
111        # Call gn format to make the output gn file prettier.
112        cmd = [gn_exe, 'format']
113        cmd.append(output_file)
114        subprocess.check_output(cmd)
115