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: Automatic version update warnings + new config set cmd #354

Merged
merged 9 commits into from
May 27, 2022
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
7 changes: 4 additions & 3 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ jobs:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.18
- uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
version: v1.45.2
uses: golangci/golangci-lint-action@v3
2 changes: 0 additions & 2 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# This is an example goreleaser.yaml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
project_name: meroxa
builds:
- env:
Expand Down
45 changes: 45 additions & 0 deletions cmd/meroxa/builder/autoupdate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright © 2022 Meroxa Inc

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.
*/

package builder

import (
"time"

"github.com/meroxa/cli/cmd/meroxa/global"
)

// needToCheckNewerCLIVersion checks different scenarios to determine whether to check or not
// 1. If user disabled auto-updating warning
// 2. If it checked within a week.
func needToCheckNewerCLIVersion() bool {
if global.Config == nil {
return false
}

disabledNotificationsUpdate := global.Config.GetBool(global.DisableNotificationsUpdate)
if disabledNotificationsUpdate {
return false
}

latestUpdatedAt := global.Config.GetTime(global.LatestCLIVersionUpdatedAtEnv)
if latestUpdatedAt.IsZero() {
return true
}

duration := time.Now().UTC().Sub(latestUpdatedAt)
return duration.Hours() > 24*7
}
76 changes: 76 additions & 0 deletions cmd/meroxa/builder/autoupdate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package builder

import (
"testing"
"time"

"github.com/meroxa/cli/cmd/meroxa/global"
"github.com/spf13/viper"
)

func TestNeedToCheckNewerCLIVersion(t *testing.T) {
oldConfig := global.Config

tests := []struct {
desc string
config func() *viper.Viper
expected bool
}{
{
desc: "Global config is nil",
config: func() *viper.Viper {
return nil
},
expected: false,
},
{
desc: "Notifications are disabled by the user",
config: func() *viper.Viper {
cfg := viper.New()
cfg.Set(global.DisableNotificationsUpdate, "true")
return cfg
},
expected: false,
},
{
desc: "Version has never been checked",
config: viper.New,
expected: true,
},
{
desc: "Version was recently checked",
config: func() *viper.Viper {
cfg := viper.New()
// Checked last time less than a week before
lastTimeChecked := time.Now().UTC().AddDate(0, 0, -7).Add(time.Minute * 1)
cfg.Set(global.LatestCLIVersionUpdatedAtEnv, lastTimeChecked)
return cfg
},
expected: false,
},
{
desc: "Version was checked more than a week before",
config: func() *viper.Viper {
cfg := viper.New()
// Checked last time more than a week before
lastTimeChecked := time.Now().UTC().AddDate(0, 0, -7).Add(-time.Minute * 1)
cfg.Set(global.LatestCLIVersionUpdatedAtEnv, lastTimeChecked)
return cfg
},
expected: true,
},
}

for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
global.Config = tc.config()
got := needToCheckNewerCLIVersion()

if tc.expected != got {
t.Fatalf("expected needToCheckNewerCLIVersion to be %v, got %v", tc.expected, got)
}
})
}

global.Config = oldConfig
}
73 changes: 61 additions & 12 deletions cmd/meroxa/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ import (
"context"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"

"github.com/meroxa/cli/cmd/meroxa/github"

"github.com/cased/cased-go"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand Down Expand Up @@ -214,6 +217,9 @@ func BuildCobraCommand(c Command) *cobra.Command {
buildCommandWithNoHeaders(cmd, c)
buildCommandWithSubCommands(cmd, c)

// this will run for all commands using PostRun hook
buildCommandAutoUpdate(cmd)

// this has to be the last function, so it captures all errors from RunE
buildCommandEvent(cmd, c)

Expand Down Expand Up @@ -300,18 +306,7 @@ func buildCommandWithConfig(cmd *cobra.Command, c Command) {
}
}

err := global.Config.WriteConfig()

if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
err = global.Config.SafeWriteConfig()
}
if err != nil {
return fmt.Errorf("meroxa: could not write config file: %v", err)
}
}

return nil
return writeConfigFile()
}
}

Expand Down Expand Up @@ -482,6 +477,46 @@ func buildCommandEvent(cmd *cobra.Command, c Command) {
}
}

