Files

86 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//go:build linux || freebsd
// +build linux freebsd
package cli
import (
"fmt"
"io"
"os"
"strings"
)
// PrintError prints an error with color styling
func PrintError(w io.Writer, err error) {
prefix, suffix := "", ""
if isColorTerminal(w) {
prefix = ColorRed + ColorBold
suffix = ColorReset
}
fmt.Fprintf(w, "%s✗ Error:%s %v\n", prefix, suffix, err)
}
// PrintWarning prints a warning with color styling
func PrintWarning(w io.Writer, msg string) {
prefix, suffix := "", ""
if isColorTerminal(w) {
prefix = ColorYellow + ColorBold
suffix = ColorReset
}
fmt.Fprintf(w, "%s⚠ Warning:%s %s\n", prefix, suffix, msg)
}
// PrintSuccess prints a success message with color styling
func PrintSuccess(w io.Writer, msg string) {
prefix, suffix := "", ""
if isColorTerminal(w) {
prefix = ColorGreen + ColorBold
suffix = ColorReset
}
fmt.Fprintf(w, "%s✓%s %s\n", prefix, suffix, msg)
}
// PrintInfo prints an info message with color styling
func PrintInfo(w io.Writer, msg string) {
prefix, suffix := "", ""
if isColorTerminal(w) {
prefix = ColorCyan + ColorBold
suffix = ColorReset
}
fmt.Fprintf(w, "%s%s %s\n", prefix, suffix, msg)
}
// FormatError formats an error with context
func FormatError(err error, context string) error {
if context == "" {
return err
}
return fmt.Errorf("%s: %w", context, err)
}
// IsTerminal checks if the writer is a terminal
func IsTerminal(w io.Writer) bool {
_, ok := w.(*os.File)
return ok && os.Getenv("TERM") != "dumb"
}
// Colorize wraps text in ANSI color codes if the writer supports it
func Colorize(w io.Writer, colorCode, text string) string {
if !isColorTerminal(w) {
return text
}
return colorCode + text + ColorReset
}
// Indent returns text indented by the specified number of spaces
func Indent(text string, spaces int) string {
indent := strings.Repeat(" ", spaces)
lines := strings.Split(text, "\n")
for i, line := range lines {
if line != "" {
lines[i] = indent + line
}
}
return strings.Join(lines, "\n")
}