summaryrefslogtreecommitdiff
path: root/main.go
blob: b30b665369cfaee44d2db133ff98a0edce6bf3fa (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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"slices"
	"sort"
	"sync"

	"github.com/fatih/color"
	"github.com/urfave/cli/v3"
)

// flags
var NoCache, DoClearCache bool
var ListAscend, ListDescend, ListNoDep bool

func main() {
	EnsureBrewAvailable()

	// declare CLI app
	cmd := &cli.Command{
		Name:  "wthis",
		Usage: "Fetch information of a Homebrew formulae or cask, like how it got installed, reverse dependencies, etc.",
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:        "no-cache",
				Aliases:     []string{"nc"},
				Usage:       "Disable caching",
				Value:       false,
				Destination: &NoCache,
			},
		},
		Action: func(ctx context.Context, cmd *cli.Command) error {
			if DoClearCache {
				ClearCache()
				fmt.Println("Cache cleared.")
				os.Exit(0)
			}

			// handle arguments
			if cmd.Args().Len() == 0 {
				printErrorAndExit("Please provide a formulae/cask name.")
			}
			pkgName := cmd.Args().First()

			fmt.Print("\033[s")
			showLoadingPrompt(fmt.Sprintf("What the heck is \"%s\"", pkgName))

			// try reading from cache
			var stat *statistics
			if NoCache {
				stat = &statistics{PkgName: pkgName}
			} else {
				stat = NewStatisticsFromCache(pkgName)
				if stat == nil {
					stat = &statistics{PkgName: 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
				remaining := 3
				for remaining > 0 {
					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")
					stat = NewStatistics(fml, cask, pkgName, rvs)
					stat.Print()
				}
			}()
			wg.Wait()

			// cache
			if !NoCache {
				stat.Cache()
			}

			return nil
		},
		Commands: []*cli.Command{
			{
		      	Name:    "list",
				Aliases: []string{"l", "ls"},
		   		Usage:   "Better brew list.",
				Flags: []cli.Flag{
					&cli.BoolFlag{
						Name:        "ascending",
						Aliases:     []string{"a"},
						Usage:       "Sort list ascendingly, based on dependency count.",
						Value:       false,
						Destination: &ListAscend,
					},
					&cli.BoolFlag{
						Name:        "descending",
						Aliases:     []string{"d"},
						Usage:       "Sort list descendingly, based on dependency count.",
						Value:       false,
						Destination: &ListDescend,
					},
					&cli.BoolFlag{
						Name:        "no-dependency",
						Aliases:     []string{"n", "nd"},
						Usage:       "Only show packages installed on request, with no dependency list.",
						Value:       false,
						Destination: &ListNoDep,
					},
				},
		       Action: func(ctx context.Context, cmd *cli.Command) error {
					depmap := GetBrewDeps()
					list := GetBrewList()

					// filter and get essential items
					var keys = []string{}
					for k := range depmap {
						if !slices.Contains(list, k) {
							delete(depmap, k)
						} else {
							keys = append(keys, k)
						}
					}

					// sort based on dependency count
					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
		       },
		   },
	        {
	            Name:    "clean",
	            Aliases: []string{"c", "cache"},
	            Usage:   "Delete all cache files.",
	            Action: func(ctx context.Context, cmd *cli.Command) error {
					// TODO error handling here
              		ClearCache()
					fmt.Println("Cache cleared.")
					return nil
	            },
	        },
		},
	}

	// run command and handle error
	if err := cmd.Run(context.Background(), os.Args); err != nil {
		log.Fatal(err)
	}
}

func fetchData(pkgName string, 
			   fmlChan chan *FormulaInfo, 
			   caskChan chan *CaskInfo, 
			   rvsChan chan []string) {
	// fetching formula/cask info and uses
	// async from brew CLI and HTTP API
	// use whoever comes first
	go func() {
		formula, cask := GetBrewInfo(pkgName)
		fmlChan <- formula
		caskChan <- cask
	}()
	go func() {
		fmlChan <- GetFormulaFromAPI(pkgName)
	}()
	go func() { 
		caskChan <- GetCaskFromAPI(pkgName)
	}()
	
	// fetching brew uses
	go func() {
		rvsChan <- GetBrewUses(pkgName)
	}()
}

func printErrorAndExit(msg string) {
	hideLoadingPrompt()
	color.Red("❌ %s", msg)
	os.Exit(1)
}