diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 8dfc84e8a..fa440a46a 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -287,7 +287,7 @@ A `@magpie-community` package npm doesn't give is installed from the community r A plugin on the list whose package isn't in `plugins/` is installed again from its own spec, switched off or not, by `plugin.InstallMissing`. `KeepUpdated` runs it 30 seconds after start and then hourly, before `CheckUpdates`. Nothing else did this. An update skips a plugin with no installed version, so the host said `no such plugin: …\node_modules\…` at every start until the user removed the plugin and added it again (#2002, Windows, after an update). Every bun command that changes `plugins/` runs one at a time under `installMu`: `install` (with the first `package.json` it writes, through temp and rename), `reinstall`'s `bun update`, and `Remove`'s and `add`'s `bun remove`, each after `mendPackageJSON` and then `mendDist`, which reads `package.json`. At start, `KeepUpdated` and `keepMovedCurrent` both run `bun add`. Two at once each read `package.json` before either writes it, so one change was lost (reproduced with Bun 1.4.3 on Windows), and a git plugin whose dependency was dropped can't be found. `TestMissingPluginsInstalledAgain` and `TestBunCommandsOneAtATime` in [`plugin_missing_test.go`](../../internal/plugin/plugin_missing_test.go) cover both. -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; `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`), `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). +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 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. diff --git a/internal/plugin/dist.go b/internal/plugin/dist.go index 197f9a580..4ead31257 100644 --- a/internal/plugin/dist.go +++ b/internal/plugin/dist.go @@ -303,41 +303,43 @@ 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. installMu held. -func installDist(ctx context.Context, bun, name, version string) error { +// again from it), and added with bun. 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) { d, err := distPkg(ctx, name) if err != nil { - return err + return "", err } if d == nil { - return fmt.Errorf("the community repo's dist branch has no %s", name) + return "", fmt.Errorf("the community repo's dist branch has no %s", name) } if version == "latest" { version = d.Latest } v, ok := d.Versions[version] if !ok { - return fmt.Errorf("the community repo's dist branch has no %s@%s", name, version) + return "", fmt.Errorf("the community repo's dist branch has no %s@%s", name, version) } if !distFile.MatchString(v.File) { - return fmt.Errorf("the community repo's dist branch names %q for %s@%s, not a tarball of its own", v.File, name, version) + return version, fmt.Errorf("the community repo's dist branch names %q for %s@%s, not a tarball of its own", v.File, name, version) } b, err := fetchJSONFaithful(ctx, distBase+"/"+v.File, 64<<20) if err != nil { - return err + return version, err } sum := sha512.Sum512(b) if got := "sha512-" + base64.StdEncoding.EncodeToString(sum[:]); got != v.Integrity { - return fmt.Errorf("%s from the community repo's dist branch isn't the tarball its index names (sha512 %s, not %s)", v.File, got, v.Integrity) + return version, fmt.Errorf("%s from the community repo's dist branch isn't the tarball its index names (sha512 %s, not %s)", v.File, got, v.Integrity) } dir := filepath.Join(Dir(), "dist") if err := os.MkdirAll(dir, 0o755); err != nil { - return err + return version, err } file := path.Base(v.File) tmp, err := os.CreateTemp(dir, file+".*") if err != nil { - return err + return version, err } _, werr := tmp.Write(b) if cerr := tmp.Close(); werr == nil { @@ -348,9 +350,9 @@ func installDist(ctx context.Context, bun, name, version string) error { } if werr != nil { os.Remove(tmp.Name()) - return werr + return version, werr } - return bunAdd(ctx, bun, "./dist/"+file, name) + return version, bunAdd(ctx, bun, "./dist/"+file, name) } // pruneDist takes out the tarballs in plugins/dist that neither @@ -442,7 +444,7 @@ func mendDist(ctx context.Context, bun string) { // what this can't mend, the command it comes before says out, err := bunCommand(ctx, bun, Dir(), append([]string{"update", "--ignore-scripts"}, stale...)...).CombinedOutput() if err != nil { - log.Printf("plugins: bun.lock behind package.json for %s; bun update: %v: %s", strings.Join(stale, ", "), err, lastLines(string(out), 3)) + log.Printf("plugins: bun.lock behind package.json for %s; bun update: %v: %s", strings.Join(stale, ", "), err, bunSaid(string(out), 3)) } else { log.Printf("plugins: bun.lock behind package.json for %s, sent back", strings.Join(stale, ", ")) } diff --git a/internal/plugin/leftover.go b/internal/plugin/leftover.go index 363e093d2..2f8aa8ccb 100644 --- a/internal/plugin/leftover.go +++ b/internal/plugin/leftover.go @@ -189,7 +189,7 @@ func removeDep(ctx context.Context, bun, name string) error { } } if err != nil { - log.Printf("plugins: bun remove %s: %v: %s; taken out of package.json instead", name, err, lastLines(string(out), 3)) + log.Printf("plugins: bun remove %s: %v: %s; taken out of package.json instead", name, err, bunSaid(string(out), 3)) } installMu.Lock() defer installMu.Unlock() @@ -253,10 +253,26 @@ func dropDeps(names ...string) error { return nil } -// bunFailedPkg is a package Bun says it couldn't install: "EBUSY: failed -// copying files from cache to destination for package ", "EACCES: -// Permission denied while installing ". -var bunFailedPkg = lazyre.New(`(?m)(?:failed [a-z /]+ for package|while installing) (@?[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)?)\s*$`) +// bunFailedPkg is a package Bun says it couldn't install, in each way +// Bun 1.4.4 (src/install) names one: "EBUSY: failed copying files from +// cache to destination for package ", "EACCES: Permission denied +// while installing ", "Failed to open node_modules folder for +// in …", "failed to install : the downloaded package was not found +// in the cache", "failed to link : …", "folder path for package +// is too long", "refusing to install dependency …", +// " downloading tarball @", "failed to download +// @", " extracting tarball from " and +// " extracting tarball for """. Only the first two were read, +// and a failure Bun named the other ways failed an add whose own package +// went in. +var bunFailedPkg = lazyre.New(`(?m)(?:(?:failed [a-z /]+ for package|while installing) (` + bunPkgName + `)\s*$` + + `|(?:Failed to open node_modules folder for|path for package|refusing to (?:install|link) dependency|extracting tarball from) (` + bunPkgName + `)(?:\s|$)` + + `|failed to (?:install|link) (` + bunPkgName + `):` + + `|(?:downloading tarball|failed to download) (` + bunPkgName + `)@` + + `|extracting tarball for "(` + bunPkgName + `)")`) + +// bunPkgName is a package's name as Bun writes it in a message. +const bunPkgName = `@?[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)?` var ansi = lazyre.New(`\x1b\[[0-9;]*m|`) @@ -265,8 +281,10 @@ func bunFailed(out string) []string { out = ansi.ReplaceAllString(out, "") var names []string for _, m := range bunFailedPkg.FindAllStringSubmatch(out, -1) { - if n := strings.TrimRight(m[1], "."); !slices.Contains(names, n) { - names = append(names, n) + for _, n := range m[1:] { + if n = strings.TrimRight(n, "."); n != "" && !slices.Contains(names, n) { + names = append(names, n) + } } } return names @@ -433,10 +451,17 @@ func dropBroken(err error, also ...string) []string { // othersFailed is whether err, a failed bun add of spec, is only another // package's failure, spec's own package installed: the add of it is done, -// and the plugin Bun couldn't install says so in its own row. -func othersFailed(err error, spec string) bool { +// and the plugin Bun couldn't install says so in its own row. want is +// the version the add was for, "" when that isn't known (a tag or a +// range): with it, the package is to be in at that version, and a failure +// that names no package is another's too, as Bun names a package of its +// own it couldn't install. Bun names some failures in words magpie doesn't +// read, and printed one that way before "Saved lockfile" with GoAnyAPI +// installed from the dist branch at the version asked, and the add failed +// (CHENGJIAHEGOXIS on X, v0.1.4210: "Failed to install 1 package"). +func othersFailed(err error, spec, want string) bool { failed := failedOf(err) - if len(failed) == 0 { + if len(failed) == 0 && want == "" { return false } name := Name(spec) @@ -447,5 +472,5 @@ func othersFailed(err error, spec string) bool { return false } v, known := installedVersion(name) - return known && v != "" + return known && v != "" && (want == "" || v == want) } diff --git a/internal/plugin/leftover_test.go b/internal/plugin/leftover_test.go index 8b339d973..aeb71dc06 100644 --- a/internal/plugin/leftover_test.go +++ b/internal/plugin/leftover_test.go @@ -2,6 +2,7 @@ package plugin import ( "context" + "errors" "os" "path/filepath" "slices" @@ -158,6 +159,96 @@ func goanyapiSandbox(t *testing.T, deps map[string]string, list, busy string) { t.Setenv("MAGPIE_FAKE_BUN_BUSY_SAYS", strings.ReplaceAll(goanyapiBusy, "agency-agents", busy)) } +// goanyapiUnnamed is what Bun 1.4.4 said adding GoAnyAPI's dist tarball +// on the reporter's Windows on v0.1.4210, its lines as the error showed +// them: GoAnyAPI installed, a package failed, and the line naming it was +// cut off by the error's last-lines (its header lines are Bun's own). +const goanyapiUnnamed = "bun add v1.4.4 (38afee6c8)\nResolving dependencies\nResolved, downloaded and extracted [1]\n" + + "Saved lockfile\n\n" + + "installed @magpie-community/tools-goanyapi@./dist/magpie-community-tools-goanyapi-0.1.1.tgz\n\n" + + "1 package removed [26.00ms]\nFailed to install 1 package\n" + +// The reporter's case on v0.1.4210: from the dist branch, GoAnyAPI went +// in at the version asked and Bun failed over a package in words magpie +// doesn't read. The add is done: Bun names a package of its own it +// couldn't install. +func TestUnnamedFailureDoesNotFailADistAdd(t *testing.T) { + goanyapiSandbox(t, nil, `{"plugins":[]}`, goanyapi) + t.Setenv("MAGPIE_FAKE_BUN_BUSY_SAYS", goanyapiUnnamed) + if _, err := AddExact(ctxMinute(t), goanyapi+"@latest"); err != nil { + t.Fatalf("add from dist failed with GoAnyAPI in: %v", err) + } + if d := depsOf(t); d[goanyapi] != "./dist/magpie-community-tools-goanyapi-0.1.1.tgz" { + t.Fatalf("GoAnyAPI isn't a dependency at its dist tarball: %v", d) + } + if !slices.ContainsFunc(Load().Plugins, func(e Entry) bool { return Name(e.Spec) == goanyapi }) { + t.Fatalf("GoAnyAPI not listed: %+v", Load().Plugins) + } +} + +// A failure that names the add's own package still fails it, and so does +// one that names none when the package isn't in at the version asked. +func TestOthersFailedNeedsTheAddsOwnVersion(t *testing.T) { + depsSandbox(t, map[string]string{goanyapi: "./dist/magpie-community-tools-goanyapi-0.1.1.tgz", "opencode-other-auth": "opencode-other-auth@1.0.0"}, `{"plugins":[]}`) + at := filepath.Join(Dir(), "node_modules", filepath.FromSlash(goanyapi)) + if err := os.MkdirAll(at, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(at, "package.json"), []byte(`{"name":"`+goanyapi+`","version":"0.1.0"}`), 0o644); err != nil { + t.Fatal(err) + } + unnamed := &bunRunError{errors.New("bun add"), goanyapiUnnamed} + own := &bunRunError{errors.New("bun add"), "EBUSY: failed copying files from cache to destination for package " + goanyapi} + other := &bunRunError{errors.New("bun add"), "EBUSY: failed copying files from cache to destination for package opencode-other-auth"} + spec := goanyapi + "@latest" + for _, c := range []struct { + err error + want string + ok bool + }{ + {unnamed, "0.1.0", true}, + {unnamed, "0.1.1", false}, // an older copy is not the add's + {unnamed, "", false}, // no version to check it against + {own, "0.1.0", false}, + {other, "0.1.0", true}, + {other, "0.1.1", false}, + {other, "", true}, + } { + if got := othersFailed(c.err, spec, c.want); got != c.ok { + t.Errorf("othersFailed(%q, want %q) = %v, want %v", c.err.(*bunRunError).out, c.want, got, c.ok) + } + } +} + +// A failed bun add's error says which package Bun couldn't install: the +// line naming it came before the last lines, which alone were shown. +func TestBunAddErrorSaysWhatFailed(t *testing.T) { + out := "bun add v1.4.4 (38afee6c8)\r\nResolving dependencies\r\nResolved, downloaded and extracted [1]\r\n" + + "Unexpected: failed copying files from cache to destination for package opencode-held-auth\r\n" + + goanyapiUnnamed[strings.Index(goanyapiUnnamed, "Saved"):] + got := bunSaid(out, 6) + for _, w := range []string{"for package opencode-held-auth", "installed " + goanyapi, "Failed to install 1 package"} { + if !strings.Contains(got, w) { + t.Errorf("bunSaid = %q, missing %q", got, w) + } + } + if strings.Contains(got, "\n\n") || strings.Contains(got, "\r") || strings.Contains(got, "Resolving") { + t.Errorf("bunSaid = %q: blank lines, CRs or lines before the failure", got) + } +} + +// A leftover Bun names in another of its ways is taken out too. +func TestLeftoverNamedOtherwiseIsTakenOut(t *testing.T) { + goanyapiSandbox(t, map[string]string{agency: "github:msitarzewski/agency-agents"}, `{"plugins":[]}`, agency) + t.Setenv("MAGPIE_FAKE_BUN_BUSY_SAYS", "bun add v1.4.4 (38afee6c8)\nerror: Failed to open node_modules folder for agency-agents in C:\\p\\node_modules\nFailed to install 1 package\n") + if _, err := AddExact(ctxMinute(t), goanyapi+"@latest"); err != nil { + t.Fatalf("add failed over a leftover: %v", err) + } + if _, in := depsOf(t)[agency]; in { + t.Fatalf("the leftover is still a dependency: %v", depsOf(t)) + } +} + // The reporter's case on v0.1.4205: GoAnyAPI isn't on npm, and its add // from the dist branch failed over the leftover, which only the npm add // was cleared of. Every add has it: the dist branch's too. @@ -275,6 +366,19 @@ func TestBunFailed(t *testing.T) { "error: GET https://registry.npmjs.org/x - 404": nil, goanyapiBusy: {agency}, strings.ReplaceAll(goanyapiBusy, "\n", "\r\n"): {agency}, + goanyapiUnnamed: nil, + // each other way Bun 1.4.4 names a package it couldn't install + "error: Failed to open node_modules folder for \x1b[31m@scope/pkg\x1b[0m in C:\\x\\node_modules\r\n": {"@scope/pkg"}, + "error: failed to install agency-agents: the downloaded package was not found in the cache": {agency}, + "error: failed to link opencode-x-auth: EPERM": {"opencode-x-auth"}, + "error: failed to link into C:\\x\\node_modules\\.bin: EPERM": nil, + "ENAMETOOLONG: folder path for package agency-agents is too long": {agency}, + "error: refusing to install dependency evil with unsafe folder path \"../x\"": {"evil"}, + "error: GET https://codeload.github.com/a/b - 404 downloading tarball agency-agents@github:a/b#1": {agency}, + "error: failed to download @scope/pkg@1.0.0": {"@scope/pkg"}, + "error: ENOENT extracting tarball from opencode-x-auth": {"opencode-x-auth"}, + "error: Unexpected extracting tarball for \"@scope/pkg\": bad (at byte 1 of 2)": {"@scope/pkg"}, + "Failed to install 1 package": nil, } { if got := bunFailed(out); !slices.Equal(got, want) { t.Errorf("bunFailed(%q) = %v, want %v", out, got, want) diff --git a/internal/plugin/store.go b/internal/plugin/store.go index 9cdc5c567..d09b60e1c 100644 --- a/internal/plugin/store.go +++ b/internal/plugin/store.go @@ -813,8 +813,18 @@ func install(ctx context.Context, spec string) error { // back stays held, as the user's bunfig asks, and a bun this machine // can't run at all can't add it from there either var ue *BunUnstartableError + // the version the add is for, when it names one: the dist branch's + // newest when it is added from there at "latest" + want := strings.TrimPrefix(strings.TrimPrefix(spec, Name(spec)), "@") + if IsPath(spec) || IsGit(spec) || !exactVersion.MatchString(want) { + want = "" + } if name, version, ok := distWanted(spec); ok && err != nil && !minAge.MatchString(err.Error()) && !errors.As(err, &ue) { - if derr := installDist(ctx, bun, name, version); derr != nil { + v, derr := installDist(ctx, bun, name, version) + if v != "" { + want = v + } + if derr != nil { // both wrapped: what Bun said at either try is read (failedOf) err = fmt.Errorf("%w (and from the community repo's dist branch: %w)", err, derr) } else { @@ -823,7 +833,7 @@ 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) { + if err != nil && othersFailed(err, spec, want) { log.Printf("plugins: %s installed; Bun couldn't install %s: %v", spec, strings.Join(failedOf(err), ", "), err) err = nil } @@ -865,7 +875,7 @@ func bunAddOnce(ctx context.Context, bun, spec string) error { if ue := wontLoad(bun, err); ue != nil { return fmt.Errorf("bun add %s: %w", spec, ue) } - return &bunRunError{fmt.Errorf("bun add %s: %v: %s", spec, cantStart(bun, err), lastLines(string(out), 6)), string(out)} + return &bunRunError{fmt.Errorf("bun add %s: %v: %s", spec, cantStart(bun, err), bunSaid(string(out), 6)), string(out)} } return nil } @@ -1046,7 +1056,7 @@ func reinstall(ctx context.Context, spec string) error { if ue := wontLoad(bun, err); ue != nil { return fmt.Errorf("bun update %s: %w", name, ue) } - return fmt.Errorf("bun update %s: %v: %s", name, cantStart(bun, err), lastLines(string(out), 6)) + return fmt.Errorf("bun update %s: %v: %s", name, cantStart(bun, err), bunSaid(string(out), 6)) } // what the checks saw the repository at (the page's, before the // reader pressed update) is what the update was to install: bun @@ -1068,6 +1078,37 @@ func reinstall(ctx context.Context, spec string) error { return nil } +// bunSaid is what a failed bun command said, for its error: every line +// that says what failed, and its last n lines. Its last lines alone hid +// it: Bun names the package it couldn't install before "Saved lockfile", +// the added package and its summary, so "Failed to install 1 package" +// came with no word of which (CHENGJIAHEGOXIS on X, v0.1.4210). Blank +// lines are left out. +func bunSaid(s string, n int) string { + s = ansi.ReplaceAllString(strings.ReplaceAll(s, "\r\n", "\n"), "") + var ls []string + for _, l := range strings.Split(s, "\n") { + if l = strings.TrimRight(l, " \t\r"); strings.TrimSpace(l) != "" { + ls = append(ls, l) + } + } + var out []string + said := 0 + for i, l := range ls { + switch { + case i >= len(ls)-n: + out = append(out, l) + case said < 8 && bunFailLine.MatchString(l): + out = append(out, l) + said++ + } + } + return strings.Join(out, "\n") +} + +// bunFailLine is a line of Bun's output that says something failed. +var bunFailLine = lazyre.New(`(?i)\b(?:error|failed|unexpected|refusing|permission denied)\b|^E[A-Z]{2,}\b`) + func lastLines(s string, n int) string { ls := strings.Split(strings.TrimSpace(s), "\n") if len(ls) > n {