taro_cli/modules/
gitignore.rs

1//! Generates a gitignore files tailored to the technology specified.
2//! 
3//! Uses [Toptal's gitignore.io](https://gitignore.io/) service.
4//! 
5//! The output file's path can be specified. If no output is specified, it will print to the standard output instead.
6
7use std::{ error::Error, fs::File, io::Write };
8
9use crate::GitIgnoreConfig;
10
11const URL: &str = "https://www.gitignore.io/api/";
12
13fn create_url(include: &[String]) -> String {
14  let mut url = String::from(URL);
15  url += include.join(",").as_str();
16  url
17}
18
19fn fetch(url: String) -> Result<String, Box<dyn Error>> {
20  let res = match reqwest::blocking::get(url) {
21    Ok(res) => res.text()?,
22    Err(_) => Err("cannot fetch gitignore")?
23  };
24
25  Ok(res)
26}
27
28/// Runs the gitignore function using the [GitIgnoreConfig] provided.
29pub fn run_gitignore(config: GitIgnoreConfig) -> Result<(), Box<dyn Error>> {
30  let url = create_url(&config.include);
31 
32  let res = fetch(url)?;
33
34  if let Some(output) = config.output {
35    let mut file = File::create(output)?;
36    file.write_all(res.as_bytes())?;
37  } else {
38    println!("{}", res);
39  }
40
41  Ok(())
42}
43
44#[cfg(test)]
45mod test {
46  use super::{*, create_url};
47
48  #[test]
49  fn test_url() {
50    let include = ["node", "python", "rust"].map(String::from);
51    let expected = String::from(URL) + "node,python,rust";
52    assert_eq!(expected, create_url(&include));
53  }
54
55  #[test]
56  fn test_fetch_endpoint() {
57    let url = String::from(URL) + "node,python,rust";
58
59    assert!(fetch(url).is_ok())
60  }
61
62  #[test]
63  fn test_fetch_result() {
64    let url = String::from(URL) + "node,python,rust";
65    let res = fetch(url).unwrap();
66
67    assert!(res.contains("node"));
68    assert!(res.contains("python"));
69    assert!(res.contains("rust"));
70  }
71}