cmder

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2024 License: MIT Imports: 12 Imported by: 1

README

cmder

cmder is a Go package designed to facilitate the execution of external commands with advanced features such as retries, timeouts, and output collection. It provides a flexible and robust way to run commands, handle their input/output, and manage their execution lifecycle.

Features

  • Command Execution: Run external commands with specified arguments.
  • Timeouts: Set timeouts for individual attempts and total execution time.
  • Retries: Retry commands on failure with customizable retry policies.
  • Output Handling: Capture and manage standard output and error streams.
  • Verbose Logging: Enable detailed logging for debugging purposes.
  • Working Directory: Specify the working directory for the command execution.
  • Input Forwarding: Forward standard input to the command.

Installation

To install the package, use:

go get github.com/GiGurra/cmder

Usage

Here's a basic example of how to use cmder to run a command:

package main

import (
	"context"
	"fmt"
	"github.com/GiGurra/cmder"
	"time"
)

func main() {
	result := cmder.New("ls", "-la").
		WithAttemptTimeout(5 * time.Second).
		WithRetries(3).
		WithVerbose(true).
		Run(context.Background())

	if result.Err != nil {
		fmt.Printf("Command failed: %v\n", result.Err)
	} else {
		fmt.Printf("Command succeeded: %s\n", result.StdOut)
	}
}

API

Spec

Every command is defined by a Spec struct (created by cmder.New(..)), which contains the command specification and options. The Spec struct provides methods to configure the command, such as setting the application to run, arguments, timeouts, retries, and output handling.

The Spec struct defines the command specification and options:

  • App: The application to run.
  • Args: Arguments for the command.
  • WorkingDirectory: The working directory for the command.
  • AttemptTimeout: Timeout for each attempt.
  • TotalTimeout: Total timeout including retries.
  • ResetAttemptTimeoutOnOutput: Reset attempt timeout on output.
  • Retries: Number of retries before giving up.
  • RetryFilter: Custom retry filter function.
  • StdIn: Standard input for the command.
  • StdOut: Standard output for the command.
  • StdErr: Standard error for the command.
  • CollectAllOutput: Whether to collect all output.
  • Verbose: Enable verbose logging.

The Spec struct provides the following builder methods to configure the command:

  • WithTotalTimeout(timeout time.Duration) Spec: Set total timeout.
  • WithStdOut(writer io.Writer) Spec: Set standard output writer.
  • WithStdErr(writer io.Writer) Spec: Set standard error writer.
  • WithResetAttemptTimeoutOnOutput(enabled bool) Spec: Enable/disable resetting attempt timeout on output.
  • WithWorkingDirectory(wd string) Spec: Set working directory.
  • WithCollectAllOutput(collect bool) Spec: Enable/disable collecting all output.
  • WithStdIn(reader io.Reader) Spec: Set standard input reader.
  • WithApp(app string) Spec: Set application to run.
  • WithArgs(newArgs ...string) Spec: Set command arguments.
  • WithExtraArgs(extraArgs ...string) Spec: Append extra arguments.
  • WithRetryFilter(filter func(err error, isAttemptTimeout bool) bool) Spec: Set retry filter.
  • WithRetries(n int) Spec: Set number of retries.
  • WithVerbose(verbose bool) Spec: Enable/disable verbose logging.
  • WithAttemptTimeout(timeout time.Duration) Spec: Set attempt timeout.
  • Run(ctx context.Context) Result: Run the command and return the result.

Each method returns a new Spec instance, allowing for method chaining to configure the command. You can also create general templates that you re-use across multiple commands and modules of your program.

Result

The Result struct contains the result of the command execution:

  • StdOut: Captured standard output.
  • StdErr: Captured standard error.
  • Combined: Combined output of standard output and error.
  • Err: Error encountered during execution.
  • Attempts: Number of attempts made.
  • ExitCode: Exit code of the command.

Testing

The package includes tests to verify its functionality. To run the tests, use:

go test ./...

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.


