1
1
use clap:: { App , Arg } ;
2
2
use serde:: { Deserialize , Serialize } ;
3
+ use serde_with:: base64:: Base64 ;
4
+ use serde_with:: serde_as;
3
5
use std:: env;
4
6
use std:: fs;
5
7
use std:: io:: { prelude:: * , Error as IOError , ErrorKind as IOErrorKind } ;
6
8
use std:: path:: Path ;
7
9
use std:: process:: Command ;
8
10
use tempdir:: TempDir ;
9
11
12
+ #[ serde_as]
13
+ #[ derive( Serialize , Deserialize , Debug ) ]
14
+ enum FileContent {
15
+ #[ serde( rename = "content" ) ]
16
+ Text ( String ) ,
17
+ #[ serde( rename = "binary-content" ) ]
18
+ Binary ( #[ serde_as( as = "Base64" ) ] Vec < u8 > ) ,
19
+ }
20
+
10
21
#[ derive( Serialize , Deserialize , Debug ) ]
11
22
struct FileNode {
12
23
name : String ,
13
- content : String ,
24
+ #[ serde( flatten) ]
25
+ content : FileContent ,
14
26
}
15
27
16
28
// The core data structure
@@ -33,7 +45,13 @@ fn dir_from_json(folder: &FolderNode, path: String) -> Result<(), IOError> {
33
45
folder. files . iter ( ) . for_each ( |file| {
34
46
println ! ( "Generating new file: {}{}" , & new_path, & file. name) ;
35
47
let mut file_handler = fs:: File :: create ( format ! ( "{}{}" , & new_path, & file. name) ) . unwrap ( ) ;
36
- let _ = file_handler. write_all ( file. content . as_bytes ( ) ) . unwrap ( ) ;
48
+
49
+ let bytes_to_write = match & file. content {
50
+ FileContent :: Text ( text) => text. as_bytes ( ) ,
51
+ FileContent :: Binary ( binary) => binary,
52
+ } ;
53
+
54
+ let _ = file_handler. write_all ( bytes_to_write) . unwrap ( ) ;
37
55
} ) ;
38
56
39
57
// base case [TODO: also handle if folder key does not exist]
@@ -70,10 +88,14 @@ fn json_from_dir(folder: &mut FolderNode, path: String) {
70
88
json_from_dir ( & mut f, new_path. clone ( ) ) ;
71
89
folder. folders . push ( f) ;
72
90
} else {
73
- if fs:: read_to_string ( path. path ( ) ) . is_err ( ) {
91
+ let file_content = if let Ok ( text) = fs:: read_to_string ( path. path ( ) ) {
92
+ FileContent :: Text ( text)
93
+ } else if let Ok ( binary) = fs:: read ( path. path ( ) ) {
94
+ FileContent :: Binary ( binary)
95
+ } else {
74
96
continue ;
75
- }
76
- let file_content = fs :: read_to_string ( path . path ( ) ) . unwrap ( ) ;
97
+ } ;
98
+
77
99
folder. files . push ( FileNode {
78
100
name : path
79
101
. path ( )
@@ -82,7 +104,7 @@ fn json_from_dir(folder: &mut FolderNode, path: String) {
82
104
. to_string_lossy ( )
83
105
. to_string ( ) ,
84
106
content : file_content,
85
- } )
107
+ } ) ;
86
108
}
87
109
}
88
110
}
0 commit comments