diff --git a/tools/hdf_dev_eco_tool/command_line/driver_add/hdf_add_driver.py b/tools/hdf_dev_eco_tool/command_line/driver_add/hdf_add_driver.py new file mode 100644 index 00000000..6802153a --- /dev/null +++ b/tools/hdf_dev_eco_tool/command_line/driver_add/hdf_add_driver.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2022 Huawei Device Co., Ltd. +# +# HDF is dual licensed: you can use it either under the terms of +# the GPL, or the BSD license, at your option. +# See the LICENSE file in the root of this repository for complete details. + + +import os +import sys +from string import Template + +import hdf_utils +from hdf_tool_exception import HdfToolException +from .linux.kconfig_file_add_config import kconfig_file_operation +from .linux.mk_file_add_config import linux_makefile_operation + +from .liteos.gn_file_add_config import build_file_operation +from .liteos.mk_file_add_config import makefile_file_operation +from ..hdf_command_error_code import CommandErrorCode +from ..hdf_defconfig_patch import HdfDefconfigAndPatch +from ..hdf_device_info_hcs import HdfDeviceInfoHcsFile + + + +class HdfAddDriver(object): + def __init__(self, args): + super(HdfAddDriver, self).__init__() + self.module = args.module_name + self.board = args.board_name + self.driver = args.driver_name + self.kernel = args.kernel_name + self.vendor = args.vendor_name + self.root = args.root_dir + self.template_file_path = hdf_utils.get_template_file_path(self.root) + if not os.path.exists(self.template_file_path): + raise HdfToolException( + 'template file: %s not exist' % + self.template_file_path, CommandErrorCode.TARGET_NOT_EXIST) + + def add_linux(self, driver_file_path): + adapter_hdf = hdf_utils.get_vendor_hdf_dir_adapter( + self.root, self.kernel) + hdf_utils.judge_file_path_exists(adapter_hdf) + + adapter_model_path = os.path.join(adapter_hdf, 'model', self.module) + hdf_utils.judge_file_path_exists(adapter_model_path) + + liteos_file_name = ['Makefile', 'Kconfig'] + file_path = {} + for file_name in liteos_file_name: + if file_name == "Makefile": + build_file_path = os.path.join(adapter_model_path, file_name) + linux_makefile_operation(build_file_path, driver_file_path, + self.module, self.driver) + file_path['Makefile'] = build_file_path + + elif file_name == "Kconfig": + kconfig_path = os.path.join(adapter_model_path, file_name) + kconfig_file_operation(kconfig_path, self.module, + self.driver, self.template_file_path) + file_path['Kconfig'] = kconfig_path + + device_info = HdfDeviceInfoHcsFile( + self.root, self.vendor, self.module, self.board, self.driver, path="") + hcs_file_path = device_info.add_hcs_config_to_exists_model() + file_path["devices_info.hcs"] = hcs_file_path + + template_string = "CONFIG_DRIVERS_HDF_${module_upper}_${driver_upper}=y\n" + data_model = { + "module_upper": self.module.upper(), + "driver_upper": self.driver.upper() + } + + new_demo_config = Template(template_string).substitute(data_model) + defconfig_patch = HdfDefconfigAndPatch( + self.root, self.vendor, self.kernel, self.board, + data_model, new_demo_config) + + config_path = defconfig_patch.get_config_config() + files = [] + patch_list = defconfig_patch.add_module(config_path, + files=files, codetype=None) + config_path = defconfig_patch.get_config_patch() + files1 = [] + defconfig_list = defconfig_patch.add_module(config_path, + files=files1, codetype=None) + file_path[self.module + "_dot_configs"] = \ + list(set(patch_list + defconfig_list)) + return file_path + + def add_liteos(self, driver_file_path): + adapter_hdf = hdf_utils.get_vendor_hdf_dir_adapter( + self.root, self.kernel) + hdf_utils.judge_file_path_exists(adapter_hdf) + + adapter_model_path = os.path.join(adapter_hdf, 'model', self.module) + hdf_utils.judge_file_path_exists(adapter_model_path) + + liteos_file_name = ['BUILD.gn', 'Makefile', 'Kconfig'] + file_path = {} + for file_name in liteos_file_name: + if file_name == "BUILD.gn": + build_file_path = os.path.join(adapter_model_path, file_name) + build_file_operation(build_file_path, driver_file_path, + self.module, self.driver) + file_path['BUILD.gn'] = build_file_path + + elif file_name == "Makefile": + makefile_path = os.path.join(adapter_model_path, file_name) + makefile_file_operation(makefile_path, driver_file_path, + self.module, self.driver) + file_path['Makefile'] = makefile_path + + elif file_name == "Kconfig": + kconfig_path = os.path.join(adapter_model_path, file_name) + kconfig_file_operation(kconfig_path, self.module, + self.driver, self.template_file_path) + file_path['Kconfig'] = kconfig_path + + # Modify hcs file + device_info = HdfDeviceInfoHcsFile( + self.root, self.vendor, self.module, self.board, self.driver, path="") + hcs_file_path = device_info.add_hcs_config_to_exists_model() + file_path["devices_info.hcs"] = hcs_file_path + + dot_file_list = hdf_utils.get_dot_configs_path( + self.root, self.vendor, self.board) + template_string = "LOSCFG_DRIVERS_HDF_${module_upper}_${driver_upper}=y\n" + new_demo_config = Template(template_string).substitute( + {"module_upper": self.module.upper(), + "driver_upper": self.driver.upper()}) + + for dot_file in dot_file_list: + file_lines = hdf_utils.read_file_lines(dot_file) + file_lines[-1] = file_lines[-1].strip() + "\n" + if new_demo_config != file_lines[-1]: + file_lines.append(new_demo_config) + hdf_utils.write_file_lines(dot_file, file_lines) + file_path[self.module + "_dot_configs"] = dot_file_list + return file_path + + def driver_create_info_format(self, config_file_json, config_item, file_path): + kernel_type = config_file_json.get(self.kernel) + if kernel_type is None: + config_file_json[self.kernel] = { + config_item.get("module_name"): { + 'module_leve_config': {}, + "driver_file_list": { + config_item.get("driver_name"): config_item.get("driver_file_path") + } + } + } + config_file_json[self.kernel][self.module]["module_leve_config"].update(file_path) + else: + model_type = kernel_type.get(config_item.get("module_name")) + if model_type is None: + temp = config_file_json.get(self.kernel) + temp_module = config_item.get("module_name") + temp[temp_module] = { + 'module_leve_config': {}, + "driver_file_list": { + config_item.get("driver_name"): config_item.get("driver_file_path") + } + } + config_file_json.get(self.kernel).get(self.module).get("module_leve_config").update(file_path) + else: + temp = config_file_json.get(self.kernel).\ + get(config_item.get("module_name")).get("driver_file_list") + temp[config_item.get("driver_name")] = config_item.get("driver_file_path") + + return config_file_json + + def add_driver(self, *args_tuple): + root, vendor, module, driver, board, kernel = args_tuple + drv_converter = hdf_utils.WordsConverter(driver) + drv_src_dir = hdf_utils.get_drv_src_dir(root, module) + new_mkdir_path = os.path.join(drv_src_dir, driver) + if not os.path.exists(new_mkdir_path): + os.mkdir(new_mkdir_path) + data_model = { + 'driver_lower_case': drv_converter.lower_case(), + 'driver_upper_camel_case': drv_converter.upper_camel_case(), + 'driver_lower_camel_case': drv_converter.lower_camel_case(), + 'driver_upper_case': drv_converter.upper_case() + } + result_path = os.path.join(new_mkdir_path, '%s_driver.c' % driver) + if os.path.exists(result_path): + return True, result_path + self._file_gen_lite('hdf_driver.c.template', result_path, data_model) + result_path = os.path.join(new_mkdir_path, '%s_driver.c' % driver) + return True, result_path + + def _file_gen_lite(self, template, source_file_path, model): + templates_dir = hdf_utils.get_templates_lite_dir() + template_path = os.path.join(templates_dir, template) + self._source_template_fill(template_path, source_file_path, model) + + def _source_template_fill(self, template_path, output_path, data_model): + if not os.path.exists(template_path): + return + raw_content = hdf_utils.read_file(template_path) + contents = Template(raw_content).safe_substitute(data_model) + hdf_utils.write_file(output_path, contents) diff --git a/tools/hdf_dev_eco_tool/command_line/driver_add/linux/kconfig_file_add_config.py b/tools/hdf_dev_eco_tool/command_line/driver_add/linux/kconfig_file_add_config.py new file mode 100644 index 00000000..8f8e00d8 --- /dev/null +++ b/tools/hdf_dev_eco_tool/command_line/driver_add/linux/kconfig_file_add_config.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (c) 2022 Huawei Device Co., Ltd. +# +# HDF is dual licensed: you can use it either under the terms of +# the GPL, or the BSD license, at your option. +# See the LICENSE file in the root of this repository for complete details. + + +import os +from string import Template + +import hdf_utils +from .mk_file_add_config import judge_driver_config_exists + + +def get_template_info(template_path): + template_path = os.path.join(template_path, + 'driver_add_kconfig_config.template') + return hdf_utils.read_file(template_path) + + +def kconfig_file_operation(path, module, driver, template_path): + config_add_config = get_template_info(template_path) + kconfig_gn_path = path + date_lines = hdf_utils.read_file_lines(kconfig_gn_path) + judge_result = judge_driver_config_exists(date_lines, driver_name=driver) + if judge_result: + return + temp_handle = Template(config_add_config) + data = { + "model_name_upper": module.upper(), + "model_name_lower": module.lower(), + "driver_name_upper": driver.upper(), + "driver_name_lower": driver.lower() + } + new_line = temp_handle.substitute(data) + + date_lines = date_lines + [new_line] + hdf_utils.write_file_lines(kconfig_gn_path, date_lines) \ No newline at end of file diff --git a/tools/hdf_dev_eco_tool/command_line/driver_add/linux/mk_file_add_config.py b/tools/hdf_dev_eco_tool/command_line/driver_add/linux/mk_file_add_config.py index 592db9d8..4a62a2b2 100644 --- a/tools/hdf_dev_eco_tool/command_line/driver_add/linux/mk_file_add_config.py +++ b/tools/hdf_dev_eco_tool/command_line/driver_add/linux/mk_file_add_config.py @@ -7,51 +7,64 @@ # the GPL, or the BSD license, at your option. # See the LICENSE file in the root of this repository for complete details. -import re + from string import Template import hdf_utils -def replace_func(info_str): - replace_dict = {'(': "{", ')': "}"} - for key, values in replace_dict.items(): - info_str = info_str.replace(key, values) - return info_str +def find_makefile_file_end_index(date_lines, model_name): + file_end_flag = "ccflags-y" + end_index = 0 + # INPUT_ROOT_DIR info + model_dir_name = ("%s_ROOT_DIR" % model_name.upper()) + model_dir_value = "" - -def linux_makefile_operation(path, driver_file_path): - lines = hdf_utils.read_file_lines(path) - - makefile_info = {} - - for index, line in enumerate(lines): - if line.find('.o') != -1: - info_value = ('/'.join(line.split("=")[-1].split('/')[:-1])).strip() - - if info_value not in list(makefile_info.values()): - makefile_info[index] = info_value - - file_path = '/'.join(driver_file_path.split('\\')) - - for key, info in makefile_info.items(): - model_name = re.search(r"[A-Z_]+", info).group() - for line in lines: - if re.search(model_name, line): - temp = Template(replace_func(info)) - temp_path = temp.safe_substitute({model_name: line.strip().split('=')[-1].strip()}) - lines_insert(file_path, temp_path, lines, key) - break - hdf_utils.write_file_lines(path, lines) - - -def lines_insert(file_path, temp_path, lines, key): - insert_temp = "" - if file_path.find(temp_path.split('model')[-1]) != -1 and insert_temp == "": - insert_temp = lines[key] - if insert_temp.strip().endswith("\\"): - lines.insert(key + 1, re.sub(r"[a-zA-Z0-9_]+\.o", file_path.split('/')[-1].replace('.c', '.o'), - insert_temp)) + for index, line in enumerate(date_lines): + if line.startswith("#"): + continue + elif line.strip().startswith(file_end_flag): + end_index = index + break + elif line.strip().startswith(model_dir_name): + model_dir_value = line.split("=")[-1].strip() else: - test = (file_path.split('/')[-1] + r" \\") - lines.insert(key, re.sub(r"[a-zA-Z0-9_]+\.o", test.replace('.c', '.o'), insert_temp)) \ No newline at end of file + continue + result_tuple = (end_index, model_dir_name, model_dir_value) + return result_tuple + + +def linux_makefile_operation(path, driver_file_path, module, driver): + makefile_gn_path = path + date_lines = hdf_utils.read_file_lines(makefile_gn_path) + source_file_path = driver_file_path.replace('\\', '/') + result_tuple = find_makefile_file_end_index(date_lines, model_name=module) + judge_result = judge_driver_config_exists(date_lines, driver_name=driver) + if judge_result: + return + end_index, model_dir_name, model_dir_value = result_tuple + + first_line = "\nobj-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\ \n" + second_line = " $(${model_name_upper}_ROOT_DIR) /${source_file_path}\n" + makefile_add_template = first_line + second_line + include_model_info = model_dir_value.split("model")[-1].strip('"')+"/" + makefile_path_config = source_file_path.split(include_model_info) + temp_handle = Template(makefile_add_template.replace("$(", "temp_flag")) + d = { + 'model_name_upper': module.upper(), + 'driver_name_upper': driver.upper(), + 'source_file_path': makefile_path_config[-1].replace(".c", ".o") + } + new_line = temp_handle.substitute(d).replace("temp_flag", "$(") + + date_lines = date_lines[:end_index-1] + [new_line] + date_lines[end_index-1:] + hdf_utils.write_file_lines(makefile_gn_path, date_lines) + + +def judge_driver_config_exists(date_lines, driver_name): + for _, line in enumerate(date_lines): + if line.startswith("#"): + continue + elif line.find(driver_name) != -1: + return True + return False \ No newline at end of file diff --git a/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/gn_file_add_config.py b/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/gn_file_add_config.py index 45f0ad1c..8fef9dbf 100644 --- a/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/gn_file_add_config.py +++ b/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/gn_file_add_config.py @@ -7,62 +7,67 @@ # the GPL, or the BSD license, at your option. # See the LICENSE file in the root of this repository for complete details. -import ast -import re -import json + from string import Template import hdf_utils -def build_file_operation(path, driver_file_path): - lines = hdf_utils.read_file_lines(path) - test_dict = {} - status = False - line_temp = '' - for index, line in enumerate(lines): +def find_build_file_end_index(date_lines, model_name): + state = False + end_index = 0 + frameworks_model_name = "FRAMEWORKS_%s_ROOT" % (model_name.upper()) + frameworks_model_value = '' + for index, line in enumerate(date_lines): if line.startswith("#"): - pass - elif line.strip().startswith("sources"): - if line.split('=')[-1].find(']') != -1 and line.find("+=") == -1: - test_dict[index] = line + continue + elif line.find("hdf_driver") != -1: + state = True + continue + elif line.startswith("}") and state: + end_index = index + state = False + elif line.strip().startswith(frameworks_model_name): + frameworks_model_value = line.split("=")[-1].strip() else: - if line.strip().startswith('FRAMEWORKS'): - test_dict[line.split('=')[0].strip()] = ast.literal_eval(line.split('=')[-1].strip()) - elif line.find('$FRAMEWORKS') != -1 and \ - line.find('.c') != -1 and \ - status is False: - if line.strip()[1:-2].startswith('$FRAMEWORKS'): - line_temp = '/'.join((line.strip()[1:-2]).split('/')[:-1]) - test_dict[index] = line_temp - status = True - elif line.find('$FRAMEWORKS') == -1: - line_temp = '' - status = False - elif line.find('$FRAMEWORKS') != -1 and \ - line.find('.c') != -1 and line_temp: - if line.find(line_temp) == -1: - line_temp = '/'.join((line.strip()[1:-2]).split('/')[:-1]) - test_dict[index] = line_temp + continue + result_tuple = (end_index, frameworks_model_name, frameworks_model_value) + return result_tuple - file_path = '/'.join(driver_file_path.split('\\')) - for i in test_dict.keys(): - if isinstance(i, str): - pass - elif isinstance(i, int): - str1 = Template(test_dict.get(i)) - source_file_path = str1.safe_substitute(test_dict) - if file_path.find("/".join(source_file_path.split("/")[1:])) != -1: - lines.insert(i + 1, re.sub(r'[a-zA-Z_0-9]+\.c', file_path.split('/')[-1], lines[i])) - elif source_file_path.strip().startswith("sources"): - temp_append_path = re.sub(r'[a-zA-Z_0-9]+\.c', file_path.split('/')[-1], - ast.literal_eval(lines[i].split('=')[-1])[0]) - source_list = ast.literal_eval(lines[i].split('=')[-1]) - source_list.append(temp_append_path) - result_str = json.dumps(source_list, indent=4) - temp_13 = (lines[i].split('=')[0] + "= " + result_str) - temp_13 = temp_13.replace("]", " ]") - lines[i] = temp_13 +def build_file_operation(path, driver_file_path, module, driver): - hdf_utils.write_file_lines(path, lines) + build_gn_path = path + date_lines = hdf_utils.read_file_lines(build_gn_path) + source_file_path = driver_file_path.replace('\\', '/') + result_tuple = find_build_file_end_index(date_lines, model_name=module) + judge_result = judge_driver_config_exists(date_lines, driver_name=driver) + if judge_result: + return + end_index, frameworks_name, frameworks_value = result_tuple + + first_line = "\n if (defined(LOSCFG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper})) {\n" + second_line = ' sources += [ "$FRAMEWORKS_${model_name_upper}_ROOT/${source_file_path}" ]\n' + third_line = " }\n" + build_add_template = first_line + second_line + third_line + include_model_info = frameworks_value.split("model")[-1].strip('"')+"/" + build_gn_path_config = source_file_path.split(include_model_info) + temp_handle = Template(build_add_template.replace("$FRAMEWORKS", "FRAMEWORKS")) + d = { + 'model_name_upper': module.upper(), + 'driver_name_upper': driver.upper(), + 'source_file_path': build_gn_path_config[-1] + } + new_line = temp_handle.substitute(d).replace("FRAMEWORKS", "$FRAMEWORKS") + + date_lines = date_lines[:end_index] + [new_line] + date_lines[end_index:] + hdf_utils.write_file_lines(build_gn_path, date_lines) + + +def judge_driver_config_exists(date_lines, driver_name): + for _, line in enumerate(date_lines): + if line.startswith("#"): + continue + elif line.find(driver_name) != -1: + return True + return False diff --git a/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/mk_file_add_config.py b/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/mk_file_add_config.py index 23a4143b..83660f30 100644 --- a/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/mk_file_add_config.py +++ b/tools/hdf_dev_eco_tool/command_line/driver_add/liteos/mk_file_add_config.py @@ -7,58 +7,56 @@ # the GPL, or the BSD license, at your option. # See the LICENSE file in the root of this repository for complete details. -import re + from string import Template import hdf_utils - -def replace_func(info_str): - replace_dict = {'(': "{", ')': "}"} - for key, values in replace_dict.items(): - info_str = info_str.replace(key, values) - return info_str +from .gn_file_add_config import judge_driver_config_exists -def makefile_operation(mk_path, driver_file_path): - lines = hdf_utils.read_file_lines(mk_path) - makefile_info = {} +def find_makefile_file_end_index(date_lines, model_name): + file_end_flag = "include $(HDF_DRIVER)" + end_index = 0 + model_dir_name = ("%s_ROOT_DIR" % model_name.upper()) + model_dir_value = "" - status = False - for index, line in enumerate(lines): - if line.find('LOCAL_SRCS') != -1 and status == False: - status = True - if line.find("endif") != -1: - status = False - elif status: - info_value = ('/'.join(line.split("=")[-1].split('/')[:-1])).strip() - if info_value not in list(makefile_info.values()): - makefile_info[index] = info_value - - file_path = '/'.join(driver_file_path.split('\\')) - for key, info in makefile_info.items(): - if re.search(r"[A-Z_]+", info) is not None: - model_name = re.search(r"[A-Z_]+", info).group() - for line in lines: - if re.search(model_name, line): - temp = {model_name: line.strip().split('=')[-1].strip()} - temp_path = Template(replace_func(info)).safe_substitute(temp) - lines_insert(file_path, temp_path, lines, key) - - hdf_utils.write_file_lines(mk_path, lines) - - -def lines_insert(file_path, temp_path, lines, key): - insert_temp = "" - if file_path.find(temp_path.split('model')[-1]) != -1 and insert_temp == "": - insert_temp = lines[key] - if insert_temp.strip().endswith("\\"): - replace_temp = re.sub(r"[a-zA-Z0-9_]+\.c", file_path.split('/')[-1], insert_temp) - if replace_temp.startswith("LOCAL_SRCS"): - insert_temp = ((len(replace_temp.split("=")[0]) + 1) * " ") + replace_temp.split("=")[-1] - lines.insert(key + 1, insert_temp) - else: - lines.insert(key + 1, replace_temp) + for index, line in enumerate(date_lines): + if line.startswith("#"): + continue + elif line.strip().startswith(file_end_flag): + end_index = index + elif line.strip().startswith(model_dir_name): + model_dir_value = line.split("=")[-1].strip() else: - test = (file_path.split('/')[-1] + r" \\") - lines.insert(key, re.sub(r"[a-zA-Z0-9_]+.c$", test, insert_temp)) \ No newline at end of file + continue + result_tuple = (end_index, model_dir_name, model_dir_value) + return result_tuple + + +def makefile_file_operation(path, driver_file_path, module, driver): + makefile_gn_path = path + date_lines = hdf_utils.read_file_lines(makefile_gn_path) + judge_result = judge_driver_config_exists(date_lines, driver_name=driver) + if judge_result: + return + source_file_path = driver_file_path.replace('\\', '/') + result_tuple = find_makefile_file_end_index(date_lines, model_name=module) + end_index, model_dir_name, model_dir_value = result_tuple + + first_line = "\nifeq ($(LOSCFG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}), y)\n" + second_line = "LOCAL_SRCS += $(${model_name_upper}_ROOT_DIR)/${source_file_path}\n" + third_line = "endif\n" + makefile_add_template = first_line + second_line + third_line + include_model_info = model_dir_value.split("model")[-1].strip('"')+"/" + makefile_path_config = source_file_path.split(include_model_info) + temp_handle = Template(makefile_add_template.replace("$(", "temp_flag")) + d = { + 'model_name_upper': module.upper(), + 'driver_name_upper': driver.upper(), + 'source_file_path': makefile_path_config[-1] + } + new_line = temp_handle.substitute(d).replace("temp_flag", "$(") + + date_lines = date_lines[:end_index-1] + [new_line] + date_lines[end_index-1:] + hdf_utils.write_file_lines(makefile_gn_path, date_lines) diff --git a/tools/hdf_dev_eco_tool/command_line/hdf_add_handler.py b/tools/hdf_dev_eco_tool/command_line/hdf_add_handler.py index fd61920e..32d2feb1 100644 --- a/tools/hdf_dev_eco_tool/command_line/hdf_add_handler.py +++ b/tools/hdf_dev_eco_tool/command_line/hdf_add_handler.py @@ -6,15 +6,16 @@ # HDF is dual licensed: you can use it either under the terms of # the GPL, or the BSD license, at your option. # See the LICENSE file in the root of this repository for complete details. + + import copy import os import json -import platform from string import Template - import hdf_utils from hdf_tool_settings import HdfToolSettings from hdf_tool_exception import HdfToolException +from .driver_add.hdf_add_driver import HdfAddDriver from .hdf_command_handler_base import HdfCommandHandlerBase from .hdf_command_error_code import CommandErrorCode from .hdf_device_info_hcs import HdfDeviceInfoHcsFile @@ -25,10 +26,6 @@ from .hdf_driver_config_file import HdfDriverConfigFile from .hdf_vendor_makefile import HdfVendorMakeFile from .hdf_defconfig_patch import HdfDefconfigAndPatch -from .driver_add.linux.mk_file_add_config import linux_makefile_operation -from .driver_add.liteos.gn_file_add_config import build_file_operation -from .driver_add.liteos.mk_file_add_config import makefile_operation - class HdfAddHandler(HdfCommandHandlerBase): def __init__(self, args): @@ -115,7 +112,7 @@ class HdfAddHandler(HdfCommandHandlerBase): os.makedirs(framework_drv_root_dir) # create .c template driver file - + state, driver_file_path = self._add_driver(*args_tuple) if not state: raise HdfToolException( @@ -175,29 +172,21 @@ class HdfAddHandler(HdfCommandHandlerBase): 'driver_file_path': driver_file_path, 'module_level_config_path': model_level_config_file_path } + config_name = "create_model.config" config_file = hdf_utils.read_file( - os.path.join('resources', 'create_model.config')) + os.path.join('resources', config_name)) config_file_json = json.loads(config_file) config_file_json[module] = config_file_out - if platform.system() == "Windows": - config_file_replace = json.dumps(config_file_json, indent=4).\ - replace(root.replace('\\', '\\\\') + '\\\\', "") - hdf_utils.write_file( - os.path.join('resources', 'create_model.config'), - config_file_replace.replace('\\\\', '/')) - if platform.system() == "Linux": - config_file_replace = json.dumps(config_file_json, indent=4).\ - replace(root + '/', "") - hdf_utils.write_file( - os.path.join('resources', 'create_model.config'), - config_file_replace) + hdf_utils.write_config(root_path=root, config_file_json=config_file_json, + config_name=config_name) + return json.dumps(config_item) else: raise HdfToolException( 'supported boards name : %s not exits ' % board) def _add_module_handler_liteos(self, framework_hdf, adapter_model_path, - data_model, converter, *args_tuple): + data_model, converter, *args_tuple): root, vendor, module, driver, board, kernel = args_tuple liteos_file_path = {} liteos_level_config_file_path = {} @@ -207,7 +196,7 @@ class HdfAddHandler(HdfCommandHandlerBase): "resources", "templates", "lite"]) for file_name in liteos_file_name: for i in hdf_utils.template_filename_filtrate( - template_path, kernel): + template_path, kernel): if i.find(file_name.split(".")[0]) > 0: out_path = os.path.join(adapter_model_path, file_name) self._render(os.path.join(template_path, i), @@ -217,7 +206,7 @@ class HdfAddHandler(HdfCommandHandlerBase): # Modify Kconfig file vendor_k = HdfVendorKconfigFile(root, vendor, kernel, path="") vendor_k_path = vendor_k.add_module([module, 'Kconfig']) - liteos_level_config_file_path[module+"_Kconfig"] = vendor_k_path + liteos_level_config_file_path[module + "_Kconfig"] = vendor_k_path # Modify hdf_lite.mk file vendor_mk = HdfVendorMkFile(root, vendor) @@ -338,15 +327,16 @@ class HdfAddHandler(HdfCommandHandlerBase): template_path = "/".join([framework_hdf] + ["tools", "hdf_dev_eco_tool", "resources", "templates", "lite"]) - if platform.system() == "Windows": - driver_file_name = "//" + driver_file_path.strip(root).replace("\\", "/"), - elif platform.system() == "Linux": - driver_file_name = "//" + driver_file_path.strip(root).replace("\\", "/") + "c", + + user_file_path = driver_file_path.split(root)[-1].replace("\\", "/") + if user_file_path.startswith("/"): + driver_file_name = "/" + user_file_path.replace("\\", "/") else: - driver_file_name = "//" + driver_file_path.strip(root).replace("\\", "/"), + driver_file_name = "//" + user_file_path.replace("\\", "/") + data_model = { "model_path": "//drivers/adapter/uhdf2/" + module, - "driver_file_name": driver_file_name[0], + "driver_file_name": driver_file_name, "model_name": module, } for file_name in os.listdir(template_path): @@ -412,28 +402,26 @@ class HdfAddHandler(HdfCommandHandlerBase): common_dir_list = dir_dict.get("common") if common_dir_list is not None: if "src" in common_dir_list: - driver_file_path = os.path.join(drv_src_dir, "common", - "src", '%s_driver.c' % driver) + driver_file_path = os.path.join(drv_src_dir, "common", "src") else: - driver_file_path = os.path.join(drv_src_dir, "common", - '%s_driver.c' % driver) + driver_file_path = os.path.join(drv_src_dir, "common") else: - driver_file_path = os.path.join(drv_src_dir, '%s_driver.c' % driver) + driver_file_path = drv_src_dir - if os.path.exists(driver_file_path): + if not os.path.exists(driver_file_path): raise HdfToolException( - 'driver "%s" already exist' % - driver, CommandErrorCode.TARGET_ALREADY_EXIST) + '"%s" is path not exist' % + driver_file_path, CommandErrorCode.TARGET_NOT_EXIST) data_model = { 'driver_lower_case': drv_converter.lower_case(), 'driver_upper_camel_case': drv_converter.upper_camel_case(), 'driver_lower_camel_case': drv_converter.lower_camel_case(), 'driver_upper_case': drv_converter.upper_case() } - self._file_gen_lite('hdf_driver.c.template', drv_src_dir, + self._file_gen_lite('hdf_driver.c.template', driver_file_path, '%s_driver.c' % driver, data_model) - - return True, driver_file_path + result_path = os.path.join(driver_file_path, '%s_driver.c' % driver) + return True, result_path def _add_driver_handler(self): self.check_arg_raise_if_not_exist("vendor_name") @@ -454,41 +442,13 @@ class HdfAddHandler(HdfCommandHandlerBase): root, module) hdf_utils.judge_file_path_exists(framework_drv_root_dir) - state, driver_file_path = self._add_driver(*args_tuple) + add_driver = HdfAddDriver(args=self.args) + state, driver_file_path = add_driver.add_driver(*args_tuple) + if board == "hispark_taurus": - adapter_hdf = hdf_utils.get_vendor_hdf_dir_adapter(root, kernel) - hdf_utils.judge_file_path_exists(adapter_hdf) - - adapter_model_path = os.path.join(adapter_hdf, 'model', module) - hdf_utils.judge_file_path_exists(adapter_model_path) - - liteos_file_name = ['BUILD.gn', 'Makefile'] - file_path = {} - for file_name in liteos_file_name: - if file_name == "BUILD.gn": - build_file_path = os.path.join(adapter_model_path, file_name) - build_file_operation(build_file_path, driver_file_path) - file_path['BUILD.gn'] = build_file_path - - elif file_name == "Makefile": - makefile_path = os.path.join(adapter_model_path, file_name) - makefile_operation(makefile_path, driver_file_path) - file_path['Makefile'] = makefile_path - + file_path = add_driver.add_liteos(driver_file_path) elif board.endswith("linux"): - adapter_hdf = hdf_utils.get_vendor_hdf_dir_adapter(root, kernel) - hdf_utils.judge_file_path_exists(adapter_hdf) - - adapter_model_path = os.path.join(adapter_hdf, 'model', module) - hdf_utils.judge_file_path_exists(adapter_model_path) - - liteos_file_name = ['Makefile'] - file_path = {} - for file_name in liteos_file_name: - if file_name == "Makefile": - build_file_path = os.path.join(adapter_model_path, file_name) - linux_makefile_operation(build_file_path, driver_file_path) - file_path['Makefile'] = build_file_path + file_path = add_driver.add_linux(driver_file_path) else: file_path = [] @@ -499,51 +459,15 @@ class HdfAddHandler(HdfCommandHandlerBase): 'driver_file_path': driver_file_path, 'enabled': True } - + config_name = "create_driver.config" config_file = hdf_utils.read_file( - os.path.join("resources", "create_driver.config")) + os.path.join("resources", config_name)) config_file_json = json.loads(config_file) - - kernel_type = config_file_json.get(kernel) - if kernel_type is None: - config_file_json[kernel] = { - config_item.get("module_name"): { - 'module_leve_config': {}, - "driver_file_list": { - config_item.get("driver_name"): config_item.get("driver_file_path") - } - } - } - config_file_json[kernel][module]["module_leve_config"].update(file_path) - else: - model_type = kernel_type.get(config_item.get("module_name")) - if model_type is None: - temp = config_file_json.get(kernel) - temp_module = config_item.get("module_name") - temp[temp_module] = { - 'module_leve_config': {}, - "driver_file_list": { - config_item.get("driver_name"): config_item.get("driver_file_path") - } - } - config_file_json.get(kernel).get(module).get("module_leve_config").update(file_path) - else: - temp = config_file_json.get(kernel).\ - get(config_item.get("module_name")).get("driver_file_list") - temp[config_item.get("driver_name")] = config_item.get("driver_file_path") - - if platform.system() == "Windows": - config_file_replace = json.dumps(config_file_json, indent=4). \ - replace(root.replace('\\', '\\\\') + '\\\\', "") - hdf_utils.write_file( - os.path.join('resources', 'create_driver.config'), - config_file_replace.replace('\\\\', '/')) - if platform.system() == "Linux": - config_file_replace = json.dumps(config_file_json, indent=4). \ - replace(root + '/', "") - hdf_utils.write_file( - os.path.join('resources', 'create_driver.config'), - config_file_replace) + result_config_file_json = add_driver.driver_create_info_format( + config_file_json, config_item, file_path) + hdf_utils.write_config(root_path=root, + config_file_json=result_config_file_json, + config_name=config_name) return config_item def _add_config_handler(self): diff --git a/tools/hdf_dev_eco_tool/command_line/hdf_defconfig_patch.py b/tools/hdf_dev_eco_tool/command_line/hdf_defconfig_patch.py index 75df3e55..ad660c96 100644 --- a/tools/hdf_dev_eco_tool/command_line/hdf_defconfig_patch.py +++ b/tools/hdf_dev_eco_tool/command_line/hdf_defconfig_patch.py @@ -66,45 +66,49 @@ class HdfDefconfigAndPatch(object): path.split("/")[-1] in self.drivers_path_list: files.append(path) if codetype is None: - with open(path, "rb") as fread: - data = fread.readlines() - insert_index = None - state = False - for index, line in enumerate(data): - if line.find("CONFIG_DRIVERS_HDF_INPUT=y".encode('utf-8')) >= 0: - insert_index = index - elif line.find(self.new_demo_config.encode('utf-8')) >= 0: - files.remove(path) - state = True - if not state: - if path.split(".")[-1] != "patch": - data.insert(insert_index + 1, - self.new_demo_config.encode('utf-8')) - else: - data.insert(insert_index + 1, - ("+" + self.new_demo_config).encode('utf-8')) - - with open(path, "wb") as fwrite: - fwrite.writelines(data) + self.binary_type_write(path) else: - with open(path, "r+", encoding=codetype) as fread: - data = fread.readlines() - insert_index = None - state = False - for index, line in enumerate(data): - if line.find("CONFIG_DRIVERS_HDF_INPUT=y") >= 0: - insert_index = index - elif line.find(self.new_demo_config) >= 0: - files.remove(path) - state = True - if not state: - if path.split(".")[-1] != "patch": - data.insert(insert_index + 1, - self.new_demo_config) - else: - data.insert(insert_index + 1, - "+" + self.new_demo_config) - - with open(path, "w", encoding=codetype) as fwrite: - fwrite.writelines(data) + self.utf_type_write(path, codetype) return files + + def binary_type_write(self, path): + with open(path, "rb") as fread: + data = fread.readlines() + insert_index = None + state = False + for index, line in enumerate(data): + if line.find("CONFIG_DRIVERS_HDF_INPUT=y".encode('utf-8')) >= 0: + insert_index = index + elif line.find(self.new_demo_config.encode('utf-8')) >= 0: + state = True + if not state: + if path.split(".")[-1] != "patch": + data.insert(insert_index + 1, + self.new_demo_config.encode('utf-8')) + else: + data.insert(insert_index + 1, + ("+" + self.new_demo_config).encode('utf-8')) + + with open(path, "wb") as fwrite: + fwrite.writelines(data) + + def utf_type_write(self, path, codetype): + with open(path, "r+", encoding=codetype) as fread: + data = fread.readlines() + insert_index = None + state = False + for index, line in enumerate(data): + if line.find("CONFIG_DRIVERS_HDF_INPUT=y") >= 0: + insert_index = index + elif line.find(self.new_demo_config) >= 0: + state = True + if not state: + if path.split(".")[-1] != "patch": + data.insert(insert_index + 1, + self.new_demo_config) + else: + data.insert(insert_index + 1, + "+" + self.new_demo_config) + + with open(path, "w", encoding=codetype) as fwrite: + fwrite.writelines(data) \ No newline at end of file diff --git a/tools/hdf_dev_eco_tool/command_line/hdf_device_info_hcs.py b/tools/hdf_dev_eco_tool/command_line/hdf_device_info_hcs.py index a1516bf2..4d0024ce 100644 --- a/tools/hdf_dev_eco_tool/command_line/hdf_device_info_hcs.py +++ b/tools/hdf_dev_eco_tool/command_line/hdf_device_info_hcs.py @@ -41,10 +41,17 @@ class HdfDeviceInfoHcsFile(object): raise HdfToolException( 'hcs file: %s not exist' % self.hcspath, CommandErrorCode.TARGET_NOT_EXIST) + self.data = { + "driver_name": self.driver, + "model_name": self.module, + } def _save(self): if self.lines: - hdf_utils.write_file(self.hcspath, ''.join(self.lines)) + codetype = "utf-8" + with open(self.hcspath, "w+", encoding=codetype) as lwrite: + for line in self.lines: + lwrite.write(line) def _find_line(self, pattern): for index, line in enumerate(self.lines): @@ -118,17 +125,13 @@ class HdfDeviceInfoHcsFile(object): hdf_utils.read_file_lines(template_path))) old_lines = list(filter(lambda x: x != "\n", hdf_utils.read_file_lines(self.hcspath))) + new_data = old_lines[:-2] + lines + old_lines[-2:] - data = { - "driver_name": self.driver, - "model_name": self.module, - } for index, _ in enumerate(new_data): - new_data[index] = Template(new_data[index]).substitute(data) - codetype = "utf-8" - with open(self.hcspath, "w+", encoding=codetype) as lwrite: - for j in new_data: - lwrite.write(j) + new_data[index] = Template(new_data[index]).substitute(self.data) + + self.lines = new_data + self._save() return self.hcspath def add_model_hcs_file_config_user(self): @@ -139,15 +142,59 @@ class HdfDeviceInfoHcsFile(object): lines[-1] = "\t\t"+lines[-1].strip()+"\n" old_lines = list(filter(lambda x: x != "\n", hdf_utils.read_file_lines(self.hcspath))) + new_data = old_lines[:-2] + lines + old_lines[-2:] - data = { - "driver_name": self.driver, - "model_name": self.module, - } for index, _ in enumerate(new_data): - new_data[index] = Template(new_data[index]).substitute(data) - codetype = "utf-8" - with open(self.hcspath, "w+", encoding=codetype) as lwrite: - for j in new_data: - lwrite.write(j) + new_data[index] = Template(new_data[index]).substitute(self.data) + + self.lines = new_data + self._save() return self.hcspath + + def add_hcs_config_to_exists_model(self): + template_path = os.path.join(self.file_path, + 'exists_model_hcs_info.template') + lines = list(map(lambda x: "\t\t\t" + x, + hdf_utils.read_file_lines(template_path))) + old_lines = list(filter(lambda x: x != "\n", + hdf_utils.read_file_lines(self.hcspath))) + + end_index, start_index = self._get_model_index(old_lines) + model_hcs_lines = old_lines[start_index:end_index] + hcs_judge = self.judge_driver_hcs_exists(date_lines=model_hcs_lines) + if hcs_judge: + return self.hcspath + for index, _ in enumerate(lines): + lines[index] = Template(lines[index]).substitute(self.data) + + self.lines = old_lines[:end_index] + lines + old_lines[end_index:] + self._save() + return self.hcspath + + def _get_model_index(self, old_lines): + model_start_index = 0 + model_end_index = 0 + start_state = False + count = 0 + for index, old_line in enumerate(old_lines): + if old_line.strip().startswith(self.module): + model_start_index = index + count += 1 + start_state = True + else: + if start_state and old_line.find("{") != -1: + count += 1 + elif start_state and old_line.find("}") != -1: + count -= 1 + if count == 0: + start_state = False + model_end_index = index + return model_end_index, model_start_index + + def judge_driver_hcs_exists(self, date_lines): + for _, line in enumerate(date_lines): + if line.startswith("#"): + continue + elif line.find(self.driver) != -1: + return True + return False diff --git a/tools/hdf_dev_eco_tool/hdf_utils.py b/tools/hdf_dev_eco_tool/hdf_utils.py index e98f5730..2f6645b0 100644 --- a/tools/hdf_dev_eco_tool/hdf_utils.py +++ b/tools/hdf_dev_eco_tool/hdf_utils.py @@ -11,7 +11,7 @@ import json import os import hashlib - +import platform from hdf_tool_exception import HdfToolException from hdf_tool_settings import HdfToolSettings @@ -362,5 +362,22 @@ def get_config_config_path(root, kernel): def judge_file_path_exists(temp_path): if not os.path.exists(temp_path): - raise HdfToolException('path "%s" not exist' % - temp_path, CommandErrorCode.TARGET_NOT_EXIST) \ No newline at end of file + raise HdfToolException( + 'path "%s" not exist' % temp_path, + CommandErrorCode.TARGET_NOT_EXIST) + + +def write_config(root_path, config_file_json, config_name): + if platform.system() == "Windows": + config_file_replace = json.dumps(config_file_json, indent=4). \ + replace(root_path.replace('\\', '\\\\') + '\\\\', "") + write_file(os.path.join('resources', config_name), + config_file_replace.replace('\\\\', '/')) + if platform.system() == "Linux": + config_file_replace = json.dumps(config_file_json, indent=4). \ + replace(root_path + '/', "") + write_file(os.path.join('resources', config_name), + config_file_replace) + + + diff --git a/tools/hdf_dev_eco_tool/resources/templates/lite/driver_add_kconfig_config.template b/tools/hdf_dev_eco_tool/resources/templates/lite/driver_add_kconfig_config.template new file mode 100644 index 00000000..9c347328 --- /dev/null +++ b/tools/hdf_dev_eco_tool/resources/templates/lite/driver_add_kconfig_config.template @@ -0,0 +1,7 @@ + +config DRIVERS_HDF_${model_name_upper}_${driver_name_upper} + bool "Enable HDF ${model_name_lower} ${driver_name_lower} driver" + default n + depends on DRIVERS_HDF_${model_name_upper} + help + Answer Y to enable HDF ${model_name_lower} ${driver_name_lower} driver. \ No newline at end of file diff --git a/tools/hdf_dev_eco_tool/resources/templates/lite/exists_model_hcs_info.template b/tools/hdf_dev_eco_tool/resources/templates/lite/exists_model_hcs_info.template new file mode 100644 index 00000000..c2b54928 --- /dev/null +++ b/tools/hdf_dev_eco_tool/resources/templates/lite/exists_model_hcs_info.template @@ -0,0 +1,11 @@ +device_${model_name}_${driver_name} :: device { // Device node of sample + device0 :: deviceNode { // DeviceNode of the sample driver + policy = 2; // Driver service release policy. For details, see section Driver Service Management. + priority= 100; // Driver startup priority (0-200). A larger value indicates a lower priority. The default value 100 is recommended. If the priorities are the same, the device loading sequence is random. + preload = 0; // On-demand loading of the driver. For details, see "NOTE" at the end of this section. + permission = 0664; // Permission for the driver to create device nodes. + moduleName = "${driver_name}_driver"; // Driver name. The value of this field must be the same as the value of moduleName in the driver entry structure. + serviceName = "${driver_name}_service"; // Name of the service released by the driver. The name must be unique. + deviceMatchAttr = ""; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. + } +}