Skip to content

Commit

Permalink
feat: update version command with caching
Browse files Browse the repository at this point in the history
  • Loading branch information
shreyasbhat0 committed Dec 5, 2023
1 parent 4ca2a7f commit ffd1e02
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 74 deletions.
67 changes: 66 additions & 1 deletion cli/cmd/utility/version.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,80 @@
package utility

import (
"context"
"fmt"
"os"
"time"

"github.com/google/go-github/github"
"github.com/hugobyte/dive-core/cli/common"
"github.com/spf13/cobra"
)

var (
latestVersion = ""
)

const versionFile = "version"

var VersionCmd = common.NewDiveCommandBuilder().
SetUse("version").
SetShort("Checks The DIVE CLI Version").
SetLong("Checks the current DIVE CLI version and warns if you are using an old version.").
SetRun(version).
Build()

func version(cmd *cobra.Command, args []string) {}
func version(cmd *cobra.Command, args []string) {

cli := common.GetCli()

fmt.Println(GetLatestVersion(cli))

}

// This function will fetch the latest version from HugoByte/Dive repo
func GetLatestVersion(cli *common.Cli) string {

// Repo Name
repo := "DIVE"
owner := "HugoByte"

versionFilePath, err := cli.FileHandler().GetAppDirPathOrAppFilePath(versionFile)
if err != nil {
cli.Logger().SetErrorToStderr()
cli.Logger().Fatal(common.CodeOf(err), err.Error())
}

versionFileInfo, err := os.Stat(versionFilePath)
if os.IsNotExist(err) {

} else if err != nil {
cli.Logger().SetErrorToStderr()
cli.Logger().Fatal(common.CodeOf(err), err.Error())

}

if versionFileInfo == nil || time.Since(versionFileInfo.ModTime()).Hours() > 1 {

client := github.NewClient(nil)
release, _, err := client.Repositories.GetLatestRelease(context.Background(), owner, repo)
if err != nil {
cli.Logger().SetErrorToStderr()
cli.Logger().Error(common.CodeOf(err), err.Error())
return ""
}

latestVersion = release.GetName()
cli.FileHandler().WriteAppFile(versionFile, []byte(latestVersion))
os.Chtimes(versionFilePath, time.Now(), time.Now())

} else {

cachedVersion, err := cli.FileHandler().ReadAppFile(versionFile)
if err == nil && string(cachedVersion) != "" {
latestVersion = string(cachedVersion)
}
}

return latestVersion
}
31 changes: 25 additions & 6 deletions cli/common/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"strings"
)

const appDir = ".dive"

type diveFileHandler struct{}

