summaryrefslogtreecommitdiff
path: root/actions.go
blob: d672332c96bd50a6050f02c504b9312736c37a20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"slices"
	"sort"
	"strings"
	"sync"

	"github.com/fatih/color"
)

func fetchAndDisplay(pkgName string) *statistics {
	showLoadingPrompt(fmt.Sprintf("What the heck is \"%s\"", pkgName))

	stat := initStat(pkgName)

	fmlChan := make(chan *FormulaInfo)
	caskChan := make(chan *CaskInfo)
	rvsChan := make(chan []string)
	fetchData(pkgName, fmlChan, caskChan, rvsChan)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		var fml *FormulaInfo
		var cask *CaskInfo
		var rvs []string
		prevLines := 0

		for i := 0; i < 5; i++ {
			select {
			case v := <-fmlChan:
				fml = v
			case v := <-caskChan:
				cask = v
			case v := <-rvsChan:
				rvs = v
			}
			if i == 0 {
				hideLoadingPrompt()
			} else {
				for j := 0; j < prevLines; j++ {
					fmt.Print("\033[F\033[K")
				}
			}
			stat = NewStatistics(fml, cask, pkgName, rvs)
			prevLines = capturePrint(stat)
		}
	}()
	wg.Wait()

	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}
	}
	stat := NewStatisticsFromCache(pkgName)
	if stat == nil {
		return &statistics{PkgName: pkgName}
	}
	return stat
}

func runList() error {
	depmap := GetBrewDeps()
	list := GetBrewList()

	keys := []string{}
	for k := range depmap {
		if !slices.Contains(list, k) {
			delete(depmap, k)
		} else {
			keys = append(keys, k)
		}
	}

	if ListAscend {
		sort.Slice(keys, func(i, j int) bool {
			return len(depmap[keys[i]]) > len(depmap[keys[j]])
		})
	} else if ListDescend {
		sort.Slice(keys, func(i, j int) bool {
			return len(depmap[keys[i]]) < len(depmap[keys[j]])
		})
	} else {
		sort.Strings(keys)
	}

	for _, pkg := range keys {
		deps := depmap[pkg]
		count := len(deps)

		color.New(color.FgBlue).Printf("%s", pkg)
		if count > 1 {
			fmt.Printf(" (%d dependencies)\n", count)
		} else {
			fmt.Printf(" (%d dependency)\n", count)
		}

		if ListNoDep {
			continue
		}
		for _, dep := range deps {
			fmt.Printf("  ► %s\n", dep)
		}
	}
	return nil
}