paru 1.11.0

Feature packed AUR helper
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
#![cfg_attr(feature = "backtrace", feature(backtrace))]

mod args;
mod chroot;
mod clean;
mod command_line;
mod completion;
mod config;
mod devel;
mod download;
mod exec;
mod fmt;
mod help;
mod info;
mod install;
mod keys;
mod news;
mod order;
mod query;
mod remove;
mod repo;
mod search;
mod stats;
mod sync;
mod upgrade;
mod util;

#[cfg(feature = "mock")]
mod mock;

#[cfg(not(feature = "mock"))]
type RaurHandle = raur::Handle;
#[cfg(feature = "mock")]
type RaurHandle = crate::mock::Mock;

#[macro_use]
extern crate smart_default;

use crate::chroot::Chroot;
use crate::config::{Config, Op};
use crate::query::print_upgrade_list;

use std::collections::HashMap;
use std::env;
use std::error::Error as StdError;
use std::fs::{read_dir, read_to_string};
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

use ansi_term::Style;
use anyhow::{bail, Error, Result};
use cini::Ini;
use tr::{tr, tr_init};

#[macro_export]
macro_rules! printtr {
    ($($tail:tt)* ) => {{
        println!("{}", ::tr::tr!($($tail)*));
    }};
}

fn debug_enabled() -> bool {
    env::var("PARU_DEBUG").as_deref().unwrap_or("0") != "0"
}

fn alpm_debug_enabled() -> bool {
    debug_enabled() && env::var("PARU_ALPM_DEBUG").as_deref().unwrap_or("1") != "0"
}

fn print_error(color: Style, err: Error) {
    #[cfg(feature = "backtrace")]
    {
        let backtrace = err.backtrace();

        if backtrace.status() == std::backtrace::BacktraceStatus::Captured {
            eprint!("{}", backtrace);
        }
    }
    let mut iter = err.chain().peekable();

    if <dyn StdError>::is::<exec::PacmanError>(*iter.peek().unwrap())
        || <dyn StdError>::is::<exec::Status>(*iter.peek().unwrap())
    {
        eprint!("{}", iter.peek().unwrap());
        return;
    }

    eprint!("{} ", color.paint(tr!("error:")));
    while let Some(link) = iter.next() {
        eprint!("{}", link);
        if iter.peek().is_some() {
            eprint!(": ");
        }
    }
    eprintln!();
}

pub async fn run<S: AsRef<str>>(args: &[S]) -> i32 {
    tr_init!(env::var("LOCALE_DIR")
        .as_deref()
        .unwrap_or("/usr/share/locale/"));
    if debug_enabled() {
        env_logger::Builder::new()
            .filter_level(log::LevelFilter::Debug)
            .format(|buf, record| {
                writeln!(
                    buf,
                    "{}: <{}> {}",
                    record.level().to_string().to_lowercase(),
                    record.module_path().unwrap_or("unknown"),
                    record.args()
                )
            })
            .format_timestamp(None)
            .init();
    }

    let _ = &*exec::DEFAULT_SIGNALS;
    let _ = &*exec::RAISE_SIGPIPE;

    let mut config = match Config::new() {
        Ok(config) => config,
        Err(err) => {
            print_error(Style::new(), err);
            return 1;
        }
    };

    match run2(&mut config, args).await {
        Err(err) => {
            print_error(config.color.error, err);
            1
        }
        Ok(ret) => ret,
    }
}

async fn run2<S: AsRef<str>>(config: &mut Config, args: &[S]) -> Result<i32> {
    if let Some(ref config_path) = config.config_path {
        let file = read_to_string(config_path)?;
        let name = config_path.display().to_string();
        config.parse(Some(name.as_str()), &file)?;
    };

    if args.is_empty() {
        config.parse_args(&["-Syu"])?;
    } else {
        config.parse_args(args)?;
    }

    handle_cmd(config).await
}

async fn handle_cmd(config: &mut Config) -> Result<i32> {
    if (config.op == Op::ChrootCtl || config.chroot)
        && Command::new("arch-nspawn").arg("-h").output().is_err()
    {
        bail!(tr!("can not use chroot builds: devtools is not installed"));
    }

    let ret = match config.op {
        Op::Database | Op::Files => exec::pacman(config, &config.args)?.code(),
        Op::Upgrade => handle_upgrade(config).await?,
        Op::Query => handle_query(config).await?,
        Op::Sync => handle_sync(config).await?,
        Op::Remove => handle_remove(config)?,
        Op::DepTest => handle_test(config).await?,
        Op::GetPkgBuild => handle_get_pkg_build(config).await?,
        Op::Show => handle_show(config).await?,
        Op::Yay => handle_yay(config).await?,
        Op::RepoCtl => handle_repo(config)?,
        Op::ChrootCtl => handle_chroot(config)?,
        // _ => bail!("unknown op '{}'", config.op),
    };

    Ok(ret)
}