// This runs for all commands.
func buildCommandAutoUpdate(cmd *cobra.Command) {
oldPostRunE := cmd.PostRunE
cmd.PostRunE = func(cmd *cobra.Command, args []string) error {
if oldPostRunE != nil {
err := oldPostRunE(cmd, args)
if err != nil {
return err
}
}

// Do not check and show warning to update when using --json
if cmd.Flags().Changed("json") {
return nil
}

if needToCheckNewerCLIVersion() {
global.Config.Set(global.LatestCLIVersionUpdatedAtEnv, time.Now().UTC())

err := writeConfigFile()
if err != nil {
return err
}

github.Client = &http.Client{}
latestCLIVersion, err := github.GetLatestCLITag(cmd.Context())
if err != nil {
return err
}

if global.Version != latestCLIVersion {
fmt.Printf("\n\n 🎁 meroxa %s is available! To update it run: `brew upgrade meroxa`", latestCLIVersion)
fmt.Printf("\n 🧐 Check out latest changes in https://github.com/meroxa/cli/releases/tag/v%s", latestCLIVersion)
fmt.Printf("\n 💡 To disable these warnings, run `meroxa config set %s=true`\n", global.DisableNotificationsUpdate)
}
}
return nil
}
}

func buildCommandWithExecute(cmd *cobra.Command, c Command) {
v, ok := c.(CommandWithExecute)
if !ok {
Expand Down Expand Up @@ -752,3 +787,17 @@ func CheckFeatureFlag(exec Command, cmd CommandWithFeatureFlag) error {
}
return nil
}

func writeConfigFile() error {
err := global.Config.WriteConfig()

if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
err = global.Config.SafeWriteConfig()
}
if err != nil {
return fmt.Errorf("meroxa: could not write config file: %v", err)
}
}
return nil
}
6 changes: 6 additions & 0 deletions cmd/meroxa/builder/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ func TestBuildCobraCommand_Structural(t *testing.T) {
// Since we can't compare functions, we ignore RunE (coming from `buildCommandEvent`)
got.RunE = nil

// Since we can't compare functions, we ignore PostRunE (coming from `buildCommandAutoUpdate`)
got.PostRunE = nil

if v := cmp.Diff(got, want, cmpopts.IgnoreUnexported(cobra.Command{})); v != "" {
t.Fatalf(v)
}
Expand Down Expand Up @@ -284,6 +287,9 @@ func TestBuildCommandWithFlags(t *testing.T) {
// Since we can't compare functions, we ignore RunE (coming from `buildCommandEvent`)
got.RunE = nil

// Since we can't compare functions, we ignore PostRunE (coming from `buildCommandAutoUpdate`)
got.PostRunE = nil

if v := cmp.Diff(got, want, cmpopts.IgnoreUnexported(cobra.Command{})); v != "" {
t.Fatalf(v)
}
Expand Down
88 changes: 88 additions & 0 deletions cmd/meroxa/github/github.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright © 2022 Meroxa Inc

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.
*/

package github

import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"regexp"
)

type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}

var (
Client HTTPClient
)

// getContentHomebrewFormula returns from GitHub the content of the formula file for Meroxa CLI.
func getContentHomebrewFormula(ctx context.Context) (string, error) {
url := "https://api.github.com/repos/meroxa/homebrew-taps/contents/Formula/meroxa.rb"
req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
return "", err
}

req.Header.Add("Accept", "application/vnd.github.v3+json")
resp, err := Client.Do(req)
if err != nil {
return "", err
}

if resp.Body != nil {
defer resp.Body.Close()
}

b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}

type FormulaDefinition struct {
Content []byte `json:"content,omitempty"`
}

var f FormulaDefinition
if err := json.Unmarshal(b, &f); err != nil {
return "", err
}

return bytes.NewBuffer(f.Content).String(), nil
}

// parseVersionFromFormulaFile receives the content of a formula file such as the one in
// "https://api.github.com/repos/meroxa/homebrew-taps/contents/Formula/meroxa.rb"
// and extracts its version number.
func parseVersionFromFormulaFile(content string) string {
r := regexp.MustCompile(`version "(\d+.\d+.\d+)"`)
return r.FindStringSubmatch(content)[1]
}

// GetLatestCLITag fetches the content formula file from GitHub and then parses its version.
// example: 2.0.0
func GetLatestCLITag(ctx context.Context) (string, error) {
brewFormulaFile, err := getContentHomebrewFormula(ctx)
if err != nil {
return brewFormulaFile, err
}

return parseVersionFromFormulaFile(brewFormulaFile), nil
}
Loading