diff options
| author | eltrac <hi@eltr.ac> | 2026-05-26 10:00:29 +0800 |
|---|---|---|
| committer | eltrac <hi@eltr.ac> | 2026-05-26 10:00:29 +0800 |
| commit | 36bc242e9db96e14811736379bbcde5ea7b00bd7 (patch) | |
| tree | 718d8d416ef3c1b8ebd193bcbf8074fe68a83212 | |
| parent | 4cec245383ab16656e1c5dcbbbe63350b57ab0ea (diff) | |
fix(tui): showing multiple results
| -rw-r--r-- | actions.go | 49 | ||||
| -rw-r--r-- | animation.go | 15 |
2 files changed, 51 insertions, 13 deletions
@@ -1,16 +1,19 @@ package main import ( + "bytes" "fmt" + "io" + "os" "slices" "sort" + "strings" "sync" "github.com/fatih/color" ) func fetchAndDisplay(pkgName string) *statistics { - fmt.Print("\033[s") showLoadingPrompt(fmt.Sprintf("What the heck is \"%s\"", pkgName)) stat := initStat(pkgName) @@ -27,22 +30,26 @@ func fetchAndDisplay(pkgName string) *statistics { var fml *FormulaInfo var cask *CaskInfo var rvs []string - remaining := 3 - for remaining > 0 { + prevLines := 0 + + for i := 0; i < 5; i++ { select { case v := <-fmlChan: fml = v - remaining-- case v := <-caskChan: cask = v - remaining-- case v := <-rvsChan: rvs = v - remaining-- } - fmt.Print("\033[u\033[J") + if i == 0 { + hideLoadingPrompt() + } else { + for j := 0; j < prevLines; j++ { + fmt.Print("\033[F\033[K") + } + } stat = NewStatistics(fml, cask, pkgName, rvs) - stat.Print() + prevLines = capturePrint(stat) } }() wg.Wait() @@ -50,6 +57,32 @@ func fetchAndDisplay(pkgName string) *statistics { return stat } +func capturePrint(s *statistics) int { + r, w, err := os.Pipe() + if err != nil { + s.Print() + return 0 + } + + oldStdout := os.Stdout + oldColor := color.Output + os.Stdout = w + color.Output = w + + s.Print() + + w.Close() + os.Stdout = oldStdout + color.Output = oldColor + + var buf bytes.Buffer + io.Copy(&buf, r) + output := buf.String() + os.Stdout.WriteString(output) + + return strings.Count(output, "\n") +} + func initStat(pkgName string) *statistics { if NoCache { return &statistics{PkgName: pkgName} diff --git a/animation.go b/animation.go index 5d2bc47..8bd94f5 100644 --- a/animation.go +++ b/animation.go @@ -7,22 +7,27 @@ import ( "time" ) -var loadingDone chan bool +var ( + loadingDone chan struct{} + loadingStopped chan struct{} +) func showLoadingPrompt(msg string) { if loadingDone != nil { return } - loadingDone = make(chan bool) + loadingDone = make(chan struct{}) + loadingStopped = make(chan struct{}) go func() { + defer close(loadingStopped) white := color.New(color.FgWhite) for { select { case <-loadingDone: - fmt.Print("\r") // move cursor to line start + fmt.Print("\r") fmt.Print(strings.Repeat(" ", len(msg)+4)) - fmt.Print("\r") // clear line + fmt.Print("\r") return default: white.Printf("\r%s", msg) @@ -39,10 +44,10 @@ func showLoadingPrompt(msg string) { }() } -// hideLoadingPrompt stops the animation cleanly. func hideLoadingPrompt() { if loadingDone != nil { close(loadingDone) + <-loadingStopped loadingDone = nil fmt.Print("\r\033[2K") } |
