Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: new flag options for cache #204

Merged
merged 7 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,13 @@ export GOPATH="$HOME/.gobrew/current/go"
- v1.9.4 - `gobrew` interactive
- v1.9.8 - bug fix where 1.21 is not detected as 1.21.0
- v1.10.10 - `ls-remote` is blazing fast, cached.
- v1.10.11 - Optional options for cache and ttl.


# DEVELOPMENT NOTES

```sh
go run ./cmd/gobrew -h
golangci-lint run ./...
go test -v ./...
```
103 changes: 41 additions & 62 deletions cmd/gobrew/main.go
Original file line number Diff line number Diff line change
@@ -1,48 +1,46 @@
package main

import (
"flag"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"

"github.com/gookit/color"
"github.com/spf13/pflag"

"github.com/kevincobain2000/gobrew"
"github.com/kevincobain2000/gobrew/utils"
)

var args []string
var actionArg = ""
var versionArg = ""
var version = "dev"

var allowedArgs = []string{
"h",
"help",
"ls",
"list",
"ls-remote",
"install",
"use",
"uninstall",
"interactive",
"noninteractive",
"prune",
"version",
"self-update",
}
var help bool
var clearCache bool
var ttl time.Duration
var disableCache bool

func init() {
log.SetFlags(0)

if !isArgAllowed() {
log.Println("[Info] Invalid usage")
log.Print(usage())
return
flag := pflag.NewFlagSet("gobrew", pflag.ContinueOnError)
flag.BoolVarP(&disableCache, "disable-cache", "d", false, "disable local cache")
flag.BoolVarP(&clearCache, "clear-cache", "c", false, "clear local cache")
flag.DurationVarP(&ttl, "ttl", "t", 20*time.Minute, "set cache duration in minutes")

flag.BoolVarP(&help, "help", "h", false, "show usage message")

if err := flag.Parse(os.Args[1:]); err != nil {
color.Errorln("[Error] Invalid usage")
Usage()
os.Exit(2)
}

flag.Parse()
args = flag.Args()
args := flag.Args()
if len(args) == 0 {
actionArg = "interactive"
} else {
Expand Down Expand Up @@ -74,6 +72,11 @@ func init() {
}

func main() {
if help {
Usage()
return
}

rootDir := os.Getenv("GOBREW_ROOT")
if rootDir == "" {
var err error
Expand All @@ -92,6 +95,9 @@ func main() {
GobrewDownloadURL: gobrew.DownloadURL,
GobrewTags: gobrew.TagsAPI,
GobrewVersionsURL: gobrew.VersionsURL,
TTL: ttl,
DisableCache: disableCache,
ClearCache: clearCache,
}

gb := gobrew.NewGoBrew(config)
Expand All @@ -101,7 +107,7 @@ func main() {
case "noninteractive":
gb.Interactive(false)
case "h", "help":
log.Print(usage())
Usage()
case "ls", "list":
gb.ListVersions()
case "ls-remote":
Expand All @@ -121,46 +127,14 @@ func main() {
gb.Version(version)
case "self-update":
gb.Upgrade(version)
default:
color.Errorln("[Error] Invalid usage")
Usage()
os.Exit(2)
}
}

func isArgAllowed() bool {
ok := true
if len(os.Args) > 1 {
_, ok = Find(allowedArgs, os.Args[1])
if !ok {
return false
}
}

if len(os.Args) > 2 {
_, ok = Find(allowedArgs, os.Args[1])
if !ok {
return false
}
}

return ok
}

// Find takes a slice and looks for an element in it. If found it will
// return it's key, otherwise it will return -1 and a bool of false.
func Find(slice []string, val string) (int, bool) {
for i, item := range slice {
if item == val {
return i, true
}
}
return -1, false
}

func usage() string {
usageMsg :=
kevincobain2000 marked this conversation as resolved.
Show resolved Hide resolved
`
# Add gobrew to your ~/.bashrc or ~/.zshrc
export PATH="$HOME/.gobrew/current/bin:$HOME/.gobrew/bin:$PATH"
export GOROOT="$HOME/.gobrew/current/go"
`
var Usage = func() {
msg := `
gobrew ` + version + `

Expand All @@ -178,6 +152,11 @@ Usage:
gobrew version Show gobrew version
gobrew help Show this message

Options:
gobrew [--clear-cache | -c] clear gobrew cache
gobrew [--disable-cache | -d] disable gobrew cache
gobrew [--ttl=20m | -t 20m] set gobrew cache ttl, default 20m

Examples:
gobrew use 1.16 # use go version 1.16
gobrew use 1.16.1 # use go version 1.16.1
Expand All @@ -195,5 +174,5 @@ Examples:
Installation Path:
` + usageMsg

return msg
fmt.Fprintf(os.Stderr, "%s\n", msg)
}
2 changes: 1 addition & 1 deletion cmd/gobrew/main_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

package main

const usageMsg = `
const usageMsg string = `
# Add gobrew to your ~/.bashrc or ~/.zshrc
export PATH="$HOME/.gobrew/current/bin:$HOME/.gobrew/bin:$PATH"
export GOROOT="$HOME/.gobrew/current/go"
Expand Down
2 changes: 1 addition & 1 deletion cmd/gobrew/main_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

package main

const usageMsg = `
const usageMsg string = `
# Add gobrew to your environment variables
PATH="%USERPROFILE%\.gobrew\current\bin;%USERPROFILE%\.gobrew\bin;%PATH%"
GOROOT="%USERPROFILE%\.gobrew\current\go"
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/ulikunitz/xz v0.5.11 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.17.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/schollz/progressbar/v3 v3.14.1 h1:VD+MJPCr4s3wdhTc7OEJ/Z3dAeBzJ7yKH/P4lC5yRTI=
github.com/schollz/progressbar/v3 v3.14.1/go.mod h1:Zc9xXneTzWXF81TGoqL71u0sBPjULtEHYtj/WVgVy8E=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
Expand Down
14 changes: 14 additions & 0 deletions gobrew.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"sort"
"strconv"
"strings"
"time"

"github.com/Masterminds/semver"
"github.com/gookit/color"
Expand Down Expand Up @@ -56,6 +57,7 @@ type GoBrew struct {
currentBinDir string
currentGoDir string
downloadsDir string
cacheFile string
Config
}

Expand All @@ -65,11 +67,18 @@ type Config struct {
GobrewDownloadURL string
GobrewTags string
GobrewVersionsURL string

// cache settings
TTL time.Duration
DisableCache bool
ClearCache bool
}

// NewGoBrew instance
func NewGoBrew(config Config) GoBrew {
installDir := filepath.Join(config.RootDir, goBrewDir)
cacheFile := filepath.Join(installDir, "cache.json")

gb := GoBrew{
Config: config,
installDir: installDir,
Expand All @@ -78,6 +87,11 @@ func NewGoBrew(config Config) GoBrew {
currentBinDir: filepath.Join(installDir, "current", "bin"),
currentGoDir: filepath.Join(installDir, "current", "go"),
downloadsDir: filepath.Join(installDir, "downloads"),
cacheFile: cacheFile,
}

if gb.ClearCache {
_ = os.RemoveAll(gb.cacheFile)
}

return gb
Expand Down
17 changes: 12 additions & 5 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,9 +528,12 @@ type Cache struct {
}

func (gb *GoBrew) getVersionsFromCache() []string {
cacheFile := filepath.Join(gb.installDir, "cache.json")
if _, err := os.Stat(cacheFile); err == nil {
data, e := os.ReadFile(cacheFile)
if gb.DisableCache {
return []string{}
}

if _, err := os.Stat(gb.cacheFile); err == nil {
data, e := os.ReadFile(gb.cacheFile)
if e != nil {
return []string{}
}
Expand All @@ -545,8 +548,8 @@ func (gb *GoBrew) getVersionsFromCache() []string {
return []string{}
}

// cache for 20 minutes
if time.Now().UTC().After(timestamp.Add(20 * time.Minute)) {
// cache for gb.TTL duration
if time.Now().UTC().After(timestamp.Add(gb.TTL)) {
return []string{}
}

Expand All @@ -557,6 +560,10 @@ func (gb *GoBrew) getVersionsFromCache() []string {
}

func (gb *GoBrew) saveVersionsToCache(versions []string) {
if gb.DisableCache {
return
}

cacheFile := filepath.Join(gb.installDir, "cache.json")
var cache = Cache{
Timestamp: time.Now().UTC().Format(time.RFC3339),
Expand Down
Loading