Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion cmd/progress-bar.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ type PBar struct {
Xpixel uint16 // X pixel
Ypixel uint16 // Y pixel
}
CustomMsg string // Custom message
CustomPrompt string // Custom prompt
}

// NewPBar create a new progress bar
Expand All @@ -50,6 +52,7 @@ func NewPBar() *PBar {
ongoingStr: ".",
signalWinch: make(chan os.Signal, 1),
signalTerm: make(chan os.Signal, 1),
CustomMsg: "",
}

signal.Notify(pb.signalWinch, syscall.SIGWINCH) // Register SIGWINCH signal
Expand Down Expand Up @@ -130,6 +133,15 @@ func (pb *PBar) RenderPBar(count int) {
todo := strings.Repeat(pb.ongoingStr, barWidth-barDone) // Fill the bar with todo string
bar := fmt.Sprintf("[%s%s]", done, todo) // Combine the done and todo string

if pb.CustomMsg != "" {
bar = pb.CustomMsg
}

prompt := "Progress: "
if pb.CustomPrompt != "" {
prompt = fmt.Sprintf(pb.CustomPrompt)
}

fmt.Printf("\x1B[%d;%dH", pb.wsrow, 0) // move cursor to row #, col #

switch {
Expand All @@ -138,7 +150,7 @@ func (pb *PBar) RenderPBar(count int) {
case pb.wscol >= uint16(10) && pb.wscol <= uint16(20):
fmt.Printf("[\x1B[33m%3d%%\x1B[0m] %s", uint16(count)*100/pb.Total, bar)
default:
fmt.Printf("Progress: [\x1B[33m%3d%%\x1B[0m] %s", uint16(count)*100/pb.Total, bar)
fmt.Printf("%s[\x1B[33m%3d%%\x1B[0m] %s", prompt, uint16(count)*100/pb.Total, bar)
}
}

Expand Down
26 changes: 22 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
package main

import (
"fmt"
"log"
"time"

cmd "github.com/elulcao/progress-bar/cmd"
)

func main() {
pb := cmd.NewPBar()
pb.CustomMsg = " "
pb.SignalHandler()
pb.Total = uint16(100)
pb.Total = uint16(10)

mockLogMessages := []string{
"Starting the application...",
"Printing more messages...",
"sending a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
"receiving a message...",
}

for i := 1; uint16(i) <= pb.Total; i++ {
pb.RenderPBar(i)
fmt.Println(i) // Do something here
time.Sleep(1 * time.Second) // Wait 1 second, for demo purpose
pb.CustomMsg = mockLogMessages[i-1]
log.Println(mockLogMessages[i-1])
// log.Println(i) // Do something here
time.Sleep(5 * time.Second) // Wait 1 second, for demo purpose
}

pb.CleanUp()
Expand Down