papa 2.1.1

A cli mod manager for the Northstar launcher
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
pub mod actions;
pub mod config;
#[cfg(feature = "northstar")]
pub mod northstar;

pub(crate) mod utils;

use std::fs;

use directories::ProjectDirs;
use log::{debug, trace};
use regex::Regex;
use rustyline::Editor;

use self::config::Config;
use crate::api;
use crate::api::model::{self, Cache, InstalledMod, Mod};

use anyhow::{anyhow, Result};

pub struct Core {
    pub config: Config,
    dirs: ProjectDirs,
    rl: Editor<()>,
    cache: Cache,
}

impl Core {
    pub fn new(config: Config, dirs: ProjectDirs, rl: Editor<()>) -> Self {
        utils::ensure_dirs(&dirs);
        let cache = Cache::build(dirs.cache_dir()).unwrap();
        Core {
            config,
            dirs,
            rl,
            cache,
        }
    }

    pub async fn update(&mut self, yes: bool) -> Result<()> {
        print!("Updating package index...");
        let index = &api::get_package_index().await?;
        println!(" Done!");
        let mut installed = utils::get_installed(self.config.mod_dir())?;
        let outdated: Vec<&model::Mod> = index
            .iter()
            .filter(|e| {
                installed.mods.iter().any(|i| {
                    i.package_name.trim() == e.name.trim() && i.version.trim() != e.version.trim()
                })
            })
            .collect();

        if outdated.is_empty() {
            println!("Already up to date!");
        } else {
            let size: i64 = outdated.iter().map(|f| f.file_size).sum();

            if !yes {
                if let Ok(line) = self.rl.readline(&format!(
                    "Will download ~{:.2} MB (compressed), okay? (This will overwrite any changes made to mod files) [Y/n]: ",
                    size as f64 / 1_048_576f64
                )) {
                    if line.to_lowercase() == "n" {
                        return Ok(());
                    }
                } else {
                    return Ok(());
                }
            }
            let mut downloaded = vec![];
            for base in outdated {
                let name = &base.name;
                let url = &base.url;
                let path = self.dirs.cache_dir().join(format!("{}.zip", name));
                match actions::download_file(url, path).await {
                    Ok(f) => downloaded.push(f),
                    Err(e) => eprintln!("{}", e),
                }
            }

            println!(
                "Extracting mod{} to {}...",
                if downloaded.len() > 1 { "s" } else { "" },
                self.config.mod_dir().display()
            );
            for f in downloaded.into_iter() {
                let mut pkg = actions::install_mod(&f, &self.config).unwrap();
                self.cache.clean(&pkg.package_name, &pkg.version)?;
                if let Some(i) = installed
                    .mods
                    .iter()
                    .position(|e| e.package_name == pkg.package_name)
                {
                    let mut inst = installed.mods.get_mut(i).unwrap();
                    inst.version = pkg.version;
                    //Don't know if sorting is needed here but seems like a good assumption
                    inst.mods
                        .sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
                    pkg.mods
                        .sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));

                    for (a, b) in inst.mods.iter().zip(pkg.mods.iter()) {
                        trace!("a mod: {:#?} | b mod: {:#?}", a, b);
                        if a.disabled() {
                            fs::remove_dir_all(&a.path).unwrap();
                            debug!(
                                "Moving mod from {} to {}",
                                b.path.display(),
                                a.path.display()
                            );
                            fs::rename(&b.path, &a.path).unwrap_or_else(|e| {
                                debug!("Unable to move sub-mod to old path");
                                debug!("{}", e);
                            });
                        }
                    }

                    inst.mods = pkg.mods;
                    println!("Updated {}", pkg.package_name);
                }
            }
            utils::save_installed(self.config.mod_dir(), &installed)?;
        }
        if let Some(current) = &self.config.nstar_version {
            if let Some(nmod) = index.iter().find(|e| e.name.to_lowercase() == "northstar") {
                if *current != nmod.version {
                    println!("An update for Northstar is available! \x1b[93m{}\x1b[0m -> \x1b[93m{}\x1b[0m", current, nmod.version);
                    println!("Run \"\x1b[96mpapa northstar update\x1b[0m\" to install it!");
                }
            }
        }
        Ok(())
    }

    pub fn list(&self) -> Result<()> {
        let mods = utils::get_installed(self.config.mod_dir())?.mods;
        if !mods.is_empty() {
            println!("Installed mods:");
            mods.into_iter().for_each(|m| {
                let disabled = if !m.any_disabled() || m.mods.len() > 1 {
                    ""
                } else {
                    "[disabled]"
                };
                println!(
                    " \x1b[92m{}@{}\x1b[0m {}",
                    m.package_name, m.version, disabled
                );
                if m.mods.len() > 1 {
                    for (i, e) in m.mods.iter().enumerate() {
                        let character = if i + 1 < m.mods.len() { "├" } else { "└" };
                        let disabled = if e.disabled() { "[disabled]" } else { "" };
                        println!(
                            "   \x1b[92m{}─\x1b[0m \x1b[0;96m{}\x1b[0m {}",
                            character, e.name, disabled
                        );
                    }
                }
            });
        } else {
            println!("No mods currently installed");
        }

        Ok(())
    }

    pub async fn install_from_url(&self, url: String) -> Result<()> {
        let file_name = url
            .as_str()
            .replace(':', "")
            .split('/')
            .collect::<Vec<&str>>()
            .join("");
        println!("Downloading to {}", file_name);
        let path = self.dirs.cache_dir().join(file_name);
        match actions::download_file(url.to_string().as_str(), path.clone()).await {
            Ok(f) => {
                let _pkg = actions::install_mod(&f, &self.config).unwrap();
                utils::remove_file(&path)?;
                println!("Installed {}", url);
            }
            Err(e) => eprintln!("{}", e),
        }

        Ok(())
    }

    pub async fn install(&mut self, mod_names: Vec<String>, yes: bool, force: bool) -> Result<()> {
        let index = utils::update_index(self.config.mod_dir()).await;
        let mut installed = utils::get_installed(self.config.mod_dir())?;
        let mut valid = vec![];
        for name in mod_names {
            let re = Regex::new(r"(.+)@?(v?\d.\d.\d)?").unwrap();

            if !re.is_match(&name) {
                println!("{} should be in 'ModName@1.2.3' format", name);
                continue;
            }

            let parts = re.captures(&name).unwrap();

            let base = index
                .iter()
                .find(|e| e.name.to_lowercase() == parts[1].to_lowercase())
                .ok_or_else(|| anyhow!("No such package {}", &parts[1]))?;

            if base.installed && !force {
                println!(
                    "Package \x1b[36m{}\x1b[0m version \x1b[36m{}\x1b[0m already installed",
                    base.name, base.version
                );
                continue;
            }

            utils::resolve_deps(&mut valid, base, &installed.mods, &index)?;
            valid.push(base);
        }

        //Gaurd against an empty list (maybe all the mods are already installed?)
        if valid.is_empty() {
            return Ok(());
        }

        let size: i64 = valid.iter().map(|f| f.file_size).sum();
        println!("Installing:\n");

        print!("\t");
        valid
            .iter()
            .for_each(|f| print!("\x1b[36m{}@{}\x1b[0m ", f.name, f.version));
        println!("\n");

        let msg = format!(
            "Will download ~{:.2} MIB (compressed), okay? [Y/n]: ",
            size as f64 / 1_048_576f64
        );

        if !yes {
            if let Ok(line) = self.rl.readline(&msg) {
                if line.to_lowercase() == "n" {
                    return Ok(());
                }
            } else {
                return Ok(());
            }
        }

        let mut downloaded = vec![];
        for base in valid {
            let name = &base.name;
            let path = self
                .dirs
                .cache_dir()
                .join(format!("{}_{}.zip", name, base.version));

            //would love to use this in the same if as the let but it's unstable so...
            if self.config.cache() {
                if let Some(f) = self.cache.check(&path) {
                    println!("Using cached version of {}", name);
                    downloaded.push(f);
                    continue;
                }
            }
            match actions::download_file(&base.url, path).await {
                Ok(f) => downloaded.push(f),
                Err(e) => eprintln!("{}", e),
            }
        }
        println!(
            "Extracting mod{} to {}",
            if downloaded.len() > 1 { "s" } else { "" },
            self.config.mod_dir().display()
        );
        for e in downloaded
            .iter()
            .map(|f| -> Result<()> {
                let pkg = actions::install_mod(f, &self.config)?;
                installed.mods.push(pkg.clone());
                self.cache.clean(&pkg.package_name, &pkg.version)?;
                println!("Installed {}", pkg.package_name);
                Ok(())
            })
            .filter(|f| f.is_err())
        {
            println!("Encountered errors while installing mods:");
            println!("{}", e.unwrap_err());
        }
        utils::save_installed(self.config.mod_dir(), &installed)?;
        Ok(())
    }

    pub fn remove(&self, mod_names: Vec<String>) -> Result<()> {
        let mut installed = utils::get_installed(self.config.mod_dir())?;
        let valid: Vec<InstalledMod> = mod_names
            .iter()
            .filter_map(|f| {
                installed
                    .mods
                    .iter()
                    .position(|e| e.package_name.trim().to_lowercase() == f.trim().to_lowercase())
                    .map(|i| installed.mods.swap_remove(i))
            })
            .collect();

        let paths = valid.iter().flat_map(|f| f.flatten_paths()).collect();

        actions::uninstall(paths)?;
        utils::save_installed(self.config.mod_dir(), &installed)?;
        Ok(())
    }

    pub fn clear(&self, full: bool) -> Result<()> {
        if full {
            println!("Clearing cache files...");
        } else {
            println!("Clearing cached packages...");
        }
        utils::clear_cache(self.dirs.cache_dir(), full)?;
        println!("Done!");

        Ok(())
    }

    pub fn update_config(&mut self, mods_dir: Option<String>, cache: Option<bool>) -> Result<()> {
        if let Some(dir) = mods_dir {
            self.config.set_dir(&dir);
            println!("Set install directory to {}", dir);
        }

        if let Some(cache) = cache {
            self.config.set_cache(&cache);
            if cache {
                println!("Turned caching on");
            } else {
                println!("Turned caching off");
            }
        }

        config::save_config(self.dirs.config_dir(), &self.config)?;
        Ok(())
    }

    pub(crate) async fn search(&self, term: Vec<String>) -> Result<()> {
        let index = utils::update_index(self.config.mod_dir()).await;

        let print = |f: &Mod| {
            println!(
                " \x1b[92m{}@{}\x1b[0m   [{}]{}\n\n    {}",
                f.name,
                f.version,
                f.file_size_string(),
                if f.installed { "[installed]" } else { "" },
                f.desc
            );
            println!();
        };

        println!("Searching...");
        println!();
        if !term.is_empty() {
            index
                .iter()
                .filter(|f| {
                    //TODO: Use better method to match strings
                    term.iter().any(|e| {
                        f.name.to_lowercase().contains(&e.to_lowercase())
                            || f.desc.to_lowercase().contains(&e.to_lowercase())
                    })
                })
                .for_each(print);
        } else {
            index.iter().for_each(print)
        }
        Ok(())
    }

    pub(crate) fn disable(&self, mods: Vec<String>) -> Result<()> {
        let mut installed = utils::get_installed(self.config.mod_dir())?;
        for m in mods {
            let m = m.to_lowercase();
            for i in installed.mods.iter_mut() {
                if i.package_name.to_lowercase() == m {
                    for sub in i.mods.iter_mut() {
                        utils::disable_mod(sub)?;
                    }
                    println!("Disabled {}", m);
                } else {
                    for e in i.mods.iter_mut() {
                        if e.name.to_lowercase() == m {
                            utils::disable_mod(e)?;
                            println!("Disabled {}", m);
                        }
                    }
                }
            }
        }
        utils::save_installed(self.config.mod_dir(), &installed)?;

        Ok(())
    }
    pub(crate) fn enable(&self, mods: Vec<String>) -> Result<()> {
        let mut installed = utils::get_installed(self.config.mod_dir())?;
        for m in mods {
            let m = m.to_lowercase();
            for i in installed.mods.iter_mut() {
                if i.package_name.to_lowercase() == m {
                    for sub in i.mods.iter_mut() {
                        utils::enable_mod(sub, self.config.mod_dir())?;
                    }
                    println!("Enabled {}", m);
                } else {
                    for e in i.mods.iter_mut() {
                        if e.name.to_lowercase() == m {
                            utils::enable_mod(e, self.config.mod_dir())?;
                            println!("Enabled {}", m);
                        }
                    }
                }
            }
        }

        utils::save_installed(self.config.mod_dir(), &installed)?;
        Ok(())
    }
}