Skip to content

Commit

Permalink
chore: use remove selfupdate logic
Browse files Browse the repository at this point in the history
  • Loading branch information
marianozunino committed Nov 22, 2024
1 parent 3442bee commit 0eb304c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 180 deletions.
167 changes: 5 additions & 162 deletions cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,10 @@ THE SOFTWARE.
package cmd

import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"

"github.com/Masterminds/semver/v3"
"github.com/minio/selfupdate"
"github.com/spf13/afero"
"github.com/marianozunino/selfupdater"

"github.com/spf13/cobra"
)

Expand All @@ -48,10 +39,9 @@ This command checks for updates, downloads the new version, and replaces the cur
Example: `goq update`,
GroupID: "available-commands",
Run: func(cmd *cobra.Command, args []string) {
if err := runSelfUpdate(http.DefaultClient, afero.NewOsFs(), os.Args[0]); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
currentVersionStr := strings.TrimPrefix(Version, "v")
updater := selfupdater.NewUpdater("marianozunino", "goq", "goq", currentVersionStr)
updater.Update()
},
}

Expand All @@ -61,150 +51,3 @@ This command checks for updates, downloads the new version, and replaces the cur
func init() {
rootCmd.AddCommand(NewUpdateCmd())
}

func getAssetName() string {
os := runtime.GOOS
arch := runtime.GOARCH

switch os {
case "darwin":
os = "Darwin"
case "linux":
os = "Linux"
}

switch arch {
case "amd64":
arch = "x86_64"
case "386":
arch = "i386"
}

return fmt.Sprintf("goq_%s_%s.tar.gz", os, arch)
}

func runSelfUpdate(httpClient *http.Client, fs afero.Fs, executablePath string) error {
fmt.Println("Checking for updates...")

releaseURL := "https://github.com/marianozunino/goq/releases/latest"

resp, err := httpClient.Get(releaseURL)
if err != nil {
return fmt.Errorf("error checking for updates: %v", err)
}
defer resp.Body.Close()

latestVersionStr := filepath.Base(resp.Request.URL.Path)
latestVersionStr = strings.TrimPrefix(latestVersionStr, "v")
currentVersionStr := strings.TrimPrefix(Version, "v")

latestVersion, err := semver.NewVersion(latestVersionStr)
if err != nil {
return fmt.Errorf("error parsing latest version: %v", err)
}

currentVersion, err := semver.NewVersion(currentVersionStr)
if err != nil {
return fmt.Errorf("error parsing current version: %v", err)
}

if !latestVersion.GreaterThan(currentVersion) {
fmt.Println("Current version is the latest")
return nil
}

fmt.Printf("New version available: %s (current: %s)\n", latestVersion, currentVersion)

assetName := getAssetName()
downloadURL := fmt.Sprintf("https://github.com/marianozunino/goq/releases/download/v%s/%s", latestVersion, assetName)

fmt.Printf("Downloading %s from %s\n", assetName, downloadURL)
resp, err = httpClient.Get(downloadURL)
if err != nil {
return fmt.Errorf("error downloading update: %v", err)
}
defer resp.Body.Close()

// Extract the tar.gz file
tmpDir, err := os.MkdirTemp("", "goq-update")
if err != nil {
return fmt.Errorf("error creating temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)

fmt.Println("Extracting update package...")
if err := extractTarGz(resp.Body, tmpDir); err != nil {
return fmt.Errorf("error extracting update: %v", err)
}

// Locate the new binary in the extracted files
newBinaryPath := filepath.Join(tmpDir, "goq")

// Apply the update
newBinary, err := os.Open(newBinaryPath)
if err != nil {
return fmt.Errorf("error opening new binary: %v", err)
}
defer newBinary.Close()

fmt.Println("Applying update...")
err = selfupdate.Apply(newBinary, selfupdate.Options{})
if err != nil {
if rerr := selfupdate.RollbackError(err); rerr != nil {
return fmt.Errorf("failed to rollback from bad update: %v", rerr)
}
return fmt.Errorf("error updating binary: %v", err)
}

fmt.Printf("Successfully updated to version %s\n", latestVersion)
return nil
}

// extractTarGz extracts a tar.gz file to a specified directory

func extractTarGz(r io.Reader, dst string) error {
gz, err := gzip.NewReader(r)
if err != nil {
return fmt.Errorf("error creating gzip reader: %v", err)
}
defer gz.Close()

tr := tar.NewReader(gz)
for {
header, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return fmt.Errorf("error reading tar header: %v", err)
}

target := filepath.Join(dst, header.Name)

// Ensure the directory exists
if header.Typeflag == tar.TypeDir {
if err := os.MkdirAll(target, os.FileMode(header.Mode)); err != nil {
return fmt.Errorf("error creating directory %s: %v", target, err)
}
continue
}

// Create the necessary directories
if err := os.MkdirAll(filepath.Dir(target), os.ModePerm); err != nil {
return fmt.Errorf("error creating directory %s: %v", filepath.Dir(target), err)
}

// Create a new file
outFile, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY, os.FileMode(header.Mode))
if err != nil {
return fmt.Errorf("error creating file %s: %v", target, err)
}

// Write the file content
if _, err := io.Copy(outFile, tr); err != nil {
return fmt.Errorf("error writing to file %s: %v", target, err)
}
outFile.Close()
}
return nil
}
16 changes: 9 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@ module github.com/marianozunino/goq
go 1.23.0