async fn handle_upgrade(config: &mut Config) -> Result<i32> {
    if config.targets.is_empty() {
        install::build_pkgbuild(config).await
    } else {
        Ok(exec::pacman(config, &config.args)?.code())
    }
}

async fn handle_query(config: &mut Config) -> Result<i32> {
    let args = &config.args;
    if args.has_arg("u", "upgrades") {
        print_upgrade_list(config).await
    } else {
        Ok(exec::pacman(config, args)?.code())
    }
}

async fn handle_show(config: &mut Config) -> Result<i32> {
    if config.news > 0 {
        news::news(config).await
    } else if config.complete {
        Ok(completion::print(config, None).await)
    } else if config.stats {
        stats::stats(config).await
    } else if config.order {
        order::order(config).await
    } else {
        Ok(0)
    }
}

async fn handle_get_pkg_build(config: &mut Config) -> Result<i32> {
    if config.print {
        download::show_pkgbuilds(config).await
    } else if config.comments {
        download::show_comments(config).await
    } else {
        download::getpkgbuilds(config).await
    }
}

async fn handle_yay(config: &mut Config) -> Result<i32> {
    if config.gendb {
        devel::gendb(config).await?;
        Ok(0)
    } else if config.clean > 0 {
        config.need_root = true;
        let unneeded = util::unneeded_pkgs(config, config.clean == 1);
        if !unneeded.is_empty() {
            let mut args = config.pacman_args();
            args.remove("c").remove("clean");
            args.targets = unneeded;
            args.op = "remove";
            Ok(exec::pacman(config, &args)?.code())
        } else {
            printtr!(" there is nothing to do");
            Ok(0)
        }
    } else if !config.targets.is_empty() {
        search::search_install(config).await
    } else {
        bail!(tr!("no operation specified (use -h for help)"));
    }
}

fn handle_remove(config: &mut Config) -> Result<i32> {
    remove::remove(config)
}

async fn handle_test(config: &Config) -> Result<i32> {
    if config.aur_filter {
        sync::filter(config).await
    } else {
        Ok(exec::pacman(config, &config.args)?.code())
    }
}

async fn handle_sync(config: &mut Config) -> Result<i32> {
    if config.args.has_arg("i", "info") {
        info::info(config, config.args.count("i", "info") > 1).await
    } else if config.args.has_arg("c", "clean") {
        clean::clean(config)?;
        Ok(0)
    } else if config.args.has_arg("l", "list") {
        sync::list(config).await
    } else if config.args.has_arg("s", "search") {
        search::search(config).await
    } else if config.args.has_arg("g", "groups")
        || config.args.has_arg("p", "print")
        || config.args.has_arg("p", "print-format")
    {
        Ok(exec::pacman(config, &config.args)?.code())
    } else {
        let target = std::mem::take(&mut config.targets);
        install::install(config, &target).await
    }
}

