forky_cli/auto_mod/
run.rs1use anyhow::Result;
2use forky_core::prelude::*;
3use forky_fs::prelude::*;
4use forky_fs::utility::fs::read_dir_recursive;
5use std::env;
6use std::fs;
7use std::path::PathBuf;
8
9const CRATE_FOLDERS: &'static [&str] =
10 &["src", "examples", "tests", "test", "macros/src", "cli/src"];
11const IGNORE_FOLDERS: &'static [&str] = &["src", "examples"];
12const IGNORE_FILES: &'static [&str] = &["mod", "lib", "main", "_lib", "sweet"];
13const CRATE_DIRS: &'static [&str] = &["src", "crates", "crates/forky"];
14
15
16pub fn run() -> Result<()> {
17 let _ = CRATE_DIRS
18 .into_iter()
19 .map(|dir| {
20 match fs::read_dir(dir) {
21 Ok(dirs) => dirs
22 .map(|e| e.unwrap().path())
23 .for_each(|p| run_for_crate(p)),
24 _ => run_for_crate(env::current_dir()?),
26 }
27 Ok(())
28 })
29 .collect::<Result<Vec<()>>>()?;
30 terminal::show_cursor();
31 Ok(())
32}
33
34pub fn run_for_crate(path: PathBuf) {
35 CRATE_FOLDERS
36 .iter()
37 .map(|s| PathBuf::push_with(&path, s))
38 .for_each(run_for_crate_folder)
39}
40
41pub fn run_for_crate_folder(path: PathBuf) {
42 read_dir_recursive(path)
43 .into_iter()
44 .filter(|p| !p.filename_included(IGNORE_FOLDERS))
45 .filter(|p| !p.filestem_ends_with_triple_underscore())
46 .map(|p| (create_mod_text(&p), p))
47 .for_each(|(c, p)| save_to_file(&p, c))
48}
49
50pub fn create_mod_text(path: &PathBuf) -> String {
51 let treat_as_mod = path.filestem_contains_double_underscore();
52
53 let mut filenames = fs::read_dir(&path)
54 .unwrap()
55 .map(|p| p.unwrap().path())
56 .filter(|p| p.is_dir() || !p.filename_included(IGNORE_FILES))
57 .filter(|p| !p.filestem_ends_with_triple_underscore())
58 .filter(|p| p.is_dir_or_extension("rs"))
59 .collect::<Vec<_>>();
60 filenames.sort();
61
62
63 let files_str: String = filenames
64 .into_iter()
65 .map(|p| {
66 let stem = p.file_stem().unwrap();
67 let name = stem.to_str().unwrap().to_owned();
68 let mut is_mod = p.is_dir() || treat_as_mod;
69 if p.filestem_starts_with_underscore() {
70 is_mod = !is_mod;
71 }
72 if is_mod {
73 format!("pub mod {name};\n")
74 } else {
75 format!("pub mod {name};\n#[allow(unused_imports)]\npub use self::{name}::*;\n")
77 }
78 })
79 .collect();
80 files_str
82}
83
84fn save_to_file(path: &PathBuf, content: String) {
85 let file_name = if path.file_name().str() == "src" {
87 "lib.rs"
88 } else {
89 "mod.rs"
90 };
91 let mut mod_path = path.clone();
92 mod_path.push(file_name);
93 fs::write(&mod_path, content).unwrap();
94 println!("created mod file: {}", &mod_path.to_str().unwrap());
95}