Files
pmg/internal/alias/alias.go
T
6546116e28 feat: migrate PMG to use PATH shims for package manager wrapper (#246)
* feat: add FilterPMGFromPath utility for PATH shim recursion prevention

* feat: add FilterPMGFromEnv to filter PATH from env slices

* feat: filter ~/.pmg/bin from PATH in proxy subprocess env

* feat: add PathExport method to Shell interface for shim PATH integration

* feat: add ShimManager for PATH shim install/remove lifecycle

* feat: wire ShimManager into setup commands with --use-aliases fallback

* refactor: add DefaultShimConfig helper to reduce setup boilerplate

* fix: resolve real binary path to prevent shim double-invocation

exec.CommandContext resolves the binary using the current process PATH,
which still contains ~/.pmg/bin. This caused pmg to launch the shim
instead of the real package manager, resulting in a second pmg instance
with its own proxy — producing duplicate error messages and wasted work.

ResolveRealBinary searches a filtered PATH (without ~/.pmg/bin) to find
the real package manager binary before execution.

* fix: resolve real binary in runner.Execute and expand path resolution tests

Ensure guard mode and proxy skip paths also resolve through
ResolveRealBinary to prevent infinite shim recursion. Add table-driven
tests covering error cases, multi-binary PATH, and PATH restoration.

* fix: handle error return values from os.Setenv and file Close calls

Address errcheck lint failures: check os.Setenv returns in
ResolveRealBinary, and check f.Close/tempFile.Close in ShimManager.

* feat: auto-migrate shell aliases to PATH shims on setup install

When running `pmg setup install`, detect existing shell aliases and
automatically remove them before installing shims. Existing users
get a seamless migration with no extra flags or commands needed.

* fix: update E2E test to verify shim installation instead of alias RC file

Replace the .pmg.rc file check with assertions that ~/.pmg/bin/ exists
and contains executable shim scripts for npm and pip.

* feat: add FilterPMGFromPath utility for PATH shim recursion prevention

* feat: add FilterPMGFromEnv to filter PATH from env slices

* feat: filter ~/.pmg/bin from PATH in proxy subprocess env

* feat: add PathExport method to Shell interface for shim PATH integration

* feat: add ShimManager for PATH shim install/remove lifecycle

* feat: wire ShimManager into setup commands with --use-aliases fallback

* refactor: add DefaultShimConfig helper to reduce setup boilerplate

* fix: resolve real binary path to prevent shim double-invocation

exec.CommandContext resolves the binary using the current process PATH,
which still contains ~/.pmg/bin. This caused pmg to launch the shim
instead of the real package manager, resulting in a second pmg instance
with its own proxy — producing duplicate error messages and wasted work.

ResolveRealBinary searches a filtered PATH (without ~/.pmg/bin) to find
the real package manager binary before execution.

* fix: resolve real binary in runner.Execute and expand path resolution tests

Ensure guard mode and proxy skip paths also resolve through
ResolveRealBinary to prevent infinite shim recursion. Add table-driven
tests covering error cases, multi-binary PATH, and PATH restoration.

* fix: handle error return values from os.Setenv and file Close calls

Address errcheck lint failures: check os.Setenv returns in
ResolveRealBinary, and check f.Close/tempFile.Close in ShimManager.

* feat: auto-migrate shell aliases to PATH shims on setup install

When running `pmg setup install`, detect existing shell aliases and
automatically remove them before installing shims. Existing users
get a seamless migration with no extra flags or commands needed.

* fix: update E2E test to verify shim installation instead of alias RC file

Replace the .pmg.rc file check with assertions that ~/.pmg/bin/ exists
and contains executable shim scripts for npm and pip.

* feat: install both aliases and shims for full coverage

Aliases win in interactive shells (including venvs), shims catch
non-interactive contexts (IDEs, CI, subprocesses). Remove --use-aliases
flag and migration logic since both are always installed together.
Update E2E to verify all shim scripts and alias RC file.

* feat: address review feedback for shim implementation

- Install both aliases and shims together for full coverage
- Move homeDir resolution into NewDefaultShimManager (internal concern)
- Add mutex to ResolveRealBinary to guard against concurrent PATH mutation
- Use filepath.SplitList for platform-correct PATH splitting
- Add ResolveRealBinary to runner.Execute and proxy flow to prevent
  shim recursion in all execution paths
- Remove print side-effects from ShimManager.Remove
- Update E2E to verify all shim scripts and alias RC file
- Expand ResolveRealBinary tests with table-driven cases

* fix: restore errcheck handling and add concurrency test for ResolveRealBinary

- Restore proper defer with log.Warnf for PATH restoration in ResolveRealBinary
- Restore errcheck handling for f.Close() and tempFile.Close() in ShimManager
- Add explanatory comment for ResolveRealBinary call in proxy_flow
- Add TestResolveRealBinaryConcurrent to verify mutex guards concurrent access

* feat: skip shell integration on Windows with informative warning

On Windows, pmg setup install now writes only the config file and
prints a warning that shell aliases and PATH shims require WSL.

* fix: PMG use pre-resolved binary path (#253)

---------

Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
2026-05-12 22:27:05 +05:30

298 lines
7.4 KiB
Go

package alias
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/safedep/dry/log"
)
// AliasManager manages shell aliases for package managers.
type AliasManager struct {
config AliasConfig
rcFileManager RcFileManager
}
// AliasConfig holds configuration for alias management.
type AliasConfig struct {
RcFileName string
PackageManagers []string
Shells []Shell
}
// RcFileManager handles creation and removal of RC files.
type RcFileManager interface {
Create(aliases []string) (string, error)
Remove() error
GetRcPath() string
}
// DefaultRcFileManager implements RcFileManager for managing the RC file.
type defaultRcFileManager struct {
HomeDir string
RcFileName string
}
var _ RcFileManager = &defaultRcFileManager{}
// NewDefaultRcFileManager creates a new DefaultRcFileManager.
func NewDefaultRcFileManager(rcFileName string) (*defaultRcFileManager, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
return &defaultRcFileManager{
HomeDir: homeDir,
RcFileName: rcFileName,
}, nil
}
// Create creates the RC file with the given aliases.
func (m *defaultRcFileManager) Create(aliases []string) (string, error) {
rcPath := m.GetRcPath()
f, err := os.Create(rcPath)
if err != nil {
return "", err
}
defer f.Close()
for _, alias := range aliases {
if _, err := f.WriteString(alias); err != nil {
return "", fmt.Errorf("failed to write alias: %w", err)
}
}
return rcPath, nil
}
// Remove deletes the RC file.
func (m *defaultRcFileManager) Remove() error {
rcPath := m.GetRcPath()
if err := os.Remove(rcPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("could not delete %s: %w", rcPath, err)
}
return nil
}
// GetRcPath returns the full path to the RC file.
func (m *defaultRcFileManager) GetRcPath() string {
return filepath.Join(m.HomeDir, m.RcFileName)
}
// DefaultConfig returns the default configuration for alias management.
func DefaultConfig() AliasConfig {
var shells []Shell
fishShell, _ := NewFishShell()
zshShell, _ := NewZshShell()
bashShell, _ := NewBashShell()
shells = append(shells, fishShell, zshShell, bashShell)
return AliasConfig{
RcFileName: ".pmg.rc",
PackageManagers: []string{"npm", "pip", "pip3", "pnpm", "bun", "uv", "yarn", "poetry", "npx", "pnpx"},
Shells: shells,
}
}
// New creates a new AliasManager with the given configuration and RC file manager.
func New(config AliasConfig, rcFileManager RcFileManager) *AliasManager {
return &AliasManager{
config: config,
rcFileManager: rcFileManager,
}
}
// Install creates the RC file with aliases and sources it in shell configurations.
func (a *AliasManager) Install() error {
aliases := a.buildAliases()
_, err := a.rcFileManager.Create(aliases)
if err != nil {
return fmt.Errorf("failed to create alias file: %w", err)
}
err = a.sourceRcFile()
if err != nil {
return fmt.Errorf("failed to update shell configs: %w", err)
}
return nil
}
// Remove deletes the RC file and removes source lines from shell configurations.
func (a *AliasManager) Remove() error {
if err := a.rcFileManager.Remove(); err != nil {
log.Warnf("Warning: %v", err)
}
if err := a.removeSourceLinesFromShells(); err != nil {
return fmt.Errorf("failed to clean shell configs: %w", err)
}
return nil
}
// GetRcPath returns the path to the alias RC file managed by AliasManager.
func (a *AliasManager) GetRcPath() string {
return a.rcFileManager.GetRcPath()
}
// IsInstalled checks if the PMG aliases are sourced in any of the shell config files.
func (a *AliasManager) IsInstalled() (bool, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return false, err
}
for _, shell := range a.config.Shells {
configPath := filepath.Join(homeDir, shell.Path())
data, err := os.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
continue
}
log.Warnf("Warning: could not read %s (%s)", shell.Name(), err)
continue
}
if strings.Contains(string(data), a.config.RcFileName) {
return true, nil
}
}
return false, nil
}
// buildAliases creates the alias strings for all configured package managers.
func (a *AliasManager) buildAliases() []string {
aliases := make([]string, 0, len(a.config.PackageManagers))
for _, pm := range a.config.PackageManagers {
aliases = append(aliases, fmt.Sprintf("alias %s='pmg %s'\n", pm, pm))
}
return aliases
}
// sourceRcFile adds source lines to all shell configuration files.
func (a *AliasManager) sourceRcFile() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
for _, shell := range a.config.Shells {
configPath := filepath.Join(homeDir, shell.Path())
if err := a.addSourceLine(configPath, shell.Source(a.rcFileManager.GetRcPath())); err != nil {
log.Warnf("Warning: skipping %s (%s)", shell.Name(), err)
}
}
return nil
}
// removeSourceLinesFromShells removes source lines from all shell configuration files.
func (a *AliasManager) removeSourceLinesFromShells() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
for _, shell := range a.config.Shells {
configPath := filepath.Join(homeDir, shell.Path())
data, err := os.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
continue
}
log.Warnf("Warning: skipping %s (%s)", shell.Name(), err)
continue
}
// Get original file permissions
info, err := os.Stat(configPath)
if err != nil {
log.Warnf("Warning: skipping %s (%s)", shell.Name(), err)
continue
}
// Create temp file
tempFile, err := os.CreateTemp(filepath.Dir(configPath), ".tmp-"+filepath.Base(configPath))
if err != nil {
log.Warnf("Warning: failed to create temporary file for %s: %s", configPath, err)
continue
}
tempPath := tempFile.Name()
// Write filtered content
scanner := bufio.NewScanner(bytes.NewReader(data))
writer := bufio.NewWriter(tempFile)
for scanner.Scan() {
line := scanner.Text()
// Skip source lines and comment
if strings.Contains(line, a.config.RcFileName) ||
strings.TrimSpace(line) == strings.TrimSpace(commentForRemovingShellSource) {
continue
}
if _, err := writer.WriteString(line + "\n"); err != nil {
log.Warnf("Warning: failed to write to temporary file: %s", err)
}
}
if err := writer.Flush(); err != nil {
log.Warnf("Warning: failed to flush temporary file: %s", err)
}
if err := tempFile.Close(); err != nil {
log.Warnf("Warning: failed to close temporary file: %s", err)
}
// Set permissions on temporary file to match original file.
if err := os.Chmod(tempPath, info.Mode()); err != nil {
log.Warnf("Warning: failed to set permissions on temporary file for %s: %s", configPath, err)
}
// Replace original file
if err := os.Rename(tempPath, configPath); err != nil {
_ = os.Remove(tempPath)
log.Warnf("Warning: failed to update %s: %s", configPath, err)
}
}
return nil
}
// addSourceLine adds a source line to the specified shell configuration file.
func (a *AliasManager) addSourceLine(configPath, sourceLine string) error {
// Read existing content - only proceed if file exists
data, err := os.ReadFile(configPath)
if err != nil {
return err // file doesn't exist or can't read, skip
}
if strings.Contains(string(data), a.config.RcFileName) {
return nil // already sourced, skip
}
f, err := os.OpenFile(configPath, os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
_, err = fmt.Fprintf(f, "\n%s", sourceLine)
return err
}