forked from gorilla-devs/ferium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
476 lines (460 loc) · 16.9 KB
/
main.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#![deny(
clippy::all,
clippy::perf,
clippy::cargo,
clippy::style,
clippy::pedantic,
clippy::suspicious,
clippy::complexity,
clippy::create_dir,
clippy::unwrap_used,
clippy::expect_used, // use anyhow::Context instead
clippy::correctness
)]
#![warn(clippy::dbg_macro, clippy::expect_used)]
#![allow(
clippy::cast_possible_truncation,
clippy::multiple_crate_versions,
clippy::large_enum_variant,
clippy::too_many_lines
)]
mod cli;
mod download;
mod subcommands;
use anyhow::{anyhow, bail, Context, Result};
use clap::{CommandFactory, Parser};
use cli::{Ferium, ModpackSubCommands, ProfileSubCommands, SubCommands};
use colored::{ColoredString, Colorize};
use dialoguer::theme::ColorfulTheme;
use ferinth::Ferinth;
use furse::Furse;
use indicatif::ProgressStyle;
use libium::config::{
self,
structs::{Config, ModIdentifier, Modpack, Profile},
};
use octocrab::OctocrabBuilder;
use once_cell::sync::Lazy;
use online::tokio::check;
use std::{
env::{var, var_os},
process::ExitCode,
};
use tokio::{runtime, task::JoinSet};
const CROSS: &str = "×";
pub static TICK: Lazy<ColoredString> = Lazy::new(|| "✓".green());
pub static YELLOW_TICK: Lazy<ColoredString> = Lazy::new(|| "✓".yellow());
pub static THEME: Lazy<ColorfulTheme> = Lazy::new(Default::default);
#[allow(clippy::expect_used)]
pub static STYLE_NO: Lazy<ProgressStyle> = Lazy::new(|| {
ProgressStyle::default_bar()
.template("{spinner} {elapsed} [{wide_bar:.cyan/blue}] {pos:.cyan}/{len:.blue}")
.expect("Progress bar template parse failure")
.progress_chars("#>-")
});
#[allow(clippy::expect_used)]
pub static STYLE_BYTE: Lazy<ProgressStyle> = Lazy::new(|| {
ProgressStyle::default_bar()
.template(
"{spinner} {bytes_per_sec} [{wide_bar:.cyan/blue}] {bytes:.cyan}/{total_bytes:.blue}",
)
.expect("Progress bar template parse failure")
.progress_chars("#>-")
});
fn main() -> ExitCode {
let cli = Ferium::parse();
let mut builder = runtime::Builder::new_multi_thread();
builder.enable_all();
builder.thread_name("ferium-worker");
if let Some(threads) = cli.threads {
builder.worker_threads(threads);
}
#[allow(clippy::expect_used)] // No error handling yet
let runtime = builder.build().expect("Could not initialise Tokio runtime");
if let Err(err) = runtime.block_on(actual_main(cli)) {
eprintln!("{}", err.to_string().red().bold());
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
async fn actual_main(cli_app: Ferium) -> Result<()> {
// The complete command should not require a config.
// See [#139](https://github.com/gorilla-devs/ferium/issues/139) for why this might be a problem.
if let SubCommands::Complete { shell } = cli_app.subcommand {
clap_complete::generate(
shell,
&mut Ferium::command(),
"ferium",
&mut std::io::stdout(),
);
return Ok(());
}
let github = cli_app
.github_token
.map_or_else(
|| {
var("GITHUB_TOKEN").map_or_else(
|_| OctocrabBuilder::new(),
|token| OctocrabBuilder::new().personal_token(token),
)
},
|token| OctocrabBuilder::new().personal_token(token),
)
.build()?;
let modrinth = Ferinth::new(
"ferium",
option_env!("CARGO_PKG_VERSION"),
Some("theRookieCoder#1287"),
None,
)?;
let curseforge = Furse::new(&cli_app.curseforge_api_key.unwrap_or_else(|| {
var("CURSEFORGE_API_KEY").unwrap_or_else(|_| {
"$2a$10$QbCxI6f4KxEs50QKwE2piu1t6oOA8ayOw27H9N/eaH3Sdp5NTWwvO".into()
})
}));
let mut config_file = config::get_file(
cli_app
.config_file
.or_else(|| var_os("FERIUM_CONFIG_FILE").map(Into::into))
.unwrap_or_else(config::file_path),
)
.await?;
let mut config = config::deserialise(&config::read_file(&mut config_file).await?)?;
// Run function(s) based on the sub(sub)command to be executed
match cli_app.subcommand {
SubCommands::Complete { .. } => unreachable!(),
SubCommands::Add {
identifier,
dont_check_game_version,
dont_check_mod_loader,
dependencies,
} => {
let profile = get_active_profile(&mut config)?;
check_internet().await?;
if let Ok(project_id) = identifier.parse::<i32>() {
subcommands::add::curseforge(
&curseforge,
project_id,
profile,
Some(!dont_check_game_version),
Some(!dont_check_mod_loader),
dependencies,
)
.await?;
} else if identifier.split('/').count() == 2 {
let split = identifier.split('/').collect::<Vec<_>>();
subcommands::add::github(
github.repos(split[0], split[1]),
profile,
Some(!dont_check_game_version),
Some(!dont_check_mod_loader),
)
.await?;
} else if let Err(err) = subcommands::add::modrinth(
&modrinth,
&identifier,
profile,
Some(!dont_check_game_version),
Some(!dont_check_mod_loader),
dependencies,
)
.await
{
return Err(
if err.to_string() == ferinth::Error::InvalidIDorSlug.to_string() {
anyhow!("Invalid indentifier")
} else {
err
},
);
}
}
SubCommands::List { verbose, markdown } => {
let profile = get_active_profile(&mut config)?;
check_empty_profile(profile)?;
if verbose {
check_internet().await?;
let mut tasks = JoinSet::new();
let mut mr_ids = Vec::<&str>::new();
for mod_ in &profile.mods {
if markdown {
match &mod_.identifier {
ModIdentifier::CurseForgeProject(project_id) => {
subcommands::list::curseforge_md(&curseforge, *project_id).await?;
}
ModIdentifier::ModrinthProject(project_id) => {
subcommands::list::modrinth_md(&modrinth, project_id.clone())
.await?;
}
ModIdentifier::GitHubRepository(full_name) => {
subcommands::list::github_md(&github, full_name.clone()).await?;
}
};
} else {
match &mod_.identifier {
ModIdentifier::CurseForgeProject(project_id) => {
tasks.spawn(subcommands::list::curseforge(
curseforge.clone(),
*project_id,
));
}
ModIdentifier::ModrinthProject(project_id) => mr_ids.push(project_id),
ModIdentifier::GitHubRepository(full_name) => {
tasks.spawn(subcommands::list::github(
github.clone(),
full_name.clone(),
));
}
};
}
}
eprint!("Querying Modrinth mod metadata... ");
let mr_projects = modrinth.get_multiple_projects(&mr_ids).await?;
let mr_teams_members = modrinth
.list_multiple_teams_members(
&mr_projects
.iter()
.map(|p| &p.team as &str)
.collect::<Vec<_>>(),
)
.await?;
println!("{}", &*TICK);
for (project, team_members) in
mr_projects.into_iter().zip(mr_teams_members.into_iter())
{
tasks.spawn(
async move { Ok(subcommands::list::modrinth(project, team_members)) },
);
}
while let Some(res) = tasks.join_next().await {
let (id, name) = res??;
profile
.mods
.iter_mut()
.find(|mod_| mod_.identifier == id)
.context("Could not find expected mod")?
.name = name;
}
} else {
for mod_ in &profile.mods {
println!(
"{:45} {}",
mod_.name.bold(),
match &mod_.identifier {
ModIdentifier::CurseForgeProject(id) =>
format!("{:10} {}", "CurseForge".red(), id.to_string().dimmed()),
ModIdentifier::ModrinthProject(id) =>
format!("{:10} {}", "Modrinth".green(), id.dimmed()),
ModIdentifier::GitHubRepository(name) => format!(
"{:10} {}",
"GitHub".purple(),
format!("{}/{}", name.0, name.1).dimmed()
),
},
);
}
}
}
SubCommands::Modpack { subcommand } => match subcommand {
ModpackSubCommands::Add {
identifier,
output_dir,
install_overrides,
} => {
check_internet().await?;
if let Ok(project_id) = identifier.parse::<i32>() {
subcommands::modpack::add::curseforge(
&curseforge,
&mut config,
project_id,
output_dir,
install_overrides,
)
.await?;
} else if let Err(err) = subcommands::modpack::add::modrinth(
&modrinth,
&mut config,
&identifier,
output_dir,
install_overrides,
)
.await
{
return Err(
if err.to_string() == ferinth::Error::InvalidIDorSlug.to_string() {
anyhow!("Invalid indentifier")
} else {
err
},
);
}
}
ModpackSubCommands::Configure {
output_dir,
install_overrides,
} => {
subcommands::modpack::configure(
get_active_modpack(&mut config)?,
output_dir,
install_overrides,
)?;
}
ModpackSubCommands::Delete { modpack_name } => {
subcommands::modpack::delete(&mut config, modpack_name)?;
}
ModpackSubCommands::List => {
if config.modpacks.is_empty() {
bail!("There are no modpacks configured, add a modpack using `ferium modpack add`")
}
subcommands::modpack::list(&config);
}
ModpackSubCommands::Switch { modpack_name } => {
subcommands::modpack::switch(&mut config, modpack_name)?;
}
ModpackSubCommands::Upgrade => {
check_internet().await?;
subcommands::modpack::upgrade(
&modrinth,
&curseforge,
get_active_modpack(&mut config)?,
)
.await?;
}
},
SubCommands::Profile { subcommand } => match subcommand {
ProfileSubCommands::Configure {
game_version,
mod_loader,
name,
output_dir,
} => {
check_internet().await?;
subcommands::profile::configure(
get_active_profile(&mut config)?,
game_version,
mod_loader,
name,
output_dir,
)
.await?;
}
ProfileSubCommands::Create {
import,
game_version,
mod_loader,
name,
output_dir,
} => {
if game_version.is_none() {
check_internet().await?;
}
subcommands::profile::create(
&mut config,
import,
game_version,
mod_loader,
name,
output_dir,
)
.await?;
}
ProfileSubCommands::Delete { profile_name } => {
subcommands::profile::delete(&mut config, profile_name)?;
}
ProfileSubCommands::List => {
if config.profiles.is_empty() {
bail!("There are no profiles configured, create a profile using `ferium profile create`")
}
subcommands::profile::list(&config);
}
ProfileSubCommands::Switch { profile_name } => {
subcommands::profile::switch(&mut config, profile_name)?;
}
},
SubCommands::Remove { mod_names } => {
let profile = get_active_profile(&mut config)?;
check_empty_profile(profile)?;
subcommands::remove(profile, mod_names)?;
}
SubCommands::Upgrade => {
check_internet().await?;
let profile = get_active_profile(&mut config)?;
check_empty_profile(profile)?;
subcommands::upgrade(modrinth, curseforge, github, profile).await?;
}
};
config.profiles.iter_mut().for_each(|profile| {
profile
.mods
.sort_unstable_by_key(|mod_| mod_.name.to_lowercase());
});
// Update config file with possibly edited config
config::write_file(&mut config_file, &config).await?;
Ok(())
}
/// Get the active profile with error handling
fn get_active_profile(config: &mut Config) -> Result<&mut Profile> {
match config.profiles.len() {
0 => {
bail!("There are no profiles configured, add a profile using `ferium profile create`")
}
1 => config.active_profile = 0,
n if n <= config.active_profile => {
println!(
"{}",
"Active profile specified incorrectly, please pick a profile to use"
.red()
.bold()
);
subcommands::profile::switch(config, None)?;
}
_ => (),
}
Ok(&mut config.profiles[config.active_profile])
}
/// Get the active modpack with error handling
fn get_active_modpack(config: &mut Config) -> Result<&mut Modpack> {
match config.modpacks.len() {
0 => bail!("There are no modpacks configured, add a modpack using `ferium modpack add`"),
1 => config.active_modpack = 0,
n if n <= config.active_modpack => {
println!(
"{}",
"Active modpack specified incorrectly, please pick a modpack to use"
.red()
.bold()
);
subcommands::modpack::switch(config, None)?;
}
_ => (),
}
Ok(&mut config.modpacks[config.active_modpack])
}
/// Check if `profile` is empty, and if so return an error
fn check_empty_profile(profile: &Profile) -> Result<()> {
if profile.mods.is_empty() {
bail!("Your currently selected profile is empty! Run `ferium help` to see how to add mods");
}
Ok(())
}
/// Check for an internet connection
async fn check_internet() -> Result<()> {
if check(Some(1)).await.is_err() {
// If it takes more than 1 second
// show that we're checking the internet connection
// and check for 4 more seconds
eprint!("Checking internet connection... ");
match check(Some(4)).await {
Ok(_) => {
println!("{}", *TICK);
Ok(())
}
Err(_) => Err(anyhow!(
"{CROSS} Ferium requires an internet connection to work"
)),
}
} else {
Ok(())
}
}