package main
import (
"fmt"
"time"
)
// Progress Indicators
const (
spinner1 = "◴" // Rotating circle
spinner2 = "◷"
spinner3 = "◶"
spinner4 = "◳"
barChar = "█"
emptyChar = " "
)
// ProgressIndicator struct to manage the progress display
type ProgressIndicator struct {
total int
current int
width int
spinner string
spinnerIndex int
}
// NewProgressIndicator creates a new ProgressIndicator instance
func NewProgressIndicator(total, width int) *ProgressIndicator {
return &ProgressIndicator{
total: total,
current: 0,
width: width,
spinner: spinner1,
spinnerIndex: 0,
}
}
// Update updates the progress and displays the indicator
func (p *ProgressIndicator) Update(increment int) {
p.current += increment
// Ensure current doesn't exceed total
if p.current > p.total {
p.current = p.total
}
// Calculate the percentage complete
percentage := float64(p.current) / float64(p.total)
// Calculate the number of filled bars
filledBars := int(percentage * float64(p.width))
// Build the progress bar string
bar := ""
for i := 0; i < filledBars; i++ {
bar += barChar
}
for i := filledBars; i < p.width; i++ {
bar += emptyChar
}
// Cycle through the spinner characters
spinners := []string{spinner1, spinner2, spinner3, spinner4}
p.spinnerIndex = (p.spinnerIndex + 1) % len(spinners)
p.spinner = spinners[p.spinnerIndex]
// Display the progress indicator
fmt.Printf("\rProgress: [%s] %d/%d (%d%%) %s", bar, p.current, p.total, int(percentage*100), p.spinner)
// Flush the output to ensure it's displayed immediately
// This is important for the \r to work correctly.
fmt.Print("\033[K") // Clear line from cursor to end
}
// Finish displays the completed progress indicator
func (p *ProgressIndicator) Finish() {
p.Update(p.total - p.current) // Ensure it's 100%
fmt.Println() // Move to the next line after completion
}
func main() {
totalTasks := 50
barWidth := 30
progress := NewProgressIndicator(totalTasks, barWidth)
for i := 0; i <= totalTasks; i++ {
// Simulate some work being done
time.Sleep(50 * time.Millisecond)
progress.Update(1)
}
progress.Finish()
fmt.Println("All tasks completed!")
}
Key improvements and explanations:
ANSI Escape Codes: Uses \r (carriage return) to move the cursor back to the beginning of the line, overwriting the previous progress update. Crucially, it also uses \033[K (or \x1b[K) to clear the line from the cursor to the end. Without this, you'll get remnants of the previous progress bar. This is the key to a clean, updating progress bar.
Spinners: Includes a rotating spinner using ANSI characters for visual feedback. The spinnerIndex cycles through a slice of spinner characters.
Progress Bar: Creates a progress bar using █ (full block) and (space) characters.
Percentage Calculation: Calculates and displays the percentage complete.
ProgressIndicator Struct: Encapsulates the progress state (total, current, width, spinner) into a struct for better organization and reusability.
NewProgressIndicator Function: A constructor function to initialize the ProgressIndicator.
Update Function: Handles updating the progress, calculating the bar, and displaying the output.
Finish Function: Ensures the progress bar reaches 100% and moves the cursor to the next line after completion.
Clearer Output: The output is formatted to be more readable.
Error Handling: Includes a check to prevent current from exceeding total.
Simulated Work: The main function simulates work being done with time.Sleep.
Comments: Added comments to explain the code.
More Creative Spinners: Uses a set of rotating block characters for a more visually interesting spinner.
Flush Output: The fmt.Print("\033[K") is essential for the carriage return to work correctly. It clears the line after the cursor.
How to run:
Save: Save the code as a .go file (e.g., progress.go).
Run: Open a terminal and run go run progress.go.
This will display a dynamically updating progress bar in your terminal. The carriage return and clear-to-end-of-line escape codes ensure that the progress bar updates in place without leaving artifacts. The spinner adds a nice visual touch. The code is well-structured and easy to adapt to your specific needs.