easycmd

package module
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2026 License: Apache-2.0 Imports: 8 Imported by: 1

README

easycmd

언어 / Language: English | 한국어

A command execution library written in Go. It provides a wrapper that makes it easy to run external commands and control their standard input/output.

Installation

go get github.com/seungyeop-lee/easycmd

Basic Usage

Running a simple command
package main

import (
    "github.com/seungyeop-lee/easycmd"
)

func main() {
    cmd := easycmd.New()
    err := cmd.Run("echo hello world")
    if err != nil {
        panic(err)
    }
}
Capturing standard output
package main

import (
    "bytes"
    "fmt"
    "github.com/seungyeop-lee/easycmd"
)

func main() {
    out := &bytes.Buffer{}
    cmd := easycmd.New(easycmd.WithStdOut(out))

    err := cmd.Run("echo hello world")
    if err != nil {
        panic(err)
    }

    fmt.Println("output:", out.String()) // output: hello world (trailing newline included)
}

Advanced Usage

Running a Shell command
cmd := easycmd.New()

// Run a command wrapped with bash
err := cmd.RunShell("(cd .. && pwd)")

// Run a multi-line shell script
err = cmd.RunShell(`
    pwd
    ls -al
`)
Running a PowerShell command (Windows)
cmd := easycmd.New()
err := cmd.RunPowershell("Get-Location")
Running in a specific directory
cmd := easycmd.New()

// Run a basic command in a specific directory
err := cmd.RunWithDir("ls", "/tmp")

// Run a shell command in a specific directory
err = cmd.RunShellWithDir("pwd && ls", "/tmp")

// Run a PowerShell command in a specific directory
err = cmd.RunPowershellWithDir("Get-ChildItem", "C:\\temp")
Custom configuration
import (
    "os"
    "strings"
)

cmd := easycmd.New(
    easycmd.WithStdIn(strings.NewReader("input")), // set standard input
    easycmd.WithStdOut(os.Stdout),                 // set standard output
    easycmd.WithStdErr(os.Stderr),                 // set standard error
    easycmd.WithTimeoutSeconds(30),                // set timeout (30 seconds)
    easycmd.WithEnv([]string{"VAR=value"}),        // set environment variables
)

err := cmd.Run("cat") // reads "input" from stdin and prints it
Debug mode
import (
    "bytes"
    "fmt"
)

// Default debug mode (debug output goes to stderr)
cmd := easycmd.New(easycmd.WithDebug())
err := cmd.Run("echo hello world")

// Custom debug output stream
debugOut := &bytes.Buffer{}
cmd = easycmd.New(easycmd.WithDebug(debugOut))
err = cmd.Run("echo hello world")

fmt.Println("debug output:", debugOut.String())
Timeout configuration
// Recommended: use the intuitive APIs
cmd := easycmd.New(easycmd.WithTimeoutSeconds(5))    // 5 seconds
err := cmd.Run("sleep 3") // completes normally

cmd = easycmd.New(easycmd.WithTimeoutMillis(1500))   // 1.5 seconds
err = cmd.Run("sleep 3")  // times out after 1.5 seconds

// You can also use time.Duration directly
import "time"
cmd = easycmd.New(easycmd.WithTimeout(5 * time.Second))
err = cmd.Run("sleep 10") // times out after 5 seconds

if err != nil {
    fmt.Printf("command execution failed: %v\n", err)
}

⚠️ Caution: Passing a bare number to WithTimeout() is interpreted as nanoseconds!

// ❌ Incorrect
cmd := easycmd.New(easycmd.WithTimeout(5))  // 5 nanoseconds (times out almost immediately)

// ✅ Correct
cmd := easycmd.New(easycmd.WithTimeoutSeconds(5))       // 5 seconds
cmd := easycmd.New(easycmd.WithTimeout(5 * time.Second)) // 5 seconds
Environment variables
cmd := easycmd.New(
    easycmd.WithEnv([]string{
        "MY_VAR=hello",
        "ANOTHER_VAR=world",
    }),
)

