prdoclib/
utils.rs

1//! Set of utils
2use crate::{common::PRNumber, config::PRDocConfig, error};
3use std::{
4	env,
5	fs::read_dir,
6	io::{self, ErrorKind},
7	path::PathBuf,
8};
9
10/// Type alias for the result of parsing a file
11pub type ParseResult = (String, bool, Option<PRNumber>);
12
13/// Get the project root (relative to closest Cargo.lock file)
14pub fn get_project_root() -> io::Result<PathBuf> {
15	let path = env::current_dir()?;
16	let path_ancestors = path.as_path().ancestors();
17
18	for p in path_ancestors {
19		let has_cargo = read_dir(p)?.any(|p| p.unwrap().file_name() == "Cargo.lock");
20		if has_cargo {
21			return Ok(PathBuf::from(p));
22		}
23	}
24	Err(io::Error::new(ErrorKind::NotFound, "Ran out of places to find Cargo.toml"))
25}
26
27pub(crate) fn get_numbers_from_file(file: &PathBuf) -> error::Result<Vec<ParseResult>> {
28	Ok(std::fs::read_to_string(file)?
29		.lines()
30		.map(|line| {
31			let num = line.parse::<PRNumber>();
32			let valid = num.is_ok();
33			let number = num.ok();
34			(line.to_string(), valid, number)
35		})
36		.collect())
37}
38
39/// Return the path of the folder where PRDoc are stored
40pub fn get_pr_doc_folder(output_dir: Option<PathBuf>, config: &PRDocConfig) -> PathBuf {
41	if let Some(path) = output_dir {
42		return path;
43	}
44
45	config.output_dir.clone()
46}
47
48/// Get the template path from the config
49pub fn get_template_path(config: &PRDocConfig) -> PathBuf {
50	config.template.clone()
51}
52
53#[cfg(test)]
54mod tests {
55	use super::*;
56
57	#[test]
58	fn it_should_find_our_project_root() {
59		let project_root = get_project_root().expect("There is no project root");
60		let toml_path = project_root.to_str().unwrap().to_owned() + "/Cargo.toml";
61		assert!(!toml_path.is_empty());
62	}
63}