fix: keep self-updates on the fork release source
Default stable and nightly updates to loveuer/picoclaw without fallback. Add explicit repository selection and a read-only release check. Validate targets and checksums while preserving installed binary names. Cover source routing and replacement failures with isolated tests.
This commit is contained in:
1 parent
c1ce9fda5f
commit
9fe249f639
4 files changed
+564
-94
No files matched your search
@@ -59,6 +59,32 @@ make build GOOS=linux GOARCH=amd64 \
|
||||
# 产物:build/picoclaw-beta-linux-amd64
|
||||
```
|
||||
|
||||
## 自更新
|
||||
|
||||
`update` 默认从本 fork 的 `loveuer/picoclaw` GitHub Releases 获取更新,不会自动回退到上游。
|
||||
|
||||
```bash
|
||||
# 检查稳定版发布产物和校验信息,不下载二进制、不替换文件
|
||||
picoclaw update --check
|
||||
|
||||
# 应用稳定版;也可将命令名换成实际安装的 picoclaw-beta
|
||||
picoclaw update
|
||||
|
||||
# 检查 / 应用本 fork 的 nightly Release
|
||||
picoclaw update --nightly --check
|
||||
picoclaw update --nightly
|
||||
|
||||
# 显式选择其他 fork 或固定版本
|
||||
picoclaw update --repo owner/repo --check
|
||||
picoclaw update --url https://github.com/loveuer/picoclaw/releases/tag/v1.0.0 --check
|
||||
```
|
||||
|
||||
`--url` 支持 GitHub 仓库、Release 页面或 Releases API 地址,与 `--repo`、`--nightly` 互斥。不会把无效地址当成默认源。`--check` 检查产物可用性,不比较版本新旧;可配合 `--platform`、`--arch` 查询其他平台,实际自更新仅允许当前系统与架构。
|
||||
|
||||
发布更新时需要先在本 fork 创建稳定版 Release 或名为 `nightly` 的 Release,并上传对应平台的 `.tar.gz`、`.tgz`、`.tar` 或 `.zip` 包。例如 `picoclaw_Linux_x86_64.tar.gz`,内部包含 `picoclaw` 或 `picoclaw-beta`(Windows 对应 `.exe`)。需要 GitHub 提供的 SHA256 digest,或包含产物文件名与 SHA256 的 checksums 文件。单独的二进制下载链接目前不支持。
|
||||
|
||||
更新会校验下载文件并替换当前可执行文件,保留实际安装名称,需要对安装目录有写权限。沿用现有回滚机制保留旧 binary 为 `.old`;不会修改用户配置、自动重启服务或覆盖工作区 Skill。更新后按部署方式重启;需要刷新内置 Skill 时,再使用 `skills install-builtin`。
|
||||
|
||||
## 配置与运行
|
||||
|
||||
### 1. 初始化
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestForkReleaseURLs(t *testing.T) {
|
||||
require.Equal(t, "https://api.github.com/repos/loveuer/picoclaw/releases/latest", GetProdReleaseAPIURL())
|
||||
require.Equal(t, "https://api.github.com/repos/loveuer/picoclaw/releases/tags/nightly", GetNightlyReleaseAPIURL())
|
||||
tests := []struct{ input, want string }{
|
||||
{"", GetProdReleaseAPIURL()},
|
||||
{"https://github.com/another/fork", "https://api.github.com/repos/another/fork/releases/latest"},
|
||||
{
|
||||
"https://github.com/another/fork/releases/latest",
|
||||
"https://api.github.com/repos/another/fork/releases/latest",
|
||||
},
|
||||
{
|
||||
"https://github.com/another/fork/releases/tag/v1.2.3",
|
||||
"https://api.github.com/repos/another/fork/releases/tags/v1.2.3",
|
||||
},
|
||||
{
|
||||
"https://github.com/another/fork/releases/tag/beta%2Fv1",
|
||||
"https://api.github.com/repos/another/fork/releases/tags/beta%2Fv1",
|
||||
},
|
||||
{
|
||||
"https://api.github.com/repos/another/fork/releases/tags/nightly",
|
||||
"https://api.github.com/repos/another/fork/releases/tags/nightly",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.input, func(t *testing.T) {
|
||||
got, err := buildReleaseAPIURL(test.input)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
for _, input := range []string{"not-a-url", "https://api.github.com.evil.example/invalid", "https://example.com/not-a-release", "https://github.com/another", "https://github.com/another/fork/issues", "file:///repos/a/b/releases/latest", "https://github.com/a/b?x=1"} {
|
||||
_, err := buildReleaseAPIURL(input)
|
||||
require.Error(t, err, input)
|
||||
}
|
||||
}
|
||||
|
||||
type releaseRoundTripper func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f releaseRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func routeReleaseRequests(t *testing.T, server *httptest.Server) {
|
||||
t.Helper()
|
||||
endpoint, err := url.Parse(server.URL)
|
||||
require.NoError(t, err)
|
||||
transport := server.Client().Transport
|
||||
withTestHTTPClient(t, &http.Client{Transport: releaseRoundTripper(func(r *http.Request) (*http.Response, error) {
|
||||
clone := r.Clone(r.Context())
|
||||
clone.URL.Scheme = endpoint.Scheme
|
||||
clone.URL.Host = endpoint.Host
|
||||
return transport.RoundTrip(clone)
|
||||
})})
|
||||
}
|
||||
|
||||
func TestUpdateCommandSelectsSourceWithoutDownloading(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
path string
|
||||
}{
|
||||
{"default fork", nil, "/repos/loveuer/picoclaw/releases/latest"},
|
||||
{"nightly", []string{"--nightly"}, "/repos/loveuer/picoclaw/releases/tags/nightly"},
|
||||
{"other fork", []string{"--repo", "another/fork", "--nightly"}, "/repos/another/fork/releases/tags/nightly"},
|
||||
{
|
||||
"pinned release",
|
||||
[]string{"--url", "https://github.com/another/fork/releases/tag/v1.2.3"},
|
||||
"/repos/another/fork/releases/tags/v1.2.3",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var requests []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.URL.Path)
|
||||
if r.URL.Path != test.path {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
writeReleasePayload(
|
||||
w,
|
||||
testReleasePayload{
|
||||
TagName: "v1.2.3",
|
||||
Assets: []testReleaseAsset{
|
||||
{
|
||||
Name: "picoclaw_Linux_x86_64.tar.gz",
|
||||
BrowserDownloadURL: "https://example.com/picoclaw_Linux_x86_64.tar.gz",
|
||||
Digest: "sha256:" + strings.Repeat("a", 64),
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}))
|
||||
defer server.Close()
|
||||
routeReleaseRequests(t, server)
|
||||
command := NewUpdateCommand("picoclaw")
|
||||
var out bytes.Buffer
|
||||
command.SetOut(&out)
|
||||
command.SetErr(&out)
|
||||
command.SetArgs(append(test.args, "--check", "--platform", "linux", "--arch", "amd64"))
|
||||
require.NoError(t, command.Execute())
|
||||
require.Equal(t, []string{test.path}, requests)
|
||||
require.Contains(t, out.String(), "no files changed")
|
||||
require.Contains(t, out.String(), "SHA256: "+strings.Repeat("a", 64))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCommandRejectsInvalidSourceBeforeNetwork(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("unexpected request:", r.URL)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer server.Close()
|
||||
routeReleaseRequests(t, server)
|
||||
for _, args := range [][]string{
|
||||
{"--check", "--repo", "../bad"},
|
||||
{"--check", "--url", "https://example.com/wrong"},
|
||||
{"--check", "--url", "https://github.com/a/b", "--repo", "a/b"},
|
||||
{"--check", "--url", "https://github.com/a/b", "--nightly"},
|
||||
{"--check", "unexpected"},
|
||||
} {
|
||||
command := NewUpdateCommand("picoclaw")
|
||||
command.SetOut(io.Discard)
|
||||
command.SetErr(io.Discard)
|
||||
command.SetArgs(args)
|
||||
require.Error(t, command.Execute(), args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingForkReleaseDoesNotFallback(t *testing.T) {
|
||||
var requests []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.URL.Path)
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
routeReleaseRequests(t, server)
|
||||
_, _, err := findAssetInfo("", "linux", "amd64")
|
||||
require.ErrorContains(t, err, "release not found")
|
||||
require.ErrorContains(t, err, "loveuer/picoclaw")
|
||||
require.Equal(t, []string{"/repos/loveuer/picoclaw/releases/latest"}, requests)
|
||||
}
|
||||
|
||||
func TestAssetSelectionRequiresExactArchitectureAndArchive(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assets := make([]testReleaseAsset, 0, 5)
|
||||
for i, name := range []string{"picoclaw_linux_arm64.tar.gz", "picoclaw_linux_amd64.tar.gz", "picoclaw_linux_amd64.tar.gz.sha256", "picoclaw_linux_armv7.tar.gz", "picoclaw_linux_386.zip"} {
|
||||
assets = append(
|
||||
assets,
|
||||
testReleaseAsset{
|
||||
Name: name,
|
||||
BrowserDownloadURL: "https://example.com/" + name,
|
||||
Digest: "sha256:" + strings.Repeat(fmt.Sprint(i+1), 64),
|
||||
},
|
||||
)
|
||||
}
|
||||
writeReleasePayload(w, testReleasePayload{Assets: assets})
|
||||
}))
|
||||
defer server.Close()
|
||||
for _, test := range []struct{ arch, filename string }{
|
||||
{"arm", "picoclaw_linux_armv7.tar.gz"},
|
||||
{"amd64", "picoclaw_linux_amd64.tar.gz"},
|
||||
{"386", "picoclaw_linux_386.zip"},
|
||||
} {
|
||||
asset, _, err := findAssetInfo(server.URL+testReleaseAPIPath, "linux", test.arch)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://example.com/"+test.filename, asset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelfUpdateRejectsDifferentTarget(t *testing.T) {
|
||||
other := "windows"
|
||||
if runtime.GOOS == other {
|
||||
other = "linux"
|
||||
}
|
||||
require.ErrorContains(t, UpdateSelfFromRelease("", other, runtime.GOARCH, "picoclaw"), "cannot self-update")
|
||||
require.ErrorContains(
|
||||
t,
|
||||
UpdateSelfFromRelease("", runtime.GOOS, "not-the-current-arch", "picoclaw"),
|
||||
"cannot self-update",
|
||||
)
|
||||
}
|
||||
|
||||
func TestFindBinaryPrefersCanonicalAndAcceptsBeta(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "picoclaw-beta"), []byte("beta"), 0o755))
|
||||
path, err := findBinaryInDir(dir, "picoclaw")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "picoclaw-beta", filepath.Base(path))
|
||||
nested := filepath.Join(dir, "nested")
|
||||
require.NoError(t, os.Mkdir(nested, 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(nested, "picoclaw"), []byte("canonical"), 0o755))
|
||||
path, err = findBinaryInDir(dir, "picoclaw")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, filepath.Join(nested, "picoclaw"), path)
|
||||
}
|
||||
|
||||
// Only the isolated copy of this test executable can enter the replacement path.
|
||||
func TestSelfUpdateChild(t *testing.T) {
|
||||
if os.Getenv("PICOCLAW_UPDATER_CHILD") != "1" {
|
||||
return
|
||||
}
|
||||
if err := UpdateSelfFromRelease(
|
||||
os.Getenv("PICOCLAW_UPDATER_TEST_RELEASE"),
|
||||
runtime.GOOS,
|
||||
runtime.GOARCH,
|
||||
"picoclaw",
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelfUpdatePreservesInstalledNameAndChecksChecksum(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a running executable cannot be replaced using the Unix test-copy approach")
|
||||
}
|
||||
for _, valid := range []bool{true, false} {
|
||||
t.Run(fmt.Sprint(valid), func(t *testing.T) {
|
||||
archive := buildTestTarGz(t, map[string]string{"picoclaw": "new fork binary payload"})
|
||||
sum := sha256.Sum256(archive)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
if !valid {
|
||||
digest = strings.Repeat("0", 64)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/asset.tar.gz" {
|
||||
_, _ = w.Write(archive)
|
||||
return
|
||||
}
|
||||
writeReleasePayload(
|
||||
w,
|
||||
testReleasePayload{
|
||||
Assets: []testReleaseAsset{
|
||||
{
|
||||
Name: "picoclaw_" + runtime.GOOS + "_" + runtime.GOARCH + ".tar.gz",
|
||||
BrowserDownloadURL: "http://" + r.Host + "/asset.tar.gz",
|
||||
Digest: "sha256:" + digest,
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
}))
|
||||
defer server.Close()
|
||||
executable, err := os.Executable()
|
||||
require.NoError(t, err)
|
||||
original, err := os.ReadFile(executable)
|
||||
require.NoError(t, err)
|
||||
target := filepath.Join(t.TempDir(), "picoclaw-beta")
|
||||
require.NoError(t, os.WriteFile(target, original, 0o755))
|
||||
command := exec.Command(target, "-test.run=^TestSelfUpdateChild$")
|
||||
command.Env = append(
|
||||
os.Environ(),
|
||||
"PICOCLAW_UPDATER_CHILD=1",
|
||||
"PICOCLAW_UPDATER_TEST_RELEASE="+server.URL+testReleaseAPIPath,
|
||||
)
|
||||
output, err := command.CombinedOutput()
|
||||
content, readErr := os.ReadFile(target)
|
||||
require.NoError(t, readErr)
|
||||
if valid {
|
||||
require.NoError(t, err, string(output))
|
||||
require.Equal(t, "new fork binary payload", string(content))
|
||||
_, err = os.Stat(filepath.Join(filepath.Dir(target), "picoclaw"))
|
||||
require.True(t, os.IsNotExist(err))
|
||||
} else {
|
||||
require.Error(t, err)
|
||||
require.Contains(t, string(output), "checksum mismatch")
|
||||
require.Equal(t, original, content)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRejectsMalformedDigestAndFailedChecksumResponse(t *testing.T) {
|
||||
for _, failedManifest := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(failedManifest), func(t *testing.T) {
|
||||
var server *httptest.Server
|
||||
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/checksums.txt" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = fmt.Fprint(w, strings.Repeat("a", 64)+" picoclaw_linux_amd64.tar.gz")
|
||||
return
|
||||
}
|
||||
assets := []testReleaseAsset{
|
||||
{
|
||||
Name: "picoclaw_linux_amd64.tar.gz",
|
||||
BrowserDownloadURL: server.URL + "/picoclaw_linux_amd64.tar.gz",
|
||||
Digest: "sha256:not-a-valid-digest",
|
||||
},
|
||||
}
|
||||
if failedManifest {
|
||||
assets = append(
|
||||
assets,
|
||||
testReleaseAsset{Name: "checksums.txt", BrowserDownloadURL: server.URL + "/checksums.txt"},
|
||||
)
|
||||
}
|
||||
writeReleasePayload(w, testReleasePayload{Assets: assets})
|
||||
}))
|
||||
defer server.Close()
|
||||
_, _, err := findAssetInfo(server.URL+testReleaseAPIPath, "linux", "amd64")
|
||||
require.ErrorContains(t, err, "no checksum found")
|
||||
})
|
||||
}
|
||||
}
|
||||
+212
-91
@@ -18,6 +18,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/minio/selfupdate"
|
||||
"github.com/spf13/cobra"
|
||||
@@ -42,11 +43,12 @@ func getWithRetry(rawURL string) (*http.Response, error) {
|
||||
return utils.DoRequestWithRetry(httpClient, req)
|
||||
}
|
||||
|
||||
// DownloadAndExtractRelease downloads a release archive (or uses a direct
|
||||
// asset URL) and extracts it to a temporary directory. It returns the
|
||||
// DownloadAndExtractRelease resolves a GitHub release and downloads its verified
|
||||
// archive into a temporary directory. It returns the
|
||||
// extraction directory on success. If releaseURL is empty, the latest
|
||||
// release of the current project is used. platform/arch can be used to
|
||||
// select the correct asset (e.g. "linux", "amd64").
|
||||
// Direct archive URLs are rejected because release checksum metadata is required.
|
||||
func DownloadAndExtractRelease(releaseURL, platform, arch string) (string, error) {
|
||||
assetURL, checksum, err := findAssetInfo(releaseURL, platform, arch)
|
||||
if err != nil {
|
||||
@@ -142,6 +144,15 @@ func UpdateSelfFromRelease(releaseURL, platform, arch, programName string) error
|
||||
if arch == "" {
|
||||
arch = runtime.GOARCH
|
||||
}
|
||||
if !strings.EqualFold(platform, runtime.GOOS) || !sameArchitecture(arch, runtime.GOARCH) {
|
||||
return fmt.Errorf(
|
||||
"cannot self-update %s/%s with a %s/%s binary; use --check to inspect another target",
|
||||
runtime.GOOS,
|
||||
runtime.GOARCH,
|
||||
platform,
|
||||
arch,
|
||||
)
|
||||
}
|
||||
|
||||
dir, err := DownloadAndExtractRelease(releaseURL, platform, arch)
|
||||
if err != nil {
|
||||
@@ -186,42 +197,65 @@ func UpdateSelf(programName string) error {
|
||||
return UpdateSelfFromRelease("", runtime.GOOS, runtime.GOARCH, programName)
|
||||
}
|
||||
|
||||
// GetReleaseAPIURL returns the GitHub Releases API URL for the given repo owner.
|
||||
// Example: owner="sky5454" -> https://api.github.com/repos/sky5454/picoclaw/releases/latest
|
||||
// DefaultRepository is the release source for this fork. Never fall back to upstream.
|
||||
const DefaultRepository = "loveuer/picoclaw"
|
||||
|
||||
// GetReleaseAPIURL returns the latest stable release API URL for another picoclaw fork.
|
||||
func GetReleaseAPIURL(owner string) string {
|
||||
return fmt.Sprintf("https://api.github.com/repos/%s/picoclaw/releases/latest", owner)
|
||||
return releaseAPIURL(owner+"/picoclaw", false)
|
||||
}
|
||||
|
||||
// GetProdReleaseAPIURL returns the production release API URL (upstream).
|
||||
// GetProdReleaseAPIURL returns this fork's latest stable release API URL.
|
||||
func GetProdReleaseAPIURL() string {
|
||||
return GetReleaseAPIURL("sipeed")
|
||||
return releaseAPIURL(DefaultRepository, false)
|
||||
}
|
||||
|
||||
// GetReleaseTagAPIURL returns the GitHub Releases API URL for a specific tag.
|
||||
// Example: owner="sipeed", tag="nightly" -> https://api.github.com/repos/sipeed/picoclaw/releases/tags/nightly
|
||||
// GetReleaseTagAPIURL returns the release API URL for a tag on another picoclaw fork.
|
||||
func GetReleaseTagAPIURL(owner, tag string) string {
|
||||
return fmt.Sprintf("https://api.github.com/repos/%s/picoclaw/releases/tags/%s", owner, tag)
|
||||
return "https://api.github.com/repos/" + owner + "/picoclaw/releases/tags/" + url.PathEscape(tag)
|
||||
}
|
||||
|
||||
// GetNightlyReleaseAPIURL returns the nightly release API URL for the production repo.
|
||||
// GetNightlyReleaseAPIURL returns this fork's nightly release API URL.
|
||||
func GetNightlyReleaseAPIURL() string {
|
||||
return GetReleaseTagAPIURL("sipeed", "nightly")
|
||||
return releaseAPIURL(DefaultRepository, true)
|
||||
}
|
||||
|
||||
// findAssetURL resolves the appropriate asset URL for the given release
|
||||
// selector. It accepts direct archive URLs as well as GitHub release URLs
|
||||
// or empty (latest release for the project).
|
||||
func releaseAPIURL(repository string, nightly bool) string {
|
||||
suffix := "/latest"
|
||||
if nightly {
|
||||
suffix = "/tags/nightly"
|
||||
}
|
||||
return "https://api.github.com/repos/" + repository + "/releases" + suffix
|
||||
}
|
||||
|
||||
func validRepository(repository string) bool {
|
||||
parts := strings.Split(repository, "/")
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
for _, part := range parts {
|
||||
if part == "." || part == ".." || !regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`).MatchString(part) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// findAssetInfo resolves the appropriate asset URL for the given release
|
||||
// selector. An empty selector uses this fork; direct archives are rejected
|
||||
// because release checksum metadata is required.
|
||||
func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
// returns (assetURL, sha256ChecksumHex, error)
|
||||
if looksLikeDirectAssetURL(releaseURL) {
|
||||
return "", "", fmt.Errorf("no checksum found for asset %s", releaseURL)
|
||||
return "", "", fmt.Errorf(
|
||||
"direct archive URLs are unsupported: use the release page or API URL to obtain a verified checksum for %s",
|
||||
releaseURL,
|
||||
)
|
||||
}
|
||||
|
||||
apiURL := buildReleaseAPIURL(releaseURL)
|
||||
if apiURL == "" {
|
||||
// If caller provided an empty releaseURL, default to the
|
||||
// production latest release API URL (stable release).
|
||||
apiURL = GetProdReleaseAPIURL()
|
||||
apiURL, err := buildReleaseAPIURL(releaseURL)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
resp, err := getWithRetry(apiURL)
|
||||
@@ -229,8 +263,14 @@ func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
return "", "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
return "", "", fmt.Errorf(
|
||||
"release not found at %s: publish the selected release and matching archives first; no alternate source was queried",
|
||||
apiURL,
|
||||
)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", "", fmt.Errorf("failed to query releases: status %d", resp.StatusCode)
|
||||
return "", "", fmt.Errorf("failed to query releases at %s: status %d", apiURL, resp.StatusCode)
|
||||
}
|
||||
|
||||
var data struct {
|
||||
@@ -261,7 +301,10 @@ func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
var platformIdx []int
|
||||
for i, a := range data.Assets {
|
||||
n := strings.ToLower(a.Name)
|
||||
if platform == "" || strings.Contains(n, platformLower) {
|
||||
if !(isZip(n) || isTarGz(n) || isTar(n)) {
|
||||
continue
|
||||
}
|
||||
if platform == "" || assetHasToken(n, platformLower) {
|
||||
platformIdx = append(platformIdx, i)
|
||||
}
|
||||
}
|
||||
@@ -278,7 +321,7 @@ func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
for _, i := range idxs {
|
||||
n := strings.ToLower(data.Assets[i].Name)
|
||||
for _, ali := range aliases {
|
||||
if strings.Contains(n, ali) {
|
||||
if assetHasToken(n, ali) {
|
||||
archIdx = append(archIdx, i)
|
||||
break
|
||||
}
|
||||
@@ -331,8 +374,7 @@ func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
if d := strings.TrimSpace(data.Assets[idx].Digest); d != "" {
|
||||
dLower := strings.ToLower(d)
|
||||
if strings.HasPrefix(dLower, "sha256:") {
|
||||
hexpart := strings.TrimPrefix(dLower, "sha256:")
|
||||
return url, hexpart, nil
|
||||
dLower = strings.TrimPrefix(dLower, "sha256:")
|
||||
}
|
||||
// If digest already looks like a 64-hex, return it
|
||||
if ok, _ := regexp.MatchString("(?i)^[a-f0-9]{64}$", dLower); ok {
|
||||
@@ -353,7 +395,7 @@ func findAssetInfo(releaseURL, platform, arch string) (string, string, error) {
|
||||
}
|
||||
bs, err := io.ReadAll(resp2.Body)
|
||||
_ = resp2.Body.Close()
|
||||
if err != nil {
|
||||
if err != nil || resp2.StatusCode != http.StatusOK {
|
||||
continue
|
||||
}
|
||||
if h, ok := findHashInChecksumContent(bs, url); ok {
|
||||
@@ -386,33 +428,72 @@ func looksLikeDirectAssetURL(u string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func buildReleaseAPIURL(releaseURL string) string {
|
||||
func buildReleaseAPIURL(releaseURL string) (string, error) {
|
||||
if releaseURL == "" {
|
||||
return ""
|
||||
return GetProdReleaseAPIURL(), nil
|
||||
}
|
||||
if strings.Contains(releaseURL, "api.github.com") {
|
||||
return releaseURL
|
||||
invalid := func() (string, error) {
|
||||
return "", fmt.Errorf(
|
||||
"invalid release URL %q: use a GitHub repository, release page, or Releases API URL",
|
||||
releaseURL,
|
||||
)
|
||||
}
|
||||
u, err := url.Parse(releaseURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.User != nil || u.RawQuery != "" ||
|
||||
u.Fragment != "" {
|
||||
return invalid()
|
||||
}
|
||||
if u.Host != "github.com" {
|
||||
return ""
|
||||
parts := strings.Split(strings.Trim(u.EscapedPath(), "/"), "/")
|
||||
if u.Host == "github.com" {
|
||||
if len(parts) < 2 || !validRepository(parts[0]+"/"+parts[1]) {
|
||||
return invalid()
|
||||
}
|
||||
repository := parts[0] + "/" + parts[1]
|
||||
switch {
|
||||
case len(parts) == 2,
|
||||
len(parts) == 3 && parts[2] == "releases",
|
||||
len(parts) == 4 && parts[2] == "releases" && parts[3] == "latest":
|
||||
return releaseAPIURL(repository, false), nil
|
||||
case len(parts) == 5 && parts[2] == "releases" && parts[3] == "tag" && parts[4] != "":
|
||||
return "https://api.github.com/repos/" + repository + "/releases/tags/" + parts[4], nil
|
||||
default:
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
// Explicit API endpoints also support compatible proxies and local test servers.
|
||||
if (len(parts) == 5 && parts[4] == "latest" || len(parts) == 6 && parts[4] == "tags" && parts[5] != "") &&
|
||||
parts[0] == "repos" &&
|
||||
parts[3] == "releases" &&
|
||||
validRepository(parts[1]+"/"+parts[2]) {
|
||||
return u.String(), nil
|
||||
}
|
||||
owner := parts[0]
|
||||
repo := parts[1]
|
||||
// if tag specified
|
||||
if len(parts) >= 5 && parts[2] == "releases" && parts[3] == "tag" {
|
||||
tag := parts[4]
|
||||
return fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/tags/%s", owner, repo, tag)
|
||||
return invalid()
|
||||
}
|
||||
|
||||
// Match complete name components, so arm cannot accidentally select arm64,
|
||||
// or 386 (x86) select x86_64. Normalize the compound x86_64 spelling first.
|
||||
func assetHasToken(name, token string) bool {
|
||||
normalize := func(value string) string {
|
||||
return strings.NewReplacer("x86_64", "amd64", "x86-64", "amd64").Replace(strings.ToLower(value))
|
||||
}
|
||||
// default to latest
|
||||
return fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
|
||||
token = normalize(token)
|
||||
for _, part := range strings.FieldsFunc(normalize(name), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) {
|
||||
if part == token {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sameArchitecture(a, b string) bool {
|
||||
for _, left := range archAliases(strings.ToLower(a)) {
|
||||
for _, right := range archAliases(strings.ToLower(b)) {
|
||||
if left == right {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NOTE: helper functions to compute SHA256 from URL/path were removed
|
||||
@@ -507,13 +588,7 @@ func humanBytes(n int64) string {
|
||||
}
|
||||
}
|
||||
|
||||
// archAliases returns common name variants for an architecture string
|
||||
// so we can match release asset names like "x86_64" vs Go's "amd64".
|
||||
// archAliases returns name variants for an architecture string.
|
||||
// If `arch` is empty or matches the local runtime.GOARCH, prefer the
|
||||
// compile-time architecture aliases provided by archAliasesForLocal
|
||||
// (implemented per-architecture via build tags). For other `arch`
|
||||
// values we use a small synonyms map.
|
||||
// archAliases returns common release filename variants for a Go architecture.
|
||||
func archAliases(arch string) []string {
|
||||
a := strings.ToLower(arch)
|
||||
if syns, ok := archSynonyms[a]; ok {
|
||||
@@ -530,7 +605,7 @@ var archSynonyms = map[string][]string{
|
||||
"x86": {"386", "x86"},
|
||||
"arm64": {"arm64", "aarch64"},
|
||||
"aarch64": {"arm64", "aarch64"},
|
||||
"arm": {"arm"},
|
||||
"arm": {"arm", "armv6", "armv7"},
|
||||
}
|
||||
|
||||
func extractArchive(archivePath, destDir string) error {
|
||||
@@ -663,62 +738,108 @@ func extractTarFromReader(tr *tar.Reader, destDir string) error {
|
||||
}
|
||||
|
||||
func findBinaryInDir(dir, programName string) (string, error) {
|
||||
wanted := []string{programName}
|
||||
if runtime.GOOS == "windows" {
|
||||
wanted = append([]string{programName + ".exe"}, wanted...)
|
||||
} else {
|
||||
// also accept programs with .exe in archives targeting windows
|
||||
wanted = append(wanted, programName+".exe")
|
||||
names := []string{programName}
|
||||
if programName == "picoclaw" {
|
||||
names = append(names, "picoclaw-beta")
|
||||
}
|
||||
var wanted []string
|
||||
for _, name := range names {
|
||||
if runtime.GOOS == "windows" {
|
||||
wanted = append(wanted, name+".exe", name)
|
||||
} else {
|
||||
wanted = append(wanted, name, name+".exe")
|
||||
}
|
||||
}
|
||||
|
||||
var found string
|
||||
if err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || found != "" {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
base := filepath.Base(p)
|
||||
for _, w := range wanted {
|
||||
if base == w {
|
||||
for _, wantedName := range wanted {
|
||||
var found string
|
||||
if err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || found != "" {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
base := filepath.Base(p)
|
||||
if base == wantedName {
|
||||
found = p
|
||||
return io.EOF // use EOF to stop walking early
|
||||
}
|
||||
return nil
|
||||
}); err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
if found != "" {
|
||||
return found, nil
|
||||
}
|
||||
return nil
|
||||
}); err != nil && err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
if found == "" {
|
||||
return "", fmt.Errorf("binary %q not found in archive", programName)
|
||||
}
|
||||
return found, nil
|
||||
return "", fmt.Errorf("binary %q not found in archive", programName)
|
||||
}
|
||||
|
||||
// NewUpdateCommand returns a cobra command that triggers UpdateSelfFromRelease.
|
||||
func NewUpdateCommand(binaryName string) *cobra.Command {
|
||||
var urlStr, platform, arch string
|
||||
var urlStr, repository, platform, arch string
|
||||
var nightly, check bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "update",
|
||||
Short: "Check and apply updates from GitHub releases",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if platform == "" {
|
||||
platform = runtime.GOOS
|
||||
Short: "Check and apply updates from this fork's GitHub releases",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if !validRepository(repository) {
|
||||
return fmt.Errorf("invalid repository %q: expected owner/repo", repository)
|
||||
}
|
||||
if arch == "" {
|
||||
arch = runtime.GOARCH
|
||||
selector := urlStr
|
||||
if selector == "" {
|
||||
selector = releaseAPIURL(repository, nightly)
|
||||
}
|
||||
fmt.Printf("Current version: %s\n", config.FormatVersion())
|
||||
if err := UpdateSelfFromRelease(urlStr, platform, arch, binaryName); err != nil {
|
||||
source, err := buildReleaseAPIURL(selector)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Update applied; restart to use the new version.")
|
||||
targetPlatform, targetArch := platform, arch
|
||||
if targetPlatform == "" {
|
||||
targetPlatform = runtime.GOOS
|
||||
}
|
||||
if targetArch == "" {
|
||||
targetArch = runtime.GOARCH
|
||||
}
|
||||
fmt.Fprintf(
|
||||
cmd.OutOrStdout(),
|
||||
"Current version: %s\nRelease source: %s\nTarget: %s/%s\n",
|
||||
config.FormatVersion(),
|
||||
source,
|
||||
targetPlatform,
|
||||
targetArch,
|
||||
)
|
||||
if check {
|
||||
asset, checksum, err := findAssetInfo(source, targetPlatform, targetArch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(
|
||||
cmd.OutOrStdout(),
|
||||
"Release asset: %s\nSHA256: %s\nCheck complete; no files changed.\n",
|
||||
asset,
|
||||
checksum,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
if err := UpdateSelfFromRelease(source, targetPlatform, targetArch, binaryName); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(cmd.OutOrStdout(), "Update applied to the current executable; restart to use the new version.")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVarP(&urlStr, "url", "u", "", "Direct URL to download release asset or release page")
|
||||
cmd.Flags().StringVar(&platform, "platform", "", "Target platform (default: runtime.GOOS)")
|
||||
cmd.Flags().StringVar(&arch, "arch", "", "Target arch (default: runtime.GOARCH)")
|
||||
cmd.Flags().StringVar(&repository, "repo", DefaultRepository, "GitHub release repository (owner/repo)")
|
||||
cmd.Flags().BoolVar(&nightly, "nightly", false, "Use the selected repository's nightly release")
|
||||
cmd.Flags().
|
||||
BoolVar(&check, "check", false, "Check release metadata without downloading the binary or replacing files")
|
||||
cmd.Flags().
|
||||
StringVarP(&urlStr, "url", "u", "", "GitHub repository, release page, or Releases API URL (archive URLs are unsupported)")
|
||||
cmd.Flags().StringVar(&platform, "platform", "", "Target platform (cross-platform queries require --check)")
|
||||
cmd.Flags().StringVar(&arch, "arch", "", "Target architecture (cross-architecture queries require --check)")
|
||||
cmd.MarkFlagsMutuallyExclusive("url", "repo")
|
||||
cmd.MarkFlagsMutuallyExclusive("url", "nightly")
|
||||
return cmd
|
||||
}
|
||||
@@ -52,7 +52,7 @@ type testReleasePayload struct {
|
||||
Assets []testReleaseAsset `json:"assets"`
|
||||
}
|
||||
|
||||
const testReleaseAPIPath = "/api.github.com/repos/sipeed/picoclaw/releases/latest"
|
||||
const testReleaseAPIPath = "/repos/loveuer/picoclaw/releases/latest"
|
||||
|
||||
// TestDownloadAndExtractRelease_IntegrationLatestRelease downloads the latest
|
||||
// public release for a single platform as an opt-in smoke test.
|
||||
@@ -303,7 +303,7 @@ func TestDownloadAndExtractRelease_RetriesTransientAssetFailure(t *testing.T) {
|
||||
var server *httptest.Server
|
||||
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api.github.com/repos/sipeed/picoclaw/releases/latest":
|
||||
case "/repos/loveuer/picoclaw/releases/latest":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(
|
||||
w,
|
||||
@@ -328,7 +328,7 @@ func TestDownloadAndExtractRelease_RetriesTransientAssetFailure(t *testing.T) {
|
||||
withTestHTTPClient(t, server.Client())
|
||||
|
||||
dir, err := DownloadAndExtractRelease(
|
||||
server.URL+"/api.github.com/repos/sipeed/picoclaw/releases/latest",
|
||||
server.URL+"/repos/loveuer/picoclaw/releases/latest",
|
||||
"windows",
|
||||
"amd64",
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user