Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions crates/vite_install/src/commands/dedupe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
use std::{collections::HashMap, process::ExitStatus};

use vite_error::Error;
use vite_path::AbsolutePath;

use crate::package_manager::{
PackageManager, PackageManagerType, ResolveCommandResult, format_path_env, run_command,
};

/// Options for the dedupe command.
#[derive(Debug, Default)]
pub struct DedupeCommandOptions<'a> {
pub check: bool,
pub pass_through_args: Option<&'a [String]>,
}

impl PackageManager {
/// Run the dedupe command with the package manager.
/// Return the exit status of the command.
#[must_use]
pub async fn run_dedupe_command(
&self,
options: &DedupeCommandOptions<'_>,
cwd: impl AsRef<AbsolutePath>,
) -> Result<ExitStatus, Error> {
let resolve_command = self.resolve_dedupe_command(options);
run_command(&resolve_command.bin_path, &resolve_command.args, &resolve_command.envs, cwd)
.await
}

/// Resolve the dedupe command.
#[must_use]
pub fn resolve_dedupe_command(&self, options: &DedupeCommandOptions) -> ResolveCommandResult {
let bin_name: String;
let envs = HashMap::from([("PATH".to_string(), format_path_env(self.get_bin_prefix()))]);
let mut args: Vec<String> = Vec::new();

match self.client {
PackageManagerType::Pnpm => {
bin_name = "pnpm".into();
args.push("dedupe".into());

// pnpm uses --check for dry-run
if options.check {
args.push("--check".into());
}
}
PackageManagerType::Yarn => {
bin_name = "yarn".into();
args.push("dedupe".into());

// yarn@2+ supports --check
if options.check {
args.push("--check".into());
}
}
PackageManagerType::Npm => {
bin_name = "npm".into();
args.push("dedupe".into());

if options.check {
args.push("--dry-run".into());
}
}
}

// Add pass-through args
if let Some(pass_through_args) = options.pass_through_args {
args.extend_from_slice(pass_through_args);
}

ResolveCommandResult { bin_path: bin_name, args, envs }
}
}

