1
+ import os
2
+
3
+ # Reads and assembles the source code in the crate at the path `crate_root`.
4
+ # `crate_root` usually equals `basm/`.
5
+ def read_assemble (crate_root , target_language ):
6
+ sol_first = []
7
+ sol_all = []
8
+ crate_src_path = os .path .join (crate_root , "src/" )
9
+ for root , dirs , files in os .walk (crate_src_path ):
10
+ if os .path .abspath (root ).startswith (os .path .abspath (os .path .join (crate_src_path , "bin/" ))):
11
+ continue
12
+ for f in files :
13
+ f_path = os .path .join (root , f )
14
+ if f_path .endswith (".rs" ):
15
+ with open (f_path , encoding = 'utf8' ) as f :
16
+ sol = f .readlines ()
17
+ if os .path .abspath (f_path ) == os .path .abspath (os .path .join (crate_root , "src/solution.rs" )):
18
+ sol_first .append ((f_path , sol ))
19
+ else :
20
+ sol_all .append ((f_path , sol ))
21
+ sol_all = sol_first + sol_all
22
+ if len (sol_all ) == 1 :
23
+ sol_flat = sol_all [0 ][1 ]
24
+ else :
25
+ sol_flat = []
26
+ for i , (f_path , sol ) in enumerate (sol_all ):
27
+ if i > 0 :
28
+ sol_flat .append ("\n " )
29
+ sol_flat .append ("// {0}\n " .format (f_path ))
30
+ sol_flat .extend (sol )
31
+ if target_language in ["Rust" , "HTML" ]:
32
+ return assemble_as_is (sol_flat )
33
+ else :
34
+ return assemble_with_commenting (sol_flat )
35
+
36
+ def assemble_as_is (sol ):
37
+ sol = [line .replace ("\ufeff " , "" ) for line in sol ]
38
+ sol = [line .rstrip () + "\n " for line in sol ]
39
+ if len (sol ) > 0 :
40
+ sol [- 1 ] = sol [- 1 ].rstrip ()
41
+ sol = "" .join (sol )
42
+ return sol
43
+
44
+ def assemble_with_commenting (sol ):
45
+ sol_all = "" .join (sol )
46
+ sol_has_block_comment = "/*" in sol_all or "*/" in sol_all
47
+ if sol_has_block_comment :
48
+ prefix , begin , end = "//" , "" , ""
49
+ else :
50
+ prefix , begin , end = "" , "/*\n " , "*/\n "
51
+ sol = [line .replace ("\ufeff " , "" ) for line in sol ]
52
+ sol = [prefix + line .rstrip () + "\n " for line in sol ]
53
+ if len (begin ) > 0 :
54
+ sol = [begin ] + sol + [end ]
55
+ if len (sol ) > 0 :
56
+ sol [- 1 ] = sol [- 1 ].rstrip ()
57
+ sol = "" .join (sol )
58
+ return sol
0 commit comments