Skip to content

Commit

Permalink
chore: init package manager detection feature
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelramos committed Nov 13, 2024
1 parent a4d2e95 commit 76b9807
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/standard/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ workspace = true

[dependencies]
thiserror = { workspace = true }
serde = { workspace = true, features = ["derive"] }
1 change: 1 addition & 0 deletions crates/standard/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod command;
pub mod error;
pub mod manager;
pub mod paths;
pub mod utils;
63 changes: 63 additions & 0 deletions crates/standard/src/manager.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
fmt::{Display, Formatter, Result as StdResult},
path::Path,
};

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CorePackageManager {
Npm,
Yarn,
Pnpm,
Bun,
}

impl From<String> for CorePackageManager {
fn from(manager: String) -> Self {
match manager.as_str() {
"npm" => Self::Npm,
"yarn" => Self::Yarn,
"pnpm" => Self::Pnpm,
"bun" => Self::Bun,
_ => panic!("Unable to identify package manager: {manager}"),
}
}
}

impl Display for CorePackageManager {
fn fmt(&self, f: &mut Formatter) -> StdResult {
match self {
Self::Npm => write!(f, "npm"),
Self::Yarn => write!(f, "yarn"),
Self::Pnpm => write!(f, "pnpm"),
Self::Bun => write!(f, "bun"),
}
}
}

/// Detects which package manager is available in the workspace.
pub fn detect_package_manager(path: &Path) -> Option<CorePackageManager> {
let package_manager_files = HashMap::from([
("package-lock.json", CorePackageManager::Npm),
("npm-shrinkwrap.json", CorePackageManager::Npm),
("yarn.lock", CorePackageManager::Yarn),
("pnpm-lock.yaml", CorePackageManager::Pnpm),
("bun.lockb", CorePackageManager::Bun),
]);

for (file, package_manager) in package_manager_files {
let lock_file = path.join(file);

if lock_file.exists() {
return Some(package_manager);
}
}

if let Some(parent) = path.parent() {
return detect_package_manager(parent);
}

None
}

0 comments on commit 76b9807

Please sign in to comment.