command

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: GPL-3.0 Imports: 9 Imported by: 0

README

Command Runner

Обёртка над os/exec для запуска внешних команд. Пакет самодостаточный — ничего не знает про apm. Debug-логирование подключается снаружи:

command.SetLogger(myLogger) // любой тип с Debug(args ...any), по умолчанию молчит

Использование

r := command.NewRunner("pkexec", verbose)
stdout, stderr, err := r.Run(ctx, []string{"apt-get", "update"})

Run всегда возвращает stdout и stderr раздельно, даже если вывод дублировался в консоль.

Опции

r.Run(ctx, args,
    command.WithEnv("LC_ALL=C"),        // добавить переменные окружения
    command.WithDir("/tmp"),            // рабочая директория
    command.WithStdin(reader),          // stdin
    command.WithShell(),                // через bash -c (пайпы, спецсимволы)
    command.WithPassthrough(),          // вывод сразу в консоль
    command.WithQuiet(),                // молчать даже в verbose-режиме
    command.WithPTY(rows, cols),        // pseudo-tty для интерактивного прогресса
    command.WithStreamHandler(h),       // свой обработчик потока stdout
    command.WithOutputCommand(cmd, &s), // вторая команда, результат в s
)

Логика вывода простая: verbose у раннера включает passthrough для всех команд, WithQuiet() его выключает точечно.

Режимы выполнения

Раннер сам выбирает режим по опциям, приоритет сверху вниз:

  1. PTY — команда получает настоящий терминал заданного размера. Нужно для команд, которые рисуют прогресс и в пайпе ведут себя иначе (или буферизуют вывод).
  2. Divider — основная команда и WithOutputCommand склеиваются в один bash-скрипт через set -e, между ними печатается строка-разделитель. Всё до разделителя — stdout основной команды, всё после — уходит в dest. Смысл: получить два результата за один запуск (например, состояние после операции), не платя за второй процесс с префиксом.
  3. Shellbash -c, когда нужны пайпы и подстановки.
  4. Direct — обычный exec, по умолчанию.

Ошибки

ErrEmptyCommand — пустая команда. Остальное — как вернул exec (включая *exec.ExitError), плюс stderr всегда доступен отдельно для анализа выше.

Documentation

Index

Constants

This section is empty.

Variables

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

Functions

func SetLogger

func SetLogger(l Logger)

SetLogger sets the debug logger

Types

type Logger

type Logger interface {
	Debug(args ...any)
}

Logger is the minimal logging interface used by the package

type Option

type Option func(*options)

Option configures command execution

func WithDir

func WithDir(dir string) Option

WithDir sets the working directory for the command

func WithEnv

func WithEnv(env ...string) Option

WithEnv adds environment variables to the command

func WithOutputCommand

func WithOutputCommand(command string, dest *string) Option

WithOutputCommand adds a second command to capture extra output. The second command's result is written to dest.

func WithPTY

func WithPTY(rows, cols uint16) Option

WithPTY runs the command in a pseudo-tty with the given window size. Used for commands that show interactive progress.

func WithPassthrough

func WithPassthrough() Option

WithPassthrough routes stdout/stderr directly to the console

func WithQuiet

func WithQuiet() Option

WithQuiet suppresses console output even if the runner is verbose

func WithShell

func WithShell() Option

WithShell runs the command via bash -c (for pipes and special characters)

func WithStdin

func WithStdin(r io.Reader) Option

WithStdin sets stdin for the command

func WithStreamHandler

func WithStreamHandler(h func(io.Reader)) Option

WithStreamHandler registers a stdout stream handler.

type Runner

type Runner interface {
	// Run executes a command with commandPrefix applied and verbose mode honored
	// Returns stdout, stderr, error
	Run(ctx context.Context, args []string, opts ...Option) (string, string, error)
}

Runner is the interface for executing commands

func NewRunner

func NewRunner(commandPrefix string, verbose bool) Runner

NewRunner creates a new Runner.

Jump to

Keyboard shortcuts

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