require (
github.com/Masterminds/semver/v3 v3.3.0
github.com/itchyny/gojq v0.12.16
github.com/minio/selfupdate v0.6.0
github.com/marianozunino/selfupdater v1.0.1
github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0
github.com/streadway/amqp v1.1.0
)

require (
aead.dev/minisign v0.2.0 // indirect
aead.dev/minisign v0.3.0 // indirect
github.com/google/go-github/v66 v66.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/itchyny/timefmt-go v0.1.6 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/crypto v0.21.0 // indirect
github.com/minio/selfupdate v0.6.0 // indirect
golang.org/x/crypto v0.29.0 // indirect
)

require (
Expand All @@ -31,15 +33,15 @@ require (
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/text v0.20.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
29 changes: 18 additions & 11 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk=
aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ=
github.com/Masterminds/semver/v3 v3.3.0 h1:B8LGeaivUe71a5qox1ICM/JLl0NqZSW5CHyL+hmvYS0=
github.com/Masterminds/semver/v3 v3.3.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
github.com/adrg/xdg v0.5.0 h1:dDaZvhMXatArP1NPHhnfaQUqWBLBsmx1h1HXQdMoFCY=
github.com/adrg/xdg v0.5.0/go.mod h1:dDdY4M4DF9Rjy4kHPeNL+ilVF+p2lK8IdM9/rTSGcI4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
Expand All @@ -15,8 +14,13 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-github/v66 v66.0.0 h1:ADJsaXj9UotwdgK8/iFZtv7MLc8E8WBl62WLd/D/9+M=
github.com/google/go-github/v66 v66.0.0/go.mod h1:+4SO9Zkuyf8ytMj0csN1NR/5OTR+MfqPp8P8dVlcvY4=
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/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
Expand All @@ -31,6 +35,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/marianozunino/selfupdater v1.0.1 h1:4eAQmEbsspsWadxX1tAtaAFkJZw/Fpu2Wem3OH8YJ4Q=
github.com/marianozunino/selfupdater v1.0.1/go.mod h1:p/bi7u0UXAni5HDX4J9N5Rb6/IeTWswnpFLoPW435SY=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand Down Expand Up @@ -85,8 +91,8 @@ go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTV
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
Expand All @@ -99,15 +105,16 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/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.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
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=
Expand Down

0 comments on commit 0eb304c

Please sign in to comment.