| 1 | + | use std::path::Path; |
| 2 | + | use std::str::FromStr; |
| 3 | + | |
| 4 | + | use anyhow::{anyhow, Error}; |
| 5 | + | |
1 | 6 | | use crate::prompt; |
2 | | - | use std::path::Path; |
| 7 | + | |
| 8 | + | pub enum PackageManager { |
| 9 | + | Yarn, |
| 10 | + | Npm, |
| 11 | + | Pnpm, |
| 12 | + | } |
| 13 | + | |
| 14 | + | impl ToString for PackageManager { |
| 15 | + | fn to_string(&self) -> String { |
| 16 | + | match self { |
| 17 | + | PackageManager::Yarn => "yarn".to_string(), |
| 18 | + | PackageManager::Npm => "npm".to_string(), |
| 19 | + | PackageManager::Pnpm => "pnpm".to_string(), |
| 20 | + | } |
| 21 | + | } |
| 22 | + | } |
| 23 | + | |
| 24 | + | impl FromStr for PackageManager { |
| 25 | + | type Err = Error; |
| 26 | + | |
| 27 | + | fn from_str(name: &str) -> Result<Self, Self::Err> { |
| 28 | + | match name { |
| 29 | + | "yarn" => Ok(PackageManager::Yarn), |
| 30 | + | "npm" => Ok(PackageManager::Npm), |
| 31 | + | "pnpm" => Ok(PackageManager::Pnpm), |
| 32 | + | _ => Err(anyhow!("Parse package manager error")), |
| 33 | + | } |
| 34 | + | } |
| 35 | + | } |
| 36 | + | |
3 | 37 | | |
4 | 38 | | // A function to guess package manager by looking for lock file in current directory only |
5 | 39 | | // If yarn.lock is found, it's likely to be a yarn project |
6 | 40 | | // If package-lock.json is found, it's likely to be a npm project |
7 | 41 | | // If pnpm-lock.yaml is found, it's likely to be a pnpm project |
8 | 42 | | // If none of the above is found, return None |
9 | | - | pub fn guess_package_manager(dir: &Path) -> Option<String> { |
| 43 | + | pub fn guess_package_manager(dir: &Path) -> Option<PackageManager> { |
10 | 44 | | let lock_file = dir.join("yarn.lock"); |
11 | 45 | | if lock_file.exists() { |
12 | | - | return Some("yarn".to_string()); |
| 46 | + | return Some(PackageManager::Yarn); |
13 | 47 | | } |
14 | 48 | | |
15 | 49 | | let lock_file = dir.join("package-lock.json"); |
16 | 50 | | if lock_file.exists() { |
17 | | - | return Some("npm".to_string()); |
| 51 | + | return Some(PackageManager::Npm); |
18 | 52 | | } |
19 | 53 | | |
20 | 54 | | let lock_file = dir.join("pnpm-lock.yaml"); |
21 | 55 | | if lock_file.exists() { |
22 | | - | return Some("pnpm".to_string()); |
| 56 | + | return Some(PackageManager::Pnpm); |
23 | 57 | | } |
24 | 58 | | |
| 59 | + | |
25 | 60 | | let items = vec!["pnpm", "npm", "yarn"]; |
26 | | - | prompt::select("Which package manager do you want to use?", items) |
| 61 | + | match prompt::select("Which package manager do you want to use?", items) { |
| 62 | + | Some(pm) => PackageManager::from_str(&pm).ok(), |
| 63 | + | None => None |
| 64 | + | } |
27 | 65 | | } |
28 | 66 | | |