summaryrefslogtreecommitdiff
path: root/main.go
blob: 1273c7730a70f605d2da0ebbdfecf9bb3ffeac31 (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
package main

import (
	"context"
	"fmt"
	"github.com/fatih/color"
	"github.com/urfave/cli/v3"
	"log"
	"os"
)

var NoCache, DoClearCache 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,
			},
			&cli.BoolFlag{
				Name:        "clear-cache",
				Aliases:     []string{"cc"},
				Usage:       "Clear cache",
				Value:       false,
				Destination: &DoClearCache,
			},
		},
		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()

			// search and print
			showLoadingPrompt(fmt.Sprintf("What the heck is \"%s\"", pkgName))
			stat := fetchToCreateStatistics(pkgName)
			hideLoadingPrompt()
			stat.Print()

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

			return nil
		},
	}

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

func fetchToCreateStatistics(pkgName string) *statistics {
	// try reading from cache
	var stat *statistics
	if !NoCache {
		stat = NewStatisticsFromCache(pkgName)
	}
	// if cache not hit or explicitly requested no cache
	if NoCache || stat == nil {
		fmlChan := make(chan *FormulaInfo)
		caskChan := make(chan *CaskInfo)
		rvsChan := make(chan []string)
		// start 2 goroutines, fetching formula/cask info and uses
		go func() {
			formula, cask := GetBrewInfo(pkgName)
			fmlChan <- formula
			caskChan <- cask
		}()
		go func() {
			rvsChan <- GetBrewUses(pkgName)
		}()
		// create fine-grained data out of raw
		stat = NewStatistics(<-fmlChan, <-caskChan, pkgName, <-rvsChan)
	}
	return stat
}

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