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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::fmt::Display;
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use walkdir::{WalkDir, DirEntry};
pub fn encode(buf: Vec<u8>) -> Result<String, String> {
Ok(*hex_d_hex::lower_hex(&buf))
}
pub fn decode(string: String) -> Result<Vec<u8>, String> {
let hex_vals = *hex_d_hex::dhex(&string);
Ok(hex_vals)
}
fn is_hidden(entry: &DirEntry) -> bool {
entry.file_name()
.to_str()
.map(|s| s.starts_with(".") && s != ".")
.unwrap_or(false)
}
pub fn capture<S: Display>(package_name: S, directory: S) -> Result<(), String> {
let mut output_rapture = match OpenOptions::new()
.create(true)
.write(true)
.open(format!("{}.rapt", package_name))
{
Ok(f) => Ok(f),
Err(e) => Err(format!("Could not open output rapture file: {}", e.to_string())),
}?;
match writeln!(output_rapture, "package {}", package_name.to_string()) {
Ok(_) => Ok(()),
Err(_) => Err(format!("Failed to write package declaration to file")),
}?;
for entry in WalkDir::new(directory.to_string())
.into_iter()
.filter_entry(|e| !is_hidden(e))
.filter_map(|e| {
let result = e.ok();
match result {
Some(f) => {
if f.file_type().is_dir() {
Some(f)
} else {
None
}
}
None => None,
}
})
{
let path = entry.path().display().to_string();
let instruction = format!("mkdir {}", path);
match writeln!(output_rapture, "{}", instruction) {
Ok(_) => Ok(()),
Err(_) => Err(format!("Failed to append {} to file {}", instruction, path)),
}?;
}
for entry in WalkDir::new(directory.to_string())
.into_iter()
.filter_entry(|e| !is_hidden(e))
.filter_map(|e| e.ok())
{
let path = entry.path().display().to_string();
let mut captured_file = File::open(path.clone());
match &mut captured_file {
Ok(f) => {
let mut contents: Vec<u8> = vec![];
match f.read_to_end(&mut contents) {
Ok(_) => {
let encoded_str = encode(contents)?;
let instruction = format!("write-hex {} {}", path, encoded_str);
match writeln!(output_rapture, "{}", instruction) {
Ok(_) => Ok(()),
Err(_) => Err(format!("Failed to append {} to file {}", instruction, path)),
}?;
}
Err(_) => {}
};
}
Err(_) => return Err(format!("Could not open file '{}' while capturing", path)),
}
}
Ok(())
}