-
Notifications
You must be signed in to change notification settings - Fork 13
/
backend.rs
428 lines (381 loc) · 12.9 KB
/
backend.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use common::defines;
#[cfg(unix)]
use config::Config;
use eyre::Result;
#[cfg(unix)]
use once_cell::sync::Lazy;
#[cfg(all(target_arch = "x86_64", unix))]
use std::ffi::OsStr;
#[cfg(unix)]
use std::process::Command;
use std::{
fmt,
path::{Path, PathBuf},
};
#[cfg(unix)]
use tempfile::tempdir;
use cache::{self, Cache};
#[cfg(target_family = "unix")]
use common::utils::set_executable_bit;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendKind {
Hacpack,
Hactool,
#[cfg(all(
target_arch = "x86_64",
any(target_os = "windows", target_os = "linux")
))]
Hactoolnet,
Hac2l,
FourNXCI,
}
#[cfg(not(feature = "android-proot"))]
impl From<config::NspExtractor> for BackendKind {
fn from(value: config::NspExtractor) -> Self {
use config::NspExtractor;
match value {
NspExtractor::Hactoolnet => Self::Hactoolnet,
NspExtractor::Hactool => Self::Hactool,
}
}
}
#[cfg(not(feature = "android-proot"))]
impl From<config::NcaExtractor> for BackendKind {
fn from(value: config::NcaExtractor) -> Self {
use config::NcaExtractor;
match value {
NcaExtractor::Hactoolnet => Self::Hactoolnet,
NcaExtractor::Hac2l => Self::Hac2l,
}
}
}
impl fmt::Display for BackendKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl BackendKind {
// This is important, don't remove it again!
fn filename(&self) -> String {
#[cfg(unix)]
{
format!("{}", self).to_lowercase()
}
#[cfg(windows)]
{
format!("{}.exe", self).to_lowercase()
}
}
}
pub struct Backend {
kind: BackendKind,
path: PathBuf,
}
impl Backend {
/// Prefers embedded, builds only if binary not available.
pub fn try_new(kind: BackendKind) -> Result<Self> {
let filename = kind.filename();
let cache = Cache::default();
let cached_path = if let Ok(cached_path) = cache.get(&filename) {
cached_path
} else {
#[cfg(windows)]
{
match kind {
BackendKind::Hacpack => cache.store_bytes(defines::HACPACK, &filename)?,
BackendKind::Hactool => cache.store_bytes(defines::HACTOOL, &filename)?,
BackendKind::Hactoolnet => cache.store_bytes(defines::HACTOOLNET, &filename)?,
BackendKind::Hac2l => cache.store_bytes(defines::HAC2L, &filename)?,
BackendKind::FourNXCI => cache.store_bytes(defines::FOURNXCI, &filename)?,
}
}
#[cfg(unix)]
{
let cached_path = match kind {
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hacpack => Backend::build(kind)?.path,
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hactool => Backend::build(kind)?.path,
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hactoolnet => cache.store_bytes(defines::HACTOOLNET, &filename)?,
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hac2l => Backend::build(kind)?.path,
#[cfg(feature = "android-proot")]
BackendKind::Hacpack => cache.store_bytes(defines::HACPACK, &filename)?,
#[cfg(feature = "android-proot")]
BackendKind::Hactool => cache.store_bytes(defines::HACTOOL, &filename)?,
#[cfg(feature = "android-proot")]
BackendKind::Hac2l => cache.store_bytes(defines::HAC2L, &filename)?,
BackendKind::FourNXCI => cache.store_bytes(defines::FOURNXCI, &filename)?,
};
set_executable_bit(&cached_path, true)?;
cached_path
}
};
Ok(Self {
kind,
path: cached_path,
})
}
#[cfg(unix)]
/// Opposite of `try_new`.
pub fn build(kind: BackendKind) -> Result<Self> {
let cfg = Config::load()?;
let cache = Cache::default();
let cached_path = match kind {
BackendKind::Hacpack => cache.store_path(build::hacpack(&cfg.hacpack_rev)?)?,
BackendKind::Hactool => cache.store_path(build::hactool(&cfg.hactool_rev)?)?,
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hactoolnet => Backend::try_new(kind)?.path,
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
BackendKind::Hac2l => cache.store_path(build::hac2l(
["linux_x64_release"],
&cfg.atmosphere_rev,
&cfg.hac2l_rev,
)?)?,
#[cfg(feature = "android-proot")]
BackendKind::Hac2l => Backend::try_new(kind)?.path,
BackendKind::FourNXCI => cache.store_path(build::four_nxci(&cfg.four_nxci_rev)?)?,
};
set_executable_bit(&cached_path, true)?;
Ok(Self {
kind,
path: cached_path,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn kind(&self) -> BackendKind {
self.kind
}
}
#[cfg(unix)]
pub mod build {
use common::{defines::APP_CACHE_DIR, utils::move_file};
use eyre::{bail, eyre};
use fs_err as fs;
use tracing::info;
use super::*;
static NPROC: Lazy<Result<u8>> = Lazy::new(|| {
Ok(
String::from_utf8_lossy(&Command::new("nproc").output()?.stdout)
.trim()
.parse()?,
)
});
pub fn hacpack(rev: &str) -> Result<PathBuf> {
let kind = BackendKind::Hacpack;
info!("Building {}", kind);
let src_dir = tempdir()?;
if !Command::new("git")
.args(["clone", "https://github.com/The-4n/hacPack"])
.arg(src_dir.path())
.status()?
.success()
{
bail!("Failed to clone {} repo", kind);
}
git_checkout(src_dir.path(), rev)?;
info!("Renaming config file");
fs::rename(
src_dir.path().join("config.mk.template"),
src_dir.path().join("config.mk"),
)?;
info!("Running make");
if !Command::new("make")
.args([
"-j",
&(NPROC.as_ref().map_err(|err| eyre!(err))? / 2).to_string(),
])
.current_dir(&src_dir)
.status()?
.success()
{
bail!("Failed to build {}", kind);
}
//* Moving bin from temp dir to cache dir
let filename = kind.filename();
fs_err::create_dir_all(APP_CACHE_DIR.as_path())?;
let dest = APP_CACHE_DIR.join(&filename);
move_file(src_dir.path().join(&filename), &dest)?;
Ok(dest)
}
pub fn hactool(rev: &str) -> Result<PathBuf> {
let kind = BackendKind::Hactool;
info!("Building {}", kind);
let src_dir = tempdir()?;
if !Command::new("git")
.args(["clone", "https://github.com/SciresM/hactool"])
.arg(src_dir.path())
.status()?
.success()
{
bail!("Failed to clone {} repo", kind);
}
git_checkout(src_dir.path(), rev)?;
info!("Renaming config file");
fs::rename(
src_dir.path().join("config.mk.template"),
src_dir.path().join("config.mk"),
)?;
// removing line 372 as it causes build to fail on android
#[cfg(target_os = "android")]
{
use std::io::{BufRead, BufReader};
info!("Removing line 372 from `main.c`");
let reader = BufReader::new(fs::File::open(src_dir.path().join("main.c"))?);
//* can't use advance_by yet
let fixed_main = reader
.lines()
.enumerate()
.filter_map(|(i, ln)| {
if i != 371 {
// i.e ln 372
return Some(ln);
}
None
})
.collect::<Result<Vec<_>, _>>()?
.join("\n");
fs::write(src_dir.path().join("main.c"), fixed_main.as_bytes())?;
}
info!("Running make");
if !Command::new("make")
.args([
"-j",
&(NPROC.as_ref().map_err(|err| eyre!(err))? / 2).to_string(),
])
.current_dir(&src_dir)
.status()?
.success()
{
bail!("Failed to build {}", kind);
}
//* Moving bin from temp dir to cache dir
let filename = kind.filename();
fs_err::create_dir_all(APP_CACHE_DIR.as_path())?;
let dest = APP_CACHE_DIR.join(&filename);
move_file(src_dir.path().join(&filename), &dest)?;
Ok(dest)
}
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
pub fn hac2l<I, S>(args: I, atmosphere_rev: &str, hac2l_rev: &str) -> Result<PathBuf>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
use tracing::debug;
let kind = BackendKind::Hac2l;
info!("Building {}", kind);
let src_dir = tempdir()?;
if !Command::new("git")
.args(["clone", "https://github.com/Atmosphere-NX/Atmosphere.git"])
.arg(src_dir.path())
.status()?
.success()
{
bail!("Failed to clone Atmosphere repo");
}
git_checkout(src_dir.path(), atmosphere_rev)?;
let hac2l_src_dir = src_dir.path().join("tools/hac2l");
if !Command::new("git")
.args(["clone", "https://github.com/Atmosphere-NX/hac2l.git"])
.arg(&hac2l_src_dir)
.status()?
.success()
{
bail!("Failed to clone {} repo", kind);
}
if !Command::new("git")
.args(["checkout", hac2l_rev])
.current_dir(&hac2l_src_dir)
.status()?
.success()
{
bail!("Failed to checkout");
}
info!("Running make");
if !Command::new("make")
.args([
"-j",
&(NPROC.as_ref().map_err(|err| eyre!(err))? / 2).to_string(),
])
.args(args)
.current_dir(&hac2l_src_dir)
.status()?
.success()
{
bail!("Failed to build {}", kind);
}
//* Moving bin from temp dir to cache dir
let filename = kind.filename();
fs_err::create_dir_all(APP_CACHE_DIR.as_path())?;
let dest = APP_CACHE_DIR.join(&filename);
for entry in walkdir::WalkDir::new(hac2l_src_dir.join("out"))
.min_depth(1)
.contents_first(true)
.into_iter()
.filter_map(|e| e.ok())
{
debug!(
?entry,
is_file = entry.file_type().is_file(),
parent_is_release = entry.path().parent().unwrap().ends_with("release")
);
if entry.file_type().is_file() && entry.path().parent().unwrap().ends_with("release") {
move_file(entry.path(), &dest)?;
return Ok(dest);
}
}
bail!("Failed to build {}", kind);
}
pub fn four_nxci(rev: &str) -> Result<PathBuf> {
let kind = BackendKind::FourNXCI;
info!("Building {}", kind);
let src_dir = tempdir()?;
if !Command::new("git")
.args(["clone", "https://github.com/The-4n/4NXCI.git"])
.arg(src_dir.path())
.status()?
.success()
{
bail!("Failed to clone {} repo", kind)
}
git_checkout(src_dir.path(), rev)?;
info!("Renaming config file");
fs::rename(
src_dir.path().join("config.mk.template"),
src_dir.path().join("config.mk"),
)?;
info!("Running make");
if !Command::new("make")
.args([
"-j",
&(NPROC.as_ref().map_err(|err| eyre!(err))? / 2).to_string(),
])
.current_dir(&src_dir)
.status()?
.success()
{
bail!("Failed to build {}", kind);
}
//* Moving bin from temp dir to cache dir
let filename = kind.filename();
fs_err::create_dir_all(APP_CACHE_DIR.as_path())?;
let dest = APP_CACHE_DIR.join(&filename);
move_file(src_dir.path().join(&filename), &dest)?;
Ok(dest)
}
fn git_checkout<P: AsRef<Path>>(repo: P, rev: &str) -> Result<()> {
if Command::new("git")
.args(["checkout", rev])
.current_dir(repo)
.status()?
.success()
{
return Ok(());
}
bail!("Failed to checkout");
}
}