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 13 14import hdf_utils 15from hdf_tool_exception import HdfToolException 16from hdf_tool_settings import HdfToolSettings 17from .hdf_command_error_code import CommandErrorCode 18 19 20class HdfVendorBuildFile(object): 21 def __init__(self, root, vendor): 22 self.vendor = vendor 23 self.file_path = hdf_utils.get_vendor_gn_path(root) 24 if not os.path.exists(self.file_path): 25 raise HdfToolException('file: %s not exist' % self.file_path, 26 CommandErrorCode.TARGET_NOT_EXIST) 27 self.contents = hdf_utils.read_file(self.file_path) 28 29 def add_module(self, module): 30 with open(self.file_path, 'r') as file_read: 31 data = file_read.readlines() 32 33 line_template = r'input' 34 new_line = {} 35 for index, line in enumerate(data): 36 result = re.search(line_template, line) 37 if result: 38 new_line["index"] = index + 1 39 new_line["value"] = line 40 new_line["value"] = new_line.get("value").replace("input", module) 41 data.insert(new_line.get("index"), new_line.get("value")) 42 config_info = HdfToolSettings().get_file_config_info() 43 write_fd = os.open(self.file_path, config_info["flags"], config_info["modes"]) 44 with os.fdopen(write_fd, "w") as write_file: 45 for i in data: 46 write_file.write(i) 47 return self.file_path 48 49 def delete_module(self, file_path, model): 50 lines = hdf_utils.read_file_lines(file_path) 51 for index, line in enumerate(lines): 52 if line.find(model) > 0: 53 del lines[index] 54 hdf_utils.write_file_lines(file_path, lines) 55 56 def rename_vendor(self): 57 pattern = r'vendor/([a-zA-Z0-9_\-]+)/' 58 replacement = 'vendor/%s/' % self.vendor 59 new_content = re.sub(pattern, replacement, self.contents) 60 hdf_utils.write_file(self.file_path, new_content) 61