cargo_task/task/
ct_init.rs

1use crate::*;
2
3/// This idempotent task runs before any valid task is executed or on ct_init.
4/// - Ensure the .cargo-task directory exists.
5/// - Ensure the .cargo-task/.gitignore file is initialized.
6/// - Ensure the .cargo-task/cargo_task_util dep crate exists.
7pub fn ct_init() {
8    check_cargo_task_dir();
9    check_gitignore();
10    check_cargo_task_util_crate();
11}
12
13fn check_cargo_task_dir() {
14    if let Ok(meta) = std::fs::metadata(CARGO_TASK_DIR) {
15        if meta.is_dir() {
16            return;
17        }
18    }
19    ct_info!("Initializing current directory for cargo-task...");
20    ct_check_fatal!(std::fs::create_dir_all(CARGO_TASK_DIR));
21}
22
23fn check_gitignore() {
24    if let Ok(meta) = std::fs::metadata(CT_DIR_GIT_IGNORE) {
25        if meta.is_file() {
26            return;
27        }
28    }
29    ct_check_fatal!(std::fs::write(CT_DIR_GIT_IGNORE, CT_DIR_GIT_IGNORE_SRC));
30}
31
32fn check_cargo_task_util_crate() {
33    // ensure the crate directory
34    let mut dir = std::path::PathBuf::new();
35    dir.push(CARGO_TASK_DIR);
36    dir.push("cargo_task_util");
37    let _ = std::fs::create_dir_all(&dir);
38
39    // ensure the Cargo.toml
40    check_util_cargo_toml();
41
42    // ensure the src/lib.rs
43    check_util_lib_rs();
44
45    // ensure the src/cargo_task_util.rs
46    check_util_ctu_rs();
47}
48
49fn check_util_cargo_toml() {
50    let mut cargo_toml = std::path::PathBuf::new();
51    cargo_toml.push(CARGO_TASK_DIR);
52    cargo_toml.push("cargo_task_util");
53    cargo_toml.push("Cargo.toml");
54
55    ct_check_fatal!(std::fs::write(
56        &cargo_toml,
57        r#"[package]
58name = "cargo_task_util"
59version = "0.0.1"
60edition = "2018"
61"#
62    ));
63}
64
65fn check_util_lib_rs() {
66    let mut lib_rs = std::path::PathBuf::new();
67    lib_rs.push(CARGO_TASK_DIR);
68    lib_rs.push("cargo_task_util");
69    lib_rs.push("src");
70    let _ = std::fs::create_dir_all(&lib_rs);
71
72    lib_rs.push("lib.rs");
73
74    const CONTENT: &str = r#"#![allow(dead_code)]
75pub mod _cargo_task_util;
76pub use _cargo_task_util::*;
77"#;
78
79    ct_check_fatal!(std::fs::write(&lib_rs, CONTENT));
80}
81
82fn check_util_ctu_rs() {
83    let mut ctu_rs = std::path::PathBuf::new();
84    ctu_rs.push(CARGO_TASK_DIR);
85    ctu_rs.push("cargo_task_util");
86    ctu_rs.push("src");
87    let _ = std::fs::create_dir_all(&ctu_rs);
88
89    ctu_rs.push("_cargo_task_util.rs");
90
91    ct_check_fatal!(std::fs::write(&ctu_rs, CARGO_TASK_UTIL_SRC));
92}