~poldi1405/go-indicators

10b8797ae3e630af76e25da58f27f7f5249268b2 — Moritz Poldrack 1 year, 9 months ago 23e4aa3
it works!
2 files changed, 38 insertions(+), 22 deletions(-)

M main.go
M progress/type.go
M main.go => main.go +9 -3
@@ 2,7 2,9 @@ package main

import (
	"fmt"
	"strings"
	"time"
	"unicode/utf8"

	"./progress"
	"./spinner"


@@ 18,13 20,17 @@ func main() {
		preparationspinner()
	*/
	var p progress.Progress
	p.Width = 30
	p.Style = "block"
	p.Width = 90
	p.Style = "trapez"

	for i := 0; i < 350; i++ {
		perc, _ := progress.GetPercentage(float64(i), 350)
		fmt.Printf(" [%v] [%3.f%%]\r", p.GetBar(float64(i), 350), perc)
		time.Sleep(50 * time.Millisecond)
		bar := p.GetBar(float64(i), 350)
		if utf8.RuneCountInString(bar) != p.Width {
			panic(fmt.Sprintf("%v%% (%v/%v) leads to %v characters while %v characters are wanted\n|%v|\n|%v|\n", perc, i, 350, utf8.RuneCountInString(bar), p.Width, strings.Repeat("=", p.Width), bar))
		}
		time.Sleep(5 * time.Millisecond)
	}
	fmt.Println()
}

M progress/type.go => progress/type.go +29 -19
@@ 1,8 1,6 @@
package progress

import (
	"fmt"
	"math"
	"strings"
	"sync"
)


@@ 24,30 22,42 @@ func (p *Progress) GetBar(parts, total float64) (result string) {
		return
	}

	a2 := p.Width
	b2, _ := GetPercentage(parts, total)
	c2 := float64(len(ProgressStyles[p.Style]))
	d2 := float64(100 / a2)
	completeSegments := math.Floor(b2 / d2)
	e2 := completeSegments
	f2 := b2 - d2*e2
	g2 := d2 / c2
	segmentIndex := int(math.Floor(f2 / g2))
	percperchar := float64(100) / float64(p.Width)
	percent, _ := GetPercentage(parts, total)
	counter := 0

	if b2 >= 100 {
		result += strings.Repeat(ProgressStyles[p.Style][maxIndex], p.Width)
	if percent > 100 {
		percent = float64(100)
	} else if percent < 0 {
		percent = float64(0)
	}

	for percent > percperchar {
		result += ProgressStyles[p.Style][maxIndex]

		percent -= percperchar
		counter++
	}

	if counter == p.Width {
		return
	}

	fmt.Println(completeSegments)
	result += strings.Repeat(ProgressStyles[p.Style][maxIndex], int(completeSegments))
	charindex := 0
	dingeling := percperchar / float64(maxIndex+1)
	for percent > dingeling {
		percent -= dingeling
		charindex++
	}

	if completeSegments < float64(p.Width) {
		result += ProgressStyles[p.Style][segmentIndex]
	if charindex > 0 {
		result += ProgressStyles[p.Style][charindex]
		counter++
	}

	if completeSegments+1 < float64(p.Width) {
		result += strings.Repeat(ProgressStyles[p.Style][0], p.Width-int(completeSegments)-1)
	for counter < p.Width {
		result += ProgressStyles[p.Style][0]
		counter++
	}
	return
}