fix(npm): handle multiple packages and flag parsing correctly (#17)

* fix(npm): handle multiple packages and flag parsing correctly

- Fixes issue where only the first package was scanned; now all packages in install command are parsed and processed.
- Correctly separates flags (e.g., --save-dev) from package names to avoid treating them as packages.
- Applies same fixes to both npm and pnpm flows.
- Updated wrapper to scan all packages before installing, maintaining original CLI behavior.

* refactor: fixed the registry type

* feat: continue installing other packages if one is denied

* Update pkg/wrapper/npm_base.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>

* fix(wrapper): exit gracefully for user-rejected packages

* fix: remove env validation

---------

Signed-off-by: Sahil Bansal <bansalsahil315@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Sahil Bansal
2025-05-12 09:23:08 +05:30
committed by GitHub
co-authored by Copilot
parent f7855e99a2
commit 8b46964c7a
6 changed files with 146 additions and 73 deletions
+12 -5
View File
@@ -24,13 +24,20 @@ func NewNpmCommand() *cobra.Command {
}
if len(args) >= 2 && utils.IsInstallCommand(string(registry.RegistryNPM), args[0]) {
pmw := wrapper.NewPackageManagerWrapper(registry.RegistryNPM)
pmw.Action = args[0]
pmw.PackageName = args[1]
// Parse arguments to separate flags and packages
flags, packages := utils.ParseNpmInstallArgs(args[1:])
if err := pmw.Wrap(); err != nil {
os.Exit(1)
// If no packages specified, just pass through to npm
if len(packages) == 0 {
return utils.ExecCmd(execPath, args, []string{})
}
// Create single wrapper instance for all packages
pmw := wrapper.NewPackageManagerWrapper(registry.RegistryNPM, flags, packages, args[0])
if err := pmw.Wrap(); err != nil {
return err
}
return nil
}
+12 -5
View File
@@ -24,13 +24,20 @@ func NewPnpmCommand() *cobra.Command {
}
if len(args) >= 2 && utils.IsInstallCommand(string(registry.RegistryPNPM), args[0]) {
pmw := wrapper.NewPackageManagerWrapper(registry.RegistryPNPM)
pmw.Action = args[0]
pmw.PackageName = args[1]
// Parse arguments to separate flags and packages
flags, packages := utils.ParseNpmInstallArgs(args[1:])
if err := pmw.Wrap(); err != nil {
os.Exit(1)
// If no packages specified, just pass through to npm
if len(packages) == 0 {
return utils.ExecCmd(execPath, args, []string{})
}
// Create single wrapper instance for all packages
pmw := wrapper.NewPackageManagerWrapper(registry.RegistryPNPM, flags, packages, args[0])
if err := pmw.Wrap(); err != nil {
return err
}
return nil
}
+64
View File
@@ -0,0 +1,64 @@
package utils
import (
"fmt"
"strings"
)
// ParseNpmInstallArgs parses npm install command arguments and returns
// separated flags and packages. It expects args to include the full command
// including "npm" and "install" at the start
func ParseNpmInstallArgs(args []string) ([]string, []string) {
var flags []string
var packages []string
for _, arg := range args {
if strings.HasPrefix(arg, "-") {
flags = append(flags, arg)
} else {
packages = append(packages, arg)
}
}
return flags, packages
}
func CleanVersion(version string) string {
version = strings.TrimPrefix(version, "^")
version = strings.TrimPrefix(version, "~")
if version == "*" {
return "latest"
}
return version
}
func ParsePackageInfo(input string) (packageName, version string, err error) {
if input == "" {
return "", "", fmt.Errorf("package info cannot be empty")
}
input = strings.TrimSpace(input)
if strings.HasPrefix(input, "@") {
lastAtIndex := strings.LastIndex(input, "@")
if lastAtIndex > 0 {
packageName = strings.TrimSpace(input[:lastAtIndex])
version = strings.TrimSpace(input[lastAtIndex+1:])
return packageName, version, nil
}
// If no version specifier, return the whole input as package name
return strings.TrimSpace(input), "", nil
}
pkg := strings.Split(input, "@")
if len(pkg) == 2 {
packageName = strings.TrimSpace(pkg[0])
version = strings.TrimSpace(pkg[1])
return packageName, version, nil
}
if len(pkg) == 1 {
packageName = strings.TrimSpace(pkg[0])
return packageName, "", nil
}
return "", "", fmt.Errorf("invalid format: expected 'package' OR 'package@version', got '%s'", input)
}
-46
View File
@@ -1,51 +1,5 @@
package utils
import (
"fmt"
"strings"
)
func CleanVersion(version string) string {
version = strings.TrimPrefix(version, "^")
version = strings.TrimPrefix(version, "~")
if version == "*" {
return "latest"
}
return version
}
func ParsePackageInfo(input string) (packageName, version string, err error) {
if input == "" {
return "", "", fmt.Errorf("package info cannot be empty")
}
input = strings.TrimSpace(input)
if strings.HasPrefix(input, "@") {
lastAtIndex := strings.LastIndex(input, "@")
if lastAtIndex > 0 {
packageName = strings.TrimSpace(input[:lastAtIndex])
version = strings.TrimSpace(input[lastAtIndex+1:])
return packageName, version, nil
}
// If no version specifier, return the whole input as package name
return strings.TrimSpace(input), "", nil
}
pkg := strings.Split(input, "@")
if len(pkg) == 2 {
packageName = strings.TrimSpace(pkg[0])
version = strings.TrimSpace(pkg[1])
return packageName, version, nil
}
if len(pkg) == 1 {
packageName = strings.TrimSpace(pkg[0])
return packageName, "", nil
}
return "", "", fmt.Errorf("invalid format: expected 'package' OR 'package@version', got '%s'", input)
}
func IsInstallCommand(pkgManager, cmd string) bool {
validActions := map[string]map[string]bool{
"npm": {
+11
View File
@@ -0,0 +1,11 @@
package wrapper
import "errors"
const (
ErrPackageInstallationDeny = "PACKAGE_INSTALLATION_DENIED"
)
var (
ErrPackageInstall = errors.New(ErrPackageInstallationDeny)
)
+47 -17
View File
@@ -2,6 +2,7 @@ package wrapper
import (
"context"
"errors"
"fmt"
"time"
@@ -17,33 +18,60 @@ import (
)
type PackageManagerWrapper struct {
RegistryType registry.RegistryType
Action string
PackageName string
RegistryType registry.RegistryType
Flags []string
Action string
PackageNames []string
currentPackage string
PackagesToInstall []string
}
func NewPackageManagerWrapper(registryType registry.RegistryType) *PackageManagerWrapper {
func NewPackageManagerWrapper(registryType registry.RegistryType, flags []string, packageNames []string, action string) *PackageManagerWrapper {
return &PackageManagerWrapper{
RegistryType: registryType,
PackageNames: packageNames,
Flags: flags,
Action: action,
}
}
func (pmw *PackageManagerWrapper) Wrap() error {
ui.StartProgressWriter()
var DefaultProgressTotal = 5
progressTracker := ui.TrackProgress(fmt.Sprintf("Scanning %s ", pmw.PackageName), DefaultProgressTotal)
if pmw.PackageName == "" {
return fmt.Errorf("package name cannot be empty")
if len(pmw.PackageNames) == 0 {
return fmt.Errorf("no packages specified")
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
if err := pmw.scanAndInstall(ctx, progressTracker); err != nil {
// Scan all packages first
for _, pkg := range pmw.PackageNames {
ui.StartProgressWriter()
var DefaultProgressTotal = 1
pmw.currentPackage = pkg
progressTracker := ui.TrackProgress(fmt.Sprintf("Scanning %s", pkg), DefaultProgressTotal)
if err := pmw.scanAndInstall(ctx, progressTracker); err != nil {
if errors.Is(err, ErrPackageInstall) {
log.Warnf("Skipping package %s due to ErrPackageInstall: %v", pkg, err)
continue
}
return err
}
pmw.PackagesToInstall = append(pmw.PackagesToInstall, pkg)
ui.StopProgressWriter()
}
if len(pmw.PackagesToInstall) == 0 {
log.Infof("No packages were installed due to security concerns")
return nil
}
// Execute installation after all scans complete
if err := pmw.executeInstallation(); err != nil {
return err
}
log.Infof("Successfully installed %s", pmw.PackageName)
log.Infof("Successfully installed all packages")
return nil
}
@@ -54,7 +82,7 @@ func (pmw *PackageManagerWrapper) scanAndInstall(ctx context.Context, progressTr
return err
}
name, version, err := utils.ParsePackageInfo(pmw.PackageName)
name, version, err := utils.ParsePackageInfo(pmw.currentPackage)
if err != nil {
return err
}
@@ -64,7 +92,7 @@ func (pmw *PackageManagerWrapper) scanAndInstall(ctx context.Context, progressTr
if err != nil {
return err
}
pmw.PackageName = fmt.Sprintf("%s@%s", name, version)
pmw.currentPackage = fmt.Sprintf("%s@%s", name, version)
}
// Get dependencies with progress tracking
@@ -76,13 +104,13 @@ func (pmw *PackageManagerWrapper) scanAndInstall(ctx context.Context, progressTr
return err
}
// We know the total deps, set progress for analysis phase
// Set progress for analysis phase
ui.IncrementTrackerTotal(progressTracker, int64(len(deps)))
if err := pmw.analyzeDependencies(ctx, deps, progressTracker); err != nil {
return err
}
return pmw.executeInstallation()
return nil
}
func (pmw *PackageManagerWrapper) resolveLatestVersion(ctx context.Context, fetcher registry.Fetcher, name string) (string, error) {
@@ -128,7 +156,7 @@ func (pmw *PackageManagerWrapper) analyzeDependencies(ctx context.Context, deps
if len(pkgAnalyser.MaliciousPkgs) > 0 {
if !utils.ConfirmInstallation(pkgAnalyser.MaliciousPkgs) {
log.Infof("Installation canceled due to security concerns")
return fmt.Errorf("installation canceled")
return ErrPackageInstall
}
yellow := color.New(color.FgYellow, color.Bold).SprintfFunc()
log.Warnf(yellow("Continuing installation despite security warnings..."))
@@ -143,7 +171,9 @@ func (pmw *PackageManagerWrapper) executeInstallation() error {
return fmt.Errorf("%s not found: %w", pmw.RegistryType, err)
}
cmdArgs := []string{pmw.Action, pmw.PackageName}
cmdArgs := []string{pmw.Action}
cmdArgs = append(cmdArgs, pmw.Flags...)
cmdArgs = append(cmdArgs, pmw.PackagesToInstall...)
if err = utils.ExecCmd(execPath, cmdArgs, []string{}); err != nil {
return fmt.Errorf("failed to execute %s command: %w", pmw.RegistryType, err)
}