Skip to content
Open
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
43 changes: 30 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,16 @@ func update(version string) error {
return nil
}

exe, err := selfupdate.ExecutablePath()
cmdPath, err := selfupdate.ExecutablePath()
if err != nil {
return errors.New("could not locate executable path")
return fmt.Errorf("could not locate executable path: %w", err)
}
if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, latest.AssetName, exe); err != nil {

// In the new release, the binary file can have any name — this is set by the relExe.
// If it has the same name as the old one, you can get it like this:
_, relExe := filepath.Split(cmdPath)

if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, relExe, cmdPath); err != nil {
return fmt.Errorf("error occurred while updating binary: %w", err)
}
log.Printf("Successfully updated to version %s", latest.Version())
Expand Down Expand Up @@ -346,7 +351,7 @@ See [goreleaser documentation](https://goreleaser.com/scm/gitlab/#generic-packag
## Example:

```go
func update() {
func update() error {
source, err := selfupdate.NewGitLabSource(selfupdate.GitLabConfig{
BaseURL: "https://private.instance.on.gitlab.com/",
})
Expand All @@ -365,19 +370,25 @@ func update() {
log.Fatal(err)
}
if !found {
log.Print("Release not found")
return
return errors.New("release not found")
}
fmt.Printf("found release %s\n", release.Version())

exe, err := selfupdate.ExecutablePath()
cmdPath, err := selfupdate.ExecutablePath()
if err != nil {
return errors.New("could not locate executable path")
}
err = updater.UpdateTo(context.Background(), release, exe)

// In the new release, the binary file can have any name — this is set by the relExe.
// If it has the same name as the old one, you can get it like this:
_, relExe := filepath.Split(cmdPath)

err = updater.UpdateTo(context.Background(), release, relExe, cmdPath)
if err != nil {
log.Fatal(err)
}

return nil
}
```

Expand All @@ -392,7 +403,7 @@ The HttpSource is designed to work with repositories built using [goreleaser-htt
If your repository is at example.com/repo/project, then you'd use the following example.

```go
func update() {
func update() error {
source, err := selfupdate.NewHttpSource(selfupdate.HttpConfig{
BaseURL: "https://example.com/",
})
Expand All @@ -411,19 +422,25 @@ func update() {
log.Fatal(err)
}
if !found {
log.Print("Release not found")
return
return errors.New("release not found")
}
fmt.Printf("found release %s\n", release.Version())

exe, err := selfupdate.ExecutablePath()
cmdPath, err := selfupdate.ExecutablePath()
if err != nil {
return errors.New("could not locate executable path")
}
err = updater.UpdateTo(context.Background(), release, exe)

// In the new release, the binary file can have any name — this is set by the relExe.
// If it has the same name as the old one, you can get it like this:
_, relExe := filepath.Split(cmdPath)

err = updater.UpdateTo(context.Background(), release, relExe, cmdPath)
if err != nil {
log.Fatal(err)
}

return nil
}
```

Expand Down
10 changes: 8 additions & 2 deletions cmd/detect-latest-release/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"path/filepath"
"runtime"

"github.com/creativeprojects/go-selfupdate"
Expand All @@ -26,11 +27,16 @@ func update(version string) error {
return nil
}

exe, err := selfupdate.ExecutablePath()
cmdPath, err := selfupdate.ExecutablePath()
if err != nil {
return fmt.Errorf("could not locate executable path: %w", err)
}
if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, latest.AssetName, exe); err != nil {

// In the new release, the binary file can have any name — this is set by the relExe.
// If it has the same name as the old one, you can get it like this:
_, relExe := filepath.Split(cmdPath)

if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, relExe, cmdPath); err != nil {
return fmt.Errorf("error occurred while updating binary: %w", err)
}
log.Printf("Successfully updated to version %s", latest.Version())
Expand Down
16 changes: 9 additions & 7 deletions cmd/get-release/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func main() {
flag.Usage = usage
flag.Parse()

if help || flag.NArg() != 1 {
if help || flag.NArg() != 2 {
usage()
return
}
Expand All @@ -38,6 +38,7 @@ func main() {
}

repo := flag.Arg(0)
relExe := flag.Arg(1)

domain, slug, err := cmd.SplitDomainSlug(repo)
if err != nil {
Expand Down Expand Up @@ -77,16 +78,16 @@ func main() {
os.Exit(1)
}

cmd := getCommand(flag.Arg(0))
cmd := getCommand(repo)
cmdPath := filepath.Join(build.Default.GOPATH, "bin", cmd)
if _, err := os.Stat(cmdPath); err != nil {
// When executable is not existing yet
if err := installFrom(ctx, latest.AssetURL, cmd, cmdPath); err != nil {
if err := installFrom(ctx, latest.AssetURL, relExe, cmdPath); err != nil {
fmt.Fprintf(os.Stderr, "Error while installing the release binary from %s: %s\n", latest.AssetURL, err)
os.Exit(1)
}
} else {
if err := updater.UpdateTo(ctx, latest, cmdPath); err != nil {
if err := updater.UpdateTo(ctx, latest, relExe, cmdPath); err != nil {
fmt.Fprintf(os.Stderr, "Error while replacing the binary with %s: %s\n", latest.AssetURL, err)
os.Exit(1)
}
Expand All @@ -101,10 +102,11 @@ Release Notes:

func usage() {
fmt.Fprintln(os.Stderr, `
Usage: get-release [flags] {package}
Usage: get-release [flags] {package} {relExe}

get-release is like "go get github.com/owner/repo@latest".
{package} is using the same format: "github.com/owner/repo".
{relExe} is the name of the new executable file (usually inside a release archive).

Flags:`)
flag.PrintDefaults()
Expand All @@ -116,7 +118,7 @@ func getCommand(pkg string) string {
return cmd
}

func installFrom(ctx context.Context, url, cmd, path string) error {
func installFrom(ctx context.Context, url, relExe, path string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return fmt.Errorf("failed to create request to download release binary from %s: %s", url, err)
Expand All @@ -129,7 +131,7 @@ func installFrom(ctx context.Context, url, cmd, path string) error {
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download release binary from %s: Invalid response ", url)
}
executable, err := selfupdate.DecompressCommand(res.Body, url, cmd, runtime.GOOS, runtime.GOARCH)
executable, err := selfupdate.DecompressCommand(res.Body, url, relExe, runtime.GOOS, runtime.GOARCH)
if err != nil {
return fmt.Errorf("failed to decompress downloaded asset from %s: %s", url, err)
}
Expand Down
56 changes: 28 additions & 28 deletions decompress.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
var (
fileTypes = []struct {
ext string
decompress func(src io.Reader, cmd, os, arch string) (io.Reader, error)
decompress func(src io.Reader, relExe, os, arch string) (io.Reader, error)
}{
{".zip", unzip},
{".tar.gz", untar},
Expand All @@ -37,23 +37,23 @@ var (
// DecompressCommand decompresses the given source. Archive and compression format is
// automatically detected from 'url' parameter, which represents the URL of asset,
// or simply a filename (with an extension).
// This returns a reader for the decompressed command given by 'cmd'. '.zip',
// This returns a reader for the decompressed command given by 'url'. '.zip',
// '.tar.gz', '.tar.xz', '.tgz', '.gz', '.bz2' and '.xz' are supported.
//
// These wrapped errors can be returned:
// - ErrCannotDecompressFile
// - ErrExecutableNotFoundInArchive
func DecompressCommand(src io.Reader, url, cmd, os, arch string) (io.Reader, error) {
func DecompressCommand(src io.Reader, url, relExe, os, arch string) (io.Reader, error) {
for _, fileType := range fileTypes {
if strings.HasSuffix(url, fileType.ext) {
return fileType.decompress(src, cmd, os, arch)
return fileType.decompress(src, relExe, os, arch)
}
}
log.Print("File is not compressed")
return src, nil
}

func unzip(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func unzip(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing zip file")

// Zip format requires its file size for Decompressing.
Expand All @@ -70,82 +70,82 @@ func unzip(src io.Reader, cmd, os, arch string) (io.Reader, error) {
}

for _, file := range z.File {
_, name := filepath.Split(file.Name)
if !file.FileInfo().IsDir() && matchExecutableName(cmd, os, arch, name) {
_, target := filepath.Split(file.Name)
if !file.FileInfo().IsDir() && matchExecutableName(relExe, os, arch, target) {
log.Printf("Executable file %q was found in zip archive", file.Name)
return file.Open()
}
}

return nil, fmt.Errorf("%w in zip file: %q", ErrExecutableNotFoundInArchive, cmd)
return nil, fmt.Errorf("%w in zip file: %q", ErrExecutableNotFoundInArchive, relExe)
}

func untar(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func untar(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing tar.gz file")

gz, err := gzip.NewReader(src)
if err != nil {
return nil, fmt.Errorf("%w tar.gz file: %s", ErrCannotDecompressFile, err)
}

return unarchiveTar(gz, cmd, os, arch)
return unarchiveTar(gz, relExe, os, arch)
}

func gunzip(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func gunzip(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing gzip file")

r, err := gzip.NewReader(src)
if err != nil {
return nil, fmt.Errorf("%w gzip file: %s", ErrCannotDecompressFile, err)
}

name := r.Name
if !matchExecutableName(cmd, os, arch, name) {
return nil, fmt.Errorf("%w: expected %q but found %q", ErrExecutableNotFoundInArchive, cmd, name)
target := r.Name
if !matchExecutableName(relExe, os, arch, target) {
return nil, fmt.Errorf("%w: expected %q but found %q", ErrExecutableNotFoundInArchive, relExe, target)
}

log.Printf("Executable file %q was found in gzip file", name)
log.Printf("Executable file %q was found in gzip file", target)
return r, nil
}

func untarxz(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func untarxz(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing tar.xz file")

xzip, err := xz.NewReader(src)
if err != nil {
return nil, fmt.Errorf("%w tar.xz file: %s", ErrCannotDecompressFile, err)
}

return unarchiveTar(xzip, cmd, os, arch)
return unarchiveTar(xzip, relExe, os, arch)
}

func unxz(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func unxz(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing xzip file")

xzip, err := xz.NewReader(src)
if err != nil {
return nil, fmt.Errorf("%w xzip file: %s", ErrCannotDecompressFile, err)
}

log.Printf("Decompressed file from xzip is assumed to be an executable: %s", cmd)
log.Printf("Decompressed file from xzip is assumed to be an executable: %s", relExe)
return xzip, nil
}

func unbz2(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func unbz2(src io.Reader, relExe, os, arch string) (io.Reader, error) {
log.Print("Decompressing bzip2 file")

bz2 := bzip2.NewReader(src)

log.Printf("Decompressed file from bzip2 is assumed to be an executable: %s", cmd)
log.Printf("Decompressed file from bzip2 is assumed to be an executable: %s", relExe)
return bz2, nil
}

func matchExecutableName(cmd, os, arch, target string) bool {
cmd = strings.TrimSuffix(cmd, ".exe")
func matchExecutableName(relExe, os, arch, target string) bool {
relExe = strings.TrimSuffix(relExe, ".exe")
pattern := regexp.MustCompile(
fmt.Sprintf(
`^%s([_-]v?%s)?([_-]%s[_-]%s)?(\.exe)?$`,
regexp.QuoteMeta(cmd),
regexp.QuoteMeta(relExe),
semverPattern,
regexp.QuoteMeta(os),
regexp.QuoteMeta(arch),
Expand All @@ -154,7 +154,7 @@ func matchExecutableName(cmd, os, arch, target string) bool {
return pattern.MatchString(target)
}

func unarchiveTar(src io.Reader, cmd, os, arch string) (io.Reader, error) {
func unarchiveTar(src io.Reader, relExe, os, arch string) (io.Reader, error) {
t := tar.NewReader(src)
for {
h, err := t.Next()
Expand All @@ -164,11 +164,11 @@ func unarchiveTar(src io.Reader, cmd, os, arch string) (io.Reader, error) {
if err != nil {
return nil, fmt.Errorf("%w tar file: %s", ErrCannotDecompressFile, err)
}
_, name := filepath.Split(h.Name)
if matchExecutableName(cmd, os, arch, name) {
_, target := filepath.Split(h.Name)
if matchExecutableName(relExe, os, arch, target) {
log.Printf("Executable file %q was found in tar archive", h.Name)
return t, nil
}
}
return nil, fmt.Errorf("%w in tar: %q", ErrExecutableNotFoundInArchive, cmd)
return nil, fmt.Errorf("%w in tar: %q", ErrExecutableNotFoundInArchive, relExe)
}
12 changes: 6 additions & 6 deletions package.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,29 @@ func DetectVersion(ctx context.Context, repository Repository, version string) (
// This function is low-level API to update the binary. Because it does not use a source provider and downloads asset directly from the URL via HTTP,
// this function is not available to update a release for private repositories.
// cmdPath is a file path to command executable.
func UpdateTo(ctx context.Context, assetURL, assetFileName, cmdPath string) error {
func UpdateTo(ctx context.Context, assetURL, relExe, cmdPath string) error {
//nolint:contextcheck
up := DefaultUpdater()
src, err := downloadReleaseAssetFromURL(ctx, assetURL)
if err != nil {
return err
}
defer src.Close()
return up.decompressAndUpdate(src, assetFileName, assetURL, cmdPath)
return up.decompressAndUpdate(src, assetURL, relExe, cmdPath)
}

// UpdateCommand updates a given command binary to the latest version.
// This function is a shortcut version of updater.UpdateCommand using a DefaultUpdater()
func UpdateCommand(ctx context.Context, cmdPath string, current string, repository Repository) (*Release, error) {
func UpdateCommand(ctx context.Context, relExe, cmdPath string, current string, repository Repository) (*Release, error) {
//nolint:contextcheck
return DefaultUpdater().UpdateCommand(ctx, cmdPath, current, repository)
return DefaultUpdater().UpdateCommand(ctx, relExe, cmdPath, current, repository)
}

// UpdateSelf updates the running executable itself to the latest version.
// This function is a shortcut version of updater.UpdateSelf using a DefaultUpdater()
func UpdateSelf(ctx context.Context, current string, repository Repository) (*Release, error) {
func UpdateSelf(ctx context.Context, relExe, current string, repository Repository) (*Release, error) {
//nolint:contextcheck
return DefaultUpdater().UpdateSelf(ctx, current, repository)
return DefaultUpdater().UpdateSelf(ctx, relExe, current, repository)
}

func downloadReleaseAssetFromURL(ctx context.Context, url string) (rc io.ReadCloser, err error) {
Expand Down
Loading