1+ #!/usr/bin/python3
2+
3+ import argparse
4+ import os
5+ import sys
6+
7+ RED = "\033 [1;31m"
8+ WHITE = "\033 [0m"
9+ GREEN = "\033 [0;32m"
10+
11+ stderr = sys .stderr .write
12+ abort = sys .exit
13+
14+ parser = argparse .ArgumentParser (description = "Helper Tools For Lazyboard Project" )
15+ sub_parsers = parser .add_subparsers (dest = "command" )
16+
17+ def gen_to_hex (data : bytes ) -> str :
18+ return ", " .join (f"0x{ b :02x} " for b in data )
19+
20+ def file_name (file_str : str ) -> str :
21+ return os .path .basename (file_str )
22+
23+ def file_extension (file : str ) -> str :
24+ _ , extension = os .path .splitext (file )
25+
26+ return extension
27+
28+ def gen_res (args : argparse .Namespace ) -> None :
29+ file_path = args .path
30+ cxx_output = args .output
31+
32+ if not os .path .exists (file_path ):
33+ stderr (f"{ RED } error:{ WHITE } Resource file path { file_path } not found\n " )
34+ abort (1 )
35+
36+ if not file_extension (cxx_output ) == ".cxx" :
37+ cxx_output += ".hxx"
38+
39+ try :
40+ with open (file = file_path , mode = "rb" ) as image_file :
41+ read_bytes = gen_to_hex (image_file .read ())
42+
43+ with open (file = cxx_output , mode = "w" , encoding = "utf-8" ) as output :
44+ header_name = file_name (cxx_output ).upper ().replace ("." , "_" )
45+
46+ output .write (f"#ifndef { header_name } \n " )
47+ output .write (f"#define { header_name } \n \n " )
48+ output .write (f"#include <stdint.h>\n \n " )
49+ output .write ("#include <initializer_list>\n \n " )
50+ output .write ("using std::initializer_list;\n \n " )
51+ output .write (f"const initializer_list<uint8_t> image_bytes = {{\n " )
52+ output .write (f" " + read_bytes + "\n " )
53+ output .write ("};\n " )
54+
55+ output .write (f"#endif // { header_name } " )
56+
57+ print (f"{ GREEN } ok:{ WHITE } Generated successfully, can found header file at: { cxx_output } " )
58+
59+ except Exception as error :
60+ stderr (f"{ RED } error:{ WHITE } Exception error: { error } " )
61+
62+ def gen_resources_command () -> None :
63+ gen_res_cmd = sub_parsers .add_parser ("gen-res" , help = "Gen resource to C++ header" )
64+ gen_res_cmd .add_argument ("--path" , help = "Resource file path" )
65+ gen_res_cmd .add_argument ("--output" , help = "C++ source output" )
66+ gen_res_cmd .set_defaults (func = gen_res )
67+
68+ def main () -> None :
69+ gen_resources_command ()
70+ arguments = parser .parse_args ()
71+
72+ if hasattr (arguments , "func" ):
73+ arguments .func (arguments )
74+
75+ else :
76+ parser .print_help ()
77+
78+ main ()
0 commit comments