diff --git a/cmd/root.go b/cmd/root.go index f9e18ea..23e035f 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -4,6 +4,7 @@ package cmd import ( + "fmt" "os" "github.com/rs/zerolog" @@ -23,8 +24,13 @@ var rootValues = struct { configurationFileName configurationFileName }{} -func Execute(version string) { +func Execute(version, commit, date, builtBy string) { rootCmd.Version = version + versionTemplate := fmt.Sprintf("{{with .Name}}"+ + "{{printf \"%%s \" .}}{{end}}"+ + "{{printf \"version %%s\\ncommit %s\\ndate %s\\nbuiltBy %s\\n\" .Version}}", + commit, date, builtBy) + rootCmd.SetVersionTemplate(versionTemplate) err := rootCmd.Execute() if err != nil { os.Exit(1) diff --git a/cmd/self_update.go b/cmd/self_update.go new file mode 100644 index 0000000..691d1bf --- /dev/null +++ b/cmd/self_update.go @@ -0,0 +1,55 @@ +// Copyright 2022 OWASP Core Rule Set Project +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "github.com/spf13/cobra" + + "github.com/coreruleset/crs-toolchain/internal/updater" +) + +// selfUpdateCmd represents the self-update command +var selfUpdateCmd = createSelfUpdateCommand() + +func init() { + buildSelfUpdateCommand() +} + +func createSelfUpdateCommand() *cobra.Command { + return &cobra.Command{ + Use: "self-update", + Short: "Performs self-update", + Long: "Checks GitHub releases for the latest version of this command. If a new version is available, " + + "it will get it and replace this binary.", + RunE: func(cmd *cobra.Command, args []string) error { + version := "dev" + if rootCmd.Version != "" { + version = rootCmd.Version + } + newVersion, err := updater.Updater(version, "") + if err != nil { + return err + } + if newVersion != "" { + logger.Info().Msgf("Updated to version %s", newVersion) + } else { + logger.Info().Msg("No updates available") + } + return nil + }, + } +} + +func buildSelfUpdateCommand() { + rootCmd.AddCommand(selfUpdateCmd) +} + +func rebuildSelfUpdateCommand() { + if selfUpdateCmd != nil { + selfUpdateCmd.Parent().RemoveCommand(selfUpdateCmd) + } + + selfUpdateCmd = createSelfUpdateCommand() + buildSelfUpdateCommand() +} diff --git a/cmd/self_update_test.go b/cmd/self_update_test.go new file mode 100644 index 0000000..0a02b2c --- /dev/null +++ b/cmd/self_update_test.go @@ -0,0 +1,82 @@ +// Copyright 2022 OWASP Core Rule Set Project +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "bytes" + "fmt" + "io/fs" + "os" + "os/exec" + "path" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/coreruleset/crs-toolchain/internal/updater" +) + +type selfUpdateTestSuite struct { + suite.Suite + tempDir string + executablePath string +} + +func (s *selfUpdateTestSuite) SetupTest() { + var err error + rebuildSelfUpdateCommand() + s.tempDir, err = os.MkdirTemp("", "self-update-tests") + s.NoError(err) + + s.executablePath = path.Join(s.tempDir, "crs-toolchain") + err = os.WriteFile(s.executablePath, []byte("Fake Binary"), fs.ModePerm) + s.NoError(err) +} + +func (s *selfUpdateTestSuite) TearDownTest() { + err := os.RemoveAll(s.tempDir) + s.NoError(err) +} + +func TestRunSelfUpdateTestSuite(t *testing.T) { + suite.Run(t, new(selfUpdateTestSuite)) +} + +func (s *selfUpdateTestSuite) TestSelfUpdateDev() { + _, err := updater.Updater("v0.0.0-dev", s.executablePath) + s.NoError(err) +} + +func (s *selfUpdateTestSuite) TestSelfUpdateBigVersion() { + newVersion, err := updater.Updater("v10000.1.1", s.executablePath) + s.NoError(err) + s.Equal("v10000.1.1", newVersion) +} + +func (s *selfUpdateTestSuite) TestSelfUpdateWithExecutablePath() { + newVersion, err := updater.Updater("v1.3.7", s.executablePath) + s.NoError(err) + s.NotEmpty(newVersion) + + s.FileExists(s.executablePath, "The executable should exist") + contents, err := os.ReadFile(s.executablePath) + s.NoError(err) + s.NotContains(string(contents), "Fake Binary", "The executable should be replaced") + + var out, stderr bytes.Buffer + + cmd := exec.Command(s.executablePath, "version") + cmd.Stdout = &out + cmd.Stderr = &stderr + + err = cmd.Run() + if err == nil { + versionString := fmt.Sprintf("crs-toolchain version %s", newVersion) + s.Contains(versionString, out.String()) + } else { + s.Equal("exit status 1", err.Error()) + oldBinaryWithUnsupportedVersionFlagError := "Error: unknown command \"version\" for \"crs-toolchain\"\nRun 'crs-toolchain --help' for usage.\n" + s.Equal(oldBinaryWithUnsupportedVersionFlagError, stderr.String()) + } +} diff --git a/cmd/version.go b/cmd/version.go new file mode 100644 index 0000000..52e8596 --- /dev/null +++ b/cmd/version.go @@ -0,0 +1,36 @@ +// Copyright 2023 OWASP Core Rule Set Project +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/coreruleset/crs-toolchain/internal/updater" +) + +func init() { + rootCmd.AddCommand(versionCmd) +} + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Print the version number of crs-toolchain", + Long: `All software has versions. This is crs-toolchain's`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("crs-toolchain", rootCmd.Version) + // do not run when in CI (e.g. GitHub Actions) + if os.Getenv("CI") != "true" { + latest, err := updater.LatestVersion() + if err != nil { + logger.Error().Err(err).Msg("Failed to check for updates") + } else if latest != "" { + fmt.Println("Latest version is:", latest) + fmt.Println("Run 'crs-toolchain self-update' to update") + } + } + }, +} diff --git a/go.mod b/go.mod index ad04c94..0c09011 100644 --- a/go.mod +++ b/go.mod @@ -4,23 +4,40 @@ go 1.20 require ( github.com/imdario/mergo v0.3.15 - github.com/magefile/mage v1.14.0 + github.com/magefile/mage v1.15.0 github.com/spf13/cobra v1.7.0 ) require ( + github.com/creativeprojects/go-selfupdate v1.1.0 github.com/google/uuid v1.3.0 github.com/itchyny/rassemble-go v0.1.0 gopkg.in/yaml.v3 v3.0.1 ) require ( + code.gitea.io/sdk/gitea v0.15.1 // indirect + github.com/Masterminds/semver/v3 v3.2.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/go-github/v30 v30.1.0 // indirect + github.com/google/go-querystring v1.1.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-retryablehttp v0.7.2 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect github.com/kr/pretty v0.2.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.18 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/ulikunitz/xz v0.5.11 // indirect + github.com/xanzy/go-gitlab v0.83.0 // indirect + golang.org/x/crypto v0.9.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/oauth2 v0.8.0 // indirect golang.org/x/sys v0.8.0 // indirect + golang.org/x/time v0.3.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/protobuf v1.30.0 // indirect gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect ) diff --git a/go.sum b/go.sum index 004c8bf..b277ac3 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,40 @@ +code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= +code.gitea.io/sdk/gitea v0.15.1 h1:WJreC7YYuxbn0UDaPuWIe/mtiNKTvLN8MLkaw71yx/M= +code.gitea.io/sdk/gitea v0.15.1/go.mod h1:klY2LVI3s3NChzIk/MzMn7G1FHrfU7qd63iSMVoHRBA= +github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= +github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creativeprojects/go-selfupdate v1.1.0 h1:OCvJUc7XtEGWSooyYFIQfF3dXD6VZNhaUk6Kd2Y6sqw= +github.com/creativeprojects/go-selfupdate v1.1.0/go.mod h1:nm7AWUJfrfYt/SB97NAcMhR0KEpPqlrVHXkWFti+ezw= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-github/v30 v30.1.0 h1:VLDx+UolQICEOKu2m4uAoMti1SxuEBAl7RSEG16L+Oo= +github.com/google/go-github/v30 v30.1.0/go.mod h1:n8jBpHl45a/rlBUtRJMOG4GhNADUQFEufcolZ95JfU8= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= +github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI= +github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= +github.com/hashicorp/go-retryablehttp v0.7.2 h1:AcYqCvkpalPnPF2pn0KamgwamS42TqUDDYFRKq/RAd0= +github.com/hashicorp/go-retryablehttp v0.7.2/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8= +github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -17,8 +46,8 @@ github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfn github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/magefile/mage v1.14.0 h1:6QDX3g6z1YvJ4olPhT1wksUcSa/V0a1B+pJb73fBjyo= -github.com/magefile/mage v1.14.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= +github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg= +github.com/magefile/mage v1.15.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= @@ -40,19 +69,63 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/ulikunitz/xz v0.5.11 h1:kpFauv27b6ynzBNT/Xy+1k+fK4WswhN/6PN5WhFAGw8= +github.com/ulikunitz/xz v0.5.11/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/xanzy/go-gitlab v0.83.0 h1:37p0MpTPNbsTMKX/JnmJtY8Ch1sFiJzVF342+RvZEGw= +github.com/xanzy/go-gitlab v0.83.0/go.mod h1:5ryv+MnpZStBH8I/77HuQBsMbBGANtVpLWC15qOjWAw= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= +golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/updater/updater.go b/internal/updater/updater.go new file mode 100644 index 0000000..39abfc4 --- /dev/null +++ b/internal/updater/updater.go @@ -0,0 +1,79 @@ +// Copyright 2023 OWASP Core Rule Set Project +// SPDX-License-Identifier: Apache-2.0 + +package updater + +import ( + "context" + "fmt" + "os" + "runtime" + + "github.com/creativeprojects/go-selfupdate" + "github.com/rs/zerolog/log" +) + +var logger = log.With().Str("component", "updater").Logger() + +// getLatestVersionFromGitHub checks the latest version on GitHub and returns it. +func getLatestVersionFromGitHub() (*selfupdate.Release, error) { + source, err := selfupdate.NewGitHubSource(selfupdate.GitHubConfig{}) + if err != nil { + logger.Fatal().Err(err) + } + updater, err := selfupdate.NewUpdater(selfupdate.Config{ + Source: source, + Validator: &selfupdate.ChecksumValidator{UniqueFilename: "crs-toolchain-checksums.txt"}, // checksum from goreleaser + }) + if err != nil { + return nil, err + } + latest, found, err := updater.DetectLatest(context.Background(), selfupdate.ParseSlug("coreruleset/crs-toolchain")) + if err != nil { + return latest, fmt.Errorf("error occurred while detecting version: %w", err) + } + if !found { + return latest, fmt.Errorf("latest version for %s/%s could not be found on GitHub repository", runtime.GOOS, runtime.GOARCH) + } + return latest, nil +} + +// LatestVersion checks the latest version on GitHub and returns it. +func LatestVersion() (string, error) { + latest, err := getLatestVersionFromGitHub() + if err != nil { + return "", err + } + return latest.Version(), nil +} + +// Updater checks the latest version on GitHub and self-updates if there is a newer release. +// Returns the version string of the updated release, or an error if something went wrong. +func Updater(version string, executablePath string) (string, error) { + emptyVersion := "" + latest, err := getLatestVersionFromGitHub() + if err != nil { + return emptyVersion, err + } + + if latest.LessOrEqual(version) { + logger.Info().Msgf("You have the latest version installed, %s", version) + return version, nil + } + logger.Info().Msgf("Your version is %s.", version) + // passing executablePath allows to test the updater without actually updating the binary + if executablePath == "" { + exe, err := os.Executable() + if err != nil { + return emptyVersion, fmt.Errorf("could not locate executable path: %w", err) + } + executablePath = exe + logger.Info().Msgf("Updating file \"%s\"", executablePath) + } + + if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, latest.AssetName, executablePath); err != nil { + return emptyVersion, fmt.Errorf("error occurred while updating binary: %w", err) + } + logger.Info().Msgf("Successfully updated to version %s", latest.Version()) + return latest.Version(), nil +} diff --git a/internal/updater/updater_test.go b/internal/updater/updater_test.go new file mode 100644 index 0000000..904f521 --- /dev/null +++ b/internal/updater/updater_test.go @@ -0,0 +1,30 @@ +// Copyright 2023 OWASP ModSecurity Core Rule Set Project +// SPDX-License-Identifier: Apache-2.0 + +package updater + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type updaterTestSuite struct { + suite.Suite +} + +func (s *updaterTestSuite) SetupTest() { +} + +func (s *updaterTestSuite) TearDownTest() { +} + +func TestRunUpdaterTestSuite(t *testing.T) { + suite.Run(t, new(updaterTestSuite)) +} + +func (s *updaterTestSuite) TestLatestVersion() { + latestVersion, err := LatestVersion() + s.NoError(err) + s.NotEmpty(latestVersion) +} diff --git a/main.go b/main.go index 40dd545..ddf61d9 100644 --- a/main.go +++ b/main.go @@ -4,8 +4,6 @@ package main import ( - "fmt" - _ "github.com/coreruleset/crs-toolchain/logger" "github.com/coreruleset/crs-toolchain/cmd" @@ -13,27 +11,13 @@ import ( // nolint: gochecknoglobals var ( - version = "dev" + version = "v0.0.0-dev" commit = "" date = "" builtBy = "" ) func main() { - cmd.Execute(buildVersion(version, commit, date, builtBy)) - -} + cmd.Execute(version, commit, date, builtBy) -func buildVersion(version, commit, date, builtBy string) string { - var result = version - if commit != "" { - result = fmt.Sprintf("%s\ncommit: %s", result, commit) - } - if date != "" { - result = fmt.Sprintf("%s\nbuilt at: %s", result, date) - } - if builtBy != "" { - result = fmt.Sprintf("%s\nbuilt by: %s", result, builtBy) - } - return result }