1 Star 1 Fork 1

xiaoyutab / xgotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
bar.go 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyutab 提交于 2024-02-22 10:26 . 1
package xconsole
import (
"fmt"
"strconv"
"strings"
"sync"
"time"
)
// 进度条对象结构体
type Bar struct {
graph string // 显示符号
rate string // 进度条
percent int // 百分比
current int // 当前进度位置
total int // 总进度
start time.Time // 开始时间
msg string // 进度条右侧显示的文字
sync.Mutex
}
// 创建进度条信息
//
// current 当前进度数
// total 总进度数
func NewBar(current, total int) *Bar {
bar := new(Bar)
bar.current = current
bar.total = total
bar.start = time.Now()
if bar.graph == "" {
bar.graph = "█"
}
bar.percent = bar.getPercent()
for i := 0; i < bar.percent; i += 2 {
bar.rate += bar.graph //初始化进度条位置
}
return bar
}
// 获取当前百分比进度
func (bar *Bar) getPercent() int {
jd := float64(bar.current) / float64(bar.total) * 100
if jd > 100 {
jd = 99
}
return int(jd)
}
// 获取当前程序执行时间
func (bar *Bar) getTime() (s string) {
u := time.Since(bar.start).Seconds()
h := int(u) / 3600
m := int(u) % 3600 / 60
if h > 0 {
s += strconv.Itoa(h) + "h "
}
if h > 0 || m > 0 {
s += strconv.Itoa(m) + "m "
}
s += strconv.Itoa(int(u)%60) + "s"
return
}
// 加载进度条
func (bar *Bar) load() {
fmt.Printf("\r[%-20s]% 3d%% %2s %s ", bar.rate, bar.percent, bar.getTime(), bar.msg)
}
// 进度条添加
//
// i 添加进度
// msg 附加消息体信息
func (bar *Bar) Add(i int, msg ...string) {
bar.Lock()
defer bar.Unlock()
if bar.current+i >= bar.total {
bar.current = bar.total
}
bar.current += i
bar.msg = strings.Join(msg, ",")
{
// msg消息截取
tem := ""
i := 0
t := false
for _, v := range bar.msg {
if i > 80 {
if !t {
tem += "..."
}
t = true
continue
}
tem += string(v)
i++
}
bar.msg = tem
}
last := bar.percent
bar.percent = bar.getPercent()
if bar.percent != last && bar.percent%5 == 0 {
bar.rate += bar.graph
}
bar.load()
}
// 完成进度条
// Add方法最大能达到99%,最后的1%由此函数来进行填充,避免进度条都走完了但是程序还没执行完的结果
func (bar *Bar) Finish() {
for {
if bar.current >= bar.total {
break
}
bar.Add(1, bar.msg)
}
bar.percent = 100
bar.rate += bar.graph
bar.load()
fmt.Println()
}
Go
1
https://gitee.com/xiaoyutab/xgotool.git
git@gitee.com:xiaoyutab/xgotool.git
xiaoyutab
xgotool
xgotool
v0.3.8

搜索帮助