1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3 4# Copyright (c) 2020-2021 Huawei Device Co., Ltd. 5# 6# HDF is dual licensed: you can use it either under the terms of 7# the GPL, or the BSD license, at your option. 8# See the LICENSE file in the root of this repository for complete details. 9 10 11import os 12import re 13from string import Template 14 15import hdf_utils 16from hdf_tool_exception import HdfToolException 17from .hdf_command_error_code import CommandErrorCode 18 19 20class HdfModuleMkFile(object): 21 def __init__(self, root, vendor, module): 22 self.module = module 23 self.file_path = hdf_utils.get_module_mk_path(root, vendor, module) 24 if os.path.exists(self.file_path): 25 self.contents = hdf_utils.read_file(self.file_path) 26 else: 27 self.contents = '' 28 29 def _begin_end(self, driver): 30 driver_id = hdf_utils.get_id(self.module, driver) 31 begin = '\n# <begin %s\n' % driver_id 32 end = '\n# %s end>\n' % driver_id 33 return begin, end 34 35 def _create_driver_item(self, driver): 36 drv_converter = hdf_utils.WordsConverter(driver) 37 data_model = { 38 'driver_upper_case': drv_converter.upper_case(), 39 'driver_lower_case': drv_converter.lower_case() 40 } 41 template_str = hdf_utils.get_template('hdf_module_mk_driver.template') 42 content = Template(template_str).safe_substitute(data_model) 43 begin_flag, end_flag = self._begin_end(driver) 44 return hdf_utils.SectionContent(begin_flag, content, end_flag) 45 46 def add_driver(self, driver): 47 drv_section = self._create_driver_item(driver) 48 old_range = hdf_utils.find_section(self.contents, drv_section) 49 if old_range: 50 hdf_utils.replace_and_save(self.contents, self.file_path, 51 old_range, drv_section) 52 return 53 tail_pattern = r'include\s+\$\(HDF_DRIVER\)' 54 replacement = '%sinclude $(HDF_DRIVER)' % drv_section.to_str() 55 new_content, count = re.subn(tail_pattern, replacement, self.contents) 56 if count != 1: 57 raise HdfToolException('Makefile: %s has more than one include' 58 ' $(HDF_DRIVER)' % self.file_path, 59 CommandErrorCode.FILE_FORMAT_WRONG) 60 hdf_utils.write_file(self.file_path, new_content) 61 62 def delete_driver(self, driver): 63 begin_flag, end_flag = self._begin_end(driver) 64 empty_content = hdf_utils.SectionContent(begin_flag, '', end_flag) 65 drv_range = hdf_utils.find_section(self.contents, empty_content) 66 if drv_range: 67 hdf_utils.delete_and_save(self.contents, self.file_path, drv_range) 68