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
15
16
17class HdfHcsFile(object):
18    def __init__(self, file_path):
19        self.file_path = file_path
20        self.file_dir = os.path.dirname(self.file_path)
21        if os.path.exists(self.file_path):
22            self.lines = hdf_utils.read_file_lines(self.file_path)
23        else:
24            self.lines = []
25        self.line_template = '#include "%s/%s_config.hcs"\n'
26        self.line_pattern = r'^\s*#include\s+"%s/%s_config.hcs"'
27        self.include_pattern = r'^\s*#include'
28
29    def _save(self):
30        if self.lines:
31            hdf_utils.write_file(self.file_path, ''.join(self.lines))
32
33    def _find_line(self, pattern):
34        for index, line in enumerate(self.lines):
35            if re.search(pattern, line):
36                return index, line
37        return 0, ''
38
39    def _find_last_include(self):
40        if not self.lines:
41            return 0
42        i = len(self.lines) - 1
43        while i >= 0:
44            line = self.lines[i]
45            if re.search(self.include_pattern, line):
46                return i + 1
47            i -= 1
48        return 0
49
50    def _create_makefile(self):
51        mk_path = os.path.join(self.file_dir, 'Makefile')
52        template_str = hdf_utils.get_template('hdf_hcs_makefile.template')
53        hdf_utils.write_file(mk_path, template_str)
54
55    def check_and_create(self):
56        if self.lines:
57            return
58        if not os.path.exists(self.file_dir):
59            os.makedirs(self.file_dir)
60        self._create_makefile()
61        self.lines.append('#include "hdf_manager/manager_config.hcs"\n')
62        self._save()
63
64    def add_driver(self, module, driver):
65        target_line = self.line_template % (module, driver)
66        target_pattern = self.line_pattern % (module, driver)
67        idx, line = self._find_line(target_pattern)
68        if line:
69            self.lines[idx] = target_line
70        else:
71            pos = self._find_last_include()
72            self.lines.insert(pos, target_line)
73        self._save()
74
75    def delete_driver(self, module, driver):
76        target_pattern = self.line_pattern % (module, driver)
77        idx, line = self._find_line(target_pattern)
78        if not line:
79            return
80        self.lines[idx] = ''
81        self._save()
82