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

Show update notifications when a new version of kit is available #418

Merged
merged 4 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"kitops/pkg/cmd/version"
"kitops/pkg/lib/constants"
"kitops/pkg/lib/repo/local"
"kitops/pkg/lib/update"
"kitops/pkg/output"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -83,6 +84,9 @@ func RunCommand() *cobra.Command {
}
ctx := context.WithValue(cmd.Context(), constants.ConfigKey{}, configHome)
cmd.SetContext(ctx)

update.CheckForUpdate(configHome)

// At this point, we've parsed the command tree and args; the CLI is being correctly
// so we don't want to print usage. Each subcommand should print its error message before
// returning
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.9.0
github.com/vbauerster/mpb/v8 v8.7.3
golang.org/x/mod v0.19.0
golang.org/x/sync v0.7.0
golang.org/x/sys v0.22.0
golang.org/x/term v0.22.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/vbauerster/mpb/v8 v8.7.3 h1:n/mKPBav4FFWp5fH4U0lPpXfiOmCEgl5Yx/NM3tKJA0=
github.com/vbauerster/mpb/v8 v8.7.3/go.mod h1:9nFlNpDGVoTmQ4QvNjSLtwLmAFjwmq0XaAF26toHGNM=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
Expand Down
22 changes: 21 additions & 1 deletion pkg/cmd/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package version