#[cfg(test)]
mod tests {
use tempfile::{TempDir, tempdir};
use vite_path::AbsolutePathBuf;
use vite_str::Str;

use super::*;

fn create_temp_dir() -> TempDir {
tempdir().expect("Failed to create temp directory")
}

fn create_mock_package_manager(pm_type: PackageManagerType, version: &str) -> PackageManager {
let temp_dir = create_temp_dir();
let temp_dir_path = AbsolutePathBuf::new(temp_dir.path().to_path_buf()).unwrap();
let install_dir = temp_dir_path.join("install");

PackageManager {
client: pm_type,
package_name: pm_type.to_string().into(),
version: Str::from(version),
hash: None,
bin_name: pm_type.to_string().into(),
workspace_root: temp_dir_path.clone(),
install_dir,
}
}

#[test]
fn test_pnpm_dedupe_basic() {
let pm = create_mock_package_manager(PackageManagerType::Pnpm, "10.0.0");
let result = pm.resolve_dedupe_command(&DedupeCommandOptions { ..Default::default() });
assert_eq!(result.bin_path, "pnpm");
assert_eq!(result.args, vec!["dedupe"]);
}

#[test]
fn test_pnpm_dedupe_check() {
let pm = create_mock_package_manager(PackageManagerType::Pnpm, "10.0.0");
let result =
pm.resolve_dedupe_command(&DedupeCommandOptions { check: true, ..Default::default() });
assert_eq!(result.bin_path, "pnpm");
assert_eq!(result.args, vec!["dedupe", "--check"]);
}

#[test]
fn test_npm_dedupe_basic() {
let pm = create_mock_package_manager(PackageManagerType::Npm, "11.0.0");
let result = pm.resolve_dedupe_command(&DedupeCommandOptions { ..Default::default() });
assert_eq!(result.args, vec!["dedupe"]);
assert_eq!(result.bin_path, "npm");
}

#[test]
fn test_npm_dedupe_check() {
let pm = create_mock_package_manager(PackageManagerType::Npm, "11.0.0");
let result =
pm.resolve_dedupe_command(&DedupeCommandOptions { check: true, ..Default::default() });
assert_eq!(result.args, vec!["dedupe", "--dry-run"]);
assert_eq!(result.bin_path, "npm");
}

#[test]
fn test_yarn_dedupe_basic() {
let pm = create_mock_package_manager(PackageManagerType::Yarn, "4.0.0");
let result = pm.resolve_dedupe_command(&DedupeCommandOptions { ..Default::default() });
assert_eq!(result.args, vec!["dedupe"]);
assert_eq!(result.bin_path, "yarn");
}

#[test]
fn test_yarn_dedupe_check() {
let pm = create_mock_package_manager(PackageManagerType::Yarn, "4.0.0");
let result =
pm.resolve_dedupe_command(&DedupeCommandOptions { check: true, ..Default::default() });
assert_eq!(result.args, vec!["dedupe", "--check"]);
assert_eq!(result.bin_path, "yarn");
}
}
1 change: 1 addition & 0 deletions crates/vite_install/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod add;
pub mod dedupe;
mod install;
pub mod remove;
pub mod update;
88 changes: 87 additions & 1 deletion packages/cli/binding/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use vite_task::{

use crate::commands::{
add::AddCommand,
dedupe::DedupeCommand,
doc::doc as doc_cmd,
fmt::{FmtConfig, fmt},
install::InstallCommand,
Expand Down Expand Up @@ -272,6 +273,17 @@ pub enum Commands {
/// Packages to update (optional - updates all if omitted)
packages: Vec<String>,

/// Additional arguments to pass through to the package manager
#[arg(last = true, allow_hyphen_values = true)]
pass_through_args: Option<Vec<String>>,
},
/// Deduplicate dependencies by removing older versions
#[command(alias = "ddp")]
Dedupe {
/// Check if deduplication would make changes
#[arg(long)]
check: bool,

/// Additional arguments to pass through to the package manager
#[arg(last = true, allow_hyphen_values = true)]
pass_through_args: Option<Vec<String>>,
Expand All @@ -281,7 +293,13 @@ pub enum Commands {
impl Commands {
/// Check if this command is a package manager command that should skip auto-install
pub fn is_package_manager_command(&self) -> bool {
matches!(self, Commands::Install { .. } | Commands::Add { .. } | Commands::Remove { .. })
matches!(
self,
Commands::Install { .. }
| Commands::Add { .. }
| Commands::Remove { .. }
| Commands::Dedupe { .. }
)
}
}

Expand Down Expand Up @@ -703,6 +721,11 @@ pub async fn main<
.await?;
return Ok(exit_status);
}
Commands::Dedupe { check, pass_through_args } => {
let exit_status =
DedupeCommand::new(cwd).execute(*check, pass_through_args.as_deref()).await?;
return Ok(exit_status);
}
};

let execution_summary_dir = EXECUTION_SUMMARY_DIR.as_path();
Expand Down Expand Up @@ -2320,4 +2343,67 @@ mod tests {
}
}
}