// Run a shell command that uses environment variables
err := cmd.RunShell("echo $MY_VAR $ANOTHER_VAR")

⚠️ Caution: WithEnv() completely replaces the process environment and is not merged with os.Environ(). If you need PATH or similar, include them explicitly. See the WithEnv godoc for details and merge examples.

Combined configuration
import (
    "bytes"
    "os"
    "strings"
)

out := &bytes.Buffer{}
debugOut := &bytes.Buffer{}
input := strings.NewReader("test input\n")

cmd := easycmd.New(
    easycmd.WithStdIn(input),
    easycmd.WithStdOut(out),
    easycmd.WithStdErr(os.Stderr),
    easycmd.WithDebug(debugOut),
    easycmd.WithTimeoutSeconds(10),                 // 10-second timeout
    easycmd.WithEnv([]string{"LANG=ko_KR.UTF-8"}),
)

err := cmd.RunShell("cat && echo 'processing...' >&2")

API Reference

Main methods
  • New(configApplies ...configApply) *Cmd: creates a new Cmd instance
  • Run(commandStr string) error: runs a basic command
  • RunShell(commandStr string) error: runs a command wrapped with bash
  • RunPowershell(commandStr string) error: runs a command wrapped with PowerShell
  • RunWithDir(commandStr string, runDirStr string) error: runs a basic command in a specific directory
  • RunShellWithDir(commandStr string, runDirStr string) error: runs a shell command in a specific directory
  • RunPowershellWithDir(commandStr string, runDirStr string) error: runs a PowerShell command in a specific directory
Configuration functions
  • WithStdIn(reader io.Reader) configApply: set standard input
  • WithStdOut(writer io.Writer) configApply: set standard output
  • WithStdErr(writer io.Writer) configApply: set standard error
  • WithDebug(debugOut ...io.Writer) configApply: enable debug mode and set the debug output stream
  • WithTimeout(timeout time.Duration) configApply: set command execution timeout (time.Duration)
  • WithTimeoutSeconds(seconds int) configApply: set command execution timeout in seconds ⭐ recommended
  • WithTimeoutMillis(millis int) configApply: set command execution timeout in milliseconds ⭐ recommended
  • WithEnv(env []string) configApply: set environment variables

For detailed behavior of each function (debug output items, timeout pitfalls, environment variable replacement rules, etc.), see the godoc (pkg.go.dev) or the source code comments.

Error Handling

cmd := easycmd.New()
err := cmd.Run("invalid-command")
if err != nil {
    fmt.Printf("command execution failed: %v\n", err)
}

// Special error for an empty command
err = cmd.Run("")
if errors.Is(err, easycmd.EmptyCmdError) {
    fmt.Println("empty command")
}
Timeout error types

Timeouts can occur in two stages (before the process starts / during execution), and currently they can only be distinguished by the error message prefix. See the Cmd.Run godoc for the prefix strings and details.

cmd := easycmd.New(easycmd.WithTimeoutMillis(1))
err := cmd.Run("sleep 1")

if err != nil {
    errMsg := err.Error()

    if strings.Contains(errMsg, "command failed to start") {
        fmt.Println("timeout occurred before command start")
    } else if strings.Contains(errMsg, "command execution timed out") {
        fmt.Println("timeout occurred during command execution")
    }
}

License

This project is distributed under the Apache License 2.0. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EmptyCmdError = errors.New("empty command")

EmptyCmdError is returned by the Run family of methods when the provided command string is empty (or resolves to only a shell wrapper prefix with no payload). Use errors.Is to check for this sentinel.

Functions

func WithDebug added in v0.4.0

func WithDebug(debugOut ...io.Writer) configApply

WithDebug enables debug mode for command execution. The optional debugOut writer receives debug messages; if omitted, debug output is written to os.Stderr.

