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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::OptimisationProfile;
use anyhow::Context;
use fs_err as fs;
use globwalk::{GlobWalkerBuilder, WalkError};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::str::FromStr;
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct Skeleton {
pub manifests: Vec<Manifest>,
pub lock_file: Option<String>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
pub relative_path: PathBuf,
pub contents: String,
}
impl Skeleton {
pub fn derive<P: AsRef<Path>>(base_path: P) -> Result<Self, anyhow::Error> {
let walker = GlobWalkerBuilder::new(&base_path, "/**/Cargo.toml")
.build()
.context("Failed to scan the files in the current directory.")?;
let mut manifests = vec![];
for manifest in walker {
match manifest {
Ok(manifest) => {
let absolute_path = manifest.path().to_path_buf();
let contents = fs::read_to_string(&absolute_path)?;
let mut parsed = cargo_manifest::Manifest::from_str(&contents)?;
parsed.complete_from_path(&absolute_path)?;
let intermediate = toml::Value::try_from(parsed)?;
let contents = toml::to_string(&intermediate)?;
let relative_path = pathdiff::diff_paths(&absolute_path, &base_path)
.ok_or_else(|| {
anyhow::anyhow!(
"Failed to compute relative path of manifest {:?}",
&absolute_path
)
})?;
manifests.push(Manifest {
relative_path,
contents,
});
}
Err(e) => match handle_walk_error(e) {
ErrorStrategy::Ignore => {}
ErrorStrategy::Crash(e) => {
return Err(e.into());
}
},
}
}
let lock_file = match fs::read_to_string(base_path.as_ref().join("Cargo.lock")) {
Ok(lock) => Some(lock),
Err(e) => {
if std::io::ErrorKind::NotFound != e.kind() {
return Err(anyhow::Error::from(e).context("Failed to read Cargo.lock file."));
}
None
}
};
Ok(Skeleton {
manifests,
lock_file,
})
}
pub fn build_minimum_project(&self, base_path: &Path) -> Result<(), anyhow::Error> {
if let Some(lock_file) = &self.lock_file {
let lock_file_path = base_path.join("Cargo.lock");
fs::write(lock_file_path, lock_file.as_str())?;
}
for manifest in &self.manifests {
let manifest_path = base_path.join(&manifest.relative_path);
let parent_directory = if let Some(parent_directory) = manifest_path.parent() {
fs::create_dir_all(&parent_directory)?;
parent_directory.to_path_buf()
} else {
base_path.to_path_buf()
};
fs::write(&manifest_path, &manifest.contents)?;
let parsed_manifest =
cargo_manifest::Manifest::from_slice(manifest.contents.as_bytes())?;
for bin in &parsed_manifest.bin.unwrap_or_default() {
let binary_relative_path = bin.path.as_deref().unwrap_or("src/main.rs");
let binary_path = parent_directory.join(binary_relative_path);
if let Some(parent_directory) = binary_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(binary_path, "fn main() {}")?;
}
for lib in &parsed_manifest.lib {
let lib_relative_path = lib.path.as_deref().unwrap_or("src/lib.rs");
let lib_path = parent_directory.join(lib_relative_path);
if let Some(parent_directory) = lib_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(lib_path, "")?;
}
for bench in &parsed_manifest.bench.unwrap_or_default() {
let bench_name = bench.name.as_ref().context("Missing benchmark name.")?;
let bench_relative_path = bench
.path
.clone()
.unwrap_or_else(|| format!("benches/{}.rs", bench_name));
let bench_path = parent_directory.join(bench_relative_path);
if let Some(parent_directory) = bench_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(bench_path, "fn main() {}")?;
}
for test in &parsed_manifest.test.unwrap_or_default() {
let test_name = test.name.as_ref().context("Missing test name.")?;
let test_relative_path = test
.path
.clone()
.unwrap_or_else(|| format!("tests/{}.rs", test_name));
let test_path = parent_directory.join(test_relative_path);
if let Some(parent_directory) = test_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(test_path, "")?;
}
for example in &parsed_manifest.example.unwrap_or_default() {
let example_name = example.name.as_ref().context("Missing example name.")?;
let example_relative_path = example
.path
.clone()
.unwrap_or_else(|| format!("examples/{}.rs", example_name));
let example_path = parent_directory.join(example_relative_path);
if let Some(parent_directory) = example_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(example_path, "fn main() {}")?;
}
if let Some(package) = parsed_manifest.package {
if let Some(build) = package.build {
if let cargo_manifest::Value::String(build_raw_path) = build {
let build_relative_path = PathBuf::from(build_raw_path);
let build_path = parent_directory.join(build_relative_path);
if let Some(parent_directory) = build_path.parent() {
fs::create_dir_all(parent_directory)?;
}
fs::write(build_path, "fn main() {}")?;
}
}
}
}
Ok(())
}
pub fn remove_compiled_dummy_libraries<P: AsRef<Path>>(
&self,
base_path: P,
profile: OptimisationProfile,
target: Option<String>,
target_dir: Option<PathBuf>,
) -> Result<(), anyhow::Error> {
let mut target_dir = match target_dir {
None => base_path.as_ref().join("target"),
Some(target_dir) => target_dir,
};
if let Some(target) = target {
target_dir = target_dir.join(target.as_str())
}
let target_directory = match profile {
OptimisationProfile::Release => target_dir.join("release"),
OptimisationProfile::Debug => target_dir.join("debug"),
};
for manifest in &self.manifests {
let parsed_manifest =
cargo_manifest::Manifest::from_slice(manifest.contents.as_bytes())?;
for lib in &parsed_manifest.lib {
let library_name = lib
.name
.clone()
.unwrap_or_else(|| parsed_manifest.package.as_ref().unwrap().name.to_owned())
.replace("-", "_");
let walker =
GlobWalkerBuilder::new(&target_directory, format!("/**/lib{}*", library_name))
.build()?;
for file in walker {
let file = file?;
fs::remove_file(file.path())?;
}
}
}
Ok(())
}
}
enum ErrorStrategy {
Ignore,
Crash(WalkError),
}
#[must_use]
fn handle_walk_error(e: WalkError) -> ErrorStrategy {
if let Some(inner) = e.io_error() {
if std::io::ErrorKind::PermissionDenied == inner.kind() {
log::warn!("Missing permission to read entry: {}\nSkipping.", inner);
return ErrorStrategy::Ignore;
}
}
ErrorStrategy::Crash(e)
}