Skip to main content

openapi_lib_generator/generate/
utils.rs

1//! Codegen utilities
2use crate::{cli::Cli, testing};
3use std::{
4  env,
5  io::Error as IOError,
6  path::{Path, PathBuf},
7  process::Output,
8};
9use thiserror::Error;
10use tokio::process::{Child, Command};
11
12/// Testing errors
13#[derive(Debug, Error)]
14pub enum ProcessError {
15  #[error(transparent)]
16  IOError(#[from] IOError),
17  #[error("Process failed \n {0}")]
18  Failure(String),
19}
20
21#[macro_export]
22/// Just makes a vec of specified items from arguments
23macro_rules! vv {
24  (strings $($e:expr,)*) => {{vec![$($e.to_string(),)* ]}};
25  (dep_names $($e:expr,)*) => {{vec![$(DependencyIdentifier::Name($e.to_string()),)* ]}};
26  (as_ref dep_names $($e:expr,)*) => {{ $crate::vv![dep_names $($e.as_ref(),)* ]}};
27}
28
29/// Attempt to run a cargo job
30pub async fn run_cargo_job<T: AsRef<str>, P: AsRef<Path>>(
31  args: &[T],
32  cwd_opt: Option<P>,
33  description_opt: Option<T>,
34) -> Result<Output, ProcessError> {
35  let mut command = Command::new("cargo");
36  let cwd_string = if let Some(cwd) = cwd_opt.as_ref() {
37    command.current_dir(&cwd.as_ref());
38    format!("in {}", cwd.as_ref().to_string_lossy())
39  } else {
40    String::default()
41  };
42  let args_vec = &Vec::from_iter(args.iter().map(AsRef::as_ref));
43  let arg_string = args_vec
44    .iter()
45    .map(|a| format!("\"{a}\" "))
46    .collect::<String>();
47  let description = description_opt
48    .map(|s| s.as_ref().to_string())
49    .unwrap_or_else(|| format!("Running `cargo` {arg_string} {cwd_string}.",));
50  println!("{description}");
51  let child: Child = command.args(args_vec).spawn()?;
52  child.wait_with_output().await.map_err(ProcessError::from)
53}
54
55/// Attempt to run a cargo make task
56pub async fn run_cargo_make_task<T: AsRef<str>>(
57  cli: &Cli,
58  task_name: T,
59) -> Result<Output, ProcessError> {
60  let output_project_dir = &cli.get_output_project_dir();
61  run_cargo_job(
62    &["make", task_name.as_ref()],
63    Some(output_project_dir),
64    None,
65  )
66  .await
67}
68
69/// trim leading whitespace from multiline code resulting in a single string
70pub fn trim_lines(s: &str) -> String {
71  trim_lines_vec(s).join("\n")
72}
73/// trim leading whitespace from multiline code resulting in a vec of strings
74pub fn trim_lines_vec(s: &str) -> Vec<String> {
75  s.lines()
76    .map(|line| line.trim_end())
77    .filter(|line| !line.is_empty())
78    .fold(
79      (String::new(), Vec::new()),
80      |(mut target, mut result), line| {
81        if target.is_empty() && !line.is_empty() {
82          let leading_whitespace = line.len() - line.trim_start_matches(" ").len();
83          target = " ".repeat(leading_whitespace);
84        }
85        if !target.is_empty() {
86          result.push(format!("{}", line.strip_prefix(&target).unwrap_or(line)));
87        }
88        (target, result)
89      },
90    )
91    .1
92}
93
94/// Get the name of this crate
95pub fn get_this_crate_name() -> &'static str {
96  env!("CARGO_CRATE_NAME")
97}
98/// Get the version of this crate
99pub fn get_this_crate_ver() -> &'static str {
100  env!("CARGO_PKG_VERSION")
101}
102/// Get the version of this crate with a 'v'
103pub fn get_this_crate_ver_pretty() -> String {
104  format!("v{}", get_this_crate_ver())
105}
106/// Get the temp root directory
107pub fn get_temp_root_dir() -> PathBuf {
108  env::temp_dir()
109}
110/// Get temp project subdir
111pub fn get_temp_subdir() -> PathBuf {
112  get_temp_root_dir().join(&format!(
113    "{}_{}",
114    get_this_crate_name(),
115    testing::TEST_SUBDIR_NAME
116  ))
117}
118
119#[cfg(test)]
120mod test_mod_name {
121  use super::*;
122  #[test]
123  fn trim_lines_works() {
124    let test = r#"
125        line zero
126          line one
127    "#;
128    assert_eq!(trim_lines_vec(test), vec!["line zero", "  line one"])
129  }
130}