import (
"kitops/pkg/lib/constants"
"kitops/pkg/lib/update"
"kitops/pkg/output"

"github.com/spf13/cobra"
Expand All @@ -32,16 +33,35 @@ the version was built from, the build time, and the version of Go it was
compiled with.`
)

const versionNotifFlag = "show-update-notifications"

type versionOpts struct {
shouldShowNotifications bool
}

func VersionCommand() *cobra.Command {
opts := &versionOpts{}

cmd := &cobra.Command{
Use: "version",
Short: shortDesc,
Long: longDesc,
Run: func(cmd *cobra.Command, args []string) {
output.Infof("Version: %s\nCommit: %s\nBuilt: %s\nGo version: %s\n", constants.Version, constants.GitCommit, constants.BuildTime, constants.GoVersion)
if cmd.Flags().Changed(versionNotifFlag) {
configHome, ok := cmd.Context().Value(constants.ConfigKey{}).(string)
if !ok {
output.Fatalln("default config path not set on command context")
}
if err := update.SetShowNotifications(configHome, opts.shouldShowNotifications); err != nil {
output.Fatalln(err)
}
gorkem marked this conversation as resolved.
Show resolved Hide resolved
} else {
output.Infof("Version: %s\nCommit: %s\nBuilt: %s\nGo version: %s\n", constants.Version, constants.GitCommit, constants.BuildTime, constants.GoVersion)
}
},
}
cmd.Flags().BoolVar(&opts.shouldShowNotifications, versionNotifFlag, false, "Enable or disable update notifications for the Kit CLI")

return cmd
}

Expand Down
17 changes: 9 additions & 8 deletions pkg/lib/constants/consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ const (
IgnoreFileName = ".kitignore"

// Constants for the directory structure of kit's cached images and credentials
// Modelkits are stored in <configpath>/kitops/storage/ and
// credentials are stored in <configpath>/kitops/credentials.json
DefaultConfigSubdir = "kitops"
StorageSubpath = "storage"
CredentialsSubpath = "credentials.json"
HarnessSubpath = "harness"
HarnessProcessFile = "process.pid"
HarnessLogFile = "harness.log"
// Modelkits are stored in $KITOPS_HOME/storage/ and
// credentials are stored in $KITOPS_HOME/credentials.json
DefaultConfigSubdir = "kitops"
StorageSubpath = "storage"
CredentialsSubpath = "credentials.json"
HarnessSubpath = "harness"
HarnessProcessFile = "process.pid"
HarnessLogFile = "harness.log"
UpdateNotificationsConfigFilename = "disable-update-notifications"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we just have a kitconfig.json where this is just a key?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a much bigger task :)

If we have a kitconfig.json, I'd expect to be able to almost configure everything there (e.g. something like viper). What that looks like is pretty nebulous.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's file an issue for it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed #419


// Kitops-specific annotations for modelkit artifacts
CliVersionAnnotation = "ml.kitops.modelkit.cli-version"
Expand Down
133 changes: 133 additions & 0 deletions pkg/lib/update/update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2024 The KitOps Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package update

import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"

"kitops/pkg/lib/constants"
"kitops/pkg/output"

"golang.org/x/mod/semver"
)

const releaseUrl = "https://api.github.com/repos/jozu-ai/kitops/releases/latest"

// Regexp for a semver version -- taken from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
// We've added an optional 'v' to the start (e.g. v1.2.3) since using a 'v' prefix is common (and used, in our case)
// Capture groups are:
//
// [1] - Major version
// [2] - Minor version
// [3] - Bugfix/z-stream version
// [4] - Pre-release identifiers (1.2.3-<info>), if present
// [5] - Build metadata (1.2.3+<metadata>), if present
var versionTagRegexp = regexp.MustCompile(`^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`)

type ghReleaseInfo struct {
TagName string `json:"tag_name"`
Prerelease bool `json:"prerelease"`
Draft bool `json:"draft"`
Url string `json:"html_url"`
}

func CheckForUpdate(configHome string) {
// If this isn't a release version of kit, don't nag the user unnecessarily
if constants.Version == "unknown" || !versionTagRegexp.MatchString(constants.Version) {
return
}

if !shouldShowNotification(configHome) {
return
}

client := &http.Client{
Timeout: 1 * time.Second,
}
resp, err := client.Get(releaseUrl)
if err != nil {
output.Debugf("Failed to check for updates: %s", err)
return
}
defer resp.Body.Close()

respBody, err := io.ReadAll(resp.Body)
if err != nil {
output.Debugf("Failed to read GitHub response body: %s", err)
return
}
info := &ghReleaseInfo{}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code for retrieving the release info could be refactored into a function for clarity.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

if err := json.Unmarshal(respBody, info); err != nil {
output.Debugf("Failed to parse GitHub response body: %s", err)
return
}
if info.Prerelease || info.Draft {
// This isn't a full release; for now just don't notify users, even if there is a newer full release we don't know about
return
}

// The Go semver package requires versions start with a 'v' (contrary to the spec)
currentVersion := fmt.Sprintf("v%s", strings.TrimPrefix(constants.Version, "v"))
latestVersion := fmt.Sprintf("v%s", strings.TrimPrefix(info.TagName, "v"))
if semver.Compare(currentVersion, latestVersion) < 0 {
output.Infof("Note: A new version of Kit is available! You are using Kit %s. The latest version is %s.", currentVersion, latestVersion)
output.Infof(" To see a list of changes, visit %s", info.Url)
output.Infof(" To disable this notification, use 'kit version --show-update-notifications=false'")
output.Infof("") // Add a newline to not confuse it with regular output
}
}

func SetShowNotifications(configHome string, shouldShow bool) error {
flagFile := filepath.Join(configHome, constants.UpdateNotificationsConfigFilename)
if shouldShow {
if err := os.Remove(flagFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("error enabling update notifications: %w", err)
}
} else {
f, err := os.Create(flagFile)
if err != nil {
if errors.Is(err, fs.ErrExist) {
return nil
}
return fmt.Errorf("error disabling update notifications: %w", err)
}
f.Close()
}
return nil
}

func shouldShowNotification(configHome string) bool {
flagFile := filepath.Join(configHome, constants.UpdateNotificationsConfigFilename)
_, err := os.Stat(flagFile)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return true
}
output.Debugf("Error checking if update notifications should be shown: %s", err)
}
return false
}