Skip to content
Merged
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
16 changes: 0 additions & 16 deletions .github/workflows/stale.yml

This file was deleted.

21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@ BUILDTIME=$(shell date +"%Y-%m-%d-%T")
BRANCH=$(shell git rev-parse --abbrev-ref HEAD | tr -d '\040\011\012\015\n')
REVISION=$(shell git rev-parse HEAD)

# Pin VERSION to the most recent nightly tag so `make build` (and Docker, etc.)
# self-reports the current in-progress release line, e.g. `1.1.7-next` while
# v1.1.7 is being prepared. goreleaser still injects its own GORELEASER_CURRENT_TAG
# for actual release artifacts; this only kicks in for non-goreleaser builds.
#
# Resolution order:
# 1. nearest reachable nightly tag matching v*-next
# 2. nearest reachable stable tag (rare: only between a release and the next nightly cron)
# 3. empty -> falls back to the constant.Version source default
GIT_DESCRIBE_VERSION := $(shell git describe --tags --abbrev=0 --match 'v*-next' 2>/dev/null \
|| git describe --tags --abbrev=0 --match 'v*' --exclude='*-*' 2>/dev/null)
VERSION := $(patsubst v%,%,$(GIT_DESCRIBE_VERSION))

ifeq ($(VERSION),)
VERSION_LDFLAG :=
else
VERSION_LDFLAG := -X $(PACKAGE).Version=$(VERSION)
endif


PACKAGE_LIST := go list ./...
FILES := $(shell find . -name "*.go" -type f)
Expand All @@ -24,7 +43,7 @@ endif

# -w -s 参数的解释:You will get the smallest binaries if you compile with -ldflags '-w -s'. The -w turns off DWARF debugging information
# for more information, please refer to https://stackoverflow.com/questions/22267189/what-does-the-w-flag-mean-when-passed-in-via-the-ldflags-option-to-the-go-comman
GOBUILD=CGO_ENABLED=0 go build -tags ${BUILD_TAG_FOR_NODE_EXPORTER} -trimpath -ldflags="-w -s -X ${PACKAGE}.GitBranch=${BRANCH} -X ${PACKAGE}.GitRevision=${REVISION} -X ${PACKAGE}.BuildTime=${BUILDTIME}"
GOBUILD=CGO_ENABLED=0 go build -tags ${BUILD_TAG_FOR_NODE_EXPORTER} -trimpath -ldflags="-w -s ${VERSION_LDFLAG} -X ${PACKAGE}.GitBranch=${BRANCH} -X ${PACKAGE}.GitRevision=${REVISION} -X ${PACKAGE}.BuildTime=${BUILDTIME}"