fn handle_repo(config: &mut Config) -> Result<i32> {
    use std::os::unix::ffi::OsStrExt;

    let repoc = config.color.sl_repo;
    let pkgc = config.color.sl_pkg;
    let version = config.color.sl_version;
    let installedc = config.color.sl_installed;

    if config.clean >= 1 {
        repo::clean(config)?;
        return Ok(0);
    }

    let (_, repos) = repo::repo_aur_dbs(config);
    let repos = repos
        .into_iter()
        .map(|r| r.name().to_string())
        .filter(|r| config.delete >= 1 || config.targets.is_empty() || config.targets.contains(r))
        .collect::<Vec<_>>();

    if config.refresh || config.sysupgrade {
        repo::refresh(config, &repos)?;
    }

    let (_, mut repos) = repo::repo_aur_dbs(config);
    repos.retain(|r| {
        config.delete >= 1
            || config.uninstall
            || config.targets.is_empty()
            || config.targets.contains(&r.name().to_string())
    });

    if config.delete >= 1 {
        let mut remove = HashMap::<&str, Vec<&str>>::new();
        let mut rmfiles = Vec::new();
        for repo in &repos {
            for pkg in repo.pkgs() {
                if config.targets.iter().any(|p| p == pkg.name()) {
                    remove.entry(repo.name()).or_default().push(pkg.name());
                }
            }
        }

        let cb = config.alpm.take_raw_log_cb();
        for repo in &repos {
            if let Some(pkgs) = remove.get(&repo.name()) {
                let path = repo
                    .servers()
                    .first()
                    .unwrap()
                    .trim_start_matches("file://");
                repo::remove(config, path, repo.name(), pkgs)?;

                let files = read_dir(path)?;

                for file in files {
                    let file = file?;
                    if let Ok(pkg) = config.alpm.pkg_load(
                        file.path().as_os_str().as_bytes(),
                        false,
                        alpm::SigLevel::NONE,
                    ) {
                        if pkgs.contains(&pkg.name()) {
                            rmfiles.push(file.path());

                            let mut sig = file.path().to_path_buf().into_os_string();
                            sig.push(".sig");
                            let sig = PathBuf::from(sig);
                            if sig.exists() {
                                rmfiles.push(sig);
                            }
                        }
                    }
                }
            }
        }
        config.alpm.set_raw_log_cb(cb);

        if !rmfiles.is_empty() {
            let mut cmd = Command::new(&config.sudo_bin);
            cmd.arg("rm").args(rmfiles);
            exec::command(&mut cmd)?;
        }

        let repos = repos
            .into_iter()
            .map(|r| r.name().to_string())
            .collect::<Vec<_>>();
        repo::refresh(config, &repos)?;

        if config.delete >= 2 {
            config.need_root = true;
            let db = config.alpm.localdb();
            let pkgs = config
                .targets
                .iter()
                .map(|p| p.as_str())
                .filter(|p| db.pkg(*p).is_ok());

            let mut args = config.pacman_globals();
            args.op("remove");
            args.targets = pkgs.collect();
            if !args.targets.is_empty() {
                exec::pacman(config, &args)?.success()?;
            }
        }

        return Ok(0);
    }

    if config.refresh || config.sysupgrade {
        return Ok(0);
    }

    let (_, mut repos) = repo::repo_aur_dbs(config);
    repos.retain(|r| {
        config.delete >= 1
            || config.targets.is_empty()
            || config.targets.contains(&r.name().to_string())
    });

    for repo in repos {
        if config.list {
            for pkg in repo.pkgs() {
                if config.quiet {
                    println!("{}", pkg.name());
                } else {
                    print!(
                        "{} {} {}",
                        repoc.paint(repo.name()),
                        pkgc.paint(pkg.name()),
                        version.paint(pkg.version().as_str())
                    );
                    let local_pkg = config.alpm.localdb().pkg(pkg.name());

                    if let Ok(local_pkg) = local_pkg {
                        let installed = if local_pkg.version() != pkg.version() {
                            tr!(" [installed: {}]", local_pkg.version())
                        } else {
                            tr!(" [installed]")
                        };
                        print!("{}", installedc.paint(installed));
                    }
                    println!();
                }
            }
        } else if config.quiet {
            println!("{}", repo.name());
        } else {
            println!(
                "{} {}",
                repo.name(),
                repo.servers()
                    .first()
                    .unwrap()
                    .trim_start_matches("file://")
            );
        }
    }

    Ok(0)
}

fn handle_chroot(config: &Config) -> Result<i32> {
    let chroot = Chroot {
        path: config.chroot_dir.clone(),
        pacman_conf: config
            .pacman_conf
            .as_deref()
            .unwrap_or("/etc/pacman.conf")
            .to_string(),
        makepkg_conf: config
            .makepkg_conf
            .as_deref()
            .unwrap_or("/etc/makepkg.conf")
            .to_string(),
        mflags: config.mflags.clone(),
        ro: repo::all_files(config),
        rw: config.pacman.cache_dir.clone(),
    };

    if !chroot.exists() {
        chroot.create(config, &["base-devel"])?;
    }

    if config.sysupgrade {
        chroot.update()?;
    }

    if config.install {
        let mut args = vec!["pacman", "-S"];
        args.extend(config.targets.iter().map(|s| s.as_str()));
        chroot.run(&args)?;
    } else if !config.sysupgrade || !config.targets.is_empty() {
        chroot.run(&config.targets)?;
    }
    Ok(0)
}