CHENGJIAHEGOXIS on X (Windows, Bun 1.4.4, after v0.1.4229) still couldn't install @magpie-community/tools-goanyapi from the dist branch: "Unexpected: failed copying files from cache to destination for package @magpie-community/tools-goanyapi ... installed ... Failed to install 1 package".38a90a34conly let a failure over *another* package pass; this one names GoAnyAPI itself, so the add was refused, and nothing magpie did made the next try different. What Bun 1.4.4 does (reproduced, sandbox HOME, its source read in src/install/PackageInstall.rs): - A local tarball is installed from its install-cache entry <cache>/@T@sha512-<32 hex>@@@1, trusted whole once there. An entry missing a file gives a copy missing it, "1 package installed", exit 0 (macOS on mote and Windows on xiaomi-gpu). Before this, magpie recorded that plugin as installed with no index.mjs. - A copy it can't make still prints "installed", writes the dependency and exits 1: a file of the old copy held open without delete sharing on Windows gives the reporter's lines with EBUSY; a read-only folder on macOS gives EACCES. The reporter's "Unexpected" is a Win32 code Bun has no errno for; which one wasn't reproduced (antivirus, a cloud placeholder or a transient hold are the candidates). Now addDist checks node_modules/<name> against the tarball installDist verified, file by file (.bun-tag and other extras ignored). A copy that differs is taken out together with Bun's cache entry and its scope link, and after 2s (distAgainAfter) the add is tried once more. A whole copy is the package in. One still not whole is errDistPartial, which install never hands to othersFailed, so the dependency is put back and the plugin isn't listed. The npm add has no tarball in hand and isn't judged this way. The fake bun now copies a dist tarball through a modelled cache entry (.held / MAGPIE_FAKE_BUN_HELD for a copy it can't make, MAGPIE_FAKE_BUN_LOSE for a file that never arrives); both sandboxes pass BUN_INSTALL_CACHE_DIR. Run: - New tests red on the old dist.go/store.go (mote): TestDistAddOverABroken- CacheEntry (no index.js), TestDistAddOverAHeldCopy (the reporter's error), TestDistAddNeverRecordsAPartialCopy (exit 0 one returned nil). - go test ./internal/plugin/... on mote at the pushed head (rebased on8bf9cb99d): ok 155s. gofmt -l clean; GOOS=windows go vet and GOOS=linux go vet -tags nogui of internal/plugin: ok. - win-run go test ./internal/plugin/ (before the rebase): the new tests pass; TestStaleMissingIsUnknownWhileDistUnread (#5351, passes alone) and TestPiPackage (#4115, red alone on basedd89f1255too) red. - Real Bun 1.4.4, real goanyapi 0.1.1 tarball served as the dist branch, through AddExact (throwaway test, not committed): clean add, a cache entry with index.mjs taken out, and on Windows a file of the old copy held open for 3s (EBUSY, then the second try after the pause) each installed, and the plugin loaded under bun (its hooks return 37/50 tools). A hold of 20s: add fails with Bun's EBUSY lines, GoAnyAPI not in package.json and not listed. - All 105 dist packages' latest tarballs added with real Bun 1.4.4 on mote: every copy equals its tarball byte for byte (only .bun-tag besides), so the check refuses none of them. Not tried: the reporter's own machine or its "Unexpected" code; the check on npm adds (#6736).
622 lines
20 KiB
Go
622 lines
20 KiB
Go
package plugin
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/sha512"
|
|
"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 hold that doesn't end, and
|
|
// $MAGPIE_FAKE_BUN_LOSE a file that never reaches the copy.
|
|
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))
|
|
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)
|
|
}
|
|
}
|
|
}
|