bat/build.rs

82 lines
2.5 KiB
Rust
Raw Normal View History

2023-10-27 08:37:48 +02:00
use std::{collections::HashMap, fs, path::Path};
2020-03-30 18:43:13 +02:00
2023-10-31 06:45:40 +01:00
fn main() -> anyhow::Result<()> {
2023-10-27 08:37:48 +02:00
#[cfg(feature = "application")]
gen_man_and_comp()?;
Ok(())
}
2020-03-30 18:43:13 +02:00
2023-10-27 08:37:48 +02:00
/// Generate manpage and shell completions for the bat application.
#[cfg(feature = "application")]
fn gen_man_and_comp() -> anyhow::Result<()> {
2020-03-30 18:43:13 +02:00
// Read environment variables.
2020-04-24 16:16:36 +02:00
let project_name = option_env!("PROJECT_NAME").unwrap_or("bat");
let executable_name = option_env!("PROJECT_EXECUTABLE").unwrap_or(project_name);
2020-09-20 19:50:39 +02:00
let executable_name_uppercase = executable_name.to_uppercase();
2020-04-24 16:16:36 +02:00
static PROJECT_VERSION: &str = env!("CARGO_PKG_VERSION");
2020-03-30 18:43:13 +02:00
2020-09-20 19:50:39 +02:00
let mut variables = HashMap::new();
variables.insert("PROJECT_NAME", project_name);
variables.insert("PROJECT_EXECUTABLE", executable_name);
variables.insert("PROJECT_EXECUTABLE_UPPERCASE", &executable_name_uppercase);
variables.insert("PROJECT_VERSION", PROJECT_VERSION);
2023-10-31 06:45:40 +01:00
let Some(out_dir_env) =
std::env::var_os("BAT_ASSETS_GEN_DIR").or_else(|| std::env::var_os("OUT_DIR"))
else {
anyhow::bail!("BAT_ASSETS_GEN_DIR or OUT_DIR should be set for build.rs");
};
let out_dir = Path::new(&out_dir_env);
2020-04-24 07:56:54 +02:00
fs::create_dir_all(out_dir.join("assets/manual")).unwrap();
fs::create_dir_all(out_dir.join("assets/completions")).unwrap();
2023-10-27 08:37:48 +02:00
render_template(
&variables,
"assets/manual/bat.1.in",
out_dir.join("assets/manual/bat.1"),
)?;
2023-10-27 08:37:48 +02:00
render_template(
&variables,
"assets/completions/bat.bash.in",
out_dir.join("assets/completions/bat.bash"),
)?;
2023-10-27 08:37:48 +02:00
render_template(
&variables,
"assets/completions/bat.fish.in",
out_dir.join("assets/completions/bat.fish"),
)?;
2023-10-27 08:37:48 +02:00
render_template(
2021-08-28 13:39:17 +02:00
&variables,
"assets/completions/_bat.ps1.in",
out_dir.join("assets/completions/_bat.ps1"),
)?;
2023-10-27 08:37:48 +02:00
render_template(
&variables,
"assets/completions/bat.zsh.in",
out_dir.join("assets/completions/bat.zsh"),
)?;
Ok(())
}
2023-10-27 08:37:48 +02:00
/// Generates a file from a template.
#[allow(dead_code)]
fn render_template(
variables: &HashMap<&str, &str>,
in_file: &str,
out_file: impl AsRef<Path>,
) -> anyhow::Result<()> {
let mut content = fs::read_to_string(in_file)?;
for (variable_name, value) in variables {
// Replace {{variable_name}} by the value
let pattern = format!("{{{{{variable_name}}}}}", variable_name = variable_name);
content = content.replace(&pattern, value);
}
fs::write(out_file, content)?;
Ok(())
}