zamm_yang 0.1.6

A basic, experimental code generator
Documentation
/// Logic for ignoring autogenerated files in Git.
mod git_ignore;

use crate::codegen::track_autogen::track_autogen;
use git_ignore::{git_ignore, git_rm};
use path_abs::PathAbs;
use std::fs;
use std::path::Path;

/// Config options for writing out to a file.
pub struct OutputConfig<'a> {
    /// The final generated code, to be output to a file verbatim.
    pub code: &'a str,
    /// The path to the output file.
    pub file_path: &'a str,
    /// Whether or not to ignore outputted files.
    pub git_ignore: bool,
    /// Whether or not to track generated files in Cargo.
    pub cargo_track: bool,
}

/// Output code to filename
pub fn output_code_verbatim(cfg: &OutputConfig) {
    let file_pathabs = PathAbs::new(Path::new(cfg.file_path))
        .unwrap_or_else(|_| panic!("Could not get absolute path for {}", cfg.file_path));
    let file_absolute = file_pathabs.as_path().to_str().unwrap();
    let file_parent = file_pathabs
        .as_path()
        .parent()
        .unwrap_or_else(|| panic!("Could not get parent directory for {}", file_absolute));
    fs::create_dir_all(file_parent).unwrap_or_else(|_| {
        panic!(
            "Could not create intermediate directories for {}",
            file_absolute
        )
    });
    git_rm(&file_absolute);
    fs::write(file_absolute, cfg.code)
        .unwrap_or_else(|_| panic!("Couldn't output generated code to {}", file_absolute));
    // track in .autogen for completeness, regardless of release options
    track_autogen(file_pathabs.as_path().to_str().unwrap().to_owned());
    if cfg.git_ignore {
        // don't ignore so that files can be added to Git and compiled on docs.rs, because docs.rs
        // does not allow the yang binary to be downloaded
        git_ignore(&file_pathabs).unwrap_or_else(|_| panic!("Could not ignore {}", file_absolute));
    }
    if cfg.cargo_track {
        // tell cargo to regenerate autogenerated files when they're edited or removed
        println!("cargo:rerun-if-changed={}", cfg.file_path);
    } else {
        println!("Generated {}", cfg.file_path);
    }
}