caniuse/main.go

88 lines
1.8 KiB
Go

package main
import (
"errors"
"flag"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/peterbourgon/ff/v3"
)
var (
resultmap = map[string]string{
"y": "✔",
"n": "✘",
"a": "◒",
"u": "‽",
"i": "ⓘ",
"w": "⚠",
}
supernums = "⁰¹²³⁴⁵⁶⁷⁸⁹"
refresh = time.Hour * 24 * 30
)
func main() {
fs := flag.NewFlagSet("caniuse", flag.ContinueOnError)
if err := ff.Parse(fs, os.Args[1:],
ff.WithEnvVarPrefix("CANIUSE"),
); err != nil {
panic(err)
}
if fs.NArg() != 1 {
fmt.Println("caniuse requires one argument")
return
}
data, err := loadData()
if err != nil {
fmt.Printf("could not load data: %v", err)
}
fmt.Println(data)
}
func showFeat(d data) {
var p []string
if d.UsagePercY > 0 {
p = append(p, fmt.Sprintf("%s %s%%", resultmap["y"], color.GreenString("%f", d.UsagePercY)))
}
if d.UsagePercA > 0 {
p = append(p, fmt.Sprintf("%s %s%%", resultmap["a"], color.YellowString("%f", d.UsagePercA)))
}
percentages := strings.Join(p, " ")
}
func loadData() (Data, error) {
var data Data
cache, err := os.UserCacheDir()
if err != nil {
return data, fmt.Errorf("could not determine cache dir: %v", err)
}
caniuseCache := filepath.Join(cache, "caniuse")
if err := os.MkdirAll(caniuseCache, os.ModePerm); err != nil {
return data, fmt.Errorf("could not create dir %q: %v", caniuseCache, err)
}
dataPath := filepath.Join(caniuseCache, "data.json")
fi, err := os.Stat(dataPath)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return data, fmt.Errorf("could not stat %q: %v", dataPath, err)
} else if errors.Is(err, fs.ErrNotExist) || time.Since(fi.ModTime()) > refresh {
if err := Download(dataPath); err != nil {
return data, fmt.Errorf("could not download data: %v", err)
}
}
return Load(dataPath)
}