-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathlib.rs
363 lines (329 loc) · 11.3 KB
/
lib.rs
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#![feature(let_chains)]
pub mod error;
pub mod gui;
pub mod integrate;
pub mod mod_lints;
pub mod providers;
pub mod state;
use std::io::{Cursor, Read};
use std::ops::Deref;
use std::str::FromStr;
use std::{
collections::HashSet,
path::{Path, PathBuf},
};
use anyhow::{Context, Result};
use directories::ProjectDirs;
use error::IntegrationError;
use integrate::IntegrationErr;
use providers::{ModResolution, ModSpecification, ProviderFactory, ReadSeek};
use state::State;
use tracing::{info, warn};
#[derive(Debug)]
pub struct Dirs {
pub config_dir: PathBuf,
pub cache_dir: PathBuf,
pub data_dir: PathBuf,
}
impl Dirs {
pub fn default_xdg() -> Result<Self> {
let legacy_dirs = ProjectDirs::from("", "", "drg-mod-integration")
.context("constructing project dirs")?;
let project_dirs =
ProjectDirs::from("", "", "mint").context("constructing project dirs")?;
Self::from_paths(
Some(legacy_dirs.config_dir())
.filter(|p| p.exists())
.unwrap_or(project_dirs.config_dir()),
Some(legacy_dirs.cache_dir())
.filter(|p| p.exists())
.unwrap_or(project_dirs.cache_dir()),
Some(legacy_dirs.data_dir())
.filter(|p| p.exists())
.unwrap_or(project_dirs.data_dir()),
)
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::from_paths(
path.as_ref().join("config"),
path.as_ref().join("cache"),
path.as_ref().join("data"),
)
}
fn from_paths<P: AsRef<Path>>(config_dir: P, cache_dir: P, data_dir: P) -> Result<Self> {
std::fs::create_dir_all(&config_dir)?;
std::fs::create_dir_all(&cache_dir)?;
std::fs::create_dir_all(&data_dir)?;
Ok(Self {
config_dir: config_dir.as_ref().to_path_buf(),
cache_dir: cache_dir.as_ref().to_path_buf(),
data_dir: data_dir.as_ref().to_path_buf(),
})
}
}
/// File::open with the file path included in any error messages
pub fn open_file<P: AsRef<Path>>(path: P) -> Result<std::fs::File> {
std::fs::File::open(&path)
.with_context(|| format!("Could not open file {}", path.as_ref().display()))
}
/// fs::read with the file path included in any error messages
pub fn read_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
std::fs::read(&path).with_context(|| format!("Could not read file {}", path.as_ref().display()))
}
/// fs::write with the file path included in any error messages
pub fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, data: C) -> Result<()> {
std::fs::write(&path, data)
.with_context(|| format!("Could not write to file {}", path.as_ref().display()))
}
pub fn is_drg_pak<P: AsRef<Path>>(path: P) -> Result<()> {
let mut reader = std::io::BufReader::new(open_file(path)?);
let pak = repak::PakBuilder::new().reader(&mut reader)?;
pak.get("FSD/FSD.uproject", &mut reader)?;
Ok(())
}
pub async fn resolve_unordered_and_integrate<P: AsRef<Path>>(
game_path: P,
state: &State,
mod_specs: &[ModSpecification],
update: bool,
) -> Result<(), IntegrationErr> {
let mods = state
.store
.resolve_mods(mod_specs, update)
.await
.map_err(|e| IntegrationErr {
mod_ctxt: None,
kind: integrate::IntegrationErrKind::Generic(e),
})?;
let mods_set = mod_specs
.iter()
.flat_map(|m| [&mods[m].spec.url, &mods[m].resolution.url.0])
.collect::<HashSet<_>>();
// TODO need more rebust way of detecting whether dependencies are missing
let missing_deps = mod_specs
.iter()
.flat_map(|m| {
mods[m]
.suggested_dependencies
.iter()
.filter_map(|m| (!mods_set.contains(&m.url)).then_some(&m.url))
})
.collect::<HashSet<_>>();
if !missing_deps.is_empty() {
warn!("the following dependencies are missing:");
for d in missing_deps {
warn!(" {d}");
}
}
let to_integrate = mod_specs
.iter()
.map(|u| mods[u].clone())
.collect::<Vec<_>>();
let urls = to_integrate
.iter()
.map(|m| m.resolution.clone())
.collect::<Vec<_>>();
info!("fetching mods...");
let paths = state
.store
.fetch_mods(&urls, update, None)
.await
.map_err(|e| IntegrationErr {
mod_ctxt: None,
kind: integrate::IntegrationErrKind::Generic(e),
})?;
integrate::integrate(
game_path,
state.config.deref().into(),
state.store.clone(),
to_integrate.into_iter().zip(paths).collect(),
)
}
async fn resolve_into_urls<'b>(
state: &State,
mod_specs: &[ModSpecification],
) -> Result<Vec<ModResolution>> {
let mods = state.store.resolve_mods(mod_specs, false).await?;
let mods_set = mod_specs
.iter()
.flat_map(|m| [&mods[m].spec.url, &mods[m].resolution.url.0])
.collect::<HashSet<_>>();
// TODO need more rebust way of detecting whether dependencies are missing
let missing_deps = mod_specs
.iter()
.flat_map(|m| {
mods[m]
.suggested_dependencies
.iter()
.filter_map(|m| (!mods_set.contains(&m.url)).then_some(&m.url))
})
.collect::<HashSet<_>>();
if !missing_deps.is_empty() {
warn!("the following dependencies are missing:");
for d in missing_deps {
warn!(" {d}");
}
}
let urls = mod_specs
.iter()
.map(|u| mods[u].clone())
.map(|m| m.resolution)
.collect::<Vec<_>>();
Ok(urls)
}
pub async fn resolve_ordered(
state: &State,
mod_specs: &[ModSpecification],
) -> Result<Vec<PathBuf>> {
let urls = resolve_into_urls(state, mod_specs).await?;
state.store.fetch_mods(&urls, false, None).await
}
pub async fn resolve_unordered_and_integrate_with_provider_init<P, F>(
game_path: P,
state: &mut State,
mod_specs: &[ModSpecification],
update: bool,
init: F,
) -> Result<()>
where
P: AsRef<Path>,
F: Fn(&mut State, String, &ProviderFactory) -> Result<()>,
{
loop {
match resolve_unordered_and_integrate(&game_path, state, mod_specs, update).await {
Ok(()) => return Ok(()),
Err(IntegrationErr { mod_ctxt, kind }) => match kind {
integrate::IntegrationErrKind::Generic(e) => match e.downcast::<IntegrationError>()
{
Ok(IntegrationError::NoProvider { url, factory }) => init(state, url, factory)?,
Err(e) => {
return Err(if let Some(mod_ctxt) = mod_ctxt {
e.context(format!("while working with mod `{:?}`", mod_ctxt))
} else {
e
})
}
},
integrate::IntegrationErrKind::Repak(e) => {
return Err(if let Some(mod_ctxt) = mod_ctxt {
anyhow::Error::from(e)
.context(format!("while working with mod `{:?}`", mod_ctxt))
} else {
e.into()
})
}
integrate::IntegrationErrKind::UnrealAsset(e) => {
return Err(if let Some(mod_ctxt) = mod_ctxt {
anyhow::Error::from(e)
.context(format!("while working with mod `{:?}`", mod_ctxt))
} else {
e.into()
})
}
},
}
}
}
#[allow(clippy::needless_pass_by_ref_mut)]
pub async fn resolve_ordered_with_provider_init<F>(
state: &mut State,
mod_specs: &[ModSpecification],
init: F,
) -> Result<Vec<PathBuf>>
where
F: Fn(&mut State, String, &ProviderFactory) -> Result<()>,
{
loop {
match resolve_ordered(state, mod_specs).await {
Ok(mod_paths) => return Ok(mod_paths),
Err(e) => match e.downcast::<IntegrationError>() {
Ok(IntegrationError::NoProvider { url, factory }) => init(state, url, factory)?,
Err(e) => return Err(e),
},
}
}
}
pub(crate) fn get_pak_from_data(mut data: Box<dyn ReadSeek>) -> Result<Box<dyn ReadSeek>> {
if let Ok(mut archive) = zip::ZipArchive::new(&mut data) {
(0..archive.len())
.map(|i| -> Result<Option<Box<dyn ReadSeek>>> {
let mut file = archive.by_index(i)?;
match file.enclosed_name() {
Some(p) => {
if file.is_file() && p.extension().filter(|e| e == &"pak").is_some() {
let mut buf = vec![];
file.read_to_end(&mut buf)?;
Ok(Some(Box::new(Cursor::new(buf))))
} else {
Ok(None)
}
}
None => Ok(None),
}
})
.find_map(Result::transpose)
.context("zip does not contain pak")?
} else {
data.rewind()?;
Ok(data)
}
}
pub(crate) enum PakOrNotPak {
Pak(Box<dyn ReadSeek>),
NotPak,
}
pub(crate) enum GetAllFilesFromDataError {
EmptyArchive,
OnlyNonPakFiles,
Other(anyhow::Error),
}
pub(crate) fn lint_get_all_files_from_data(
mut data: Box<dyn ReadSeek>,
) -> Result<Vec<(PathBuf, PakOrNotPak)>, GetAllFilesFromDataError> {
if let Ok(mut archive) = zip::ZipArchive::new(&mut data) {
if archive.is_empty() {
return Err(GetAllFilesFromDataError::EmptyArchive);
}
let mut files = Vec::new();
for i in 0..archive.len() {
let mut file = archive
.by_index(i)
.map_err(|e| GetAllFilesFromDataError::Other(e.into()))?;
if let Some(p) = file.enclosed_name().map(Path::to_path_buf) {
if file.is_file() {
if p.extension().filter(|e| e == &"pak").is_some() {
let mut buf = vec![];
file.read_to_end(&mut buf)
.map_err(|e| GetAllFilesFromDataError::Other(e.into()))?;
files.push((
p.to_path_buf(),
PakOrNotPak::Pak(Box::new(Cursor::new(buf))),
));
} else {
let mut buf = vec![];
file.read_to_end(&mut buf)
.map_err(|e| GetAllFilesFromDataError::Other(e.into()))?;
files.push((p.to_path_buf(), PakOrNotPak::NotPak));
}
}
}
}
if files
.iter()
.filter(|(_, pak_or_not_pak)| matches!(pak_or_not_pak, PakOrNotPak::Pak(..)))
.count()
>= 1
{
Ok(files)
} else {
Err(GetAllFilesFromDataError::OnlyNonPakFiles)
}
} else {
data.rewind()
.map_err(|e| GetAllFilesFromDataError::Other(e.into()))?;
Ok(vec![(
PathBuf::from_str(".").unwrap(),
PakOrNotPak::Pak(data),
)])
}
}