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)

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"
)

Functions

LogStartStop

func LogStartStop(msg string, command func(p Printer) error) error
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
}
func (s *reprintableStream) Write(p []byte) (total int, err error)

newReprintableStream

func newReprintableStream(s io.Writer, prefix, color string) io.Writer

LogCommand

func LogCommand(c *exec.Cmd, p Printer) error
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)
base, err := StripExtension("file.txt", ".txt")
if err != nil {
    // handle error
}
// base == "file"

Implementation Details and Algorithms


Interactions With Other Parts of the System


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]