oscmd.go
Overview
The oscmd.go file provides utility functions and types for running and logging external operating system commands with enhanced output formatting and error handling. It includes mechanisms for color-coded console output, structured logging around command execution, and stream decoration for command stdout/stderr. Additionally, it offers a helper to enforce file extension expectations.
This file primarily focuses on improving the developer experience when invoking OS commands programmatically by providing consistent, readable logs and output streams formatted with color and prefixes. It facilitates diagnostic output and error reporting in a clear, user-friendly manner.
Types and Variables
Printer
type Printer func(a ...any)
Description:
A function type alias for printing arbitrary arguments. It is used as a standardized callback signature for printing messages, often with formatted or colorized output.Usage:
Passed as a callback parameter to functions likeLogStartStoporLogCommandto direct logging output.
ANSI Color Constants
var (
Reset = "\033[0m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
Gray = "\033[37m"
White = "\033[97m"
)
Description:
String constants representing ANSI escape codes for terminal colors. Used to colorize console output for status messages and logs.Usage:
Applied to strings to highlight success (Green), warnings or commands (Yellow), errors (Red), and other informational output.
Functions
LogStartStop
func LogStartStop(msg string, command func(p Printer) error) error
Purpose:
Executes a provided command function with logging around its lifecycle: starting, running, and completion status.Parameters:
msg string: A descriptive message about the command or operation being run.command func(p Printer) error: A function representing the command to execute. It receives aPrintercallback to print messages during execution.
Returns:
error: The error returned by the command function, if any.
Behavior:
Prints a "Starting" message with green color.
Calls the
commandfunction, passing a printer that prepends a green prompt to logs.On completion, prints either "Finished successfully" in green or "Finished with error" in red along with the error details.
Example:
err := LogStartStop("Download files", func(p Printer) error {
p("Downloading from URL...")
// perform the download here
return nil // or return an error if failed
})
reprintableStream (struct)
type reprintableStream struct {
prefix []byte
clean bool
stream io.Writer
}
Description:
Implements theio.Writerinterface to wrap another stream and decorate each line of output with a prefix and color.Fields:
prefix []byte: The byte sequence prepended before each new line. Typically includes color sequences and indentation.clean bool: Indicates whether the next write should first write the prefix (true when starting a new line).stream io.Writer: The underlying output stream to write to (e.g.,os.Stdout).
Method:
func (s *reprintableStream) Write(p []byte) (total int, err error)
Behavior:
Writes the input bytes to the underlying stream, inserting the prefix before each new line. It detects newline characters ('\n') and inserts the prefix after them for subsequent lines. This ensures multi-line output is consistently decorated.
newReprintableStream
func newReprintableStream(s io.Writer, prefix, color string) io.Writer
Purpose:
Factory function to create areprintableStreamwriter that decorates each line of output with a colored prefix.Parameters:
s io.Writer: The underlying output stream (usuallyos.Stdout).prefix string: The text prefix to prepend on each line.color string: ANSI color code to apply to the prefix.
Returns:
io.Writer: The decorated stream implementingio.Writer.
Usage:
Used internally byLogCommandto decorate command output streams with color and indentation.
LogCommand
func LogCommand(c *exec.Cmd, p Printer) error
Purpose:
Runs an external OS command while pretty-printing its stdout and stderr streams with colorized, prefixed output.Parameters:
c *exec.Cmd: The command to execute (fromos/execpackage).p Printer: A printing function for logging the command invocation.
Returns:
error: The error returned by executing the command.
Behavior:
Prints the command directory and command string with yellow color.
Wraps the command's
StdoutandStderrwithreprintableStreams that prefix each output line with a yellow marker.Executes the command synchronously by calling
c.Run().
Example:
cmd := exec.Command("ls", "-l")
cmd.Dir = "/tmp"
err := LogCommand(cmd, func(a ...any) { fmt.Println(a...) })
StripExtension
func StripExtension(p, expected string) (string, error)
Purpose:
Validates that a file path ends with the expected extension and returns the path without that extension.Parameters:
p string: The file path to check.expected string: The expected file extension, including the dot (e.g., ".txt").
Returns:
string: The file path without the extension if it matches.error: An error if the extension is missing or does not match the expected.
Behavior:
Extracts the extension from
pusingpath.Ext.Checks if the extension is present and matches
expected.Returns the stripped path or an error describing the mismatch.
Example:
base, err := StripExtension("file.txt", ".txt")
if err != nil {
// handle error
}
// base == "file"
Implementation Details and Algorithms
Stream Decoration:
ThereprintableStreamtype intercepts writes to an output stream, scanning for newline characters to insert a prefix and color escape codes at the beginning of each new line. This allows multi-line outputs (such as command stdout/stderr) to be neatly formatted with consistent indentation and color.Command Execution with Logging:
LogStartStopprovides a generic wrapper around a command function, printing standardized start and finish messages with color-coded status. It accepts aPrintercallback so the command can print intermediate messages with consistent formatting.Command Output Handling:
LogCommandintegrates the stream decoration logic directly with theexec.Cmdoutput streams, applying color and indentation dynamically during command execution.Extension Validation:
StripExtensionenforces expected file extensions, guarding against incorrect file inputs and facilitating safe file path manipulations.
Interactions With Other Parts of the System
This utility file is designed to be used by higher-level components that need to invoke OS commands and report progress or errors to the console or logs.
It can be combined with workflow or agent orchestration layers that require running subprocesses with clear status logs (potentially related to Agent Workflow Management or Agent Execution Runner).
The color-coded output and logging conventions promote consistent UX in CLI or developer tools elsewhere in the system.
The
Printertype and logging abstractions are reusable for any component needing structured console output.The file has no direct dependencies on higher-level business logic but serves as a foundational utility module within the
utilpackage.
Diagram of Structure and Flow
flowchart TD
A[LogStartStop] --> B[command func with Printer]
A --> C[Print start message]
A --> D["Call command(p Printer)"]
A --> E[Print success or error message]
subgraph Stream Decoration
F[reprintableStream] --> G[Write method]
H[newReprintableStream] --> F
end
I[LogCommand] --> J[Print command info]
I --> K[Decorate Stdout with reprintableStream]
I --> L[Decorate Stderr with reprintableStream]
I --> M[Run exec.Cmd]
N[StripExtension] --> O[Check extension]
N --> P[Return stripped path or error]
Explanation:
The flowchart illustrates howLogStartStoporchestrates command execution with logging, the role ofreprintableStreamin decorating output streams, and howLogCommandsets up decorated command execution.StripExtensionis a standalone utility validating file extensions.