tools:
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
github.com/xtls/xray-core v1.260206.0
go.uber.org/atomic v1.11.0
go.uber.org/zap v1.27.1
golang.org/x/mod v0.34.0
golang.org/x/sync v0.20.0
golang.org/x/time v0.15.0
google.golang.org/grpc v1.79.2
Expand Down Expand Up @@ -96,7 +97,6 @@ require (
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/exp v0.0.0-20260312153236-7ab1446f8b90 // indirect
golang.org/x/mod v0.34.0 // indirect
golang.org/x/net v0.52.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.35.0 // indirect
Expand Down
7 changes: 7 additions & 0 deletions internal/cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ import (
var cliLogger = log.MustNewLogger("info").Sugar().Named("cli")

func startAction(ctx *cli.Context) error {
// No subcommand and no config source given -> the user almost certainly
// just typed `ehco` to see what it does. Show help instead of fataling
// with "invalid listen".
if ConfigPath == "" && LocalAddr == "" {
return cli.ShowAppHelp(ctx)
}

cfg, err := InitConfigAndComponents()
if err != nil {
cliLogger.Fatalf("InitConfigAndComponents meet err=%s", err.Error())
Expand Down
151 changes: 131 additions & 20 deletions internal/cli/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,19 @@ import (

"github.com/Ehco1996/ehco/internal/constant"
cli "github.com/urfave/cli/v2"
"golang.org/x/mod/semver"
)

const (
githubLatestReleaseAPI = "https://api.github.com/repos/Ehco1996/ehco/releases/latest"
githubReleasesAPI = "https://api.github.com/repos/Ehco1996/ehco/releases?per_page=30"
systemdServiceName = "ehco"

channelAuto = "auto"
channelStable = "stable"
channelNightly = "nightly"

nightlyTagSuffix = "-next"
)

type ghAsset struct {
Expand All @@ -28,8 +36,11 @@ type ghAsset struct {
}

type ghRelease struct {
TagName string `json:"tag_name"`
Assets []ghAsset `json:"assets"`
TagName string `json:"tag_name"`
Prerelease bool `json:"prerelease"`
Draft bool `json:"draft"`
PublishedAt time.Time `json:"published_at"`
Assets []ghAsset `json:"assets"`
}

var UpdateCMD = &cli.Command{
Expand All @@ -38,12 +49,17 @@ var UpdateCMD = &cli.Command{
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Usage: "force update even if already at the latest version",
Usage: "force update even if already at the latest version, or to allow downgrade / channel switch",
},
&cli.BoolFlag{
Name: "no-restart",
Usage: "skip systemctl restart after replacing the binary",
},
&cli.StringFlag{
Name: "channel",
Value: channelAuto,
Usage: "release channel to track: auto (match current build), stable, or nightly",
},
},
Action: runUpdate,
}
Expand All @@ -52,15 +68,28 @@ func runUpdate(c *cli.Context) error {
ctx, cancel := context.WithTimeout(c.Context, 5*time.Minute)
defer cancel()

rel, err := fetchLatestRelease(ctx)
channel, err := resolveChannel(c.String("channel"), constant.Version)
if err != nil {
return err
}

rel, err := fetchTargetRelease(ctx, channel)
if err != nil {
return fmt.Errorf("fetch latest release: %w", err)
return fmt.Errorf("fetch %s release: %w", channel, err)
}
latest := strings.TrimPrefix(rel.TagName, "v")
cliLogger.Infof("current version=%s latest version=%s", constant.Version, latest)
if !c.Bool("force") && latest == constant.Version {
cliLogger.Info("already up to date, nothing to do")
return nil
cliLogger.Infof("channel=%s current version=%s latest version=%s", channel, constant.Version, latest)

force := c.Bool("force")
if !force {
if latest == constant.Version {
cliLogger.Info("already up to date, nothing to do")
return nil
}
if cmp := compareVersions(latest, constant.Version); cmp < 0 {
return fmt.Errorf("refusing to downgrade from %s to %s; rerun with --force to override",
constant.Version, latest)
}
}

asset, err := pickReleaseAsset(rel.Assets)
Expand Down Expand Up @@ -98,29 +127,111 @@ func runUpdate(c *cli.Context) error {
return restartSystemdService()
}

func fetchLatestRelease(ctx context.Context) (*ghRelease, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, githubLatestReleaseAPI, nil)
if err != nil {
func resolveChannel(flagVal, currentVersion string) (string, error) {
switch flagVal {
case channelStable, channelNightly:
return flagVal, nil
case channelAuto, "":
if isNightlyVersion(currentVersion) {
return channelNightly, nil
}
return channelStable, nil
default:
return "", fmt.Errorf("invalid --channel %q (want one of auto, stable, nightly)", flagVal)
}
}

func isNightlyVersion(v string) bool {
// goreleaser injects bare versions like "1.1.7-next" or "1.1.6"; both
// stable and nightly builds skip the leading "v". A nightly is anything
// carrying a prerelease suffix (currently "-next"), but we use a generic
// "contains a dash" check so future suffixes (e.g. "-rc.1") still work.
return strings.Contains(v, "-")
}

func fetchTargetRelease(ctx context.Context, channel string) (*ghRelease, error) {
switch channel {
case channelStable:
return fetchLatestStableRelease(ctx)
case channelNightly:
return fetchLatestNightlyRelease(ctx)
default:
return nil, fmt.Errorf("unknown channel %q", channel)
}
}

func fetchLatestStableRelease(ctx context.Context) (*ghRelease, error) {
var rel ghRelease
if err := getJSON(ctx, githubLatestReleaseAPI, &rel); err != nil {
return nil, err
}
if rel.TagName == "" {
return nil, fmt.Errorf("empty tag name in github response")
}
return &rel, nil
}

func fetchLatestNightlyRelease(ctx context.Context) (*ghRelease, error) {
// /releases/latest excludes prereleases by design, so list recent
// releases and pick the freshest nightly ourselves.
var all []ghRelease
if err := getJSON(ctx, githubReleasesAPI, &all); err != nil {
return nil, err
}
var best *ghRelease
for i := range all {
r := &all[i]
if r.Draft || !r.Prerelease {
continue
}
if !strings.HasSuffix(r.TagName, nightlyTagSuffix) {
continue
}
if best == nil || r.PublishedAt.After(best.PublishedAt) {
best = r
}
}
if best == nil {
return nil, fmt.Errorf("no nightly release found (looking for tags ending in %q)", nightlyTagSuffix)
}
return best, nil
}

func getJSON(ctx context.Context, url string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return nil, fmt.Errorf("github api %s: %s", resp.Status, strings.TrimSpace(string(body)))
return fmt.Errorf("github api %s: %s", resp.Status, strings.TrimSpace(string(body)))
}
var rel ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
return nil, err
return json.NewDecoder(resp.Body).Decode(out)
}

// compareVersions returns -1/0/1 like semver.Compare. Inputs may have or
// omit the leading "v"; unparseable inputs fall back to string compare so a
// malformed version never crashes the updater (it just disables the
// downgrade guard for that case, which --force handles).
func compareVersions(a, b string) int {
va, vb := ensureV(a), ensureV(b)
if semver.IsValid(va) && semver.IsValid(vb) {
return semver.Compare(va, vb)
}
if rel.TagName == "" {
return nil, fmt.Errorf("empty tag name in github response")
return strings.Compare(a, b)
}

func ensureV(s string) string {
if strings.HasPrefix(s, "v") {
return s
}
return &rel, nil
return "v" + s
}

func pickReleaseAsset(assets []ghAsset) (*ghAsset, error) {
Expand Down
6 changes: 5 additions & 1 deletion internal/constant/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import "time"
type RelayType string

var (
Version = "1.1.6"
// Version is overridden at link time by Makefile / goreleaser ldflags.
// The literal here is a fallback for raw `go build` invocations on master,
// kept slightly newer than the most recent stable tag so the update
// command's nightly auto-detection and downgrade guard behave sanely.
Version = "1.1.7-next"
GitBranch string
GitRevision string
BuildTime string
Expand Down
Loading