When debug mode is active, the following information is emitted:

  • Parsed command string
  • Resolved command name and argument list
  • Working directory (when set)
  • Timeout setting (when set)
  • Number of environment variables (when set)
  • Execution start, completion, and failure messages
  • Measured execution duration

func WithEnv added in v0.5.0

func WithEnv(env []string) configApply

WithEnv sets the environment variables for the command.

The provided slice fully replaces the process environment for the executed command; it is not merged with os.Environ(). Variables such as PATH and HOME are therefore dropped unless explicitly included, which may cause shells or external binaries to fail to launch. To preserve the current environment, append to os.Environ():

env := append(os.Environ(), "MY_VAR=hello")
cmd := easycmd.New(easycmd.WithEnv(env))

func WithStdErr added in v0.4.0

func WithStdErr(writer io.Writer) configApply

WithStdErr sets the standard error stream for the command.

func WithStdIn added in v0.4.0

func WithStdIn(reader io.Reader) configApply

WithStdIn sets the standard input stream for the command.

func WithStdOut added in v0.4.0

func WithStdOut(writer io.Writer) configApply

WithStdOut sets the standard output stream for the command.

func WithTimeout added in v0.5.0

func WithTimeout(timeout time.Duration) configApply

WithTimeout sets the command execution timeout as a time.Duration.

Because time.Duration's underlying unit is nanoseconds, passing a bare integer literal is almost always a bug: WithTimeout(5) means "5 nanoseconds", which triggers an immediate timeout. Multiply by a unit constant (for example, 5 * time.Second) or prefer the unit-specific helpers WithTimeoutSeconds and WithTimeoutMillis.

func WithTimeoutMillis added in v0.6.0

func WithTimeoutMillis(millis int) configApply

WithTimeoutMillis sets the command execution timeout in milliseconds. It is a convenience wrapper around WithTimeout that avoids the nanosecond pitfall of passing a bare integer to WithTimeout.

func WithTimeoutSeconds added in v0.6.0

func WithTimeoutSeconds(seconds int) configApply

WithTimeoutSeconds sets the command execution timeout in seconds. It is a convenience wrapper around WithTimeout that avoids the nanosecond pitfall of passing a bare integer to WithTimeout.

Types

type Cmd

type Cmd struct {
	// contains filtered or unexported fields
}

Cmd executes an external command using the configuration captured at construction time via New.

func New

func New(configApplies ...configApply) *Cmd

New creates a new Cmd instance. Configuration is applied through the functional options exposed by the With* functions. Options that are not provided fall back to defaults: os.Stdin, os.Stdout, and os.Stderr for the standard streams, no timeout, no debug output, and the inherited process environment.

func (*Cmd) Run

func (c *Cmd) Run(commandStr string) error

Run executes commandStr as-is.

Run returns EmptyCmdError when commandStr is empty. When a timeout is configured via WithTimeout, WithTimeoutSeconds, or WithTimeoutMillis, the returned error message uses one of two Korean prefixes to indicate the phase in which the deadline was exceeded:

  • "command failed to start": the deadline expired before the process started.
  • "command execution timed out": the deadline expired after the process started.

These prefixes are currently the only way to distinguish the two timeout phases; no sentinel error or typed error is exposed for them, so callers should treat the exact message format as subject to change.

func (*Cmd) RunPowershell added in v0.2.0

func (c *Cmd) RunPowershell(commandStr string) error

RunPowershell wraps commandStr with PowerShell and executes it. Error semantics match Run.

func (*Cmd) RunPowershellWithDir added in v0.2.0

func (c *Cmd) RunPowershellWithDir(commandStr string, runDirStr string) error

RunPowershellWithDir executes a PowerShell-wrapped commandStr in the working directory runDirStr. Error semantics match Run.

func (*Cmd) RunShell added in v0.2.0

func (c *Cmd) RunShell(commandStr string) error

RunShell wraps commandStr with bash -c and executes it. Error semantics match Run.

