|
5 | 5 | # The MIT License (MIT) |
6 | 6 | # |
7 | 7 | # Copyright (c) 2017-2020 Kestrel Technology LLC |
| 8 | +# Copyright (c) 2020-2023 Henny B. Sipma |
| 9 | +# Copyright (c) 2024 Aarno Labs LLC |
8 | 10 | # |
9 | 11 | # Permission is hereby granted, free of charge, to any person obtaining a copy |
10 | 12 | # of this software and associated documentation files (the "Software"), to deal |
|
29 | 31 | from typing import Dict, TYPE_CHECKING, Optional |
30 | 32 |
|
31 | 33 | import chc.util.fileutil as UF |
| 34 | +from chc.util.loggingutil import chklogger |
32 | 35 |
|
33 | 36 | if TYPE_CHECKING: |
34 | | - import chc.app.CApplication |
| 37 | + from chc.app.CApplication import CApplication |
35 | 38 |
|
36 | 39 |
|
37 | 40 | class CSrcFile: |
38 | 41 | """Represents the text file that holds the C source code.""" |
39 | 42 |
|
40 | | - def __init__(self, capp: "chc.app.CApplication.CApplication", fname: str) -> None: |
41 | | - self.capp = capp |
42 | | - self.fname = fname |
43 | | - self._lines: Dict[int, str] = {} |
44 | | - if not self.fname.endswith(".c"): |
45 | | - self.fname = fname + ".c" |
| 43 | + def __init__(self, capp: "CApplication", fname: str) -> None: |
| 44 | + self._capp = capp |
| 45 | + self._fname = fname |
| 46 | + self._lines: Optional[Dict[int, str]] = None |
| 47 | + |
| 48 | + @property |
| 49 | + def capp(self) -> "CApplication": |
| 50 | + return self._capp |
| 51 | + |
| 52 | + @property |
| 53 | + def fname(self) -> str: |
| 54 | + """Returns the absolute c filename relative to the project directory.""" |
| 55 | + |
| 56 | + return self._fname |
46 | 57 |
|
47 | 58 | @property |
48 | 59 | def lines(self) -> Dict[int, str]: |
49 | | - if len(self._lines) == 0: |
50 | | - self._initialize() |
| 60 | + if self._lines is None: |
| 61 | + self._lines = {} |
| 62 | + if os.path.isfile(self.fname): |
| 63 | + n: int = 1 |
| 64 | + with open(self.fname) as fp: |
| 65 | + for line in fp: |
| 66 | + self._lines[n] = line |
| 67 | + n += 1 |
| 68 | + else: |
| 69 | + chklogger.logger.warning( |
| 70 | + "Source file %s not found", self.fname) |
51 | 71 | return self._lines |
52 | 72 |
|
53 | 73 | def get_line_count(self) -> int: |
54 | | - return sum(1 for line in open(self.fname)) |
| 74 | + return len(self.lines) |
55 | 75 |
|
56 | 76 | def get_line(self, n: int) -> Optional[str]: |
57 | | - self._initialize() |
58 | | - if n <= len(self.lines): |
| 77 | + if self.get_line_count() > n: |
59 | 78 | return str(n) + " " + self.lines[n] |
60 | 79 | return None |
61 | | - |
62 | | - def _initialize(self) -> None: |
63 | | - if len(self._lines) > 0: |
64 | | - return |
65 | | - if os.path.isfile(self.fname): |
66 | | - print("Reading file " + self.fname) |
67 | | - n = 1 |
68 | | - with open(self.fname) as f: |
69 | | - for line in f: |
70 | | - self._lines[n] = line |
71 | | - n += 1 |
72 | | - else: |
73 | | - print("Source file " + self.fname + " not found") |
|
0 commit comments