Okay, let's get creative with some Go CLI progress indicators using ANSI characters! We'll make a few different styles.
Key Concepts Used:
ANSI Escape Codes: To control color and cursor position.
\x1b[<n>m: Set graphics mode (e.g., \x1b[32m for green text, \x1b[0m to reset).
\r: Carriage Return. Moves the cursor to the beginning of the current line without moving down. This allows overwriting the previous indicator state.
\x1b[?25l: Hide cursor.
\x1b[?25h: Show cursor.
Go's fmt package: For printing.
Go's time package: To simulate work and control update speed.
Go's strings package: For repeating characters.
go
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
// ANSI Color Codes
const (
reset = "\x1b[0m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
gray = "\x1b[90m" // Bright black / gray
white = "\x1b[97m"
// Cursor control
hideCursor = "\x1b[?25l"
showCursor = "\x1b[?25h"
)
// --- Indicator 1: Classic Bar with Color Transition ---
func progressBar(prefix string, current, total int, width int) {
if total <= 0 {
return // Avoid division by zero
}
percent := float64(current) / float64(total)
filledWidth := int(percent * float64(width))
emptyWidth := width - filledWidth
// Color transition from red -> yellow -> green
var barColor string
if percent < 0.4 {
barColor = red
} else if percent < 0.8 {
barColor = yellow
} else {
barColor = green
}
bar := fmt.Sprintf("%s [%s%s%s%s] %.1f%%",
prefix,
barColor,
strings.Repeat("█", filledWidth), // Full block character
gray,
strings.Repeat("░", emptyWidth), // Light shade character
percent*100,
)
// Using \r (carriage return) to overwrite the line
fmt.Printf("\r%s%s%s", bar, reset, strings.Repeat(" ", 10)) // Add padding to overwrite longer previous lines
}
// --- Indicator 2: Pac-Man ---
func pacManIndicator(prefix string, current, total int, width int, iteration int) {
if total <= 0 {
return
}
percent := float64(current) / float64(total)
pos := int(percent * float64(width))
// Pac-Man character alternates between C and c (or use other characters)
pacChar := "C"
if iteration%2 == 0 {
pacChar = "c"
}
// Ensure pos doesn't go out of bounds for the dots string
dotsCount := width - pos - 1 // -1 for the pacman character itself
if dotsCount < 0 {
dotsCount = 0
}
if pos >= width {
pos = width -1 // Place Pac-Man at the end if 100%
pacChar = "🏁" // Change to a flag at the end
}
bar := fmt.Sprintf("%s %s%s%s%s %.1f%%",
prefix,
yellow, // Pac-Man color
strings.Repeat(" ", pos), // Leading spaces
pacChar,
strings.Repeat("·", dotsCount), // Dots to eat (use · or .)
percent*100,
)
fmt.Printf("\r%s%s%s", bar, reset, strings.Repeat(" ", 10))
}
// --- Indicator 3: Spinning Wheel (Indeterminate Style) ---
// Good for when total is unknown or just waiting
func spinner(prefix string, iteration int) {
chars := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} // Braille spinner
// chars := []string{"|", "/", "-", "\\"} // Simpler spinner
char := chars[iteration%len(chars)]
fmt.Printf("\r%s %s%s%s", prefix, cyan, char, reset)
}
// --- Indicator 4: Growing Plant ---
func growingPlant(prefix string, current, total int) {
if total <= 0 {
return
}
percent := float64(current) / float64(total)
stages := []string{"🌱", "🌿", "🌳", "🌲"} // Seedling, herb, deciduous tree, evergreen tree
stageIndex := int(percent * float64(len(stages)))
if stageIndex >= len(stages) {
stageIndex = len(stages) - 1
}
plant := stages[stageIndex]
progress := fmt.Sprintf("%.1f%%", percent*100)
// Optional: Add some ground or context
ground := strings.Repeat(" ", 5 - len(progress)/2) // Center the percentage roughly
fmt.Printf("\r%s %s %s %s%s%s", prefix, green, plant, ground, progress, reset)
}
// --- Indicator 5: Wave ---
func waveIndicator(prefix string, current, total int, width int, iteration int) {
if total <= 0 {
return
}
percent := float64(current) / float64(total)
filledWidth := int(percent * float64(width))
waveChars := []string{"〰", "﹏"} // Simple wave characters
bar := "["
for i := 0; i < width; i++ {
if i < filledWidth {
// Alternate wave characters based on position and iteration
waveChar := waveChars[(i+iteration)%len(waveChars)]
bar += blue + waveChar
} else {
bar += gray + "·" // Use dots for the empty part
}
}
bar += reset + "]"
fmt.Printf("\r%s %s %.1f%%%s", prefix, bar, percent*100, strings.Repeat(" ", 10))
}
func main() {
// Hide cursor and ensure it's shown on exit (even if panic)
fmt.Print(hideCursor)
defer fmt.Print(showCursor)
// Graceful shutdown handling (to show cursor)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
fmt.Print(showCursor) // Show cursor on Ctrl+C
fmt.Println("\nOperation interrupted.")
os.Exit(0)
}()
totalTasks := 100
width := 40 // Width for bar-like indicators
fmt.Println("--- Progress Bar ---")
for i := 0; i <= totalTasks; i++ {
progressBar("Processing:", i, totalTasks, width)
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nDone.\n") // Newline after completion
fmt.Println("--- Pac-Man Indicator ---")
for i := 0; i <= totalTasks; i++ {
pacManIndicator("Eating Dots:", i, totalTasks, width, i) // Pass iteration for animation
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nDone.\n")
fmt.Println("--- Spinner (Indeterminate) ---")
// Simulate a short wait
for i := 0; i < 30; i++ { // Run for a fixed number of iterations
spinner("Waiting:", i)
time.Sleep(100 * time.Millisecond)
}
fmt.Println("\rWaiting: Done. ") // Overwrite spinner and print done message
fmt.Println("\n--- Growing Plant ---")
for i := 0; i <= totalTasks; i++ {
growingPlant("Nurturing:", i, totalTasks)
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nFully Grown!\n")
fmt.Println("--- Wave Indicator ---")
for i := 0; i <= totalTasks; i++ {
waveIndicator("Filling:", i, totalTasks, width, i) // Pass iteration for wave animation
time.Sleep(50 * time.Millisecond)
}
fmt.Println("\nFilled!\n")
fmt.Println("All indicators demonstrated.")
}
Explanation:
ANSI Constants: Define constants for common colors and cursor control for readability.
hideCursor, showCursor: These make the animations look cleaner by hiding the blinking terminal cursor. defer fmt.Print(showCursor) ensures the cursor is shown again even if the program exits unexpectedly.
Graceful Shutdown: The signal.Notify part catches Ctrl+C (SIGINT) or SIGTERM to ensure the cursor is restored before exiting.
Carriage Return \r: This is crucial. Before printing the updated state of an indicator, \r moves the cursor back to the start of the line. The new print then overwrites the old one.
Padding:strings.Repeat(" ", 10) is added at the end of some prints. This is important to clear any characters from a longer previous state on the same line (e.g., if the percentage string changes from 9.9% to 10.0% or if the prefix changes). Adjust padding as needed.
progressBar: A classic bar that changes color based on completion percentage. Uses block (█) and shade (░) characters.
pacManIndicator: Uses spaces, a cycling character (C/c), and dots (·) to create a Pac-Man animation. The iteration parameter helps cycle the Pac-Man mouth.
spinner: An indeterminate progress indicator using cycling Braille characters. Good for tasks where the total duration isn't known. The iteration cycles through the characters.
growingPlant: A more conceptual indicator where a plant emoji "grows" through stages based on percentage completion.
waveIndicator: Fills a bar with animated wave characters (〰, ﹏). The iteration parameter makes the wave appear to move.
main Function: Demonstrates how to use each indicator in a loop, simulating work with time.Sleep. It prints a newline (\n) after each indicator finishes its loop so the next output starts cleanly on a new line.
How to Run:
Save the code as progress.go.
Open your terminal.
Run it using go run progress.go.
You should see each indicator animate in place in your terminal!