diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 6ffdff398..985a5a9e8 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -289,6 +289,8 @@ A plugin on the list whose package isn't in `plugins/` is installed again from i Every `bun add`, `bun update` and `bun remove` installs every dependency in `plugins/package.json` again, and Bun writes a package it adds there before it installs and exits 1 with it there. So a dependency no plugin is installed as, which Bun then can't install, failed every install of any plugin after it: CHENGJIAHEGOXIS on X (v0.1.4178, Windows) couldn't install GoAnyAPI over agency-agents, a repository with no `package.json` left by an add that failed, with "EBUSY: failed copying files from cache to destination for package agency-agents" (a file of its copy in `node_modules` held open, reproduced with Bun 1.4.2 on Windows), and nothing on the page named it. [`leftover.go`](../../internal/plugin/leftover.go) now: a package Bun says it couldn't install (`bunFailed`: "failed … for package ", "while installing ") that no plugin is installed as (`needed`: an entry on the list, on or off, an add in flight, pi's agent beside a pi plugin) is taken out of `package.json` and `node_modules` and the command run again (`dropBroken`, in `bunAdd` and `runBun`, so the dist branch's add of a package npm doesn't have gets it too: on v0.1.4205 the same reporter's GoAnyAPI, on no npm, failed from dist over agency-agents with Bun 1.4.4's "Unexpected: failed copying files … for package agency-agents", as only the npm add was cleared); a failed `install` puts back the dependencies and `bun.lock` it found (`depsState.undo`); an add whose own package is in while another listed plugin's failed is done (`othersFailed`, reading what Bun said at both the npm and the dist try: `failedOf` walks every wrapped error), that plugin's row saying what is wrong; on v0.1.4210 the same reporter's dist add failed with only "Failed to install 1 package" in its last six lines, Bun's line naming the package cut off, so `bunFailed` now reads every way Bun 1.4.4 names a failed package (`failed to install :`, "refusing to install dependency", "extracting tarball", "downloading tarball @", "Failed to open node_modules folder for"), and a failure that names no package still counts as another's when the add's own package is installed at the exact version asked for (`want`: the spec's exact version, or the one `installDist` read from the index); every Bun error magpie shows keeps its failure lines from anywhere in the output before the last lines (`bunSaid`, `TestBunAddErrorSaysWhatFailed`); `Remove` and `add`'s clean-ups take the dependency out by hand when `bun remove` fails (`removeDep`). What is left from before (`plugin.Leftovers`) is listed under Installed as "Not used by any plugin", each with a Remove (`/api/plugins` `leftovers`, `POST /api/plugins/leftover`, `pmLeftovers` in `plugininstalled.js`, imported when Plugins first draws). With `plugins.json` there and unreadable nothing is a leftover. The fake bun's `MAGPIE_FAKE_BUN_BUSY` and `MAGPIE_FAKE_BUN_NOREMOVE` stand in for the Windows failure: `TestLeftoverDoesNotFailAnotherAdd`, `TestFailedAddLeavesNoDependency`, `TestAnotherPluginsFailureDoesNotFailAdd`, `TestLeftoverDoesNotFailADistAdd`, `TestAnotherPluginsFailureDoesNotFailADistAdd` (with `MAGPIE_FAKE_BUN_NPM404` and the reporter's Bun output in `MAGPIE_FAKE_BUN_BUSY_SAYS`), `TestUnnamedFailureDoesNotFailADistAdd`, `TestOthersFailedNeedsTheAddsOwnVersion`, `TestRemoveTakesDependencyOutWhenBunFails`, `TestLeftoversListedAndRemoved`, `TestNoLeftoversWhenListUnreadable` and `TestBunFailed` in [`leftover_test.go`](../../internal/plugin/leftover_test.go), `TestPluginLeftoversReachThePage` in internal/gui, and `plugin-leftover.test.cjs` (both engines, every language, 980px and 420px). +A dist add is judged by the copy Bun leaves, not by what Bun says ([`distcopy.go`](../../internal/plugin/distcopy.go)). Bun 1.4.4 installs a local tarball from its install cache's entry for it (`/@T@sha512-@@@1`, linked from `///`) and trusts that entry whole once it is there: an entry missing a file gives a copy missing it, "1 package installed" and exit 0 (reproduced on macOS and Windows). A copy it can't make still prints "installed …", writes the dependency and exits 1 with "Failed to install 1 package": CHENGJIAHEGOXIS on X (v0.1.4229, Windows) got "Unexpected: failed copying files from cache to destination for package @magpie-community/tools-goanyapi"; a file of the old copy held open without delete sharing gives the same lines with EBUSY, and a read-only folder on macOS with EACCES. `addDist` checks `node_modules/` against the tarball `installDist` verified, file by file (`distCopyDiffers`; files Bun adds, `.bun-tag`, don't count). A copy that differs is taken out with the cache entry and its link (`dropDistCopy`, folders made writable where that stops it), and after `distAgainAfter` (2s) the add is tried once more. A whole copy is the package installed, and an error then is Bun's over another package (`othersFailed`, as above). One still not whole is `errDistPartial`, naming the file, which `install` never hands to `othersFailed`, so `depsState.undo` takes the dependency out and the plugin isn't listed. The npm add has no tarball in hand to check against and isn't judged this way. The fake bun copies a dist tarball through a modelled cache entry, with `.held` in the old copy or `MAGPIE_FAKE_BUN_HELD` for a copy it can't make and `MAGPIE_FAKE_BUN_LOSE` for a file that never arrives: `TestDistAddOverABrokenCacheEntry`, `TestDistAddOverAHeldCopy` and `TestDistAddNeverRecordsAPartialCopy` in [`distcopy_test.go`](../../internal/plugin/distcopy_test.go). + A name the user types is resolved before anything is installed (`resolve` in [`resolve.go`](../../internal/plugin/resolve.go)), in `plugin.Add`, which the CLI's `magpie plugin add`, the Plugins page's field (`/api/plugins/add`) and the movers all go through. A bare name that one of the community's listings goes by, case aside, is that package at the version given: its package or that without the scope, its short name (`workbuddy`, `think-tags`), its shown name (`WorkBuddy`, `Command Code`), a provider id it serves or the subscription it replaces, and a retired subscription's id through its mover (`qoder-cn`, `plugin.SubscriptionPlugin` = `MovePackage`). A name two listings go by, or one no listing goes by that isn't an npm name, is refused with the community plugins named. A name no listing goes by is npm's own package (`opencode-gemini-auth`) only when the list was fetched within the six hours: when the fetch fails, the copy kept or built in may not name a newer plugin, so the name is refused with why, and `npm:` installs npm's package as written. Before, `WorkBuddy` failed as no npm name, and `workbuddy` installed npm's unscoped `workbuddy` (Atlas on Discord, 10-25). Scoped names, paths and git specs are kept as written, and a backup's or a sync's plugins are installed by their own spec (`plugin.AddExact`), never resolved. `TestResolveCommunityNames`, `TestResolveRefusesWhatItCantName`, `TestResolveListUnread` and `TestAddByCommunityName` in [`resolve_test.go`](../../internal/plugin/resolve_test.go) cover these. A plugin added from a git repository is reinstalled by `reinstall`'s `bun update`, which re-resolves its branch or tag where `bun add` keeps the commit `bun.lock` has. Bun resolves a git spec through its own bare clone of the repository, kept in the install cache (`installCacheDir` in [`installcache.go`](../../internal/plugin/installcache.go)), and a fetch there moves `FETCH_HEAD` but not the clone's `refs/heads`, so every resolve after the first named the first install's commit again: an update of a plugin added as an unfixed `git+https://…` URL said it had installed while the plugin, `bun.lock` and the clone all stayed at the old commit, and an uninstall followed by an add again resolved it too (#2954). `refreshGitCache` ([`gitrev.go`](../../internal/plugin/gitrev.go)) now fetches the clone's branches and tags before `install`'s `bun add` (best-effort: a remote that can't be reached leaves the install to what the cache has) and before `reinstall`'s `bun update` (an error: an update that didn't happen is not reported as done); a spec that names a commit (`#`) is left alone, for nothing is resolved for one and its pin stands. When `bun update` exits 0 but the plugin is still behind the commit the checks saw the repository at, `reinstall` says so rather than claiming the update. `TestGitUpdateInstallsTheBranchsCommitNow` and `TestGitUpdateKeepsACommitPin` (on the bun on PATH, against a local `git+file://` repository) and `TestGitUpdateSaysWhenItDidnt` (with the fake bun keeping the lock's commit, as Bun's stale cache did) in [`plugin_gitupdate_test.go`](../../internal/plugin/plugin_gitupdate_test.go) cover these. diff --git a/internal/plugin/dist.go b/internal/plugin/dist.go index 4ead31257..cf1ecb495 100644 --- a/internal/plugin/dist.go +++ b/internal/plugin/dist.go @@ -303,7 +303,8 @@ var exactVersion = lazyre.New(`^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z // installDist installs the package's version from the dist branch: its // tarball fetched, checked against the index's sha512, kept in // plugins/dist (bun.lock names it there, and a later bun add installs it -// again from it), and added with bun. It says the version it added (at +// again from it), and added with bun, the copy Bun made checked against it +// (addDist). It says the version it added (at // "latest", the branch's newest), "" when it got no further than knowing // the branch has none. installMu held. func installDist(ctx context.Context, bun, name, version string) (string, error) { @@ -352,7 +353,7 @@ func installDist(ctx context.Context, bun, name, version string) (string, error) os.Remove(tmp.Name()) return version, werr } - return version, bunAdd(ctx, bun, "./dist/"+file, name) + return version, addDist(ctx, bun, name, file, b) } // pruneDist takes out the tarballs in plugins/dist that neither diff --git a/internal/plugin/distcopy.go b/internal/plugin/distcopy.go new file mode 100644 index 000000000..a0cb4aed5 --- /dev/null +++ b/internal/plugin/distcopy.go @@ -0,0 +1,148 @@ +package plugin + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha512" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "strings" + "time" +) + +// A dist tarball's add is judged by the copy Bun leaves in node_modules, +// not by what Bun says. Bun 1.4.4 installs a local tarball from its +// install cache (/@T@sha512-<32 hex>@@@1), trusting that entry +// whole once it is there: an entry missing a file (cut short, or a file +// taken out of it since) gives a copy missing that file, Bun saying "1 +// package installed" and exiting 0. And a copy it can't make (a file of +// the old one held open on Windows: "EBUSY: failed copying files from +// cache to destination") still has it print "installed …", write the +// dependency and exit 1 with "Failed to install 1 package" +// (CHENGJIAHEGOXIS on X: "Unexpected: failed copying files …" adding +// GoAnyAPI on v0.1.4229). The tarball magpie checked against the index's +// sha512 is in hand, so the copy is checked against it, file by file. + +// errDistPartial is a dist add whose copy in node_modules isn't the +// tarball's, after the add was tried again: the plugin isn't installed, +// whatever Bun said. +var errDistPartial = errors.New("the plugin's files didn't all reach plugins/node_modules") + +// distAgainAfter is the pause before a dist add is tried again over a +// copy that wasn't whole: what held a file of it (an antivirus' scan, a +// host still letting go) has a moment to finish. Moved by tests. +var distAgainAfter = 2 * time.Second + +// addDist adds the dist tarball file (plugins/dist/, its bytes tgz) +// as name's, and checks the copy Bun made. A copy that isn't the +// tarball's is taken out with Bun's cached copy of the tarball, and the +// add tried once more; one still not whole is errDistPartial, with what +// Bun said. A whole copy is name installed: an error then is Bun's over +// another package, as before. +func addDist(ctx context.Context, bun, name, file string, tgz []byte) error { + err := bunAdd(ctx, bun, "./dist/"+file, name) + bad := distCopyDiffers(tgz, name) + if bad == "" { + return err + } + dropDistCopy(name, tgz) + select { + case <-ctx.Done(): + return fmt.Errorf("%w (%s): %w", errDistPartial, bad, ctx.Err()) + case <-time.After(distAgainAfter): + } + err = bunAdd(ctx, bun, "./dist/"+file, name) + bad2 := distCopyDiffers(tgz, name) + if bad2 == "" { + return err + } + if err == nil { + return fmt.Errorf("%w (%s)", errDistPartial, bad2) + } + return fmt.Errorf("%w (%s): %w", errDistPartial, bad2, err) +} + +// distCopyDiffers says how node_modules/ isn't the package in tgz, +// or "" when every file of tgz is there with its bytes. Files the copy has +// besides (Bun's .bun-tag) don't count. +func distCopyDiffers(tgz []byte, name string) string { + at := filepath.Join(Dir(), "node_modules", filepath.FromSlash(name)) + gz, err := gzip.NewReader(bytes.NewReader(tgz)) + if err != nil { + return "the tarball can't be read: " + err.Error() + } + tr := tar.NewReader(gz) + files := 0 + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return "the tarball can't be read: " + err.Error() + } + if h.Typeflag != tar.TypeReg { + continue + } + // npm pack's files are under package/; the first part is the + // package's folder whatever it is named, as Bun takes it + _, rel, ok := strings.Cut(path.Clean(strings.TrimPrefix(h.Name, "./")), "/") + if !ok || rel == "" || rel == ".." || strings.HasPrefix(rel, "../") { + continue + } + want, err := io.ReadAll(tr) + if err != nil { + return "the tarball can't be read: " + err.Error() + } + files++ + got, err := os.ReadFile(filepath.Join(at, filepath.FromSlash(rel))) + if errors.Is(err, fs.ErrNotExist) { + return rel + " is missing" + } + if err != nil { + return rel + " can't be read: " + err.Error() + } + if !bytes.Equal(got, want) { + return rel + " isn't the tarball's" + } + } + if files == 0 { + return "the tarball has no files" + } + return "" +} + +// dropDistCopy takes out node_modules/ and Bun's cached copy of +// tgz: the next add extracts the tarball afresh. Best-effort: a file +// still held stays, and the next add says so. +func dropDistCopy(name string, tgz []byte) { + removeTree(filepath.Join(Dir(), "node_modules", filepath.FromSlash(name))) + sum := sha512.Sum512(tgz) + entry := "@T@sha512-" + hex.EncodeToString(sum[:])[:32] + "@@@1" + root := installCacheDir() + removeTree(filepath.Join(root, entry)) + os.Remove(filepath.Join(root, filepath.FromSlash(name), entry)) +} + +// removeTree takes out dir, making its folders writable where that is +// what stops it (a read-only folder's files can't be unlinked on unix). +func removeTree(dir string) { + if os.RemoveAll(dir) == nil { + return + } + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil && d.IsDir() { + os.Chmod(p, 0o755) + } + return nil + }) + os.RemoveAll(dir) +} diff --git a/internal/plugin/distcopy_test.go b/internal/plugin/distcopy_test.go new file mode 100644 index 000000000..648ffb5ec --- /dev/null +++ b/internal/plugin/distcopy_test.go @@ -0,0 +1,106 @@ +package plugin + +import ( + "crypto/sha512" + "encoding/hex" + "errors" + "os" + "path/filepath" + "slices" + "testing" +) + +// goanyapiAt is node_modules' copy of GoAnyAPI. +func goanyapiAt() string { + return filepath.Join(Dir(), "node_modules", filepath.FromSlash(goanyapi)) +} + +// noDistPause tries a dist add again at once. +func noDistPause(t *testing.T) { + was := distAgainAfter + distAgainAfter = 0 + t.Cleanup(func() { distAgainAfter = was }) +} + +// goanyapiListed says whether plugins.json lists GoAnyAPI. +func goanyapiListed() bool { + return slices.ContainsFunc(Load().Plugins, func(e Entry) bool { return Name(e.Spec) == goanyapi }) +} + +// Bun's cache entry for the dist tarball missing a file: Bun 1.4.4 +// copies the entry as it is, says "1 package installed" and exits 0 +// (seen on macOS and Windows). The copy is checked against the tarball, +// the entry taken out and the add tried again: the plugin is whole. +func TestDistAddOverABrokenCacheEntry(t *testing.T) { + goanyapiSandbox(t, nil, `{"plugins":[]}`, "") + sum := sha512.Sum512(npmTarball(t, goanyapi, "0.1.1")) + entry := filepath.Join(installCacheDir(), "@T@sha512-"+hex.EncodeToString(sum[:])[:32]+"@@@1") + if err := os.MkdirAll(entry, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(entry, "package.json"), []byte(`{"name":"`+goanyapi+`","version":"0.1.1","main":"index.js","type":"module"}`), 0o644); err != nil { + t.Fatal(err) + } + noDistPause(t) + if _, err := AddExact(ctxMinute(t), goanyapi+"@latest"); err != nil { + t.Fatalf("add from dist failed: %v", err) + } + if _, err := os.Stat(filepath.Join(goanyapiAt(), "index.js")); err != nil { + t.Fatalf("GoAnyAPI's copy has no index.js: %v", err) + } + if !goanyapiListed() { + t.Fatalf("GoAnyAPI not listed: %+v", Load().Plugins) + } +} + +// The reporter's case (CHENGJIAHEGOXIS, v0.1.4229 on Windows): Bun +// couldn't copy GoAnyAPI over its old copy ("Unexpected: failed copying +// files from cache to destination for package …", "installed …", +// "Failed to install 1 package"). The old copy is taken out, and the add +// tried again goes in. +func TestDistAddOverAHeldCopy(t *testing.T) { + goanyapiSandbox(t, nil, `{"plugins":[]}`, "") + if err := os.MkdirAll(goanyapiAt(), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(goanyapiAt(), ".held"), nil, 0o644); err != nil { + t.Fatal(err) + } + noDistPause(t) + if _, err := AddExact(ctxMinute(t), goanyapi+"@latest"); err != nil { + t.Fatalf("add from dist failed: %v", err) + } + if _, err := os.Stat(filepath.Join(goanyapiAt(), "index.js")); err != nil { + t.Fatalf("GoAnyAPI's copy has no index.js: %v", err) + } + if d := depsOf(t); d[goanyapi] != "./dist/magpie-community-tools-goanyapi-0.1.1.tgz" || !goanyapiListed() { + t.Fatalf("GoAnyAPI isn't in: deps %v, plugins %+v", d, Load().Plugins) + } +} + +// A copy that is still not the tarball's after the second try is no +// plugin installed, whether Bun exited 0 over it or said "installed" +// and failed: not listed, no dependency left, and the error says which +// file. +func TestDistAddNeverRecordsAPartialCopy(t *testing.T) { + for _, c := range []struct{ name, env, val string }{ + {"exit 0, a file missing", "MAGPIE_FAKE_BUN_LOSE", "index.js"}, + {"held", "MAGPIE_FAKE_BUN_HELD", "1"}, + } { + t.Run(c.name, func(t *testing.T) { + goanyapiSandbox(t, nil, `{"plugins":[]}`, "") + t.Setenv(c.env, c.val) + noDistPause(t) + _, err := AddExact(ctxMinute(t), goanyapi+"@latest") + if !errors.Is(err, errDistPartial) { + t.Fatalf("add = %v, want errDistPartial", err) + } + if goanyapiListed() { + t.Fatalf("GoAnyAPI listed: %+v", Load().Plugins) + } + if d := depsOf(t); d[goanyapi] != "" { + t.Fatalf("GoAnyAPI left a dependency: %v", d) + } + }) + } +} diff --git a/internal/plugin/plugin_git_test.go b/internal/plugin/plugin_git_test.go index 4c89da4de..e6e1a24b5 100644 --- a/internal/plugin/plugin_git_test.go +++ b/internal/plugin/plugin_git_test.go @@ -2,11 +2,15 @@ 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" @@ -82,6 +86,7 @@ func fakeBun(args []string) error { 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 @@ -115,24 +120,22 @@ func fakeBun(args []string) error { 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 + // 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, v, err := fakeTarball(spec) + name, held, err := fakeDistAdd(spec) if err != nil { return err } - at := filepath.Join("node_modules", filepath.FromSlash(name)) - if err := os.MkdirAll(at, 0o755); err != nil { - return err - } - 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 + 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) { @@ -194,6 +197,10 @@ func fakeBun(args []string) error { 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) @@ -210,6 +217,82 @@ func fakeBun(args []string) error { 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) { @@ -415,7 +498,7 @@ func gitSandbox(t *testing.T) (github, log string) { } 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) + 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 }) diff --git a/internal/plugin/plugin_off_kept_test.go b/internal/plugin/plugin_off_kept_test.go index dbaa26c33..468a06e62 100644 --- a/internal/plugin/plugin_off_kept_test.go +++ b/internal/plugin/plugin_off_kept_test.go @@ -49,7 +49,7 @@ func offSandbox(t *testing.T) string { bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, self, args...) cmd.Dir = dir - cmd.Env = append(os.Environ(), "MAGPIE_FAKE_BUN=1", "MAGPIE_FAKE_BUN_LOG="+log) + cmd.Env = append(os.Environ(), "MAGPIE_FAKE_BUN=1", "MAGPIE_FAKE_BUN_LOG="+log, "BUN_INSTALL_CACHE_DIR="+installCacheDir()) return cmd } t.Cleanup(func() { bunCommand = orig }) diff --git a/internal/plugin/store.go b/internal/plugin/store.go index d09b60e1c..6ebaef1fc 100644 --- a/internal/plugin/store.go +++ b/internal/plugin/store.go @@ -833,7 +833,9 @@ func install(ctx context.Context, spec string) error { } // another plugin's package Bun couldn't install, and this one in: the // add is done, and that plugin's row says what is wrong with it - if err != nil && othersFailed(err, spec, want) { + // (never over a copy of its own that isn't whole: Bun said + // "installed" over it, and may have exited 0) + if err != nil && !errors.Is(err, errDistPartial) && othersFailed(err, spec, want) { log.Printf("plugins: %s installed; Bun couldn't install %s: %v", spec, strings.Join(failedOf(err), ", "), err) err = nil }