CHENGJIAHEGOXIS on X, on v0.1.4241 (Windows): installing GoAnyAPI from
the Plugins page still failed with "Unexpected: failed copying files
from cache to destination for package @magpie-community/tools-goanyapi"
and "(LICENSE is missing)", at both of addDist's tries.
Cause, from Bun 1.4.4's source (src/install/PackageInstall.rs): on
Windows Bun copies each cached file by CreateHardLinkW, then CopyFileW,
with no other fallback; a Win32 error it has no errno for prints as
"Unexpected". On a machine where that copy fails (agency-agents failed
the same way there before) dropping the cache entry and trying again
can't help, which is all v0.1.4205 to v0.1.4241 did.
Now, when Bun's copy is still not whole after the second try, magpie
makes it from the tarball installDist verified against the index's
sha512 (unpackDist): the files go into a temp folder beside
node_modules/<name> with .bun-tag = the tarball's integrity, as Bun
writes it, and the folder is renamed into place. Bun takes a tarball
package whose .bun-tag matches as installed and never copies over it,
so bun add runs once more to write the dependency and bun.lock. Only a
package with no dependencies (optional, peer, bundled) whose
package.json names it is made this way; a path leaving the package is
refused. When magpie can't make it either, the add is errDistPartial as
before.
Run at c00c491bc + this change:
- mote: go test -count=1 ./internal/plugin/... ok (153s); go vet,
GOOS=windows go vet, GOOS=linux go vet -tags nogui ./internal/plugin/
clean; gofmt -l clean.
- xiaomi-gpu (Windows 11): go test -run
'TestDistAdd|TestUnpackDist|Leftover|Unnamed|TestDist' ./internal/plugin/ ok.
- Red on the old code: TestDistAddBunCantCopy against origin/main's
distcopy.go failed in both subtests with the reporter's error shape
("Unexpected: failed copying files … (package.json is missing)",
"(index.js is missing)").
- Real Bun 1.4.4, throwaway tests (not committed): on mote, a copy
unpacked with .bun-tag plus a MARK file survived bun add of another
package, bun install, bun update, bun remove of another, and bun
install with bun.lock deleted. On Windows, unpackDist then real
`bun add ./dist/<tgz>` wrote the dependency and lock, kept MARK, and
`bun install` said "no changes".
Not tried: the reporter's machine and its exact Win32 code; I could not
make real Bun's cache copy fail on Windows (a denied read is got past by
the hardlink, and across volumes Bun re-extracted its entry), so the
fallback itself ran with the fake bun only. A dist package with
dependencies is not unpacked, and the npm add is not covered.
630 lines
21 KiB
Go
630 lines
21 KiB
Go
package plugin
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/sha512"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// Lemon on Discord: can a plugin be installed straight from git (GitHub)?
|
|
// bun add takes github:owner/repo, owner/repo, a GitHub URL and git+…
|
|
// URLs, and installs the package at node_modules/<the name its own
|
|
// package.json gives>, not the spec's.
|
|
func TestIsGit(t *testing.T) {
|
|
for spec, want := range map[string]bool{
|
|
"github:owner/repo": true,
|
|
"github:owner/repo#v1.2.0": true,
|
|
"gitlab:owner/repo": true,
|
|
"owner/repo": true,
|
|
"owner/repo#main": true,
|
|
"https://github.com/owner/repo": true,
|
|
"https://github.com/owner/repo.git": true,
|
|
"git+https://github.com/owner/repo.git": true,
|
|
"git+ssh://git@github.com/owner/repo.git": true,
|
|
"git+file:///tmp/repo.git": true,
|
|
"git://github.com/owner/repo.git": true,
|
|
"opencode-gemini-auth": false,
|
|
"opencode-gemini-auth@latest": false,
|
|
"@magpie-community/opencode-kiro-auth": false,
|
|
"@magpie-community/opencode-kiro-auth@1.2": false,
|
|
"./my-plugin.js": false,
|
|
"/abs/plugin": false,
|
|
"file:///abs/plugin": false,
|
|
`C:\plugins\x`: false,
|
|
"https://example.com/x.tgz": false,
|
|
} {
|
|
if got := IsGit(spec); got != want {
|
|
t.Errorf("IsGit(%q) = %v, want %v", spec, got, want)
|
|
}
|
|
}
|
|
// an npm spec is named as it was
|
|
for spec, want := range map[string]string{"@scope/x@1.2": "@scope/x", "x@latest": "x", "x": "x"} {
|
|
if got := Name(spec); got != want {
|
|
t.Errorf("Name(%q) = %q, want %q", spec, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The test binary stands in for bun when MAGPIE_FAKE_BUN is set: add,
|
|
// update and remove as bun does them — a git spec fetched from local
|
|
// repositories ($MAGPIE_FAKE_GITHUB/owner/repo.git for GitHub's), and, like
|
|
// bun, keeping the commit its lock has when a spec is added again; an npm
|
|
// one put at node_modules/<its name>, at the version its spec names.
|
|
func init() {
|
|
if os.Getenv("MAGPIE_FAKE_BUN") == "1" {
|
|
if err := fakeBun(os.Args[1:]); err != nil {
|
|
fmt.Fprintln(os.Stderr, "fake bun:", err)
|
|
os.Exit(1)
|
|
}
|
|
os.Exit(0)
|
|
}
|
|
}
|
|
|
|
func fakeBun(args []string) error {
|
|
if f, err := os.OpenFile(os.Getenv("MAGPIE_FAKE_BUN_LOG"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
|
|
fmt.Fprintln(f, strings.Join(args, " "))
|
|
f.Close()
|
|
}
|
|
if len(args) < 3 || args[1] != "--ignore-scripts" {
|
|
return fmt.Errorf("unexpected %q", args)
|
|
}
|
|
var pj map[string]any
|
|
failSays := "" // what Bun says failing after it wrote package.json
|
|
b, err := os.ReadFile("package.json")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := json.Unmarshal(b, &pj); err != nil {
|
|
return err
|
|
}
|
|
deps := map[string]string{}
|
|
if d, ok := pj["dependencies"].(map[string]any); ok {
|
|
for k, v := range d {
|
|
deps[k], _ = v.(string)
|
|
}
|
|
}
|
|
lock := map[string]string{}
|
|
if b, err := os.ReadFile("fake.lock"); err == nil {
|
|
_ = json.Unmarshal(b, &lock)
|
|
}
|
|
switch args[0] {
|
|
case "add":
|
|
spec := args[2]
|
|
for n, s := range deps {
|
|
if s == spec && lock[n] != "" {
|
|
return nil // as bun: the lock's commit stays
|
|
}
|
|
}
|
|
// a package npm doesn't have, as Bun 1.4.4 says it: nothing written
|
|
if n := os.Getenv("MAGPIE_FAKE_BUN_NPM404"); n != "" && !IsPath(spec) && Name(spec) == n {
|
|
fmt.Println("bun add v1.4.4 (38afee6c8)")
|
|
fmt.Println("Resolving dependencies")
|
|
fmt.Println("Resolved, downloaded and extracted [1]")
|
|
fmt.Println("error: GET https://registry.npmjs.org/" + strings.Replace(n, "/", "%2f", 1) + " - 404")
|
|
return errors.New("exit 1")
|
|
}
|
|
// a tarball of plugins/dist (installDist): the package it holds,
|
|
// copied as Bun 1.4.4 copies it, from its install cache's entry
|
|
// for the tarball, which it trusts whole once it is there
|
|
if IsPath(spec) && strings.HasSuffix(spec, ".tgz") {
|
|
name, held, err := fakeDistAdd(spec)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
deps[name] = spec
|
|
if held {
|
|
// as the reporter's Bun 1.4.4 said it: installed, the
|
|
// dependency written, and exit 1
|
|
failSays = "bun add v1.4.4 (38afee6c8)\nResolving dependencies\nResolved, downloaded and extracted [1]\n" +
|
|
"Unexpected: failed copying files from cache to destination for package " + name + "\n" +
|
|
"Saved lockfile\n\ninstalled " + name + "@" + spec + "\n\n1 package removed [43.00ms]\nFailed to install 1 package\n"
|
|
}
|
|
break
|
|
}
|
|
if !IsGit(spec) {
|
|
name := Name(spec)
|
|
at := filepath.Join("node_modules", filepath.FromSlash(name))
|
|
if err := os.MkdirAll(at, 0o755); err != nil {
|
|
return err
|
|
}
|
|
v := strings.TrimPrefix(strings.TrimPrefix(spec, name), "@")
|
|
// a file to load, as a plugin's package has: add says why it
|
|
// won't take a package that names none (notPlugin)
|
|
b, _ := json.Marshal(map[string]string{"name": name, "version": v, "main": "index.js"})
|
|
if err := os.WriteFile(filepath.Join(at, "index.js"), []byte("export default async () => ({})\n"), 0o644); err != nil {
|
|
return err
|
|
}
|
|
if err := os.WriteFile(filepath.Join(at, "package.json"), b, 0o644); err != nil {
|
|
return err
|
|
}
|
|
deps[name] = spec
|
|
break
|
|
}
|
|
name, commit, err := fakeFetch(spec)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
deps[name], lock[name] = spec, commit
|
|
case "update":
|
|
if os.Getenv("MAGPIE_FAKE_BUN_STUCK") == "1" {
|
|
return nil // as bun whose cache's clone of the repository is stale: the lock's commit stays (#2954)
|
|
}
|
|
for _, n := range args[2:] {
|
|
if deps[n] == "" {
|
|
return fmt.Errorf("no dependency %s", n)
|
|
}
|
|
name, commit, err := fakeFetch(deps[n])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
lock[name] = commit
|
|
}
|
|
case "remove":
|
|
if os.Getenv("MAGPIE_FAKE_BUN_NOREMOVE") == "1" {
|
|
return errors.New("error: lockfile had changes, but lockfile is frozen")
|
|
}
|
|
for _, n := range args[2:] {
|
|
delete(deps, n)
|
|
delete(lock, n)
|
|
os.RemoveAll(filepath.Join("node_modules", n))
|
|
}
|
|
default:
|
|
return fmt.Errorf("unexpected %q", args)
|
|
}
|
|
pj["dependencies"] = deps
|
|
b, _ = json.MarshalIndent(pj, "", " ")
|
|
if err := os.WriteFile("package.json", b, 0o644); err != nil {
|
|
return err
|
|
}
|
|
b, _ = json.Marshal(lock)
|
|
if err := os.WriteFile("fake.lock", b, 0o644); err != nil {
|
|
return err
|
|
}
|
|
if failSays != "" {
|
|
fmt.Print(failSays)
|
|
return errors.New("exit 1")
|
|
}
|
|
// as bun does on Windows with a file of a package's copy held open:
|
|
// package.json written, then every command fails over that package
|
|
// while it is a dependency (CHENGJIAHEGOXIS's agency-agents)
|
|
// ($MAGPIE_FAKE_BUN_BUSY_SAYS: Bun's whole output instead)
|
|
if n := os.Getenv("MAGPIE_FAKE_BUN_BUSY"); n != "" && deps[n] != "" {
|
|
if says := os.Getenv("MAGPIE_FAKE_BUN_BUSY_SAYS"); says != "" {
|
|
fmt.Print(says)
|
|
return errors.New("exit 1")
|
|
}
|
|
fmt.Println("bun add v1.4.2 (fake)")
|
|
fmt.Println("EBUSY: failed copying files from cache to destination for package " + n)
|
|
return errors.New("exit 1")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// fakeDistAdd puts the package in the tarball at path into node_modules
|
|
// as Bun 1.4.4 does: extracted into the install cache's entry for the
|
|
// tarball (@T@sha512-<32 hex>@@@1) when there is none, and copied from
|
|
// that entry, whatever it holds. A copy over a folder holding .held (a
|
|
// file of the old copy held open, as on Windows) isn't made, and held
|
|
// says so; $MAGPIE_FAKE_BUN_HELD=1 is a copy it can never make (the
|
|
// reporter's, v0.1.4241), and $MAGPIE_FAKE_BUN_LOSE a file that never
|
|
// reaches the copy. A copy whose .bun-tag is the tarball's integrity is
|
|
// taken as installed and never copied over.
|
|
func fakeDistAdd(path string) (name string, held bool, err error) {
|
|
tgz, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
name, _, err = fakeTarball(path)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
if os.Getenv("BUN_INSTALL_CACHE_DIR") == "" {
|
|
return "", false, errors.New("no BUN_INSTALL_CACHE_DIR")
|
|
}
|
|
sum := sha512.Sum512(tgz)
|
|
entry := filepath.Join(os.Getenv("BUN_INSTALL_CACHE_DIR"), "@T@sha512-"+hex.EncodeToString(sum[:])[:32]+"@@@1")
|
|
if _, err := os.Stat(entry); err != nil {
|
|
gz, err := gzip.NewReader(bytes.NewReader(tgz))
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
tr := tar.NewReader(gz)
|
|
for {
|
|
h, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
_, rel, _ := strings.Cut(h.Name, "/")
|
|
to := filepath.Join(entry, filepath.FromSlash(rel))
|
|
if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil {
|
|
return "", false, err
|
|
}
|
|
b, _ := io.ReadAll(tr)
|
|
if err := os.WriteFile(to, b, 0o644); err != nil {
|
|
return "", false, err
|
|
}
|
|
}
|
|
link := filepath.Join(os.Getenv("BUN_INSTALL_CACHE_DIR"), filepath.FromSlash(name))
|
|
os.MkdirAll(link, 0o755)
|
|
os.Symlink(entry, filepath.Join(link, filepath.Base(entry)))
|
|
}
|
|
at := filepath.Join("node_modules", filepath.FromSlash(name))
|
|
// a copy whose .bun-tag is the tarball's integrity is installed, as
|
|
// Bun 1.4.4 checks a tarball's copy, and left as it is
|
|
if tag, err := os.ReadFile(filepath.Join(at, ".bun-tag")); err == nil && string(tag) == "sha512-"+base64.StdEncoding.EncodeToString(sum[:]) {
|
|
return name, false, nil
|
|
}
|
|
if _, err := os.Stat(filepath.Join(at, ".held")); err == nil || os.Getenv("MAGPIE_FAKE_BUN_HELD") == "1" {
|
|
return name, true, nil
|
|
}
|
|
err = filepath.WalkDir(entry, func(p string, d fs.DirEntry, err error) error {
|
|
if err != nil || d.IsDir() {
|
|
return err
|
|
}
|
|
rel, _ := filepath.Rel(entry, p)
|
|
if rel == os.Getenv("MAGPIE_FAKE_BUN_LOSE") {
|
|
return nil // a file taken out of every copy as it is made
|
|
}
|
|
b, err := os.ReadFile(p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(filepath.Join(at, rel)), 0o755); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(filepath.Join(at, rel), b, 0o644)
|
|
})
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
return name, false, nil
|
|
}
|
|
|
|
// fakeTarball is the name and version of the package in the tarball at
|
|
// path.
|
|
func fakeTarball(path string) (name, version string, err error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
defer f.Close()
|
|
gz, err := gzip.NewReader(f)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
tr := tar.NewReader(gz)
|
|
for {
|
|
h, err := tr.Next()
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("%s has no package/package.json: %v", path, err)
|
|
}
|
|
if h.Name != "package/package.json" {
|
|
continue
|
|
}
|
|
var p struct{ Name, Version string }
|
|
if err := json.NewDecoder(tr).Decode(&p); err != nil {
|
|
return "", "", err
|
|
}
|
|
return p.Name, p.Version, nil
|
|
}
|
|
}
|
|
|
|
// fakeFetch clones spec's repository and puts the package in it at
|
|
// node_modules/<its name>.
|
|
func fakeFetch(spec string) (name, commit string, err error) {
|
|
s, ref, _ := strings.Cut(spec, "#")
|
|
var url, ghRepo string
|
|
switch {
|
|
case strings.HasPrefix(s, "git+file://"):
|
|
url = strings.TrimPrefix(s, "git+")
|
|
case strings.HasPrefix(s, "github:"), strings.HasPrefix(s, "https://github.com/"), IsGit(s) && !strings.Contains(s, ":"):
|
|
ghRepo = strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(s, "github:"), "https://github.com/"), ".git")
|
|
url = filepath.Join(os.Getenv("MAGPIE_FAKE_GITHUB"), filepath.FromSlash(ghRepo)+".git")
|
|
default:
|
|
return "", "", fmt.Errorf("fetches only git, not %s", spec)
|
|
}
|
|
tmp, err := os.MkdirTemp("", "fakebun")
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
defer os.RemoveAll(tmp)
|
|
clone := []string{"clone", "-q"}
|
|
if ref != "" {
|
|
clone = append(clone, "--branch", ref)
|
|
}
|
|
if out, err := exec.Command("git", append(clone, url, tmp)...).CombinedOutput(); err != nil {
|
|
return "", "", fmt.Errorf("git clone %s: %v: %s", url, err, out)
|
|
}
|
|
out, err := exec.Command("git", "-C", tmp, "rev-parse", "HEAD").Output()
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
var p struct{ Name string }
|
|
b, err := os.ReadFile(filepath.Join(tmp, "package.json"))
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
if err := json.Unmarshal(b, &p); err != nil || p.Name == "" {
|
|
return "", "", fmt.Errorf("%s has no package name", spec)
|
|
}
|
|
dest := filepath.Join("node_modules", filepath.FromSlash(p.Name))
|
|
os.RemoveAll(dest)
|
|
err = filepath.WalkDir(tmp, func(path string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rel, _ := filepath.Rel(tmp, path)
|
|
if d.IsDir() && d.Name() == ".git" {
|
|
return filepath.SkipDir
|
|
}
|
|
if d.IsDir() {
|
|
return os.MkdirAll(filepath.Join(dest, rel), 0o755)
|
|
}
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(filepath.Join(dest, rel), b, 0o644)
|
|
})
|
|
commit = strings.TrimSpace(string(out))
|
|
// as bun tags what it installed: owner-repo-<7 digits> for GitHub's
|
|
// tarball, the whole commit for a clone
|
|
tag := commit
|
|
if ghRepo != "" {
|
|
tag = strings.ReplaceAll(ghRepo, "/", "-") + "-" + commit[:7]
|
|
}
|
|
if err == nil {
|
|
err = os.WriteFile(filepath.Join(dest, ".bun-tag"), []byte(tag), 0o644)
|
|
}
|
|
return p.Name, commit, err
|
|
}
|
|
|
|
// gitRepo is a plugin's repository: a checkout to commit to and the bare
|
|
// repository it pushes to, which is fetched from.
|
|
type gitRepo struct {
|
|
t *testing.T
|
|
work, bare string
|
|
}
|
|
|
|
func (r gitRepo) git(dir string, args ...string) {
|
|
r.t.Helper()
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t", "GIT_CONFIG_NOSYSTEM=1")
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
r.t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)
|
|
}
|
|
}
|
|
|
|
// release commits the plugin at version v and pushes it.
|
|
func (r gitRepo) release(v string) {
|
|
r.t.Helper()
|
|
pj := fmt.Sprintf(`{"name": "my-oc-plugin", "version": %q, "type": "module", "main": "index.js"}`, v)
|
|
if err := os.WriteFile(filepath.Join(r.work, "package.json"), []byte(pj), 0o644); err != nil {
|
|
r.t.Fatal(err)
|
|
}
|
|
r.git(r.work, "add", "-A")
|
|
r.git(r.work, "commit", "-qm", "v"+v)
|
|
r.git(r.work, "push", "-q", r.bare, "HEAD:main")
|
|
}
|
|
|
|
func newGitRepo(t *testing.T, bare string) gitRepo {
|
|
t.Helper()
|
|
r := gitRepo{t: t, work: filepath.Join(t.TempDir(), "work"), bare: bare}
|
|
if err := os.MkdirAll(r.work, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.git(r.work, "init", "-q", "-b", "main")
|
|
r.git(filepath.Dir(r.work), "init", "-q", "--bare", "-b", "main", bare)
|
|
js, err := os.ReadFile("testdata/fake/index.js")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(r.work, "index.js"), js, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(r.work, "README.md"), []byte("# my-oc-plugin\n\nFrom git.\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.release("1.0.0")
|
|
return r
|
|
}
|
|
|
|
// A plugin added from GitHub (or any git URL) is kept as it was given,
|
|
// is known by the package its repository names, and lists, switches off
|
|
// and on, updates (fetching the repository again), shows its README and
|
|
// is removed like any other; npm is never asked about it.
|
|
func TestGitPlugin(t *testing.T) {
|
|
github, log := gitSandbox(t)
|
|
realBun, _ := exec.LookPath("bun")
|
|
asked := false
|
|
origLatest := latestOf
|
|
latestOf = func(ctx context.Context, names []string) map[string]string {
|
|
asked = asked || slices.Contains(names, "my-oc-plugin")
|
|
return map[string]string{"my-oc-plugin": "9.0.0"}
|
|
}
|
|
t.Cleanup(func() { latestOf = origLatest })
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
|
|
repo := newGitRepo(t, filepath.Join(github, "owner", "repo.git"))
|
|
const spec = "github:owner/repo"
|
|
e, err := Add(ctx, spec)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gitPluginRest(t, ctx, repo, spec, e, realBun, log, &asked)
|
|
}
|
|
|
|
// gitSandbox is a HOME of the test's own where bun is the fake above,
|
|
// fetching GitHub's repositories from the folder it returns, and GitHub's
|
|
// API (asked for a repository's newest commit) answers from the same; and
|
|
// the fake bun's log.
|
|
func gitSandbox(t *testing.T) (github, log string) {
|
|
t.Helper()
|
|
if _, err := exec.LookPath("git"); err != nil {
|
|
t.Skip("no git on PATH")
|
|
}
|
|
dir := t.TempDir()
|
|
t.Setenv("HOME", dir)
|
|
t.Setenv("USERPROFILE", dir)
|
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
|
|
t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
|
|
realBun, _ := exec.LookPath("bun")
|
|
self, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("MAGPIE_BUN", self) // never downloaded
|
|
github = filepath.Join(dir, "github")
|
|
log = filepath.Join(dir, "bun.log")
|
|
orig := bunCommand
|
|
bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd {
|
|
if len(args) > 0 && args[0] == "run" && realBun != "" {
|
|
return orig(ctx, realBun, dir, args...)
|
|
}
|
|
cmd := exec.CommandContext(ctx, self, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(os.Environ(), "MAGPIE_FAKE_BUN=1", "MAGPIE_FAKE_GITHUB="+github, "MAGPIE_FAKE_BUN_LOG="+log, "BUN_INSTALL_CACHE_DIR="+installCacheDir())
|
|
return cmd
|
|
}
|
|
t.Cleanup(func() { bunCommand = orig })
|
|
t.Cleanup(Settle)
|
|
// GitHub's API: GET /repos/{owner}/{repo}/commits?per_page=1[&sha=ref]
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
|
if len(p) != 4 || p[0] != "repos" || p[3] != "commits" || r.URL.Query().Get("per_page") != "1" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
ref := r.URL.Query().Get("sha")
|
|
if ref == "" {
|
|
ref = "HEAD"
|
|
}
|
|
out, err := exec.Command("git", "-C", filepath.Join(github, p[1], p[2]+".git"), "rev-parse", ref+"^{commit}").Output()
|
|
if err != nil {
|
|
http.Error(w, `{"message":"No commit found for SHA: `+ref+`"}`, http.StatusUnprocessableEntity)
|
|
return
|
|
}
|
|
fmt.Fprintf(w, `[{"sha": %q, "commit": {"message": "x"}}]`, strings.TrimSpace(string(out)))
|
|
}))
|
|
t.Cleanup(srv.Close)
|
|
api := githubAPI
|
|
githubAPI = srv.URL
|
|
t.Cleanup(func() { githubAPI = api; forgetHeads() })
|
|
forgetHeads()
|
|
return github, log
|
|
}
|
|
|
|
func forgetHeads() {
|
|
headsMu.Lock()
|
|
heads = map[string]headAnswer{}
|
|
headsMu.Unlock()
|
|
}
|
|
|
|
func gitPluginRest(t *testing.T, ctx context.Context, repo gitRepo, spec string, e Entry, realBun, log string, asked *bool) {
|
|
t.Helper()
|
|
if e.Spec != spec {
|
|
t.Fatalf("added as %q, want the spec as given", e.Spec)
|
|
}
|
|
if n, v, p := Name(spec), Installed(spec), PackageName(spec); n != "my-oc-plugin" || v != "1.0.0" || p != "my-oc-plugin" {
|
|
t.Fatalf("Name, Installed, PackageName = %q %q %q", n, v, p)
|
|
}
|
|
if got := Target(spec); got != filepath.Join(Dir(), "node_modules", "my-oc-plugin") {
|
|
t.Fatalf("Target = %s", got)
|
|
}
|
|
if Pinned(spec) {
|
|
t.Fatal("a git plugin is pinned")
|
|
}
|
|
if l := Load().Plugins; len(l) != 1 || l[0].Spec != spec {
|
|
t.Fatalf("plugins = %+v", l)
|
|
}
|
|
if realBun != "" {
|
|
loaded, err := Plugins(ctx)
|
|
if err != nil || len(loaded) != 1 || loaded[0].Error != "" {
|
|
t.Fatalf("Plugins = %+v, %v", loaded, err)
|
|
}
|
|
ps, err := Providers(ctx)
|
|
if err != nil || len(ps) != 1 || ps[0].ID != "fakeco" || ps[0].Spec != spec {
|
|
t.Fatalf("Providers = %+v, %v", ps, err)
|
|
}
|
|
}
|
|
if p, err := Readme(ctx, spec); err != nil || !strings.Contains(p.Readme, "From git.") {
|
|
t.Fatalf("Readme = %+v, %v", p, err)
|
|
}
|
|
|
|
// update fetches the repository's commit now, the spec kept
|
|
repo.release("2.0.0")
|
|
if err := Update(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if v := Installed(spec); v != "2.0.0" {
|
|
t.Fatalf("after update: %s", v)
|
|
}
|
|
repo.release("3.0.0")
|
|
if err := Upgrade(ctx, Name(spec)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if v := Installed(spec); v != "3.0.0" || Load().Plugins[0].Spec != spec {
|
|
t.Fatalf("after upgrade: %s %+v", v, Load().Plugins)
|
|
}
|
|
// npm's my-oc-plugin, whatever it is, is never offered over it
|
|
if u, err := CheckUpdates(ctx); err != nil || *asked || len(u.Waiting) != 0 || Installed(spec) != "3.0.0" {
|
|
t.Fatalf("CheckUpdates = %+v, %v; npm asked: %v", u, err, *asked)
|
|
}
|
|
|
|
// off and on, by its package or by the spec
|
|
if err := SetOff("my-oc-plugin", true); err != nil || !Load().Plugins[0].Off {
|
|
t.Fatalf("off: %v %+v", err, Load().Plugins)
|
|
}
|
|
if err := SetOff(spec, false); err != nil || Load().Plugins[0].Off {
|
|
t.Fatalf("on: %v %+v", err, Load().Plugins)
|
|
}
|
|
|
|
// the same package from another URL takes the entry's place
|
|
file := gitFileURL(repo.bare)
|
|
if _, err := Add(ctx, file); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if l := Load().Plugins; len(l) != 1 || l[0].Spec != file || Name(file) != "my-oc-plugin" || Installed(file) != "3.0.0" {
|
|
t.Fatalf("plugins = %+v", l)
|
|
}
|
|
|
|
if err := Remove(ctx, "my-oc-plugin"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if l := Load().Plugins; len(l) != 0 {
|
|
t.Fatalf("plugins = %+v", l)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(Dir(), "node_modules", "my-oc-plugin")); !os.IsNotExist(err) {
|
|
t.Fatalf("still installed: %v", err)
|
|
}
|
|
b, _ := os.ReadFile(log)
|
|
for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") {
|
|
if !strings.Contains(l, " --ignore-scripts ") {
|
|
t.Errorf("bun %s: scripts run", l)
|
|
}
|
|
}
|
|
}
|