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 23, 2024
1 parent b66f73e commit 96651a7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 177 deletions.
178 changes: 8 additions & 170 deletions cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,36 +23,23 @@ 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/marianozunino/rop/internal/logger"
"github.com/minio/selfupdate"
"github.com/rs/zerolog/log"
"github.com/spf13/afero"
"github.com/marianozunino/selfupdater"
"github.com/spf13/cobra"
)

func NewUpdateCmd() *cobra.Command {
cfg := &config{}

updateCmd := &cobra.Command{
Use: "update",
Short: "Update rop to the latest version",
Short: "Update the rop tool to the latest available version.",
Long: `Automatically update the rop tool to the latest available version from the official source.
This command checks for updates, downloads the new version, and replaces the current executable with the updated one.`,
Example: `rop update`,
Run: func(cmd *cobra.Command, args []string) {
logger.ConfigureLogger(cfg.verbose)
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", "rop", "rop", currentVersionStr)
updater.Update()
},
}

Expand All @@ -62,152 +49,3 @@ func NewUpdateCmd() *cobra.Command {
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("rop_%s_%s.tar.gz", os, arch)
}

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

releaseURL := "https://github.com/marianozunino/rop/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) {
log.Info().Msg("Current version is the latest")
return nil
}

log.Info().Msgf("New version available: %s (current: %s)", latestVersion, currentVersion)

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

log.Debug().Msgf("Downloading %s from %s", 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("", "rop-update")
if err != nil {
return fmt.Errorf("error creating temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)

log.Info().Msg("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, "rop")

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

log.Info().Msg("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)
}

log.Info().Msgf("Successfully updated to version %s", 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
}

7 changes: 4 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ module github.com/marianozunino/rop
go 1.23.0

require (
github.com/Masterminds/semver/v3 v3.3.0
github.com/charmbracelet/huh v0.6.0
github.com/charmbracelet/lipgloss v0.13.0
github.com/minio/selfupdate v0.6.0
github.com/spf13/afero v1.11.0
github.com/marianozunino/selfupdater v1.0.1
github.com/spf13/cobra v1.8.1
k8s.io/api v0.31.1
k8s.io/apimachinery v0.31.1
Expand All @@ -26,9 +24,12 @@ require (
github.com/charmbracelet/x/term v0.2.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/google/go-github/v66 v66.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/minio/selfupdate v0.6.0 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
Expand Down
11 changes: 7 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ aead.dev/minisign v0.2.0 h1:kAWrq/hBRu4AARY6AlciO83xhNnW9UaC8YipS2uhLPk=
aead.dev/minisign v0.2.0/go.mod h1:zdq6LdSd9TbuSxchxwhpA9zEb9YXcVGoE8JakuiGaIQ=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
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=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
Expand Down Expand Up @@ -59,9 +57,14 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
Expand Down Expand Up @@ -92,6 +95,8 @@ github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
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 @@ -140,8 +145,6 @@ github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
Expand Down

0 comments on commit 96651a7

Please sign in to comment.