For more details, refer to the source code and comments within the package.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultRetryFilter

func DefaultRetryFilter(err error, isAttemptTimeout bool) bool

func TimeoutRetryFilter

func TimeoutRetryFilter(err error, isAttemptTimeout bool) bool

TimeoutRetryFilter is a simple retry policy that retries on timeouts only

Types

type Result

type Result struct {
	StdOut   string
	StdErr   string
	Combined string
	Err      error
	Attempts int
	ExitCode int
}

type Spec

type Spec struct {

	// Minimum input
	App  string
	Args []string

	// Extra options
	WorkingDirectory            string
	AttemptTimeout              time.Duration
	TotalTimeout                time.Duration
	ResetAttemptTimeoutOnOutput bool
	Retries                     int
	RetryFilter                 func(err error, isAttemptTimeout bool) bool

	// Input/Output
	StdIn            io.Reader
	StdOut           io.Writer // if capturing output while running
	StdErr           io.Writer // if capturing output while running
	CollectAllOutput bool      // if running for a very long time, set this false to avoid OOM

	// debug functionality
	Verbose bool
}

func New

func New(appAndArgs ...string) Spec

func NewA

func NewA(app string, args ...string) Spec

func (Spec) Run

func (c Spec) Run(ctx context.Context) Result

func (Spec) WithApp

func (c Spec) WithApp(app string) Spec

WithApp sets the application to run

func (Spec) WithArgs

func (c Spec) WithArgs(newArgs ...string) Spec

WithArgs sets the arguments for the command

func (Spec) WithAttemptTimeout

func (c Spec) WithAttemptTimeout(timeout time.Duration) Spec

WithAttemptTimeout sets the timeout for the command This is the total time the command can run, per attempt

func (Spec) WithCollectAllOutput

func (c Spec) WithCollectAllOutput(collect bool) Spec

WithCollectAllOutput sets whether to collect all output. Default is true. If false, you need to inject your own io.Writer

func (Spec) WithExtraArgs

func (c Spec) WithExtraArgs(extraArgs ...string) Spec

WithExtraArgs appends the arguments to the command

func (Spec) WithResetAttemptTimeoutOnOutput

func (c Spec) WithResetAttemptTimeoutOnOutput(enabled bool) Spec

WithResetAttemptTimeoutOnOutput resets the timeout if output is received from the command

func (Spec) WithRetries

func (c Spec) WithRetries(n int) Spec

WithRetries sets the number of retries before giving up

func (Spec) WithRetryFilter

func (c Spec) WithRetryFilter(filter func(err error, isAttemptTimeout bool) bool) Spec

WithRetryFilter sets the retry filter

func (Spec) WithStdErr

func (c Spec) WithStdErr(writer io.Writer) Spec

WithStdErr sets the standard error for the command

func (Spec) WithStdErrForwarded

func (c Spec) WithStdErrForwarded() Spec

func (Spec) WithStdIn

func (c Spec) WithStdIn(reader io.Reader) Spec

WithStdIn sets the standard input for the command

func (Spec) WithStdInForwarded

func (c Spec) WithStdInForwarded() Spec

WithStdInForwarded sets the standard input to os.Stdin

func (Spec) WithStdOut

func (c Spec) WithStdOut(writer io.Writer) Spec

WithStdOut sets the standard output for the command

func (Spec) WithStdOutErrForwarded

func (c Spec) WithStdOutErrForwarded() Spec

func (Spec) WithStdOutForwarded

func (c Spec) WithStdOutForwarded() Spec

func (Spec) WithTotalTimeout

func (c Spec) WithTotalTimeout(timeout time.Duration) Spec

WithTotalTimeout sets the total timeout for the command including retries

func (Spec) WithVerbose

func (c Spec) WithVerbose(verbose bool) Spec

WithVerbose sets the verbose flag

func (Spec) WithWorkingDirectory

func (c Spec) WithWorkingDirectory(wd string) Spec

WithWorkingDirectory sets the working directory for the command

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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