mk_lib/schema/
use_npm.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

use anyhow::Context as _;
use hashbrown::HashMap;
use serde::Deserialize;

use crate::defaults::default_node_package_manager;
use crate::file::ToUtf8 as _;

use super::Task;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NpmPackage {
  /// The name of the package
  pub name: String,

  /// The version of the package
  pub version: Option<String>,

  /// The path to the package
  pub scripts: Option<HashMap<String, String>>,

  /// The package manager to use
  pub package_manager: Option<String>,
}

// TODO: Make use of the work_dir field
#[derive(Debug, Deserialize)]
pub struct UseNpmArgs {
  /// The package manager to use
  #[serde(default)]
  pub package_manager: Option<String>,

  /// The working directory to run the command in
  #[serde(default)]
  pub work_dir: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum UseNpm {
  Bool(bool),
  UseNpm(Box<UseNpmArgs>),
}

impl UseNpm {
  pub fn capture(&self) -> anyhow::Result<HashMap<String, Task>> {
    match self {
      UseNpm::Bool(true) => self.capture_tasks(),
      UseNpm::UseNpm(args) => args.capture_tasks(),
      _ => Ok(HashMap::new()),
    }
  }

  fn capture_tasks(&self) -> anyhow::Result<HashMap<String, Task>> {
    UseNpmArgs {
      package_manager: None,
      work_dir: None,
    }
    .capture_tasks()
  }
}

impl UseNpmArgs {
  pub fn capture_tasks(&self) -> anyhow::Result<HashMap<String, Task>> {
    let path = Path::new("package.json");
    if !path.exists() || !path.is_file() {
      return Err(anyhow::anyhow!("package.json does not exist"));
    }

    let file = File::open(path).context(format!("Failed to open file - {}", path.to_utf8()?))?;
    let reader = BufReader::new(file);

    let package: NpmPackage = serde_json::from_reader(reader)?;
    let package_manager = self
      .package_manager
      .clone()
      .unwrap_or_else(default_node_package_manager);

    assert!(!package_manager.is_empty());

    let tasks: HashMap<String, Task> = package
      .scripts
      .unwrap_or_default()
      .into_iter()
      .map(|(k, _)| (k.clone(), Task::String(format!("{package_manager} run {k}"))))
      .collect();
    Ok(tasks)
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_use_npm_1() -> anyhow::Result<()> {
    let json = r#"{
      "name": "test",
      "version": "1.0.0",
      "scripts": {
        "build": "echo 'Building'",
        "test": "echo 'Testing'"
      }
    }"#;
    let package = serde_json::from_str::<NpmPackage>(json)?;
    assert_eq!(package.name, "test");
    assert_eq!(package.version, Some("1.0.0".to_string()));
    assert_eq!(
      package.scripts,
      Some({
        let mut map = HashMap::new();
        map.insert("build".to_string(), "echo 'Building'".to_string());
        map.insert("test".to_string(), "echo 'Testing'".to_string());
        map
      })
    );
    Ok(())
  }

  #[test]
  fn test_use_npm_2() -> anyhow::Result<()> {
    let yaml = "true";

    let use_npm = serde_yaml::from_str::<UseNpm>(yaml)?;
    if let UseNpm::Bool(value) = use_npm {
      assert!(value);
    } else {
      panic!("Invalid value");
    }

    Ok(())
  }

  #[test]
  fn test_use_npm_3() -> anyhow::Result<()> {
    let yaml = "false";

    let use_npm = serde_yaml::from_str::<UseNpm>(yaml)?;
    if let UseNpm::Bool(value) = use_npm {
      assert!(!value);
    } else {
      panic!("Invalid value");
    }

    Ok(())
  }

  #[test]
  fn test_use_npm_4() -> anyhow::Result<()> {
    let yaml = "
      package_manager: npm
    ";

    let use_npm = serde_yaml::from_str::<UseNpm>(yaml)?;
    if let UseNpm::UseNpm(args) = use_npm {
      assert_eq!(args.package_manager, Some("npm".to_string()));
    } else {
      panic!("Invalid value");
    }

    Ok(())
  }

  #[test]
  fn test_use_npm_5() -> anyhow::Result<()> {
    let yaml = "
      package_manager: yarn
      work_dir: /path/to/dir
    ";

    let use_npm = serde_yaml::from_str::<UseNpm>(yaml)?;
    if let UseNpm::UseNpm(args) = use_npm {
      assert_eq!(args.package_manager, Some("yarn".to_string()));
      assert_eq!(args.work_dir, Some("/path/to/dir".to_string()));
    } else {
      panic!("Invalid value");
    }

    Ok(())
  }
}