crcutil 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crcutil/__init__.py +0 -0
- crcutil/__main__.py +112 -0
- crcutil/config/log_config.yaml +63 -0
- crcutil/core/__init__.py +0 -0
- crcutil/core/crc.py +290 -0
- crcutil/core/prompt.py +177 -0
- crcutil/dto/__init__.py +0 -0
- crcutil/dto/bootstrap_paths_dto.py +10 -0
- crcutil/dto/hash_diff_report_dto.py +17 -0
- crcutil/dto/hash_dto.py +10 -0
- crcutil/dto/user_instructions_dto.py +17 -0
- crcutil/enums/__init__.py +0 -0
- crcutil/enums/user_request.py +24 -0
- crcutil/exception/__init__.py +0 -0
- crcutil/exception/bootstrap_error.py +2 -0
- crcutil/exception/corrupt_hash_error.py +2 -0
- crcutil/exception/unexpected_argument_error.py +2 -0
- crcutil/exception/user_error.py +2 -0
- crcutil/serializer/__init__.py +0 -0
- crcutil/serializer/hash_diff_report_serializer.py +26 -0
- crcutil/serializer/hash_serializer.py +14 -0
- crcutil/util/__init__.py +0 -0
- crcutil/util/crcutil_logger.py +47 -0
- crcutil/util/file_importer.py +178 -0
- crcutil/util/keyboard_monitor.py +28 -0
- crcutil/util/static.py +7 -0
- crcutil-1.0.0.dist-info/LICENSE +21 -0
- crcutil-1.0.0.dist-info/METADATA +120 -0
- crcutil-1.0.0.dist-info/RECORD +32 -0
- crcutil-1.0.0.dist-info/WHEEL +5 -0
- crcutil-1.0.0.dist-info/entry_points.txt +2 -0
- crcutil-1.0.0.dist-info/top_level.txt +1 -0
crcutil/__init__.py
ADDED
|
File without changes
|
crcutil/__main__.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
from jsonschema.exceptions import ValidationError
|
|
5
|
+
|
|
6
|
+
from crcutil.core.crc import Crc
|
|
7
|
+
from crcutil.core.prompt import Prompt
|
|
8
|
+
from crcutil.exception.bootstrap_error import BootstrapError
|
|
9
|
+
from crcutil.exception.corrupt_hash_error import CorruptHashError
|
|
10
|
+
from crcutil.exception.unexpected_argument_error import UnexpectedArgumentError
|
|
11
|
+
from crcutil.exception.user_error import UserError
|
|
12
|
+
from crcutil.util.crcutil_logger import CrcutilLogger
|
|
13
|
+
from crcutil.util.file_importer import FileImporter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main() -> None:
|
|
17
|
+
try:
|
|
18
|
+
bootstrap_paths_dto = FileImporter.bootstrap()
|
|
19
|
+
|
|
20
|
+
log_dir = bootstrap_paths_dto.log_dir
|
|
21
|
+
hash_file_location = bootstrap_paths_dto.hash_file
|
|
22
|
+
report_file_location = bootstrap_paths_dto.report_file
|
|
23
|
+
|
|
24
|
+
log_config_file_path = (
|
|
25
|
+
FileImporter.get_project_root()
|
|
26
|
+
/ "crcutil"
|
|
27
|
+
/ "config"
|
|
28
|
+
/ "log_config.yaml"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
log_config = FileImporter.get_logging_config(log_config_file_path)
|
|
32
|
+
|
|
33
|
+
CrcutilLogger(log_dir, log_config)
|
|
34
|
+
|
|
35
|
+
instructions_dto = Prompt.get_user_instructions_dto()
|
|
36
|
+
location = instructions_dto.location
|
|
37
|
+
user_request = instructions_dto.request
|
|
38
|
+
hash_diff_files = instructions_dto.hash_diff_files
|
|
39
|
+
hash_diff_dtos = []
|
|
40
|
+
if hash_diff_files:
|
|
41
|
+
hash_diff_dtos = [
|
|
42
|
+
FileImporter.get_hash(x) for x in hash_diff_files
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
crc_obj = Crc(
|
|
46
|
+
location=location,
|
|
47
|
+
hash_file_location=hash_file_location,
|
|
48
|
+
user_request=user_request,
|
|
49
|
+
hash_diff_1=hash_diff_dtos[0] if hash_diff_dtos else [],
|
|
50
|
+
hash_diff_2=hash_diff_dtos[1] if hash_diff_dtos else [],
|
|
51
|
+
)
|
|
52
|
+
hash_diff_report = crc_obj.do()
|
|
53
|
+
if hash_diff_report:
|
|
54
|
+
FileImporter.save_hash_diff_report(
|
|
55
|
+
report_file_location, hash_diff_report
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
sys.exit(0)
|
|
59
|
+
|
|
60
|
+
except SystemExit as e:
|
|
61
|
+
if e.code == 0:
|
|
62
|
+
description = "Successful System Exit"
|
|
63
|
+
CrcutilLogger.get_logger().debug(description)
|
|
64
|
+
else:
|
|
65
|
+
description = "\n=====Unexpected Error=====\n" f"{e!s}"
|
|
66
|
+
CrcutilLogger.get_logger().exception(description)
|
|
67
|
+
raise
|
|
68
|
+
|
|
69
|
+
except UnexpectedArgumentError as e:
|
|
70
|
+
sys.tracebacklimit = 0
|
|
71
|
+
description = (
|
|
72
|
+
"\n=====User Argument Error=====\n"
|
|
73
|
+
"These arguments are unrecognized: \n"
|
|
74
|
+
)
|
|
75
|
+
for argument in e.args[0]:
|
|
76
|
+
description += "-> " + argument + "\n"
|
|
77
|
+
CrcutilLogger.get_logger().error(description)
|
|
78
|
+
sys.exit(1)
|
|
79
|
+
|
|
80
|
+
except UserError as e:
|
|
81
|
+
sys.tracebacklimit = 0
|
|
82
|
+
description = "\n=====User Error=====\n" f"{e!s}"
|
|
83
|
+
CrcutilLogger.get_logger().error(description)
|
|
84
|
+
|
|
85
|
+
except CorruptHashError as e:
|
|
86
|
+
sys.tracebacklimit = 0
|
|
87
|
+
description = "\n=====Corrupt Hash Error=====\n" f"{e!s}"
|
|
88
|
+
CrcutilLogger.get_logger().error(description)
|
|
89
|
+
|
|
90
|
+
except json.decoder.JSONDecodeError as e:
|
|
91
|
+
sys.tracebacklimit = 0
|
|
92
|
+
description = "\n=====Corrupt Hash Error=====\n" f"{e!s}"
|
|
93
|
+
CrcutilLogger.get_logger().error(description)
|
|
94
|
+
|
|
95
|
+
except ValidationError as e:
|
|
96
|
+
sys.tracebacklimit = 0
|
|
97
|
+
description = "\n=====Invalid Schema Error=====\n" f"{e!s}"
|
|
98
|
+
CrcutilLogger.get_logger().error(description)
|
|
99
|
+
|
|
100
|
+
# No regular logger can be expected to be initialized
|
|
101
|
+
except BootstrapError as e:
|
|
102
|
+
description = "\n=====Program Initialization Error=====\n" f"{e!s}"
|
|
103
|
+
e.args = (description,)
|
|
104
|
+
raise
|
|
105
|
+
|
|
106
|
+
except Exception as e: # noqa: BLE001
|
|
107
|
+
description = "\n=====Unexpected Error=====\n" f"{e!s}"
|
|
108
|
+
CrcutilLogger.get_logger().exception(description)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
main()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
---
|
|
2
|
+
version: 1
|
|
3
|
+
disable_existing_loggers: False
|
|
4
|
+
formatters:
|
|
5
|
+
console_color:
|
|
6
|
+
(): colorlog.ColoredFormatter
|
|
7
|
+
format: '%(log_color)s%(message)s%(reset)s'
|
|
8
|
+
log_colors:
|
|
9
|
+
DEBUG: cyan
|
|
10
|
+
WARNING: yellow
|
|
11
|
+
ERROR: red
|
|
12
|
+
CRITICAL: red,bg_white
|
|
13
|
+
datefmt: '%Y-%m-%dT%H:%M:%SZ'
|
|
14
|
+
|
|
15
|
+
simple_color:
|
|
16
|
+
(): colorlog.ColoredFormatter
|
|
17
|
+
format: '%(log_color)s%(asctime)s %(levelname)-8s%(reset)s %(message)s'
|
|
18
|
+
log_colors:
|
|
19
|
+
DEBUG: cyan
|
|
20
|
+
WARNING: yellow
|
|
21
|
+
ERROR: red
|
|
22
|
+
CRITICAL: red,bg_white
|
|
23
|
+
datefmt: '%Y-%m-%dT%H:%M:%SZ'
|
|
24
|
+
|
|
25
|
+
detailed_color:
|
|
26
|
+
(): colorlog.ColoredFormatter
|
|
27
|
+
format: '%(log_color)s%(asctime)s | %(process)d | %(levelname)s | %(filename)s | %(lineno)d | %(funcName)s | %(message)s%(reset)s'
|
|
28
|
+
log_colors:
|
|
29
|
+
DEBUG: cyan
|
|
30
|
+
WARNING: yellow
|
|
31
|
+
ERROR: red
|
|
32
|
+
CRITICAL: red,bg_white
|
|
33
|
+
datefmt: '%Y-%m-%dT%H:%M:%SZ'
|
|
34
|
+
|
|
35
|
+
simple:
|
|
36
|
+
format: '%(asctime)s %(levelname)-8s %(message)s'
|
|
37
|
+
datefmt: '%Y-%m-%dT%H:%M:%SZ'
|
|
38
|
+
|
|
39
|
+
detailed:
|
|
40
|
+
format: '%(asctime)s | %(process)d | %(levelname)s | %(filename)s | %(lineno)d | %(funcName)s | %(message)s'
|
|
41
|
+
datefmt: '%Y-%m-%dT%H:%M:%SZ'
|
|
42
|
+
|
|
43
|
+
handlers:
|
|
44
|
+
console_color:
|
|
45
|
+
class: logging.StreamHandler
|
|
46
|
+
level: INFO
|
|
47
|
+
formatter: console_color
|
|
48
|
+
stream: ext://sys.stdout
|
|
49
|
+
|
|
50
|
+
regular_file_handler:
|
|
51
|
+
filename: 'fallback_regular.log'
|
|
52
|
+
class: logging.FileHandler
|
|
53
|
+
level: DEBUG
|
|
54
|
+
formatter: detailed
|
|
55
|
+
encoding: utf8
|
|
56
|
+
|
|
57
|
+
loggers:
|
|
58
|
+
console:
|
|
59
|
+
level: INFO
|
|
60
|
+
handlers: [console_color]
|
|
61
|
+
regular:
|
|
62
|
+
level: DEBUG
|
|
63
|
+
handlers: [console_color, regular_file_handler]
|
crcutil/core/__init__.py
ADDED
|
File without changes
|
crcutil/core/crc.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import zlib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from alive_progress import alive_bar
|
|
8
|
+
|
|
9
|
+
from crcutil.core.prompt import Prompt
|
|
10
|
+
from crcutil.dto.hash_diff_report_dto import HashDiffReportDTO
|
|
11
|
+
from crcutil.dto.hash_dto import HashDTO
|
|
12
|
+
from crcutil.enums.user_request import UserRequest
|
|
13
|
+
from crcutil.exception.corrupt_hash_error import CorruptHashError
|
|
14
|
+
from crcutil.util.crcutil_logger import CrcutilLogger
|
|
15
|
+
from crcutil.util.file_importer import FileImporter
|
|
16
|
+
from crcutil.util.keyboard_monitor import KeyboardMonitor
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Crc:
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
location: Path,
|
|
23
|
+
hash_file_location: Path,
|
|
24
|
+
user_request: UserRequest,
|
|
25
|
+
hash_diff_1: list[HashDTO],
|
|
26
|
+
hash_diff_2: list[HashDTO],
|
|
27
|
+
) -> None:
|
|
28
|
+
self.location = location
|
|
29
|
+
self.hash_file_location = hash_file_location
|
|
30
|
+
self.user_request = user_request
|
|
31
|
+
self.hash_diff_1 = hash_diff_1
|
|
32
|
+
self.hash_diff_2 = hash_diff_2
|
|
33
|
+
|
|
34
|
+
def do(self) -> HashDiffReportDTO | None:
|
|
35
|
+
"""
|
|
36
|
+
Performs a Hash/Diff
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
HashDiffReportDTO | None: If request is Diff, None if Hash
|
|
40
|
+
Raises:
|
|
41
|
+
ValueError: If request other than diff or hash
|
|
42
|
+
"""
|
|
43
|
+
if self.user_request is UserRequest.HASH:
|
|
44
|
+
match self.__get_hash_status():
|
|
45
|
+
case -1:
|
|
46
|
+
self.__create_hash()
|
|
47
|
+
case 0:
|
|
48
|
+
self.__continue_hash()
|
|
49
|
+
case 1:
|
|
50
|
+
self.__create_hash(is_hash_overwrite=True)
|
|
51
|
+
return None
|
|
52
|
+
elif self.user_request is UserRequest.DIFF:
|
|
53
|
+
hash_1 = self.hash_diff_1
|
|
54
|
+
hash_2 = self.hash_diff_2
|
|
55
|
+
|
|
56
|
+
hash_1_dict = {dto.file: dto.crc for dto in hash_1}
|
|
57
|
+
hash_2_dict = {dto.file: dto.crc for dto in hash_2}
|
|
58
|
+
|
|
59
|
+
changes = [
|
|
60
|
+
dto
|
|
61
|
+
for dto in hash_2
|
|
62
|
+
if dto.file in hash_1_dict and hash_1_dict[dto.file] != dto.crc
|
|
63
|
+
]
|
|
64
|
+
missing_1 = [
|
|
65
|
+
dto_1 for dto_1 in hash_1 if dto_1.file not in hash_2_dict
|
|
66
|
+
]
|
|
67
|
+
missing_2 = [
|
|
68
|
+
dto_2 for dto_2 in hash_2 if dto_2.file not in hash_1_dict
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
return HashDiffReportDTO(
|
|
72
|
+
changes=changes, missing_1=missing_1, missing_2=missing_2
|
|
73
|
+
)
|
|
74
|
+
else:
|
|
75
|
+
description = f"Unsupported request: {self.user_request!s}"
|
|
76
|
+
raise ValueError(description)
|
|
77
|
+
|
|
78
|
+
def __create_hash(self, is_hash_overwrite: bool = False) -> None:
|
|
79
|
+
if is_hash_overwrite:
|
|
80
|
+
Prompt.overwrite_hash_confirm()
|
|
81
|
+
|
|
82
|
+
self.hash_file_location.write_text("{}")
|
|
83
|
+
|
|
84
|
+
description = f"Creating Hash: {self.location}"
|
|
85
|
+
CrcutilLogger.get_logger().debug(description)
|
|
86
|
+
|
|
87
|
+
all_locations = self.seek(self.location)
|
|
88
|
+
self.__write_locations(all_locations)
|
|
89
|
+
self.__write_hash(self.location, all_locations)
|
|
90
|
+
|
|
91
|
+
def __continue_hash(self) -> None:
|
|
92
|
+
Prompt.continue_hash_confirm()
|
|
93
|
+
offset_position = ""
|
|
94
|
+
|
|
95
|
+
original_hashes = FileImporter.get_hash(self.hash_file_location)
|
|
96
|
+
|
|
97
|
+
description = (
|
|
98
|
+
f"Resuming existing Hash: {self.hash_file_location} "
|
|
99
|
+
f"with location: {self.location}"
|
|
100
|
+
)
|
|
101
|
+
CrcutilLogger.get_logger().debug(description)
|
|
102
|
+
|
|
103
|
+
for hash_dto in original_hashes:
|
|
104
|
+
if not hash_dto.crc:
|
|
105
|
+
offset_position = hash_dto.file
|
|
106
|
+
break
|
|
107
|
+
|
|
108
|
+
all_locations = self.seek(self.location)
|
|
109
|
+
for hash_dto in original_hashes:
|
|
110
|
+
if hash_dto.file not in all_locations:
|
|
111
|
+
description = (
|
|
112
|
+
"An element in the Hash does not exist "
|
|
113
|
+
f"in the supplied location: {hash_dto.file}\n"
|
|
114
|
+
f"Cannot continue"
|
|
115
|
+
)
|
|
116
|
+
raise CorruptHashError(description)
|
|
117
|
+
|
|
118
|
+
original_hashes_str = [x.file for x in original_hashes]
|
|
119
|
+
for location in all_locations:
|
|
120
|
+
if location not in original_hashes_str:
|
|
121
|
+
description = (
|
|
122
|
+
"An element in the supplied location does not exist "
|
|
123
|
+
f"in the Hash: {location}\n"
|
|
124
|
+
f"Cannot continue"
|
|
125
|
+
)
|
|
126
|
+
raise CorruptHashError(description)
|
|
127
|
+
|
|
128
|
+
filtered_locations = self.seek(self.location, offset_position)
|
|
129
|
+
self.__write_hash(
|
|
130
|
+
self.location, filtered_locations, len(original_hashes)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def __write_locations(self, str_relative_locations: list[str]) -> None:
|
|
134
|
+
hashes = [HashDTO(file=x, crc=0) for x in str_relative_locations]
|
|
135
|
+
FileImporter.save_hash(self.hash_file_location, hashes)
|
|
136
|
+
|
|
137
|
+
def __write_hash(
|
|
138
|
+
self,
|
|
139
|
+
parent_location: Path,
|
|
140
|
+
str_relative_locations: list[str],
|
|
141
|
+
total_count: int = 0,
|
|
142
|
+
) -> None:
|
|
143
|
+
monitor = KeyboardMonitor()
|
|
144
|
+
try:
|
|
145
|
+
monitor.start()
|
|
146
|
+
play_icon, pause_icon = (
|
|
147
|
+
("▶", "⏸")
|
|
148
|
+
if sys.stdout.encoding.lower().startswith("utf")
|
|
149
|
+
else (">", "||")
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
pause_description = "\n*Press p to pause/resume"
|
|
153
|
+
quit_description = "*Press q to quit"
|
|
154
|
+
CrcutilLogger.get_console_logger().info(pause_description)
|
|
155
|
+
CrcutilLogger.get_console_logger().info(quit_description)
|
|
156
|
+
|
|
157
|
+
length = (
|
|
158
|
+
total_count if total_count else len(str_relative_locations)
|
|
159
|
+
)
|
|
160
|
+
with alive_bar(length, dual_line=True) as bar:
|
|
161
|
+
if total_count:
|
|
162
|
+
offset_count = total_count - len(str_relative_locations)
|
|
163
|
+
for _ in range(offset_count):
|
|
164
|
+
bar()
|
|
165
|
+
|
|
166
|
+
for str_relative_location in str_relative_locations:
|
|
167
|
+
while monitor.is_paused:
|
|
168
|
+
bar.text = f"{pause_icon} PAUSED"
|
|
169
|
+
while monitor.is_quit:
|
|
170
|
+
sys.exit(0)
|
|
171
|
+
|
|
172
|
+
bar.text = f"{play_icon} {str_relative_location}"
|
|
173
|
+
|
|
174
|
+
relative_location = Path(str_relative_location)
|
|
175
|
+
abs_location = (
|
|
176
|
+
parent_location / relative_location
|
|
177
|
+
).resolve()
|
|
178
|
+
|
|
179
|
+
crc = self.__get_crc_hash(abs_location, parent_location)
|
|
180
|
+
hashes = FileImporter.get_hash(self.hash_file_location)
|
|
181
|
+
hashes.append(HashDTO(file=str_relative_location, crc=crc))
|
|
182
|
+
|
|
183
|
+
FileImporter.save_hash(self.hash_file_location, hashes)
|
|
184
|
+
|
|
185
|
+
bar()
|
|
186
|
+
except KeyboardInterrupt:
|
|
187
|
+
monitor.stop()
|
|
188
|
+
|
|
189
|
+
def __walk(self, path: Path) -> list[Path]:
|
|
190
|
+
"""
|
|
191
|
+
Recursively collects all file/dirs in a given path
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
path (pathlib.Path): The parent directory to traverse
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
[Path] All file/dir in the tree
|
|
198
|
+
"""
|
|
199
|
+
items = []
|
|
200
|
+
|
|
201
|
+
if path.is_file():
|
|
202
|
+
items.append(path)
|
|
203
|
+
elif path.is_dir():
|
|
204
|
+
items.append(path)
|
|
205
|
+
for child in path.iterdir():
|
|
206
|
+
sub_items = self.__walk(child)
|
|
207
|
+
items.extend(sub_items)
|
|
208
|
+
|
|
209
|
+
return items
|
|
210
|
+
|
|
211
|
+
def seek(
|
|
212
|
+
self, initial_position: Path, offset_position: str = ""
|
|
213
|
+
) -> list[str]:
|
|
214
|
+
raw = self.__walk(initial_position)
|
|
215
|
+
normalized = [x.relative_to(initial_position) for x in raw]
|
|
216
|
+
sorted_normalized = sorted(normalized, key=lambda path: path.name)
|
|
217
|
+
sorted_normalized = [str(x) for x in sorted_normalized if x != Path()]
|
|
218
|
+
|
|
219
|
+
if not offset_position:
|
|
220
|
+
return sorted_normalized
|
|
221
|
+
else:
|
|
222
|
+
is_collect = False
|
|
223
|
+
remaining = []
|
|
224
|
+
for item in sorted_normalized:
|
|
225
|
+
# Only flip once
|
|
226
|
+
if item == offset_position and not is_collect:
|
|
227
|
+
is_collect = not is_collect
|
|
228
|
+
if is_collect:
|
|
229
|
+
remaining.append(item)
|
|
230
|
+
return remaining
|
|
231
|
+
|
|
232
|
+
def __get_hash_status(self) -> int:
|
|
233
|
+
"""
|
|
234
|
+
Gets the current status of a Hash file:
|
|
235
|
+
Possible values:
|
|
236
|
+
-1) File does not exist
|
|
237
|
+
0) File exists and is incomplete/pending
|
|
238
|
+
1) File exists and is finished
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
int: The status of the hash file
|
|
242
|
+
"""
|
|
243
|
+
status = -1
|
|
244
|
+
if self.hash_file_location.exists():
|
|
245
|
+
hash_dto = FileImporter.get_hash(self.hash_file_location)
|
|
246
|
+
|
|
247
|
+
for dto in hash_dto:
|
|
248
|
+
if not dto.crc:
|
|
249
|
+
return 0
|
|
250
|
+
|
|
251
|
+
status = 1
|
|
252
|
+
|
|
253
|
+
return status
|
|
254
|
+
|
|
255
|
+
def __get_crc_hash(self, location: Path, parent_location: Path) -> int:
|
|
256
|
+
crc = 0
|
|
257
|
+
crc = (
|
|
258
|
+
zlib.crc32(
|
|
259
|
+
self.__get_crc_from_path(location, parent_location), crc
|
|
260
|
+
)
|
|
261
|
+
& 0xFFFFFFFF
|
|
262
|
+
)
|
|
263
|
+
crc = zlib.crc32(self.__get_crc_from_attr(location), crc) & 0xFFFFFFFF
|
|
264
|
+
|
|
265
|
+
if location.is_file():
|
|
266
|
+
crc = (
|
|
267
|
+
zlib.crc32(self.__get_crc_from_file_contents(location), crc)
|
|
268
|
+
& 0xFFFFFFFF
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
return crc
|
|
272
|
+
|
|
273
|
+
def __get_crc_from_path(
|
|
274
|
+
self, location: Path, parent_location: Path
|
|
275
|
+
) -> bytes:
|
|
276
|
+
return str(location.relative_to(parent_location)).encode("utf-8")
|
|
277
|
+
|
|
278
|
+
def __get_crc_from_attr(self, location: Path) -> bytes:
|
|
279
|
+
stat = location.stat()
|
|
280
|
+
if location.is_dir():
|
|
281
|
+
return f"{stat.st_mode}".encode()
|
|
282
|
+
else:
|
|
283
|
+
return f"{stat.st_size}:{stat.st_mode}".encode()
|
|
284
|
+
|
|
285
|
+
def __get_crc_from_file_contents(self, location: Path) -> bytes:
|
|
286
|
+
file_crc = 0
|
|
287
|
+
with location.open("rb") as f:
|
|
288
|
+
for chunk in iter(lambda: f.read(4096), b""):
|
|
289
|
+
file_crc = zlib.crc32(chunk, file_crc) & 0xFFFFFFFF
|
|
290
|
+
return file_crc.to_bytes(4, "little", signed=False)
|
crcutil/core/prompt.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import pathlib
|
|
5
|
+
import sys
|
|
6
|
+
from argparse import RawTextHelpFormatter
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
from crcutil.dto.user_instructions_dto import UserInstructionsDTO
|
|
10
|
+
from crcutil.enums.user_request import UserRequest
|
|
11
|
+
from crcutil.exception.unexpected_argument_error import (
|
|
12
|
+
UnexpectedArgumentError,
|
|
13
|
+
)
|
|
14
|
+
from crcutil.exception.user_error import UserError
|
|
15
|
+
from crcutil.util.crcutil_logger import CrcutilLogger
|
|
16
|
+
from crcutil.util.file_importer import FileImporter
|
|
17
|
+
from crcutil.util.static import Static
|
|
18
|
+
|
|
19
|
+
EXPECTED_LOCATION_LENGHT_HASH = 1
|
|
20
|
+
EXPECTED_LOCATION_LENGHT_DIFF = 2
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Prompt(Static):
|
|
24
|
+
@staticmethod
|
|
25
|
+
def get_user_instructions_dto() -> UserInstructionsDTO:
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
description="crcutil", formatter_class=RawTextHelpFormatter
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
request_help_str = "Supported Requests: \n"
|
|
31
|
+
|
|
32
|
+
for request in list(UserRequest):
|
|
33
|
+
request_help_str += "-> " + request.value + "\n"
|
|
34
|
+
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"request",
|
|
37
|
+
metavar="Request",
|
|
38
|
+
type=str,
|
|
39
|
+
nargs="?",
|
|
40
|
+
help=request_help_str,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"-l",
|
|
45
|
+
"--location",
|
|
46
|
+
metavar="location",
|
|
47
|
+
type=pathlib.Path,
|
|
48
|
+
nargs="*",
|
|
49
|
+
help=(
|
|
50
|
+
"Path to hash, or if requesting diff, "
|
|
51
|
+
"then path of both hash files to diff"
|
|
52
|
+
),
|
|
53
|
+
default=[],
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"-v",
|
|
58
|
+
"--version",
|
|
59
|
+
action="store_true",
|
|
60
|
+
help=("Displays version"),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
args, unknown = parser.parse_known_args()
|
|
64
|
+
|
|
65
|
+
if unknown:
|
|
66
|
+
raise UnexpectedArgumentError(unknown)
|
|
67
|
+
|
|
68
|
+
is_version = args.version
|
|
69
|
+
|
|
70
|
+
if is_version:
|
|
71
|
+
crcutil_version = ""
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
crcutil_version = version("crcutil")
|
|
75
|
+
|
|
76
|
+
except PackageNotFoundError:
|
|
77
|
+
pyproject = FileImporter.get_pyproject()
|
|
78
|
+
crcutil_version = pyproject["project"]["version"]
|
|
79
|
+
|
|
80
|
+
CrcutilLogger.get_logger().info(crcutil_version)
|
|
81
|
+
sys.exit(0)
|
|
82
|
+
|
|
83
|
+
request = args.request
|
|
84
|
+
if not request:
|
|
85
|
+
description = "Expected a request but none supplied, see -h"
|
|
86
|
+
raise UserError(description)
|
|
87
|
+
request = UserRequest.get_user_request_from_str(request)
|
|
88
|
+
|
|
89
|
+
location = args.location
|
|
90
|
+
location_1 = pathlib.Path()
|
|
91
|
+
location_2 = pathlib.Path()
|
|
92
|
+
hash_diff_files = []
|
|
93
|
+
if args.location:
|
|
94
|
+
if (
|
|
95
|
+
len(args.location) == EXPECTED_LOCATION_LENGHT_HASH
|
|
96
|
+
and request is UserRequest.HASH
|
|
97
|
+
):
|
|
98
|
+
location_1 = FileImporter.get_path_from_str(args.location[0])
|
|
99
|
+
elif (
|
|
100
|
+
len(args.location) == EXPECTED_LOCATION_LENGHT_DIFF
|
|
101
|
+
and request is UserRequest.DIFF
|
|
102
|
+
):
|
|
103
|
+
location_1 = FileImporter.get_path_from_str(args.location[0])
|
|
104
|
+
location_2 = FileImporter.get_path_from_str(args.location[1])
|
|
105
|
+
hash_diff_files = [location_1, location_2]
|
|
106
|
+
elif (
|
|
107
|
+
len(args.location) != EXPECTED_LOCATION_LENGHT_DIFF
|
|
108
|
+
and request is UserRequest.DIFF
|
|
109
|
+
):
|
|
110
|
+
description = (
|
|
111
|
+
f"Expected 2 Hash files but got: "
|
|
112
|
+
f"{len(args.location)}\n"
|
|
113
|
+
f"Example: crcutil diff -l path_to_hash_1 path_to_hash_2"
|
|
114
|
+
)
|
|
115
|
+
raise UserError(description)
|
|
116
|
+
elif not args.location and request is UserRequest.DIFF:
|
|
117
|
+
description = (
|
|
118
|
+
"Expected 2 Hash files but got: 0\n"
|
|
119
|
+
"Example: crcutil diff -l path_to_hash_1 path_to_hash_2"
|
|
120
|
+
)
|
|
121
|
+
raise UserError(description)
|
|
122
|
+
else:
|
|
123
|
+
description = (
|
|
124
|
+
"Expected a location but none supplied\n"
|
|
125
|
+
"Example: crcutil hash -l path_to_hash"
|
|
126
|
+
)
|
|
127
|
+
raise UserError(description)
|
|
128
|
+
|
|
129
|
+
debug = (
|
|
130
|
+
"Received a User Request:\n"
|
|
131
|
+
f"Request: {request.value if request else None}\n"
|
|
132
|
+
f"Location: {location!s}\n"
|
|
133
|
+
)
|
|
134
|
+
CrcutilLogger.get_logger().debug(debug)
|
|
135
|
+
|
|
136
|
+
return UserInstructionsDTO(
|
|
137
|
+
request=request,
|
|
138
|
+
location=location_1,
|
|
139
|
+
hash_diff_files=hash_diff_files,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def overwrite_hash_confirm() -> None:
|
|
144
|
+
warning = (
|
|
145
|
+
"⚠️"
|
|
146
|
+
if sys.stdout.encoding.lower().startswith("utf")
|
|
147
|
+
else "[WARNING]"
|
|
148
|
+
)
|
|
149
|
+
confirmation = (
|
|
150
|
+
input(f"{warning} Hash file already exists, " "OVERWRITE? (y/n): ")
|
|
151
|
+
.strip()
|
|
152
|
+
.lower()
|
|
153
|
+
)
|
|
154
|
+
if confirmation != "y":
|
|
155
|
+
debug = "Overwrite of hash file cancelled by user"
|
|
156
|
+
CrcutilLogger.get_logger().debug(debug)
|
|
157
|
+
sys.exit(0)
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def continue_hash_confirm() -> None:
|
|
161
|
+
warning = (
|
|
162
|
+
"⚠️"
|
|
163
|
+
if sys.stdout.encoding.lower().startswith("utf")
|
|
164
|
+
else "[WARNING]"
|
|
165
|
+
)
|
|
166
|
+
confirmation = (
|
|
167
|
+
input(
|
|
168
|
+
f"{warning} Incomplete Hash file already exists, "
|
|
169
|
+
"RESUME? (y/n): "
|
|
170
|
+
)
|
|
171
|
+
.strip()
|
|
172
|
+
.lower()
|
|
173
|
+
)
|
|
174
|
+
if confirmation != "y":
|
|
175
|
+
debug = "Resume of hash file cancelled by user"
|
|
176
|
+
CrcutilLogger.get_logger().debug(debug)
|
|
177
|
+
sys.exit(0)
|
crcutil/dto/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from crcutil.dto.hash_dto import HashDTO
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Frozen=True creates an implicit hash method, eq is created by default
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class HashDiffReportDTO:
|
|
15
|
+
changes: list[HashDTO]
|
|
16
|
+
missing_1: list[HashDTO]
|
|
17
|
+
missing_2: list[HashDTO]
|
crcutil/dto/hash_dto.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from crcutil.enums.user_request import UserRequest
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# Frozen=True creates an implicit hash method, eq is created by default
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class UserInstructionsDTO:
|
|
15
|
+
request: UserRequest
|
|
16
|
+
location: Path
|
|
17
|
+
hash_diff_files: list[Path]
|
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UserRequest(Enum):
|
|
7
|
+
HASH = "hash"
|
|
8
|
+
DIFF = "diff"
|
|
9
|
+
|
|
10
|
+
@staticmethod
|
|
11
|
+
def get_user_request_from_str(
|
|
12
|
+
user_request_candidate: str,
|
|
13
|
+
) -> UserRequest:
|
|
14
|
+
requests = list(UserRequest)
|
|
15
|
+
user_request_candidate = user_request_candidate.lower()
|
|
16
|
+
|
|
17
|
+
for request in requests:
|
|
18
|
+
if (
|
|
19
|
+
user_request_candidate == request.value
|
|
20
|
+
or user_request_candidate.replace("_", " ") == request.value
|
|
21
|
+
):
|
|
22
|
+
return request
|
|
23
|
+
|
|
24
|
+
raise ValueError("Request not supported: " + user_request_candidate)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from crcutil.dto.hash_diff_report_dto import HashDiffReportDTO
|
|
7
|
+
|
|
8
|
+
from crcutil.util.static import Static
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class HashDiffReportSerializer(Static):
|
|
12
|
+
@staticmethod
|
|
13
|
+
def to_json(dto: HashDiffReportDTO) -> dict:
|
|
14
|
+
obj = {}
|
|
15
|
+
changes = dto.changes
|
|
16
|
+
missing_1 = dto.missing_1
|
|
17
|
+
missing_2 = dto.missing_2
|
|
18
|
+
|
|
19
|
+
obj["Changes"] = [x.file for x in changes]
|
|
20
|
+
obj["Present in 1 Missing in 2"] = [x.file for x in missing_1]
|
|
21
|
+
obj["Present in 2 Missing in 1"] = [x.file for x in missing_2]
|
|
22
|
+
return obj
|
|
23
|
+
|
|
24
|
+
@staticmethod
|
|
25
|
+
def to_dto(hash_diff_report_dict: dict) -> HashDiffReportDTO:
|
|
26
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from crcutil.dto.hash_dto import HashDTO
|
|
4
|
+
from crcutil.util.static import Static
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class HashSerializer(Static):
|
|
8
|
+
@staticmethod
|
|
9
|
+
def to_json(hash_dto: list[HashDTO]) -> dict:
|
|
10
|
+
return {dto.file: dto.crc for dto in hash_dto}
|
|
11
|
+
|
|
12
|
+
@staticmethod
|
|
13
|
+
def to_dto(hash_dict: dict) -> list[HashDTO]:
|
|
14
|
+
return [HashDTO(file=file, crc=crc) for file, crc in hash_dict.items()]
|
crcutil/util/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
# ruff: noqa: ANN002, ANN003, ANN204, RUF012
|
|
4
|
+
import logging.config
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class SingletonMeta(type):
|
|
10
|
+
_instances = {}
|
|
11
|
+
|
|
12
|
+
def __call__(cls, *args, **kwargs):
|
|
13
|
+
if cls not in cls._instances:
|
|
14
|
+
cls._instances[cls] = super().__call__(*args, **kwargs)
|
|
15
|
+
return cls._instances[cls]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CrcutilLogger(metaclass=SingletonMeta):
|
|
19
|
+
def __init__(self, log_dir: Path, log_config: dict) -> None:
|
|
20
|
+
if not hasattr(self, "initialized"): # Avoid reinitialization
|
|
21
|
+
# Time data in UTC required by date named log files
|
|
22
|
+
day = str(datetime.now(timezone.utc).day)
|
|
23
|
+
month = str(datetime.now(timezone.utc).month)
|
|
24
|
+
year = str(datetime.now(timezone.utc).year)
|
|
25
|
+
|
|
26
|
+
log_file_name = f"{year}-{month}-{day}.log"
|
|
27
|
+
# Rewrite contents of YAML config to accomodate
|
|
28
|
+
# for date based log file names
|
|
29
|
+
log_config["handlers"]["regular_file_handler"]["filename"] = (
|
|
30
|
+
log_dir / log_file_name
|
|
31
|
+
)
|
|
32
|
+
# Load config with changes as Dict
|
|
33
|
+
logging.config.dictConfig(log_config)
|
|
34
|
+
# Initialize loggers
|
|
35
|
+
self.logger = logging.getLogger("regular")
|
|
36
|
+
self.console_logger = logging.getLogger("console")
|
|
37
|
+
self.initialized = True
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def get_logger(cls) -> logging.Logger:
|
|
41
|
+
instance = cls._instances[cls]
|
|
42
|
+
return instance.logger
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def get_console_logger(cls) -> logging.Logger:
|
|
46
|
+
instance = cls._instances[cls]
|
|
47
|
+
return instance.console_logger
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from crcutil.dto.hash_diff_report_dto import HashDiffReportDTO
|
|
7
|
+
from crcutil.dto.hash_dto import HashDTO
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
import ctypes.wintypes
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import platform
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import toml
|
|
17
|
+
|
|
18
|
+
from crcutil.dto.bootstrap_paths_dto import BootstrapPathsDTO
|
|
19
|
+
from crcutil.exception.bootstrap_error import BootstrapError
|
|
20
|
+
from crcutil.serializer.hash_diff_report_serializer import (
|
|
21
|
+
HashDiffReportSerializer,
|
|
22
|
+
)
|
|
23
|
+
from crcutil.serializer.hash_serializer import HashSerializer
|
|
24
|
+
|
|
25
|
+
if platform.system() == "Windows":
|
|
26
|
+
import win32evtlog # pyright: ignore # noqa: PGH003
|
|
27
|
+
import win32evtlogutil # pyright: ignore # noqa: PGH003
|
|
28
|
+
|
|
29
|
+
import yaml
|
|
30
|
+
|
|
31
|
+
from crcutil.util.static import Static
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FileImporter(Static):
|
|
35
|
+
encoding = "utf-8"
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def get_path_from_str(
|
|
39
|
+
path_candidate: str,
|
|
40
|
+
is_dir_expected: bool = False,
|
|
41
|
+
is_file_expected: bool = False,
|
|
42
|
+
) -> Path:
|
|
43
|
+
"""
|
|
44
|
+
Get pathlib.Path from a str
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
path_candidate (str): The likely Path
|
|
48
|
+
is_dir_expected (bool): Is the path expected to be a dir?
|
|
49
|
+
is_file_expected (bool): Is the path expected to be a file?
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
A pathlib.Path
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
ValueError: If path_candidate is not supplied or path doesn't exist
|
|
56
|
+
or path does not meet is_dir_expected/is_file_expected condition
|
|
57
|
+
"""
|
|
58
|
+
if not path_candidate:
|
|
59
|
+
description = "Expected a path candidate but none supplied "
|
|
60
|
+
raise ValueError(description)
|
|
61
|
+
|
|
62
|
+
path = Path(path_candidate)
|
|
63
|
+
|
|
64
|
+
if not path.exists():
|
|
65
|
+
description = f"Path candidate ({path_candidate}) does not exist"
|
|
66
|
+
raise ValueError(description)
|
|
67
|
+
|
|
68
|
+
if is_dir_expected and not path.is_dir():
|
|
69
|
+
description = (
|
|
70
|
+
f"Expected a dir for ({path_candidate}) but this is not a dir"
|
|
71
|
+
)
|
|
72
|
+
raise ValueError(description)
|
|
73
|
+
|
|
74
|
+
if is_file_expected and not path.is_file():
|
|
75
|
+
description = (
|
|
76
|
+
f"Expected a file for ({path_candidate}) but path not a file"
|
|
77
|
+
f"candidate is not a file {path_candidate}"
|
|
78
|
+
)
|
|
79
|
+
raise ValueError(description)
|
|
80
|
+
|
|
81
|
+
return path
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def get_logging_config(logging_config_path: Path) -> dict:
|
|
85
|
+
with logging_config_path.open(
|
|
86
|
+
"r", errors="strict", encoding=FileImporter.encoding
|
|
87
|
+
) as file:
|
|
88
|
+
return yaml.safe_load(file)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def get_project_root() -> Path:
|
|
92
|
+
"""
|
|
93
|
+
Gets the root of this project
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
pathlib.Path: The project's root
|
|
97
|
+
"""
|
|
98
|
+
return Path(__file__).parent.parent.parent
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def get_pyproject() -> dict:
|
|
102
|
+
return toml.load(
|
|
103
|
+
FileImporter.get_project_root().parent / "pyproject.toml"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def save_hash(crc_path: Path, hash_dto: list[HashDTO]) -> None:
|
|
108
|
+
with crc_path.open(
|
|
109
|
+
"w", errors="strict", encoding=FileImporter.encoding
|
|
110
|
+
) as file:
|
|
111
|
+
hash_data = HashSerializer.to_json(hash_dto)
|
|
112
|
+
json.dump(hash_data, file, indent=4)
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def save_hash_diff_report(
|
|
116
|
+
report_path: Path, hash_diff_report_dto: HashDiffReportDTO
|
|
117
|
+
) -> None:
|
|
118
|
+
with report_path.open(
|
|
119
|
+
"w", errors="strict", encoding=FileImporter.encoding
|
|
120
|
+
) as file:
|
|
121
|
+
hash_data = HashDiffReportSerializer.to_json(hash_diff_report_dto)
|
|
122
|
+
json.dump(hash_data, file, indent=4)
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def get_hash(crc_path: Path) -> list[HashDTO]:
|
|
126
|
+
with crc_path.open(
|
|
127
|
+
"r", errors="strict", encoding=FileImporter.encoding
|
|
128
|
+
) as file:
|
|
129
|
+
return HashSerializer.to_dto(json.load(file))
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def bootstrap() -> BootstrapPathsDTO:
|
|
133
|
+
try:
|
|
134
|
+
home_folder = Path()
|
|
135
|
+
system = platform.system()
|
|
136
|
+
|
|
137
|
+
if system == "Windows":
|
|
138
|
+
csidl_personal = 5
|
|
139
|
+
shgfp_type_current = 0
|
|
140
|
+
|
|
141
|
+
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
|
|
142
|
+
ctypes.windll.shell32.SHGetFolderPathW( # pyright: ignore # noqa: PGH003
|
|
143
|
+
None, csidl_personal, None, shgfp_type_current, buf
|
|
144
|
+
)
|
|
145
|
+
home_folder = buf.value or ""
|
|
146
|
+
if not home_folder:
|
|
147
|
+
description = "Could not locate Documents folder"
|
|
148
|
+
raise FileNotFoundError(description) # noqa: TRY301
|
|
149
|
+
elif system == "Linux":
|
|
150
|
+
home_folder = os.getenv("HOME") or ""
|
|
151
|
+
else:
|
|
152
|
+
description = f"Unsupported OS: {system}"
|
|
153
|
+
raise OSError(description) # noqa: TRY301
|
|
154
|
+
|
|
155
|
+
crcutil_dir = Path(home_folder) / "crcutil"
|
|
156
|
+
log_dir = crcutil_dir / "log"
|
|
157
|
+
hash_file = crcutil_dir / "hash.json"
|
|
158
|
+
report_file = crcutil_dir / "diff.json"
|
|
159
|
+
|
|
160
|
+
crcutil_dir.mkdir(exist_ok=True)
|
|
161
|
+
log_dir.mkdir(exist_ok=True)
|
|
162
|
+
|
|
163
|
+
return BootstrapPathsDTO(
|
|
164
|
+
log_dir=log_dir, hash_file=hash_file, report_file=report_file
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
except Exception as e:
|
|
168
|
+
if platform.system == "Windows":
|
|
169
|
+
win32evtlogutil.ReportEvent( # pyright: ignore # noqa: PGH003
|
|
170
|
+
"plexutil",
|
|
171
|
+
eventID=1,
|
|
172
|
+
eventType=win32evtlog.EVENTLOG_ERROR_TYPE, # pyright: ignore # noqa: PGH003
|
|
173
|
+
strings=[""],
|
|
174
|
+
)
|
|
175
|
+
if e.args and len(e.args) >= 0:
|
|
176
|
+
raise BootstrapError(e.args[0]) from e
|
|
177
|
+
|
|
178
|
+
raise BootstrapError from e
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pynput import keyboard
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class KeyboardMonitor:
|
|
7
|
+
def __init__(self) -> None:
|
|
8
|
+
self.is_paused = False
|
|
9
|
+
self.is_quit = False
|
|
10
|
+
self.listener = None
|
|
11
|
+
|
|
12
|
+
def start(self) -> None:
|
|
13
|
+
self.listener = keyboard.Listener(on_press=self.on_press)
|
|
14
|
+
self.listener.start()
|
|
15
|
+
|
|
16
|
+
def stop(self) -> None:
|
|
17
|
+
if self.listener:
|
|
18
|
+
self.listener.stop()
|
|
19
|
+
self.is_quit = True
|
|
20
|
+
|
|
21
|
+
def on_press(self, key: keyboard.Key | keyboard.KeyCode | None) -> None:
|
|
22
|
+
try:
|
|
23
|
+
if key == keyboard.KeyCode.from_char("p"):
|
|
24
|
+
self.is_paused = not self.is_paused
|
|
25
|
+
if key == keyboard.KeyCode.from_char("q"):
|
|
26
|
+
self.stop()
|
|
27
|
+
except AttributeError:
|
|
28
|
+
pass
|
crcutil/util/static.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 CARLOS FLOREZ
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: crcutil
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Author-email: Carlos Florez <carlos@florez.co.uk>
|
|
5
|
+
Maintainer-email: Carlos Florez <carlos@florez.co.uk>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 CARLOS FLOREZ
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Repository, https://github.com/florez-carlos/crcutil
|
|
29
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
30
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
31
|
+
Requires-Python: >=3.11.6
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
License-File: LICENSE
|
|
34
|
+
Requires-Dist: alive-progress==3.1.5
|
|
35
|
+
Requires-Dist: pyyaml==6.0.1
|
|
36
|
+
Requires-Dist: toml==0.10.2
|
|
37
|
+
Requires-Dist: pywin32==306; sys_platform == "win32"
|
|
38
|
+
Requires-Dist: jsonschema==4.23.0
|
|
39
|
+
Requires-Dist: colorlog==6.4.0
|
|
40
|
+
Requires-Dist: pynput==1.7.7
|
|
41
|
+
|
|
42
|
+
# CRCUtil
|
|
43
|
+
Recursively traverses a given location and generates a hash.json containing a CRC value for every encountered file/dir
|
|
44
|
+
|
|
45
|
+
> [!NOTE]
|
|
46
|
+
> Installation is supported only for the following:
|
|
47
|
+
> - Windows
|
|
48
|
+
> - Linux
|
|
49
|
+
|
|
50
|
+
> [!NOTE]
|
|
51
|
+
> Development requires a fully configured [Dotfiles](https://github.com/florez-carlos/dotfiles) dev environment <br>
|
|
52
|
+
|
|
53
|
+
## Table of Contents
|
|
54
|
+
|
|
55
|
+
* [Installation](#installation)
|
|
56
|
+
* [pip](#pip)
|
|
57
|
+
* [Usage](#usage)
|
|
58
|
+
* [hash](#hash)
|
|
59
|
+
* [diff](#diff)
|
|
60
|
+
* [pause/resume](#pauseresume)
|
|
61
|
+
* [Development](#development)
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
### Pip
|
|
65
|
+
```bash
|
|
66
|
+
python3 -m pip install crcutil
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Usage
|
|
70
|
+
|
|
71
|
+
### Hash
|
|
72
|
+
|
|
73
|
+
-l The location for which to generate the hash
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
crcutil hash -l C:\DESIRED\PATH
|
|
77
|
+
```
|
|
78
|
+
This will generate a hash.json file in: <br >
|
|
79
|
+
- Windows
|
|
80
|
+
```bash
|
|
81
|
+
C:\Users\<USERNAME>\Documents\crcutil\
|
|
82
|
+
```
|
|
83
|
+
- Linux
|
|
84
|
+
```bash
|
|
85
|
+
$HOME/crcutil
|
|
86
|
+
```
|
|
87
|
+
### Diff
|
|
88
|
+
If you hold 2 hashes generated from the same directory and would like to compare the differences.
|
|
89
|
+
|
|
90
|
+
-l The location of both hash files to compare
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
crcutil diff -l C:\HASH_FILE_1.json C:\HASH_FILE_2.json
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
This will compare both hash files and generate a diff.json in:
|
|
97
|
+
- Windows
|
|
98
|
+
```bash
|
|
99
|
+
C:\Users\<USERNAME>\Documents\crcutil\
|
|
100
|
+
```
|
|
101
|
+
- Linux
|
|
102
|
+
```bash
|
|
103
|
+
$HOME/crcutil
|
|
104
|
+
```
|
|
105
|
+
### Pause/Resume
|
|
106
|
+
- The program can be paused/resumed at any time by pressing p, if a CRC is being calculated for a file
|
|
107
|
+
you have to wait for the calculation to complete before the program can pause.
|
|
108
|
+
- If you exit the program or it crashes unexpectedly mid operation, invoke the same command and the program will continue where it left off,
|
|
109
|
+
as long as the hash file is not corrupted
|
|
110
|
+
|
|
111
|
+
## Development
|
|
112
|
+
|
|
113
|
+
> [!NOTE]
|
|
114
|
+
> Development requires a fully configured [Dotfiles](https://github.com/florez-carlos/dotfiles) dev environment <br>
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
source init.sh
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
crcutil/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
crcutil/__main__.py,sha256=CfFljouHtIG0HSn7jPl5B3xMg-z40iI4NaxVDWb7LQo,3786
|
|
3
|
+
crcutil/config/log_config.yaml,sha256=4hF_bhxLU2zSVY4hH-3jlNokbQ74n7jMimi8SMJqoAg,1827
|
|
4
|
+
crcutil/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
crcutil/core/crc.py,sha256=qHawylqr3Ax0gElkLtqWof_19vSZOI9WdrE3h6F1HPI,9868
|
|
6
|
+
crcutil/core/prompt.py,sha256=SM8iCheD_WU_3tFDedf1_mUCwRLedCk_DwTxLF7GnVE,5621
|
|
7
|
+
crcutil/dto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
crcutil/dto/bootstrap_paths_dto.py,sha256=yddkNWf9bjK2nQX5b8RgMOy5V7AN56ff99HNHuK-VpQ,242
|
|
9
|
+
crcutil/dto/hash_diff_report_dto.py,sha256=JhkHt5aQMVthSIQ4_uRraR7SEgytLbEn8W6HuNhufmM,377
|
|
10
|
+
crcutil/dto/hash_dto.py,sha256=QengNw1dd4o0zRHnf8ZsAS1jnQmlQmFW8tOpbhiMvNc,210
|
|
11
|
+
crcutil/dto/user_instructions_dto.py,sha256=4dp-XBitsjgeqZn69cAnQfeGoADB9qanG8n84guRrm0,408
|
|
12
|
+
crcutil/enums/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
crcutil/enums/user_request.py,sha256=yOR5hk7XJGHBFboDxrD4sj_WPnu9Vl1jZ6ruNInNUS8,643
|
|
14
|
+
crcutil/exception/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
+
crcutil/exception/bootstrap_error.py,sha256=qB0xmmoJ-b44CPAvAyvUTWmnbmu6WL_Wawvs-5ZHdcY,42
|
|
16
|
+
crcutil/exception/corrupt_hash_error.py,sha256=JaGdMvILUjx5cKd_Xc-9n_kfrGlZ_nuMWl10aOB-yS8,44
|
|
17
|
+
crcutil/exception/unexpected_argument_error.py,sha256=YCqbzCmRwwESV0GjI_r9G3sUUWUI7bZygS21xyrFQ6Y,51
|
|
18
|
+
crcutil/exception/user_error.py,sha256=g1b20vkPUokp1cOBW0IQlZx7y-yqOQJHSkI-nGXzcOY,37
|
|
19
|
+
crcutil/serializer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
20
|
+
crcutil/serializer/hash_diff_report_serializer.py,sha256=_Y7Uo7ps3OWw0zQOi6Ar34Kq-OyNvs9j56VbpR6VAoY,751
|
|
21
|
+
crcutil/serializer/hash_serializer.py,sha256=UoooePyREyfS_M3ltJmD1SVjOk2lRMiODf69MCSGyrE,420
|
|
22
|
+
crcutil/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
+
crcutil/util/crcutil_logger.py,sha256=2AKhPaHK5VTBHgrHQmYVr_ImnihjLuknUHb6dAjwnG8,1647
|
|
24
|
+
crcutil/util/file_importer.py,sha256=P2EyiUAjbeYhDnKVRyyLgO4PDLdX2IPzRMG-6qaomWs,5785
|
|
25
|
+
crcutil/util/keyboard_monitor.py,sha256=BbUXqXb2SHo8T1wJdUTuKnCW8mmqE8wmoVCjoDpB8ac,781
|
|
26
|
+
crcutil/util/static.py,sha256=vx9yPhRtfeEwFszrs7VHz38R_AukdXBr-J2VBVnRklw,169
|
|
27
|
+
crcutil-1.0.0.dist-info/LICENSE,sha256=VXEYCQROiczzjIGffiGDQGAUIKVWJwQQ84OQogJ3NsA,1070
|
|
28
|
+
crcutil-1.0.0.dist-info/METADATA,sha256=9U5p_q_VS278vp0EYCzJ4WHwhASMGNHMubkHvUzgxg0,3698
|
|
29
|
+
crcutil-1.0.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
30
|
+
crcutil-1.0.0.dist-info/entry_points.txt,sha256=CBOiMMOtkRvDjBre1UVuQY8Xfbt0QFILCI28NdW8fJc,50
|
|
31
|
+
crcutil-1.0.0.dist-info/top_level.txt,sha256=HXu4JGsGLsOKjs9kzsJ4rzyFSF_UEoiBXuy_qtq4zz0,8
|
|
32
|
+
crcutil-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
crcutil
|