Files
ThothII/tools/tht/internal/compose/runner.go
T

87 lines
2.4 KiB
Go

// Package compose executes Docker Compose through a fixed executable and argument arrays.
package compose
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"github.com/aritmolab/thothii/tools/tht/internal/config"
)
// Result is the captured output and process exit code for one Docker invocation.
type Result struct {
Stdout string
Stderr string
ExitCode int
}
// Runner is the shell-free Docker command boundary used by the host CLI.
type Runner interface {
Run(context.Context, []string, io.Reader) (Result, error)
}
// execRunner executes the Docker CLI. It never invokes a shell.
type execRunner struct {
binary string
}
// NewRunner returns a runner for binary. An empty binary selects docker from PATH.
func NewRunner(binary string) Runner {
if binary == "" {
binary = "docker"
}
return execRunner{binary: binary}
}
// Run invokes Docker with the supplied argument array and optional standard input.
func (r execRunner) Run(ctx context.Context, args []string, stdin io.Reader) (Result, error) {
command := exec.CommandContext(ctx, r.binary, args...)
command.Stdin = stdin
var stdout, stderr bytes.Buffer
command.Stdout = &stdout
command.Stderr = &stderr
err := command.Run()
result := Result{Stdout: stdout.String(), Stderr: stderr.String()}
if err == nil {
return result, nil
}
var exitError *exec.ExitError
if errors.As(err, &exitError) {
result.ExitCode = exitError.ExitCode()
return result, err
}
if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) {
result.ExitCode = 127
return result, fmt.Errorf("%w: %w", exec.ErrNotFound, err)
}
return result, err
}
// InstallationRunner applies an installation's validated Compose arguments to commands that
// explicitly start with compose. Direct Docker image commands remain host-side.
type InstallationRunner struct {
Installation config.Installation
Runner Runner
}
// SessionInventoryScope supplies the installation's intended visibility to lifecycle callers.
func (r InstallationRunner) SessionInventoryScope() string {
if r.Installation.Profile == "local" {
return "mine"
}
return "all"
}
// Run transforms only Compose invocations. It never performs shell interpolation.
func (r InstallationRunner) Run(ctx context.Context, args []string, stdin io.Reader) (Result, error) {
if len(args) > 0 && args[0] == "compose" {
return r.Runner.Run(ctx, r.Installation.ComposeArgs(args[1:]...), stdin)
}
return r.Runner.Run(ctx, args, stdin)
}