gig/src/main.rs

91 lines
2.6 KiB
Rust

use figlet_rs::FIGfont;
use gig::{Args, Gitignore, GitignoreRepo, get_lang_from_file_name};
use clap::Parser;
use anyhow::{Result, Context};
use dialoguer::Select;
use tracing::{warn, info};
fn print_header() {
let standard_font = FIGfont::standard().unwrap();
let figure = standard_font.convert("gig");
if let Some(output) = figure {
println!("{}", output);
}
}
fn merge_gitignores(gitignores: Vec<Gitignore>) -> String {
let mut merged = String::new();
for gitignore in gitignores {
merged += format!("### {} ###\n", gitignore.language).as_str();
merged += gitignore.text.as_str();
merged += format!("### End of {} ###\n", gitignore.language).as_str();
merged += "\n";
}
merged
}
fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.with_target(false)
.with_ansi(true)
.init();
print_header();
let args = Args::parse();
let repository: GitignoreRepo = GitignoreRepo::new()?;
let mut used: Vec<String> = vec![];
for template in args.templates {
let possible: Vec<String> = repository.find(template.clone());
let chose: String;
if possible.len() > 1 {
let selection: usize = Select::new()
.with_prompt(format!("Which template do you mean by {}?", template))
.items(&possible)
.interact()
.with_context(|| "Failed to do a `Select` prompt.")?;
chose = possible[selection].clone();
} else if possible.is_empty() {
warn!("No template found for {}! Skipping...", template);
continue;
} else {
chose = possible[0].clone();
}
used.push(chose);
}
let gitignores: Vec<Gitignore> = used
.into_iter()
.filter_map(|path| {
let text = std::fs::read_to_string(&path).ok()?;
let language = get_lang_from_file_name(path);
Some(Gitignore { language, text })
})
.collect();
let names: Vec<String> = gitignores.iter().map(|g| g.language.clone()).collect();
let merged = merge_gitignores(gitignores);
std::fs::write(".gitignore", &merged)
.with_context(|| "Failed to write to .gitignore")?;
let names: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
let summary = match names.as_slice() {
[] => String::new(),
[a] => a.to_string(),
[a, b] => format!("{} and {}", a, b),
[rest @ .., last] => format!("{}, and {}", rest.join(", "), last),
};
info!("Created a .gitignore file with {}", summary);
Ok(())
}