Files
magpie/internal/plugin/dist.go
T
JoeyWu-tech 6cb1cfb794 plugin: a lock behind package.json's dist tarball is mended, its tarballs kept (#3622)
Part 1 of 2, pruneDist (coffemon's first commit):

pruneDist took out every tarball in plugins/dist that
plugins/package.json doesn't name, as encoding/json reads it. Bun
installs a package from the tarball bun.lock's packages has it at, and
that can be one package.json has moved on from: gkd2323c's lock (#3622,
Windows, Bun 1.4.4) had autoclaw, codearts and cloudflare-workers-ai at
the tarballs before the ones package.json names, and those were gone
from plugins/dist, where nothing but pruneDist takes a file out. With
Bun's own copy of such a tarball, every bun command that changes
plugins/ puts the older version back; with none, every add and removal,
of any plugin, fails with "ENOENT extracting tarball from <that
package>" (part 2 has the likely why there was none).

Now a tarball the lock's packages has a package at stays, beside the
ones package.json names. Kept, it is what Bun installs: a package whose
lock is behind package.json stays at the older version without a word,
where 4e5b2ad8, once Bun had no copy, failed every command with ENOENT.
part 2 sends such a lock back to package.json before each bun
command when package.json has the package at a dist tarball too; with
package.json at npm it stays behind (#3720). package.json is read as
text, every dist/<file> in it counting, where encoding/json keeps one
value of a key named twice: Bun 1.4.0 adds a tarball's package a second
time instead of replacing it, the new tarball first, which Bun reads,
and encoding/json reads the second, so 4e5b2ad8 took out the tarball Bun
installs from. No magpie runs plugins on that Bun unless MAGPIE_BUN
names it (BunVersion has been 1.4.2 since 10-03, before plugins/dist
was), so that is how a decoded package.json loses it, not a path a user
is known to have taken. A tarball only the lock's workspaces names goes:
Bun 1.4.2 and 1.4.3 leave the one an add replaced there until their next
command, and nothing installs from it. With no bun.lock, package.json
alone decides, as before; with one that can't be read, nothing goes, as
with a package.json that can't be read.

This keeps the tarballs a lock has from going, and mends no lock: one
behind package.json's dist tarball, the reporter's or one that falls
behind later, is sent back by part 2, its tarball there or
gone.

What was run (tree 8f285445, on origin/main 4e5b2ad8, go1.26.8,
linux/amd64):
- TestDistTarballTheLockNamesStays (new): the reporter's package.json
  and lock, built around the lines #3622 quotes; the package.json real
  Bun 1.4.2 writes for `bun add ./dist/<0.2.6>` over 0.2.1, and the one
  Bun 1.4.0 writes (the package named twice), each with the lock both
  write, and the Bun 1.4.0 one with no lock; no lock; a lock that can't
  be read (a folder in its place). The tarballs the lock's packages or
  package.json name stay, the one only the lock's workspaces name goes,
  and one nothing names goes; with no lock package.json alone decides,
  and with an unreadable one nothing goes. With the change the TestDist
  tests are ok on each Bun. Broken by hand, each put back after, with
  Bun 1.4.2, 1.4.3 and 1.4.4 (outside graftcp, the proxy wrapper this
  box runs commands in, umask 077, logs kept):
  - 4e5b2ad8's pruneDist: the reporter's, both named-twice and the
    unreadable-lock cases red on each ("<tarball> taken out");
  - package.json decoded as 4e5b2ad8 did, the lock still read: the
    named-twice case with no lock red on each ("<0.2.6> taken out");
  - the whole lock read for tarballs instead of its packages: the
    workspaces case red on each ("0.2.1 kept"), and
    TestDistInstallsAPackageNPMDoesntHave red on 1.4.2 and 1.4.3
    (0.1.4's tarball stays after 0.1.3 is pinned: those two leave it in
    the workspaces).
- internal/plugin, -tags nogui, with Bun 1.4.4, the one magpie runs now:
  ok but TestPluginSOCKSProxy, red the same at origin/main 7a60e78c
  (#2207, open, filed for 1.4.3); TestFlowBigReplyProd and
  TestRenewOtherHost skip by their own condition.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build
  -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet
  and go build without the tag on linux: exit 1 (no GTK, WebKitGTK or
  fontconfig headers on this box).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 64 ok, internal/plugin among them, and 8 red, none in
  what this changes:
  - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398;
    TestCursorFolderFromTheEditorIsNotTheCLI,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
    TestOmpDetectedWithPiDir: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink: this box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - provider: "fatal error: close of synctest channel from outside
    bubble" in TestUnreadLoginsWriteErrorsKeepCredentials, main's CI
    red, #3632; the package's tests after it didn't run.
  - sessions TestAgyTitleLater: a same-size write in the same mtime
    tick, 2 of 200 on main alone, #3708.
  - testenv TestProgram: this box's umask 077, #3640.

Not tried: Windows, where the reporter is (CI's Windows job runs none of
these tests: it compiles them and runs a named few). package.json and
the lock are read for the forward-slash form magpie hands Bun
("./dist/<file>"), which the reporter's Bun 1.4.4 on Windows kept in
both. A tarball they name only with backslashes goes, where 4e5b2ad8 on
Windows kept one package.json named so (it read package.json through
filepath.ToSlash).

Part 2 of 2, mendDist (coffemon's second commit):

The commit before keeps the tarballs bun.lock has packages at, but a
lock behind package.json stays behind: gkd2323c's (#3622, Windows, Bun
1.4.4) had autoclaw, codearts and cloudflare-workers-ai at tarballs
pruneDist had taken, while package.json and the lock's workspaces had
moved on. Bun installs what the lock has, at every command that changes
plugins/. From that tarball, kept now, or from its own copy of it, it
put the older version back without a word; with neither, every install,
update and removal, of any plugin, failed with "ENOENT extracting
tarball from <that package>". Bun keeps its copy of a local tarball in
its install cache as @T@<16hex>@@@1 on 1.4.2 and 1.4.3, and as
@T@sha512-<32hex>@@@1, the start of the tarball's sha512, on 1.4.4, so a
Bun moved to 1.4.4 has no copy of one an older Bun made (magpie takes a
Bun release two days after it is out, bunSettle: 1.4.4, out on 10-22,
from 10-24). pruneInstallCache leaves these copies alone (no package
name before their first @). On Linux, such a lock and copies made by
1.4.2 or by 1.4.3 give an add on 1.4.4 the reporter's error, for both
packages locked at gone tarballs; the same Bun's add succeeds and puts
both back at their older versions.

Now mendDist runs before each bun command that changes plugins/ (in
runBun and install, under installMu): the packages the lock has at a
dist tarball package.json doesn't name, while package.json has them at
one plugins/dist holds, get one `bun update --ignore-scripts` of them
all, which resolves them from package.json again. It comes after
a9242eb6's mendPackageJSON, which cuts what follows package.json's
object (plugins#405): mendDist decodes package.json, and with that tail
there it would return without a mend, leaving the lock behind for the
command. A package.json that names the lock's tarball too, as Bun
1.4.0's names a package twice, isn't behind. Nothing is asked of the
registry: no package on dist has a dependency (its index.json, 42
packages, on 10-26). `bun add` of them doesn't do it on Bun 1.4.2 and
1.4.3, which keep what the lock has, and with no copy of them, an update
of one package alone fails on the others still locked at gone tarballs.
Each mend is logged with the packages it sent back, so a lock that falls
behind again, which nothing here explains, leaves a line saying when.
What it can't mend is left to the command it comes before, as before:
package.json's tarball gone too, or a package.json or bun.lock it can't
read. A lock behind package.json across npm and plugins/dist it leaves
alone, and Bun installs the lock's version (#3720). A lock with nothing
stale costs reading the two files, decoding package.json and a scan of
the lock; a tarball is looked at only where the lock and package.json
name different ones.

A lock already behind, the reporter's among them, is sent back at the
next bun command magpie runs that changes plugins/, as package.json's
tarball is in plugins/dist: pruneDist never takes one package.json
names.

What was run (tree 5ae0b4a1, on origin/main 4e5b2ad8, go1.26.8,
linux/amd64):
- TestDistLockBehindPackageJSONIsMended (new), with real Bun: autoclaw
  and codearts installed from plugins/dist at 0.2.1 and 0.2.0, then at
  0.2.6 and 0.2.1 (the reporter's), and the lock's packages given back
  the entries Bun wrote for the first ones; with Bun's copies kept, with
  them gone, with the older tarballs put back in plugins/dist, as the
  commit before keeps them, and with the copies gone and plugins#405's
  tail after package.json's object. From each state an unrelated
  plugin's add (zcode) and then its removal succeed and leave both
  packages at package.json's versions, in node_modules and alone in the
  lock, and package.json's specs for both as they were; the add's prune
  takes the older tarballs. With the change the TestDist tests are ok on
  each Bun, and the two new ones at -count=10 on 1.4.2 and 1.4.4. Broken
  by hand, each put back after, with Bun 1.4.2, 1.4.3 and 1.4.4 (outside
  graftcp, the proxy wrapper this box runs commands in, umask 077, logs
  kept):
  - no mendDist: every case red on each, the older versions back with
    the copies or the older tarballs kept (`is at "0.2.1", want 0.2.6`),
    the add failing with "ENOENT extracting tarball from" both packages
    with the copies gone;
  - mendDist before install's add only: every case red at the removal on
    each, the older versions back, or with the copies gone package.json
    still naming zcode after Remove;
  - one `bun update` a package: both copies-gone cases red on each, the
    add failing with "ENOENT extracting tarball from" both packages, as
    with no mendDist (each update alone fails on the other's gone
    tarball);
  - `bun add` of package.json's tarballs instead of `bun update`: every
    case red on 1.4.2 and 1.4.3, ok on 1.4.4;
  - the trigger as first written (the lock's tarball gone): the
    tarballs-kept case red on each, the older versions back (`is at
    "0.2.1", want 0.2.6`);
  - mendDist before package.json's tail is cut: in install, the tail
    case red on each at the add, "ENOENT extracting tarball from" both
    packages; in runBun, red on each at the removal, package.json still
    naming zcode after Remove.
- internal/plugin, -tags nogui, with Bun 1.4.4, the one magpie runs now:
  ok but TestPluginSOCKSProxy, red the same at origin/main 7a60e78c
  (#2207, open, filed for 1.4.3); TestFlowBigReplyProd and
  TestRenewOtherHost skip by their own condition.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build
  -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet
  and go build without the tag on linux: exit 1 (no GTK, WebKitGTK or
  fontconfig headers on this box).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 65 ok, internal/plugin among them, and 7 red, none in
  what this changes:
  - agent TestCodexDriftReached: #3398; TestInstalledVersion,
    TestHowInstalled, TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
    TestOmpDetectedWithPiDir: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSync and TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink: this box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - provider: "fatal error: close of synctest channel from outside
    bubble" in TestUnreadLoginsWriteErrorsKeepCredentials, main's CI
    red, #3632; the package's tests after it didn't run.
  - testenv TestProgram: this box's umask 077, #3640.

Not tried: Windows, where the reporter is (CI's Windows job runs none of
these tests: it compiles them and runs a named few); the reporter's own
plugins/ folder; the step that left their lock's packages at the
tarballs before while package.json and the workspaces moved on. On Linux
each Bun from 1.4.2 to 1.4.4 writes the packages at the tarball an add
names, so the test makes that state by hand.

Review (macOS arm64, go1.26.8, squashed into one commit per issue, on
origin/main 1cbdda25b), plus the class plugins#405 belongs to, a file
here written over a longer one without truncating:
- bun.lock: real Bun 1.4.4 reads the lock's first object and goes on
  past bytes after it (a lock with an older lock's packages appended:
  `bun install` checked 1 install, no changes, tail left as it was). So
  a tail doesn't stop Bun, but pruneDist's and mendDist's regexp read
  the whole file: the tail's older tarball was kept, and sent to bun
  update before every command. Both now read lockHead, the first
  object, braces and quotes inside strings skipped.
  TestDistLockTailIsntRead (bun update run for a lock whose object is
  behind, not for one whose tail is, nor one with "}\"{]" in a string)
  and a TestDistTarballTheLockNamesStays case (the tail's tarball
  goes). Broken by hand: lockHead returning the whole file turned the
  tail case and both tail subtests red ("0.2.1 kept", "bun update run:
  true"); escapes not skipped turned the braces-in-strings subtest red.
- package.json: every magpie write of it is temp+rename (mendPackageJSON
  since a9242eb68) but the first one install makes, an os.WriteFile;
  that goes through edit.WriteAtomic now. bun's own writes are bun's.
- TestDist* ok on Bun 1.4.2, 1.4.3 and 1.4.4; broken by hand with
  1.4.4: mendDist's calls removed turned
  TestDistLockBehindPackageJSONIsMended red, and the old pruneDist
  turned TestDistTarballTheLockNamesStays red ("taken out").
- internal/plugin whole package ok (144s); gofmt clean; vet ok for
  linux nogui, windows, darwin nogui.
Not tried: Windows, where both reports come from.
2026-10-27 15:57:59 +08:00

328 lines
11 KiB
Go

package plugin
import (
"bytes"
"context"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"time"
)
// The community repo's dist branch: every version of each
// @magpie-community package, packed by the repo's publish workflow
// (scripts/dist.mjs there) as soon as it is merged. npm can't take a new
// package's first version without an owner's 2FA (trusted publishing sets
// up only a package that exists), so a reviewed plugin used to wait,
// unmerged, for someone to publish it by hand. magpie asks npm first, as
// before, and turns here only for what npm doesn't give: a package or
// version npm doesn't have, or npm not answering. A tarball is installed
// only when its sha512 is the one index.json names.
// distBase is where the branch is read; moved by tests. Read through the
// 「国内镜像」 switch's jsDelivr copy first when it is on (source.DoFaithful).
var distBase = "https://raw.githubusercontent.com/magpie-community/plugins/dist"
// distScope is the scope of the packages the branch has.
const distScope = "@magpie-community/"
type distVersion struct {
File string `json:"file"` // tgz/<npm pack's file name>
Integrity string `json:"integrity"` // sha512-<base64>, as npm writes it
Manifest json.RawMessage `json:"manifest"` // the version's package.json
}
type distPackage struct {
Latest string `json:"latest"`
Readme string `json:"readme"`
Versions map[string]distVersion `json:"versions"`
}
type distIndex struct {
Packages map[string]distPackage `json:"packages"`
}
var (
distMu sync.Mutex
distIdx *distIndex
distAt time.Time // when distIdx was read, or last failed to be
distOK bool // whether the last read was distIdx's
distKeep = 10 * time.Minute
distWait = time.Minute // after a read failed, before asking again
)
// distFile is a file the index may name: one tarball under tgz/, nothing
// that leaves the branch or plugins/dist.
var distFile = regexp.MustCompile(`^tgz/[A-Za-z0-9._-]+\.tgz$`)
// distPkg is what the dist branch has of the package, nil when it has
// none, the package isn't one of its scope, or the branch can't be read.
func distPkg(ctx context.Context, name string) *distPackage {
if !strings.HasPrefix(name, distScope) || distBase == "" {
return nil
}
distMu.Lock()
defer distMu.Unlock()
stale := distIdx == nil || time.Since(distAt) > distKeep
if stale && (distOK || distAt.IsZero() || time.Since(distAt) > distWait) {
b, err := fetchJSONFaithful(ctx, distBase+"/index.json", 32<<20)
var idx distIndex
if err == nil && json.Unmarshal(b, &idx) == nil {
distIdx, distOK = &idx, true
} else {
// what was read last stays, until a read works
distOK = false
}
distAt = time.Now()
}
if distIdx == nil {
return nil
}
p, ok := distIdx.Packages[name]
if !ok {
return nil
}
return &p
}
// distInfo is the package's newest version on the dist branch, as npm's
// /latest would say it, and whether there is one.
func distInfo(ctx context.Context, name string) (NPM, bool) {
d := distPkg(ctx, name)
if d == nil {
return NPM{}, false
}
v, ok := d.Versions[d.Latest]
if !ok {
return NPM{}, false
}
var l npmLatest
if json.Unmarshal(v.Manifest, &l) != nil {
return NPM{}, false
}
info := npmOf(l)
info.Version = d.Latest
return info, true
}
// distWanted is the package and version an npm spec asks for, when the
// dist branch could serve it: a @magpie-community package, at a version
// or "latest" (not a range or another tag).
func distWanted(spec string) (name, version string, ok bool) {
if IsPath(spec) || IsGit(spec) {
return "", "", false
}
name = Name(spec)
if !strings.HasPrefix(name, distScope) || !pkgName.MatchString(name) {
return "", "", false
}
version = strings.TrimPrefix(strings.TrimPrefix(spec, name), "@")
if version == "" {
version = "latest"
}
if version != "latest" && !exactVersion.MatchString(version) {
return "", "", false
}
return name, version, true
}
var exactVersion = regexp.MustCompile(`^\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 {
d := distPkg(ctx, name)
if d == nil {
return fmt.Errorf("the community repo's dist branch has no %s, or can't be read", 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)
}
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)
}
b, err := fetchJSONFaithful(ctx, distBase+"/"+v.File, 64<<20)
if err != nil {
return 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)
}
dir := filepath.Join(Dir(), "dist")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
file := path.Base(v.File)
tmp, err := os.CreateTemp(dir, file+".*")
if err != nil {
return err
}
_, werr := tmp.Write(b)
if cerr := tmp.Close(); werr == nil {
werr = cerr
}
if werr == nil {
werr = os.Rename(tmp.Name(), filepath.Join(dir, file))
}
if werr != nil {
os.Remove(tmp.Name())
return werr
}
return bunAdd(ctx, bun, "./dist/"+file)
}
// pruneDist takes out the tarballs in plugins/dist that neither
// plugins/package.json nor bun.lock's packages has a package at: one an
// update from npm, or a newer one, took the place of. Bun installs a
// package from the tarball the lock's packages has it at, which
// package.json can have moved on from (#3622), so that one stays too.
// package.json is read as text, every mention counting: Bun 1.4.0 adds a
// tarball's package again instead of replacing it, and of the two keys
// encoding/json takes the second where Bun takes the first, so the tarball
// taken out was the one Bun installs from. A tarball only the lock's
// workspaces names (Bun 1.4.2 and 1.4.3 keep the one replaced there, and
// drop it on their next command) goes. installMu held. One it can't tell
// about (package.json, or a bun.lock that is there, unreadable) stays.
func pruneDist() {
pj, err := os.ReadFile(filepath.Join(Dir(), "package.json"))
if err != nil {
return
}
lock, err := os.ReadFile(filepath.Join(Dir(), "bun.lock"))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return
}
locked := map[string]bool{}
for _, m := range distLockedAt.FindAllSubmatch(lockHead(lock), -1) {
locked[string(m[2])] = true
}
ents, err := os.ReadDir(filepath.Join(Dir(), "dist"))
if err != nil {
return
}
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".tgz") && !locked[e.Name()] && !distNamed(pj, e.Name()) {
os.Remove(filepath.Join(Dir(), "dist", e.Name()))
}
}
}
// distNamed is whether package.json b names the tarball plugins/dist/file
// anywhere: "./dist/file" (the spec magpie hands Bun) or "file:dist/file".
func distNamed(b []byte, file string) bool {
return bytes.Contains(b, []byte("dist/"+file+`"`))
}
// distLockedAt is a package bun.lock's packages has at a tarball in
// plugins/dist, and that tarball: "<name>": ["<name>@./dist/<file>", …].
var distLockedAt = regexp.MustCompile(`\["((?:@[^"/@]+/)?[^"/@]+)@(?:file:)?(?:\./)?dist/([A-Za-z0-9._-]+\.tgz)"`)
// mendDist sends bun.lock back to package.json for the packages it has at a
// dist tarball package.json doesn't name, when package.json has them at one
// plugins/dist holds. Bun installs what the lock has, at every command that
// changes plugins/: from that tarball, which pruneDist keeps, or from its
// copy of it, it put the older version back, and with neither it failed
// every install, update and removal, of any plugin, with "ENOENT extracting
// tarball from <it>". Bun 1.4.4 keys its copies by the tarball's sha512, so
// it has none of those 1.4.2 and 1.4.3 made (#3622, gkd2323c on Windows,
// Bun 1.4.4: autoclaw, codearts and cloudflare-workers-ai were locked at
// tarballs pruneDist had taken, while package.json and the lock's
// workspaces had moved on). A `bun update` of them all at once resolves
// them from package.json again: `bun add` doesn't on Bun 1.4.2 and 1.4.3,
// which keep what the lock has, and with no copy a package left out fails
// the update with it. A package.json that names the lock's tarball too (Bun
// 1.4.0 names a package twice) isn't behind. Each mend is logged, as
// nothing here says why a lock falls behind. installMu held.
func mendDist(ctx context.Context, bun string) {
lock, err := os.ReadFile(filepath.Join(Dir(), "bun.lock"))
if err != nil {
return
}
b, err := os.ReadFile(filepath.Join(Dir(), "package.json"))
if err != nil {
return
}
var pj struct {
Dependencies map[string]string `json:"dependencies"`
}
if json.Unmarshal(b, &pj) != nil {
return
}
var stale []string
for _, m := range distLockedAt.FindAllSubmatch(lockHead(lock), -1) {
name, locked := string(m[1]), string(m[2])
file, ok := distSpec(pj.Dependencies[name])
if ok && file != locked && distHas(file) == nil && !distNamed(b, locked) && !slices.Contains(stale, name) {
stale = append(stale, name)
}
}
if len(stale) > 0 {
// 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))
} else {
log.Printf("plugins: bun.lock behind package.json for %s, sent back", strings.Join(stale, ", "))
}
}
}
// lockHead is bun.lock's first object, what Bun reads of it: Bun goes on
// past bytes left after it (tried on 1.4.4), which a shorter lock written
// over a longer one without truncating leaves, as package.json had
// (plugins#405). Read as packages, such a tail's old tarballs would be
// kept and sent to bun update at every command. A lock with no whole
// object is read as it is.
func lockHead(b []byte) []byte {
depth, inStr, esc := 0, false, false
for i, c := range b {
switch {
case esc:
esc = false
case inStr:
esc = c == '\\'
inStr = c != '"'
case c == '"':
inStr = true
case c == '{' || c == '[':
depth++
case c == '}' || c == ']':
depth--
if depth == 0 {
return b[:i+1]
}
}
}
return b
}
// distSpec is the tarball in plugins/dist a package.json dependency is at.
func distSpec(spec string) (string, bool) {
s := filepath.ToSlash(strings.TrimPrefix(spec, "file:"))
return strings.CutPrefix(strings.TrimPrefix(s, "./"), "dist/")
}
// distHas is os.Stat's answer for plugins/dist/file.
func distHas(file string) error {
_, err := os.Stat(filepath.Join(Dir(), "dist", file))
return err
}