mod dedupe_command_tests {
use super::*;

#[test]
fn test_args_dedupe_command_basic() {
let args = Args::try_parse_from(&["vite-plus", "dedupe"]).unwrap();
if let Commands::Dedupe { check, .. } = &args.commands {
assert!(!check);
} else {
panic!("Expected Dedupe command");
}
}

#[test]
fn test_args_dedupe_command_with_alias() {
let args = Args::try_parse_from(&["vite-plus", "ddp"]).unwrap();
assert!(matches!(args.commands, Commands::Dedupe { .. }));
}

#[test]
fn test_args_dedupe_command_with_check() {
let args = Args::try_parse_from(&["vite-plus", "dedupe", "--check"]).unwrap();
if let Commands::Dedupe { check, .. } = &args.commands {
assert!(check);
} else {
panic!("Expected Dedupe command");
}
}

#[test]
fn test_args_dedupe_command_with_pass_through_args() {
let args = Args::try_parse_from(&[
"vite-plus",
"dedupe",
"--",
"--some-flag",
"--another-flag",
])
.unwrap();
if let Commands::Dedupe { pass_through_args, .. } = &args.commands {
assert_eq!(
pass_through_args,
&Some(vec!["--some-flag".to_string(), "--another-flag".to_string()])
);
} else {
panic!("Expected Dedupe command");
}
}

#[test]
fn test_args_dedupe_command_with_check_and_pass_through() {
let args =
Args::try_parse_from(&["vite-plus", "dedupe", "--check", "--", "--custom-flag"])
.unwrap();
if let Commands::Dedupe { check, pass_through_args, .. } = &args.commands {
assert!(check);
assert_eq!(pass_through_args, &Some(vec!["--custom-flag".to_string()]));
} else {
panic!("Expected Dedupe command");
}
}
}
}
49 changes: 49 additions & 0 deletions packages/cli/binding/src/commands/dedupe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use std::process::ExitStatus;

use vite_install::{commands::dedupe::DedupeCommandOptions, package_manager::PackageManager};
use vite_path::AbsolutePathBuf;

use crate::Error;

/// Dedupe command for deduplicating dependencies by removing older versions.
///
/// This command automatically detects the package manager and translates
/// the dedupe command to the appropriate package manager-specific syntax.
pub struct DedupeCommand {
cwd: AbsolutePathBuf,
}

impl DedupeCommand {
pub fn new(cwd: AbsolutePathBuf) -> Self {
Self { cwd }
}

pub async fn execute(
self,
check: bool,
pass_through_args: Option<&[String]>,
) -> Result<ExitStatus, Error> {
// Detect package manager
let package_manager = PackageManager::builder(&self.cwd).build().await?;

let dedupe_command_options = DedupeCommandOptions { check, pass_through_args };
package_manager.run_dedupe_command(&dedupe_command_options, &self.cwd).await
}
}

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

#[test]
fn test_dedupe_command_new() {
let workspace_root = if cfg!(windows) {
AbsolutePathBuf::new("C:\\test".into()).unwrap()
} else {
AbsolutePathBuf::new("/test".into()).unwrap()
};

let cmd = DedupeCommand::new(workspace_root.clone());
assert_eq!(cmd.cwd, workspace_root);
}
}
1 change: 1 addition & 0 deletions packages/cli/binding/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub(crate) mod add;
pub(crate) mod dedupe;
pub(crate) mod doc;
pub(crate) mod fmt;
pub(crate) mod install;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[2]> vite command-not-exists # should exit with non-zero code
error: 'vite' requires a subcommand but one was not provided
[subcommands: run, lint, fmt, build, test, lib, dev, doc, cache, install, i, add, remove, rm, un, uninstall, update, up, help]
[subcommands: run, lint, fmt, build, test, lib, dev, doc, cache, install, i, add, remove, rm, un, uninstall, update, up, dedupe, ddp, help]

Usage: vite [OPTIONS] [TASK] [-- <TASK_ARGS>...] <COMMAND>

Expand Down
1 change: 1 addition & 0 deletions packages/global/snap-tests/cli-helper-message/snap.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Commands:
add Add packages to dependencies
remove Remove packages from dependencies
update Update packages to their latest versions
dedupe Deduplicate dependencies by removing older versions
help Print this message or the help of the given subcommand(s)

Arguments:
Expand Down
14 changes: 14 additions & 0 deletions packages/global/snap-tests/command-dedupe-npm10/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "command-dedupe-npm10",
"version": "1.0.0",
"packageManager": "npm@10.9.4",
"dependencies": {
"testnpm2": "1.0.1"
},
"devDependencies": {
"test-vite-plus-package": "1.0.0"
},
"optionalDependencies": {
"test-vite-plus-package-optional": "1.0.0"
}
}
Loading
Loading