-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_cli.py
51 lines (43 loc) · 1.53 KB
/
app_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import argparse
import sys, os
from config import DIR_RESULTS
from sha256 import sha256
def parse_args(arguments: list) -> argparse.Namespace:
parser = argparse.ArgumentParser("sha256_cli")
parser.add_argument(
"input_string",
help="The input message or file path to be hashed.",
)
parser.add_argument(
"--output_file", "-o", help="Specify the output file to write the hash result."
)
parser.add_argument(
"--file",
"-f",
action="store_true",
help="If provided, treat the input string as a file path",
)
return parser.parse_args(arguments)
def hash_and_print(inp: str, output_file=None):
hashed = sha256.hash(inp)
if output_file:
if not os.path.exists(DIR_RESULTS):
os.makedirs(DIR_RESULTS)
with open(os.path.join(DIR_RESULTS, output_file), "w") as file:
file.write(hashed)
print(f"Hash result has been written to results/{output_file}")
else:
print(hashed)
def hash_from_file(input_filepath: str, output_file: str):
try:
with open(input_filepath, "r") as file:
input_content = file.read().strip()
hash_and_print(input_content, output_file)
except FileNotFoundError:
raise FileNotFoundError(f"File with input string not found - {input_filepath}")
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
if args.file:
hash_from_file(args.input_string, args.output_file)
else:
hash_and_print(args.input_string, args.output_file)