func NewDiveFileHandler() *diveFileHandler {
Expand Down Expand Up @@ -63,11 +65,10 @@ func (df *diveFileHandler) ReadJson(fileName string, obj interface{}) error {
}
func (df *diveFileHandler) ReadAppFile(fileName string) ([]byte, error) {

uhd, err := df.GetHomeDir()
appFilePath, err := df.GetAppDirPathOrAppFilePath(fileName)
if err != nil {
return nil, WrapMessageToError(err, "Failed to Read App File")
}
appFilePath := filepath.Join(uhd, ".dive", fileName)

data, err := df.ReadFile(appFilePath)

Expand All @@ -80,19 +81,21 @@ func (df *diveFileHandler) ReadAppFile(fileName string) ([]byte, error) {

func (df *diveFileHandler) WriteAppFile(fileName string, data []byte) error {

uhd, err := df.GetHomeDir()
appFileDir, err := df.GetAppDirPathOrAppFilePath("")
if err != nil {
return WrapMessageToErrorf(err, "Failed To Write App File %s", fileName)
return WrapMessageToErrorf(err, "Failed To Get App File Path %s", fileName)
}
appFileDir := filepath.Join(uhd, ".dive")

err = df.MkdirAll(appFileDir, os.ModePerm)

if err != nil {
return WrapMessageToErrorf(err, "Failed To Write App File %s", fileName)
}

appFilePath := filepath.Join(appFileDir, fileName)
appFilePath, err := df.GetAppDirPathOrAppFilePath(fileName)
if err != nil {
return WrapMessageToErrorf(err, "Failed To Get App File Path %s", fileName)
}

file, err := df.OpenFile(appFilePath, "append|write|create", 0644)
if err != nil {
Expand Down Expand Up @@ -263,3 +266,19 @@ func (df *diveFileHandler) RemoveFiles(fileNames []string) error {
}
return nil
}

func (df *diveFileHandler) GetAppDirPathOrAppFilePath(fileName string) (string, error) {

var path string
uhd, err := df.GetHomeDir()
if err != nil {
return "", WrapMessageToErrorf(err, "Failed To Write App File %s", fileName)
}
if fileName == "" {
path = filepath.Join(uhd, appDir)
} else {
path = filepath.Join(uhd, appDir, fileName)
}

return path, nil
}
1 change: 1 addition & 0 deletions cli/common/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ type FileHandler interface {
OpenFile(filePath string, fileOpenMode string, permission int) (*os.File, error)
RemoveFile(fileName string) error
RemoveFiles(fileNames []string) error
GetAppDirPathOrAppFilePath(fileName string) (string, error)
}

// CommandBuilder is an interface for building a Cobra command.
Expand Down
67 changes: 0 additions & 67 deletions cli/common/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,8 @@ package common

import (
"encoding/json"
"os/exec"
"runtime"
"time"

"github.com/kurtosis-tech/stacktrace"
)

var lastChecked time.Time
var latestVersion = ""

type DiveServiceResponse struct {
ServiceName string `json:"service_name,omitempty"`
PublicEndpoint string `json:"endpoint_public,omitempty"`
Expand Down Expand Up @@ -43,65 +35,6 @@ func (dive *DiveServiceResponse) EncodeToString() (string, error) {
return string(encodedBytes), nil
}

func OpenFile(URL string) error {
var args []string
switch runtime.GOOS {
case linuxOSName:
args = []string{openFileLinuxCommandName, URL}
case macOSName:
args = []string{openFileMacCommandName, URL}
case windowsOSName:
args = []string{openFileWindowsCommandName, openFileWindowsCommandFirstArgumentDefault, URL}
default:
return stacktrace.NewError("Unsupported operating system")
}
command := exec.Command(args[0], args[1:]...)
if err := command.Start(); err != nil {
return stacktrace.Propagate(err, "An error occurred while opening '%v'", URL)
}
return nil
}

// This function will fetch the latest version from HugoByte/Dive repo
// func GetLatestVersion() string {

// // Repo Name
// repo := "DIVE"
// owner := "HugoByte"
// userHomeDir, err := os.UserHomeDir()

// if err != nil {
// fmt.Println(err)
// return ""
// }
// cachedFile := filepath.Join(userHomeDir, "/.dive/version_cache.txt")

// if time.Since(lastChecked).Hours() > 1 {
// cachedVersion, err := ReadConfigFile(cachedFile)
// fmt.Println("here ")

// if err == nil && string(cachedVersion) != "" {
// latestVersion = string(cachedVersion)
// fmt.Println("here 1")
// } else {
// fmt.Println("here 2")
// client := github.NewClient(nil)
// release, _, err := client.Repositories.GetLatestRelease(context.Background(), owner, repo)
// if err != nil {
// fmt.Println(err)
// return ""
// }

// latestVersion = release.GetName()
// writeCache(cachedFile, latestVersion)
// }
// lastChecked = time.Now()

// }

// return latestVersion
// }

type Services map[string]*DiveServiceResponse

type EnclaveInfo struct {
Expand Down
26 changes: 26 additions & 0 deletions cli/common/utils.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package common

import (
"os/exec"
"runtime"

"github.com/kurtosis-tech/stacktrace"
)

func ValidateArgs(args []string) error {
if len(args) != 0 {

Expand Down Expand Up @@ -29,3 +36,22 @@ func WriteServiceResponseData(serviceName string, data DiveServiceResponse, cliC

return nil
}

func OpenFile(URL string) error {
var args []string
switch runtime.GOOS {
case linuxOSName:
args = []string{openFileLinuxCommandName, URL}
case macOSName:
args = []string{openFileMacCommandName, URL}
case windowsOSName:
args = []string{openFileWindowsCommandName, openFileWindowsCommandFirstArgumentDefault, URL}
default:
return stacktrace.NewError("Unsupported operating system")
}
command := exec.Command(args[0], args[1:]...)
if err := command.Start(); err != nil {
return stacktrace.Propagate(err, "An error occurred while opening '%v'", URL)
}
return nil
}

0 comments on commit ffd1e02

Please sign in to comment.