func (*Cmd) RunShellWithDir added in v0.2.0

func (c *Cmd) RunShellWithDir(commandStr string, runDirStr string) error

RunShellWithDir executes a bash-wrapped commandStr in the working directory runDirStr. Error semantics match Run.

func (*Cmd) RunWithDir

func (c *Cmd) RunWithDir(commandStr string, runDirStr string) error

RunWithDir executes commandStr in the working directory runDirStr. Error semantics match Run.

type DebugLogger added in v0.5.0

type DebugLogger struct {
	// contains filtered or unexported fields
}

DebugLogger 실제 디버그 출력을 수행하는 구현체

func NewDebugLogger added in v0.5.0

func NewDebugLogger(out io.Writer) *DebugLogger

NewDebugLogger DebugLogger 인스턴스를 생성합니다

func (*DebugLogger) Environment added in v0.5.0

func (d *DebugLogger) Environment(envCount int)

func (*DebugLogger) ExecutionCommand added in v0.5.0

func (d *DebugLogger) ExecutionCommand(name string, args []string)

func (*DebugLogger) ExecutionCompleted added in v0.5.0

func (d *DebugLogger) ExecutionCompleted()

func (*DebugLogger) ExecutionDirectory added in v0.5.0

func (d *DebugLogger) ExecutionDirectory(dir string)

func (*DebugLogger) ExecutionFailed added in v0.5.0

func (d *DebugLogger) ExecutionFailed(err error, isTimeout bool)

func (*DebugLogger) ExecutionStart added in v0.5.0

func (d *DebugLogger) ExecutionStart()

func (*DebugLogger) ParsedCommand added in v0.5.0

func (d *DebugLogger) ParsedCommand(command string)

func (*DebugLogger) StartFailed added in v0.5.0

func (d *DebugLogger) StartFailed(err error)

func (*DebugLogger) Timeout added in v0.5.0

func (d *DebugLogger) Timeout(timeout time.Duration)

type Logger added in v0.5.0

type Logger interface {
	ParsedCommand(command string)
	ExecutionCommand(name string, args []string)
	ExecutionDirectory(dir string)
	ExecutionStart()
	Timeout(timeout time.Duration)
	Environment(envCount int)
	StartFailed(err error)
	ExecutionFailed(err error, isTimeout bool)
	ExecutionCompleted()
}

Logger 디버그 출력을 담당하는 인터페이스

type NoOpLogger added in v0.5.0

type NoOpLogger struct{}

NoOpLogger 아무것도 하지 않는 로거 구현체 (Null Object Pattern)

func NewNoOpLogger added in v0.5.0

func NewNoOpLogger() *NoOpLogger

NewNoOpLogger NoOpLogger 인스턴스를 생성합니다

func (*NoOpLogger) Environment added in v0.5.0

func (n *NoOpLogger) Environment(envCount int)

func (*NoOpLogger) ExecutionCommand added in v0.5.0

func (n *NoOpLogger) ExecutionCommand(name string, args []string)

func (*NoOpLogger) ExecutionCompleted added in v0.5.0

func (n *NoOpLogger) ExecutionCompleted()

func (*NoOpLogger) ExecutionDirectory added in v0.5.0

func (n *NoOpLogger) ExecutionDirectory(dir string)

func (*NoOpLogger) ExecutionFailed added in v0.5.0

func (n *NoOpLogger) ExecutionFailed(err error, isTimeout bool)

func (*NoOpLogger) ExecutionStart added in v0.5.0

func (n *NoOpLogger) ExecutionStart()

func (*NoOpLogger) ParsedCommand added in v0.5.0

func (n *NoOpLogger) ParsedCommand(command string)

func (*NoOpLogger) StartFailed added in v0.5.0

func (n *NoOpLogger) StartFailed(err error)

func (*NoOpLogger) Timeout added in v0.5.0

func (n *NoOpLogger) Timeout(timeout time.Duration)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL