• Stars
    star
    527
  • Rank 81,318 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created over 6 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Binary self-update mechanism for Go commands using GitHub

Self-Update Mechanism for Go Commands Using GitHub

GoDoc Badge TravisCI Status AppVeyor Status Codecov Status

go-github-selfupdate is a Go library to provide a self-update mechanism to command line tools.

Go does not provide a way to install/update the stable version of tools. By default, Go command line tools are updated:

  1. using go get -u, but it is not stable because HEAD of the repository is built
  2. using system's package manager, but it is harder to release because of depending on the platform
  3. downloading executables from GitHub release page, but it requires users to download and put it in an executable path manually

go-github-selfupdate resolves the problem of 3 by detecting the latest release, downloading it and putting it in $GOPATH/bin automatically.

go-github-selfupdate detects the information of the latest release via GitHub Releases API and checks the current version. If a newer version than itself is detected, it downloads the released binary from GitHub and replaces itself.

  • Automatically detect the latest version of released binary on GitHub
  • Retrieve the proper binary for the OS and arch where the binary is running
  • Update the binary with rollback support on failure
  • Tested on Linux, macOS and Windows (using Travis CI and AppVeyor)
  • Many archive and compression formats are supported (zip, tar, gzip, xzip)
  • Support private repositories
  • Support GitHub Enterprise
  • Support hash, signature validation (thanks to @tobiaskohlbau)

And small wrapper CLIs are provided:

Slide at GoCon 2018 Spring (Japanese)

Try Out Example

Example to understand what this library does is prepared as CLI.

Install it at first.

$ go get -u github.com/rhysd/go-github-selfupdate/cmd/selfupdate-example

And check the version by -version. -help flag is also available to know all flags.

$ selfupdate-example -version

It should show v1.2.3.

Then run -selfupdate

$ selfupdate-example -selfupdate

It should replace itself and finally show a message containing release notes.

Please check the binary version is updated to v1.2.4 with -version. The binary is up-to-date. So running -selfupdate again only shows 'Current binary is the latest version'.

Real World Examples

Following tools are using this library.

Usage

Code Usage

It provides selfupdate package.

  • selfupdate.UpdateSelf(): Detect the latest version of itself and run self update.
  • selfupdate.UpdateCommand(): Detect the latest version of given repository and update given command.
  • selfupdate.DetectLatest(): Detect the latest version of given repository.
  • selfupdate.DetectVersion(): Detect the user defined version of given repository.
  • selfupdate.UpdateTo(): Update given command to the binary hosted on given URL.
  • selfupdate.Updater: Context manager of self-update process. If you want to customize some behavior of self-update (e.g. specify API token, use GitHub Enterprise, ...), please make an instance of Updater and use its methods.

Following is the easiest way to use this package.

import (
    "log"
    "github.com/blang/semver"
    "github.com/rhysd/go-github-selfupdate/selfupdate"
)

const version = "1.2.3"

func doSelfUpdate() {
    v := semver.MustParse(version)
    latest, err := selfupdate.UpdateSelf(v, "myname/myrepo")
    if err != nil {
        log.Println("Binary update failed:", err)
        return
    }
    if latest.Version.Equals(v) {
        // latest version is the same as current version. It means current binary is up to date.
        log.Println("Current binary is the latest version", version)
    } else {
        log.Println("Successfully updated to version", latest.Version)
        log.Println("Release note:\n", latest.ReleaseNotes)
    }
}

Following asks user to update or not.

import (
    "bufio"
    "github.com/blang/semver"
    "github.com/rhysd/go-github-selfupdate/selfupdate"
    "log"
    "os"
)

const version = "1.2.3"

func confirmAndSelfUpdate() {
    latest, found, err := selfupdate.DetectLatest("owner/repo")
    if err != nil {
        log.Println("Error occurred while detecting version:", err)
        return
    }

    v := semver.MustParse(version)
    if !found || latest.Version.LTE(v) {
        log.Println("Current version is the latest")
        return
    }

    fmt.Print("Do you want to update to", latest.Version, "? (y/n): ")
    input, err := bufio.NewReader(os.Stdin).ReadString('\n')
    if err != nil || (input != "y\n" && input != "n\n") {
        log.Println("Invalid input")
        return
    }
    if input == "n\n" {
        return
    }

    exe, err := os.Executable()
    if err != nil {
        log.Println("Could not locate executable path")
        return
    }
    if err := selfupdate.UpdateTo(latest.AssetURL, exe); err != nil {
        log.Println("Error occurred while updating binary:", err)
        return
    }
    log.Println("Successfully updated to version", latest.Version)
}

If GitHub API token is set to [token] section in gitconfig or $GITHUB_TOKEN environment variable, this library will use it to call GitHub REST API. It's useful when reaching rate limits or when using this library with private repositories.

Note that os.Args[0] is not available since it does not provide a full path to executable. Instead, please use os.Executable().

Please see the documentation page for more detail.

This library should work with GitHub Enterprise. To configure API base URL, please setup Updater instance and use its methods instead (actually all functions above are just a shortcuts of methods of an Updater instance).

Following is an example of usage with GitHub Enterprise.

import (
    "log"
    "github.com/blang/semver"
    "github.com/rhysd/go-github-selfupdate/selfupdate"
)

const version = "1.2.3"

func doSelfUpdate(token string) {
    v := semver.MustParse(version)
    up, err := selfupdate.NewUpdater(selfupdate.Config{
        APIToken: token,
        EnterpriseBaseURL: "https://github.your.company.com/api/v3",
    })
    latest, err := up.UpdateSelf(v, "myname/myrepo")
    if err != nil {
        log.Println("Binary update failed:", err)
        return
    }
    if latest.Version.Equals(v) {
        // latest version is the same as current version. It means current binary is up to date.
        log.Println("Current binary is the latest version", version)
    } else {
        log.Println("Successfully updated to version", latest.Version)
        log.Println("Release note:\n", latest.ReleaseNotes)
    }
}

If APIToken field is not given, it tries to retrieve API token from [token] section of .gitconfig or $GITHUB_TOKEN environment variable. If no token is found, it raises an error because GitHub Enterprise API does not work without authentication.

If your GitHub Enterprise instance's upload URL is different from the base URL, please also set the EnterpriseUploadURL field.

Naming Rules of Released Binaries

go-github-selfupdate assumes that released binaries are put for each combination of platforms and archs. Binaries for each platform can be easily built using tools like gox

You need to put the binaries with the following format.

{cmd}_{goos}_{goarch}{.ext}

{cmd} is a name of command. {goos} and {goarch} are the platform and the arch type of the binary. {.ext} is a file extension. go-github-selfupdate supports .zip, .gzip, .tar.gz and .tar.xz. You can also use blank and it means binary is not compressed.

If you compress binary, uncompressed directory or file must contain the executable named {cmd}.

And you can also use - for separator instead of _ if you like.

For example, if your command name is foo-bar, one of followings is expected to be put in release page on GitHub as binary for platform linux and arch amd64.

  • foo-bar_linux_amd64 (executable)
  • foo-bar_linux_amd64.zip (zip file)
  • foo-bar_linux_amd64.tar.gz (tar file)
  • foo-bar_linux_amd64.xz (xzip file)
  • foo-bar-linux-amd64.tar.gz (- is also ok for separator)

If you compress and/or archive your release asset, it must contain an executable named one of followings:

  • foo-bar (only command name)
  • foo-bar_linux_amd64 (full name)
  • foo-bar-linux-amd64 (- is also ok for separator)

To archive the executable directly on Windows, .exe can be added before file extension like foo-bar_windows_amd64.exe.zip.

Naming Rules of Versions (=Git Tags)

go-github-selfupdate searches binaries' versions via Git tag names (not a release title). When your tool's version is 1.2.3, you should use the version number for tag of the Git repository (i.e. 1.2.3 or v1.2.3).

This library assumes you adopt semantic versioning. It is necessary for comparing versions systematically.

Prefix before version number \d+\.\d+\.\d+ is automatically omitted. For example, ver1.2.3 or release-1.2.3 are also ok.

Tags which don't contain a version number are ignored (i.e. nightly). And releases marked as pre-release are also ignored.

Structure of Releases

In summary, structure of releases on GitHub looks like:

  • v1.2.0
    • foo-bar-linux-amd64.tar.gz
    • foo-bar-linux-386.tar.gz
    • foo-bar-darwin-amd64.tar.gz
    • foo-bar-windows-amd64.zip
    • ... (Other binaries for v1.2.0)
  • v1.1.3
    • foo-bar-linux-amd64.tar.gz
    • foo-bar-linux-386.tar.gz
    • foo-bar-darwin-amd64.tar.gz
    • foo-bar-windows-amd64.zip
    • ... (Other binaries for v1.1.3)
  • ... (older versions)

Hash or Signature Validation

go-github-selfupdate supports hash or signature validatiom of the downloaded files. It comes with support for sha256 hashes or ECDSA signatures. In addition to internal functions the user can implement the Validator interface for own validation mechanisms.

// Validator represents an interface which enables additional validation of releases.
type Validator interface {
	// Validate validates release bytes against an additional asset bytes.
	// See SHA2Validator or ECDSAValidator for more information.
	Validate(release, asset []byte) error
	// Suffix describes the additional file ending which is used for finding the
	// additional asset.
	Suffix() string
}

SHA256

To verify the integrity by SHA256 generate a hash sum and save it within a file which has the same naming as original file with the suffix .sha256. For e.g. use sha256sum, the file selfupdate/testdata/foo.zip.sha256 is generated with:

sha256sum foo.zip > foo.zip.sha256

ECDSA

To verify the signature by ECDSA generate a signature and save it within a file which has the same naming as original file with the suffix .sig. For e.g. use openssl, the file selfupdate/testdata/foo.zip.sig is generated with:

openssl dgst -sha256 -sign Test.pem -out foo.zip.sig foo.zip

go-github-selfupdate makes use of go internal crypto package. Therefore the used private key has to be compatbile with FIPS 186-3.

Development

Running tests

All library sources are put in /selfupdate directory. So you can run tests as following at the top of the repository:

$ go test -v ./selfupdate

Some tests are not run without setting a GitHub API token because they call GitHub API too many times. To run them, please generate an API token and set it to an environment variable.

$ export GITHUB_TOKEN="{token generated by you}"
$ go test -v ./selfupdate

The above command runs almost all tests and it's enough to check the behavior before creating a pull request. Some tests are still not tested because they depend on my personal API access token, though; for repositories on GitHub Enterprise or private repositories on GitHub.

Debugging

This library can output logs for debugging. By default, logger is disabled. You can enable the logger by the following and can know the details of the self update.

selfupdate.EnableLog()

CI

Tests run on CIs (Travis CI, Appveyor) are run with the token I generated. However, because of security reasons, it is not used for the tests for pull requests. In the tests, a GitHub API token is not set and API rate limit is often exceeding. So please ignore the test failures on creating a pull request.

Dependencies

This library utilizes

  • go-github to retrieve the information of releases
  • go-update to replace current binary
  • semver to compare versions
  • xz to support XZ compress format

Copyright (c) 2013 The go-github AUTHORS. All rights reserved.

Copyright 2015 Alan Shreve

Copyright (c) 2014 Benedikt Lang

Copyright (c) 2014-2016 Ulrich Kunitz

What is different from tj/go-update?

This library's goal is the same as tj/go-update, but it's different in following points.

tj/go-update:

  • does not support Windows
  • only allows v for version prefix
  • does not ignore pre-release
  • has only a few tests
  • supports Apex store for putting releases

License

Distributed under the MIT License

More Repositories

1

vim.wasm

Vim editor ported to WebAssembly
Vim Script
5,305
star
2

actionlint

:octocat: Static checker for GitHub Actions workflow files
Go
2,381
star
3

NyaoVim

Web-enhanced Extensible Neovim Frontend
TypeScript
2,207
star
4

git-messenger.vim

Vim and Neovim plugin to reveal the commit messages under the cursor
Vim Script
1,263
star
5

vim-grammarous

A powerful grammar checker for Vim using LanguageTool.
Vim Script
1,058
star
6

vim-clang-format

Vim plugin for clang-format, a formatter for C, C++, Obj-C, Java, JavaScript, and so on.
Vim Script
1,036
star
7

clever-f.vim

Extended f, F, t and T key mappings for Vim.
Vim Script
968
star
8

Shiba

Rich markdown live preview app with linter
TypeScript
751
star
9

gocaml

๐Ÿซ Statically typed functional programming language implementation with Go and LLVM
Go
732
star
10

kiro-editor

A terminal UTF-8 text editor written in Rust ๐Ÿ“๐Ÿฆ€
Rust
728
star
11

committia.vim

A Vim plugin for more pleasant editing on commit messages
Vim Script
687
star
12

conflict-marker.vim

Weapon to fight against conflicts in Vim.
Vim Script
442
star
13

hgrep

Grep with human-friendly search results
Rust
413
star
14

wain

WebAssembly implementation from scratch in Safe Rust with zero dependencies
Rust
405
star
15

electron-about-window

'About This App' mini-window for Electron apps
TypeScript
405
star
16

Mstdn

Tiny web-based mastodon client for your desktop
TypeScript
390
star
17

vim-color-spring-night

Low-contrast calm color scheme for Vim
Rust
276
star
18

cargo-husky

Setup Git hooks automatically for cargo projects with ๐Ÿถ
Rust
260
star
19

tui-textarea

Simple yet powerful multi-line text editor widget for ratatui and tui-rs
Rust
249
star
20

dot-github

.github directory generator
Go
248
star
21

8cc.vim

C Compiler written in Vim script
Vim Script
227
star
22

vim-startuptime

A small Go program for better `vim --startuptime` alternative
Go
191
star
23

notes-cli

Small markdown note taking CLI app playing nicely with your favorite editor and other CLI tools
Go
191
star
24

dotfiles

dotfiles symbolic links management CLI
Go
191
star
25

neovim-component

<neovim-editor> WebComponent to embed Neovim to your app with great ease
TypeScript
188
star
26

reply.vim

REPLs play nicely with :terminal on Vim and Neovim
Vim Script
183
star
27

monolith-of-web

A chrome extension to make a single static HTML file of the web page using a WebAssembly port of monolith CLI
TypeScript
178
star
28

github-complete.vim

Vim input completion for GitHub
Vim Script
168
star
29

Trendy

Menubar app to keep you in the loop of GitHub trends :octocat:
TypeScript
166
star
30

git-brws

Command line tool to open repository, file, commit, diff, tag, pull request, blame, issue or project's website in browser for various repository hosting services.
Rust
166
star
31

devdocs.vim

Open devdocs.io from Vim
Vim Script
164
star
32

react-vimjs

Vim in Your Web App
JavaScript
158
star
33

vim-operator-surround

Vim operator mapping to enclose text objects with surrounds like paren, quote and so on.
Vim Script
137
star
34

react-vim-wasm

Vim editor embedded in your React web application
TypeScript
128
star
35

accelerated-jk

A vim plugin to accelerate up-down moving!
Vim Script
125
star
36

action-setup-vim

GitHub Action to setup Vim or Neovim on Linux, macOS and Windows for testing Vim plugins
TypeScript
121
star
37

dogfiles

dog + dotfiles = dogfiles
Vim Script
120
star
38

vim-gfm-syntax

GitHub Flavored Markdown syntax highlight extension for Vim
Vim Script
117
star
39

wandbox-vim

Wandbox plugin for vimmers. http://melpon.org/wandbox/
Vim Script
108
star
40

fixjson

JSON Fixer for Humans using (relaxed) JSON5
TypeScript
99
star
41

tinyjson

Simple JSON parser/generator for Rust
Rust
97
star
42

remark-emoji

Remark markdown transformer to replace :emoji: in text
JavaScript
93
star
43

YourFukurou

Hackable YoruFukurou alternative Twitter client
TypeScript
88
star
44

vim-lsp-ale

Bridge between vim-lsp and ALE
Vim Script
86
star
45

Dachs

Dachs; A Doggy ๐Ÿถ Programming Language
C++
81
star
46

vim-textobj-anyblock

A text object for any of '', "", (), {}, [] and <>.
Vim Script
79
star
47

vim-wasm

WebAssembly filetype support for Vim
Vim Script
77
star
48

world-map-gen

๐Ÿ—บ๏ธRandom world map generator CLI and library for Rust and WebAssembly
Rust
74
star
49

vim-go-impl

A Vim plugin to use `impl` command
Vim Script
72
star
50

rust-doc.vim

Search Rust documents and open with browser from Vim.
Vim Script
71
star
51

ghci-color

colorize ghci output
PowerShell
71
star
52

electron-in-page-search

Module to introduce Electron's native in-page search avoiding pitfalls
TypeScript
66
star
53

translate-markdown

CLI tool to translate Markdown document with Google translate
JavaScript
66
star
54

tweet-app

Desktop Twitter client only for tweeting. Timeline never shows up.
TypeScript
65
star
55

dirname-filename-esm

__dirname and __filename for ES Modules environment
JavaScript
64
star
56

github-clone-all

Clone (~1000) repos matched to query on GitHub using Search API
Go
63
star
57

Tui

Twitter client based on mobile.twitter.com in menu bar
TypeScript
62
star
58

array_view

Wrapper for references to array in C++.
C++
58
star
59

vim-textobj-ruby

Make text objects with various ruby block structures.
Vim Script
56
star
60

changelog-from-release

Simple changelog generator via GitHub releases
Go
54
star
61

fast-json-clone

Clone plain JSON value faster than the fastest
TypeScript
54
star
62

riscv32-cpu-chisel

Learning how to make RISC-V 32bit CPU with Chisel
Scala
53
star
63

vim-llvm

Vim filetype support for LLVM (including official files)
Vim Script
49
star
64

Tilectron

Tiling window browser built on Electron.
JavaScript
45
star
65

nyaovim-markdown-preview

Live Markdown Preview on NyaoVim
HTML
45
star
66

Chromenu

Mobile Chrome in your menubar
TypeScript
43
star
67

Crisp

Lisp dialect implemented with Crystal
Crystal
43
star
68

path-slash

Tiny Rust library to convert a file path from/to slash path
Rust
41
star
69

open-pdf.vim

Convert pdf file to plain text, cache it and open it quickly in vim using pdftotext.
Vim Script
39
star
70

fixred

Fix outdated links in files with redirect URLs
Rust
35
star
71

ghpr-blame.vim

Vim plugin which is like `git-blame`, but for pull requests on GitHub
Vim Script
34
star
72

vim-healthcheck

Polyfill of Neovim's health-check for Vim
Vim Script
33
star
73

nyaovim-mini-browser

Embedded Mini Browser for NyaoVim
HTML
31
star
74

vim-color-splatoon

Vim Splatoon randomized color scheme. Let's play!
Vim Script
29
star
75

unite-redpen.vim

A unite.vim integration of redpen for automatic proof reading
Vim Script
24
star
76

vimwasm-try-plugin

Try Vim plugin on your browser without installing it using vim.wasm!
Go
24
star
77

go-fakeio

Small Go library to fake stdout/stderr/stdin mainly for unit testing
Go
24
star
78

react-component-octicons

Zero-dependency React component for Octicons
TypeScript
24
star
79

vim-fixjson

Vim plugin for fixjson; a JSON fixer for Humans
Vim Script
24
star
80

unite-codic.vim

A unite.vim source for codic-vim.
Vim Script
23
star
81

vim-goyacc

Vim filetype support for goyacc
Vim Script
22
star
82

gofmtrlx

(a bit) relaxed gofmt
Go
22
star
83

try-colorscheme.vim

Try colorscheme on your Vim without installation
Vim Script
21
star
84

node-github-trend

node.js library for scraping GitHub trending repositories.
TypeScript
20
star
85

node-github-emoji

Node.js library for GitHub Emoji :octocat: with TypeScript support
TypeScript
20
star
86

vim-syntax-christmas-tree

Vim filetype plugin for X'mas
Vim Script
20
star
87

FrozenString

C++ immutable string library in C++11 constexpr and type-level
C++
18
star
88

nyaovim-tree-view

Tree-view sidebar for NyaoVim
JavaScript
18
star
89

vim-github-actions

(Outdated) Vim syntax/indent support for GitHub Actions *.workflow files
Vim Script
18
star
90

zsh-bundle-exec

No longer need to type in 'bundle exec'.
Shell
17
star
91

rhysd

README.md for my profile page
Ruby
17
star
92

toy-riscv-backend

Toy RISC-V LLVM backend
C++
16
star
93

locerr

โŒ locerr (locational error): Library for nice-looking errors in source code
Go
16
star
94

unite-ruby-require.vim

A unite.vim source for searching gems to require
Vim Script
15
star
95

vim-textobj-conflict

Vim text object plugin to select conflicts
Vim Script
15
star
96

electron-open-url

Open URL with Electron window from command line or Node.js program
JavaScript
15
star
97

vim-notes-cli

Vim plugin for notes-cli
Vim Script
15
star
98

marked-sanitizer-github

A sanitizer for marked.js which sanitizes HTML elements in markdown with the same manner as GitHub
TypeScript
14
star
99

api-dts

d.ts generator from JSON API response
Go
13
star
100

Irasutoyer

Desktop app for Irasutoya lovers
TypeScript
13
star