cargo_new_aoc/
lib.rs

1use clap::Parser;
2use std::env;
3use std::fs;
4use std::path::Path;
5use std::process::Command;
6
7const MAIN_RS: &str = include_str!("main_rs_template.rs");
8
9/// A program that facilitates creating Rust projects for Advent of Code solutions
10#[derive(Parser, Debug)]
11pub struct Args {
12    /// Name of the project (will be run with `cargo new`)
13    name: String,
14}
15
16pub fn run(args: Args) {
17    println!("WARNING: NOT FULLY TESTED, SO USE WITH CAUTION");
18    let Args { name } = args;
19    let exec = &format!("cargo new {name}");
20    let status = if cfg!(target_os = "windows") {
21        Command::new("cmd").args(["/C", exec]).status()
22    } else {
23        Command::new("sh").args(["-c", exec]).status()
24    };
25    match status {
26        Ok(exit_status) => println!("cargo finished with status {exit_status}"),
27        Err(e) => return eprintln!("error: {e:?}; exiting"),
28    }
29    let project_dir = Path::new(&name);
30    match env::set_current_dir(project_dir) {
31        Ok(_) => println!("successfully changed cwd to {}", project_dir.display()),
32
33        Err(e) => {
34            return eprintln!(
35                "failed to change directory to {}: {e:?}",
36                project_dir.display()
37            )
38        }
39    }
40    match fs::write("src/main.rs", MAIN_RS) {
41        Ok(_) => println!("successfully wrote to src/main.rs"),
42        Err(e) => return eprintln!("failed to write to src/main.rs: {e:?}"),
43    }
44    println!(
45        "change directory into {} and happy coding!",
46        project_dir.display()
47    );
48}