ecformat 0.1.0

command line tool to keep files correct in respect of your EditorConfig
// SPDX-FileCopyrightText: NONE
//
// SPDX-License-Identifier: CC0-1.0

use std::{env, fs, path::PathBuf, process::Command};

fn main() {
    // Prepare license information of dependencies
    // (only if not build as a dependency for use as lib crate)
    if "ecformat" == env!("CARGO_PKG_NAME") {
        let install_status = Command::new("cargo")
            .args(["install", "cargo-about", "--locked", "--version", "0.8.2"])
            .status()
            .expect("cargo-about needs to be installed");

        if !install_status.success() {
            panic!("cargo-about could not be installed. Exit code {install_status}");
        }

        let out_dir = env::var("OUT_DIR").expect("Output directory necessary");
        let md_path = [&out_dir, "about.md"].into_iter().collect::<PathBuf>();
        let about_status = Command::new("cargo")
            .args([
                "about",
                "generate",
                "--fail",
                "--locked",
                "-o",
                md_path.to_str().unwrap(),
                "about.hbs",
            ])
            .status()
            .expect("cargo-about needs to run");

        println!("cargo::rerun-if-changed=about.hbs");
        println!("cargo::rerun-if-changed=about.toml");
        if !about_status.success() {
            panic!("cargo-about failed with exit code {about_status}");
        }

        // Replace HTML escape sequences with the actual characters,
        // as markdown renderer do not replace every occurrent of them properly.
        // They are part of the license texts ({text} in `about.hbs`)
        // because the output is HTML by default.
        let markdown = fs::read_to_string(&md_path)
            .unwrap_or_else(|_| panic!("{} needs to be readable", md_path.display()));
        let markdown_unescaped = htmlize::unescape(markdown);

        fs::write(&md_path, markdown_unescaped.as_bytes())
            .unwrap_or_else(|_| panic!("{} needs to be writable", md_path.display()));
    }
}