iocaine 3.4.0

The deadliest poison known to AI
// SPDX-FileCopyrightText: Gergely Nagy
// SPDX-FileContributor: Gergely Nagy
//
// SPDX-License-Identifier: MIT

use anyhow::Result;
use clap::Args;
use glob::Pattern;

use iocaine_powder::bullshit::SquashFS;

pub fn run(args: ShowEmbedArgs) -> Result<()> {
    let patterns = if args.patterns.is_empty() {
        Vec::from([Pattern::new("*")?])
    } else {
        args.patterns
    };

    let files: Vec<_> = SquashFS::iter()
        .filter(|name| patterns.iter().any(|pattern| pattern.matches(name)))
        .collect();

    for name in &files {
        if args.contents {
            if files.len() > 1 {
                println!("==> {name} <==");
            }
            // Allow unwrap() here, because the named file is guaranteed to
            // exist at this point.
            #[allow(clippy::unwrap_used)]
            let contents = SquashFS::get(name).unwrap();
            let contents = &String::from_utf8_lossy(&contents);
            println!("{contents}");
        } else {
            println!("{name}");
        }
    }

    if !files.is_empty() {
        return Ok(());
    }
    anyhow::bail!("No matching embedded files found");
}

#[derive(Clone, Debug, Args)]
pub struct ShowEmbedArgs {
    /// Show the contents of matching files, instead of their names.
    #[arg(short, long, default_value_t = false)]
    contents: bool,

    /// Filter the list to filenames matching any of the patterns.
    patterns: Vec<Pattern>,
}