package artifact
import (
"archive/zip"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
)
// SupportsPath reports whether path has a supported artifact archive
// extension.
func SupportsPath(path string) bool {
return supportedExt(strings.ToLower(filepath.Ext(path)))
}
func supportedExt(ext string) bool {
switch ext {
case ".jar", ".zip", ".pyz", ".mcdr":
return true
default:
return false
}
}
// ReadInfo extracts package metadata from an artifact file. For .jar/.zip
// files all readers are tried; for .pyz/.mcdr only the MCDR reader runs. An
// archive may carry descriptors for several ecosystems, so callers select the
// runtime identity with PreferredPackageInfos.
func ReadInfo(filePath string) ([]PackageInfo, error) {
return readInfo(filePath, nil)
}
func readInfo(filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
ext := strings.ToLower(filepath.Ext(filePath))
if !supportedExt(ext) {
return nil, fmt.Errorf("unsupported artifact format: %s", ext)
}
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("open artifact: %w", err)
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return nil, fmt.Errorf("stat artifact: %w", err)
}
zipReader, err := zip.NewReader(file, stat.Size())
if err != nil {
return nil, fmt.Errorf("read zip: %w", err)
}
var results []PackageInfo
if ext == ".pyz" || ext == ".mcdr" {
return new(mcdrReader).readWithInputs(zipReader, filePath, inputs)
}
for _, r := range readers {
var infos []PackageInfo
var err error
if reader, ok := r.(inputReader); ok && inputs != nil {
infos, err = reader.readWithInputs(zipReader, filePath, inputs)
} else {
infos, err = r.Read(zipReader, filePath)
}
if err != nil {
continue
}
results = append(results, infos...)
}
if jarEcosystemsConflict(results) {
return nil, fmt.Errorf(
"ambiguous artifact %q: packages span incompatible ecosystems",
filePath,
)
}
return results, nil
}
// PreferredPackageInfos keeps the identities a runtime loads. An unspecified
// runtime keeps the loader identity that loads every other descriptor present,
// such as Quilt for an artifact that also carries fabric.mod.json.
func PreferredPackageInfos(
infos []PackageInfo,
runtime catalog.Ecosystem,
) []PackageInfo {
if len(infos) <= 1 {
return infos
}
if runtime == catalog.EcosystemUnspecified {
runtime = loaderIdentity(infos)
if runtime == catalog.EcosystemUnspecified {
return infos
}
}
for _, ecosystem := range runtime.Loads() {
selected := slices.DeleteFunc(
append([]PackageInfo(nil), infos...),
func(info PackageInfo) bool {
return info.Ref.Ecosystem != ecosystem
},
)
if len(selected) > 0 {
return selected
}
}
return infos
}
// loaderIdentity returns the ecosystem whose Loads list covers every ecosystem
// the artifact declares, or unspecified when none does.
func loaderIdentity(infos []PackageInfo) catalog.Ecosystem {
present := make([]catalog.Ecosystem, 0, len(infos))
for _, info := range infos {
if !slices.Contains(present, info.Ref.Ecosystem) {
present = append(present, info.Ref.Ecosystem)
}
}
if len(present) < 2 {
return catalog.EcosystemUnspecified
}
var candidate catalog.Ecosystem
for _, ecosystem := range present {
covers := true
for _, other := range present {
if other != ecosystem && !ecosystem.Satisfy(other) {
covers = false
break
}
}
if !covers {
continue
}
if candidate != catalog.EcosystemUnspecified {
return catalog.EcosystemUnspecified
}
candidate = ecosystem
}
return candidate
}
// jarEcosystemsConflict returns true when the detected artifacts span two or
// more ecosystem families that cannot coexist in a single deployable JAR.
func jarEcosystemsConflict(infos []PackageInfo) bool {
families := make(map[catalog.Family]struct{}, len(infos))
for _, info := range infos {
family := info.Ref.Ecosystem.Family()
if family == catalog.FamilyNone {
continue
}
families[family] = struct{}{}
}
return len(families) > 1
}
package artifact
import (
"context"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/mclucy/lucy/catalog"
)
// descriptorInputs memoizes immutable parsed root entries while leaving
// inventory and loader projections independent.
type descriptorInputs struct {
entries sync.Map
}
func descriptorInput[T any](inputs *descriptorInputs, key string, parse func() (T, error)) (T, error) {
if inputs == nil {
return parse()
}
if saved, ok := inputs.entries.Load(key); ok {
return saved.(func() (T, error))()
}
saved, _ := inputs.entries.LoadOrStore(key, sync.OnceValues(parse))
return saved.(func() (T, error))()
}
// Analyses retains evidence for the files observed in one operation. It is
// not a replacement for verifying bytes at an ownership or store boundary.
// The zero value is ready for use.
type Analyses struct {
files sync.Map // clean path -> *Analysis
}
func (a *Analyses) File(path string) *Analysis {
path = filepath.Clean(path)
if a != nil {
if file, ok := a.files.Load(path); ok {
return file.(*Analysis)
}
}
file := &Analysis{path: path}
file.initial = sync.OnceValues(func() (os.FileInfo, error) { return os.Stat(path) })
file.info = file.observe(func() ([]PackageInfo, error) { return readInfo(path, &file.inputs) })
file.hash = file.observe(file.readHashes)
file.murmur = file.observe(File{Path: path}.MurmurHash)
if a != nil {
actual, _ := a.files.LoadOrStore(path, file)
return actual.(*Analysis)
}
return file
}
// Analysis holds local package evidence. Returned descriptor values are
// read-only. Native views depend on the loader and Minecraft version.
type Analysis struct {
path string
initial func() (os.FileInfo, error)
info func() ([]PackageInfo, error)
hash func() (analysisHashes, error)
murmur func() (uint32, error)
views sync.Map // descriptorViewKey -> func() (DescriptorView, error)
inputs descriptorInputs
}
type descriptorViewKey struct {
loader catalog.Ecosystem
minecraft string
}
// DescriptorView contains the server-visible modules and the side evidence
// from the same native descriptor traversal.
type DescriptorView struct {
Modules []catalog.DescriptorModule
ClientOnly bool
Known bool
}
func (a *Analysis) Info() ([]PackageInfo, error) { return a.info() }
func (a *Analysis) Descriptor(ctx context.Context, loader catalog.Ecosystem, minecraft string) (DescriptorView, error) {
if err := ctx.Err(); err != nil {
return DescriptorView{}, err
}
key := descriptorViewKey{loader: loader, minecraft: minecraft}
if view, ok := a.views.Load(key); ok {
return view.(func() (DescriptorView, error))()
}
read := a.observe(func() (DescriptorView, error) {
modules, err := readModulesFor(ctx, a.path, loader, minecraft, &a.inputs)
if err != nil {
return DescriptorView{}, err
}
clientOnly, known := descriptorSideResult(modules)
return DescriptorView{Modules: normalizeModules(modules), ClientOnly: clientOnly, Known: known}, nil
})
view, _ := a.views.LoadOrStore(key, read)
return view.(func() (DescriptorView, error))()
}
// Observe one filesystem version across the reads that contribute evidence.
// A cached result still needs a version check before it can be reused.
func (a *Analysis) observe[T any](read func() (T, error)) func() (T, error) {
var once sync.Once
var value T
var readErr error
return func() (T, error) {
firstRead := false
once.Do(func() {
firstRead = true
if readErr = a.checkFile(); readErr != nil {
return
}
value, readErr = read()
if readErr == nil {
readErr = a.checkFile()
}
})
var zero T
if readErr != nil {
return zero, readErr
}
if !firstRead {
if err := a.checkFile(); err != nil {
return zero, err
}
}
return value, nil
}
}
func (a *Analysis) checkFile() error {
baseline, err := a.initial()
if err != nil {
return err
}
current, err := os.Stat(a.path)
if err != nil {
return err
}
if !os.SameFile(baseline, current) || !current.Mode().IsRegular() || baseline.Mode() != current.Mode() ||
baseline.Size() != current.Size() || !baseline.ModTime().Equal(current.ModTime()) {
return fmt.Errorf("artifact changed during analysis: %s", a.path)
}
return nil
}
type analysisHashes struct {
sha1 [sha1.Size]byte
sha256 [sha256.Size]byte
}
func (a *Analysis) SHA1() ([sha1.Size]byte, error) {
hashes, err := a.hash()
return hashes.sha1, err
}
func (a *Analysis) SHA256() (string, error) {
hashes, err := a.hash()
if err != nil {
return "", err
}
return hex.EncodeToString(hashes.sha256[:]), nil
}
func (a *Analysis) MurmurHash() (uint32, error) { return a.murmur() }
func (a *Analysis) readHashes() (analysisHashes, error) {
file, err := os.Open(a.path)
if err != nil {
return analysisHashes{}, fmt.Errorf("open artifact: %w", err)
}
defer file.Close()
one, two := sha1.New(), sha256.New()
if _, err := io.Copy(io.MultiWriter(one, two), file); err != nil {
return analysisHashes{}, fmt.Errorf("hash artifact: %w", err)
}
var result analysisHashes
one.Sum(result.sha1[:0])
two.Sum(result.sha256[:0])
return result, nil
}
package artifact
import (
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/version"
)
// decodedModule is one descriptor module with both views of one parse. Module
// feeds the resolver, and the remaining fields feed ReadInfo.
type decodedModule struct {
Module catalog.DescriptorModule
// PackageEcosystem is the identity ReadInfo reports. Empty means the
// module ecosystem.
PackageEcosystem catalog.Ecosystem
Metadata catalog.Metadata
Compatibility Compatibility
// PackageVersion overrides the version ReadInfo reports. Empty keeps the
// module version.
PackageVersion version.Version
// PackageDependencies replaces the dependencies ReadInfo derives from
// Module. A non-nil empty slice means the descriptor declares none.
PackageDependencies []Dependency
// Origins maps a module dependency ID to its reader origin.
Origins map[string]catalog.DependencyOrigin
// PackageNames maps a module dependency ID to the identity ReadInfo
// reports.
PackageNames map[string]string
// SkipPackage keeps the module in the resolver inventory while ReadInfo
// omits it.
SkipPackage bool
}
// decodedDescriptor is one descriptor file together with the archive entries
// that carry further descriptors.
type decodedDescriptor struct {
Modules []decodedModule
Nested []string
// SkipNested marks a descriptor the loader excludes from the server, which
// stops its bundled archives from being read.
SkipNested bool
}
func (d decodedDescriptor) catalogModules() []catalog.DescriptorModule {
modules := make([]catalog.DescriptorModule, 0, len(d.Modules))
for _, decoded := range d.Modules {
modules = append(modules, decoded.Module)
}
return modules
}
// packageInfoFromDecoded projects one decoded module into the reader view.
func packageInfoFromDecoded(
filePath string,
decoded decodedModule,
) (PackageInfo, error) {
ecosystem := decoded.PackageEcosystem
if ecosystem == "" {
ecosystem = decoded.Module.Ecosystem
}
dependencies := decoded.PackageDependencies
if dependencies == nil {
var err error
dependencies, err = packageDependenciesFromModule(decoded, ecosystem)
if err != nil {
return PackageInfo{}, err
}
}
packageVersion := decoded.PackageVersion
if packageVersion == "" {
packageVersion = decoded.Module.Version
}
return PackageInfo{
Ref: catalog.VersionedRef{
Ref: catalog.Ref{
Name: input.ToProjectName(decoded.Module.ID),
Provider: catalog.ProviderUnknown,
},
Ecosystem: ecosystem,
Version: packageVersion,
},
FilePath: filePath,
Dependencies: dependencies,
Metadata: decoded.Metadata,
Compatibility: decoded.Compatibility,
}, nil
}
func packageDependenciesFromModule(
decoded decodedModule,
ecosystem catalog.Ecosystem,
) ([]Dependency, error) {
dependencies := make(
[]Dependency,
0,
len(decoded.Module.Dependencies),
)
for _, dependency := range decoded.Module.Dependencies {
if dependency.Kind == catalog.DependencyKindPython {
continue
}
constraint, err := dependencyExpr(
dependency,
decoded.Module.VersionDialect,
)
if err != nil {
return nil, err
}
switch dependency.Kind {
case catalog.DependencyKindIncompatible,
catalog.DependencyKindConflict:
constraint = constraint.Negate()
}
name := dependency.ID
if mapped, ok := decoded.PackageNames[dependency.ID]; ok {
name = mapped
}
origin := catalog.DependencyRegular
if mapped, ok := decoded.Origins[dependency.ID]; ok {
origin = mapped
}
dependencies = append(dependencies, Dependency{
Ref: catalog.VersionedRef{
Ref: catalog.Ref{
Name: input.ToProjectName(name),
Provider: catalog.ProviderUnknown,
},
Ecosystem: ecosystem,
},
Constraint: constraint,
Mandatory: dependency.Kind == catalog.DependencyKindRequired,
Kind: dependency.Kind,
Origin: origin,
})
}
return dependencies, nil
}
// dependencyExpr flattens a descriptor dependency node into the expression the
// reader reports. Any-of alternatives are disjunctive and all-of nodes are
// conjunctive.
func dependencyExpr(
dependency catalog.DescriptorDependency,
dialect version.Dialect,
) (version.Expr, error) {
expr, err := version.ParseConstraint(dependency.Constraint, dialect)
if err != nil {
return nil, err
}
for _, condition := range dependency.AllOf {
conjunct, err := dependencyExpr(condition, dialect)
if err != nil {
return nil, err
}
expr = conjunctionExpr(expr, conjunct)
}
for _, alternative := range dependency.AnyOf {
disjunct, err := dependencyExpr(alternative, dialect)
if err != nil {
return nil, err
}
if len(disjunct) == 0 {
return nil, nil
}
expr = append(expr, disjunct...)
}
return expr, nil
}
// conjunctionExpr multiplies two disjunctive normal form expressions. An empty
// expression imposes no constraint.
func conjunctionExpr(left, right version.Expr) version.Expr {
if len(left) == 0 {
return right
}
if len(right) == 0 {
return left
}
result := make(version.Expr, 0, len(left)*len(right))
for _, leftClause := range left {
for _, rightClause := range right {
clause := make(
[]version.SubExpr,
0,
len(leftClause)+len(rightClause),
)
clause = append(clause, leftClause...)
clause = append(clause, rightClause...)
result = append(result, clause)
}
}
return result
}
func packageInfosFromDecoded(
filePath string,
decoded *decodedDescriptor,
) ([]PackageInfo, error) {
if decoded == nil {
return nil, nil
}
infos := make([]PackageInfo, 0, len(decoded.Modules))
for _, module := range decoded.Modules {
if module.SkipPackage {
continue
}
info, err := packageInfoFromDecoded(filePath, module)
if err != nil {
return nil, err
}
infos = append(infos, info)
}
return infos, nil
}
package artifact
import (
"encoding/json/v2"
"fmt"
"io"
)
// readDescriptorJSON decodes a descriptor the way its loader does. Published
// descriptors sometimes embed raw control characters in string values; strict
// JSON rejects them, but the loader accepts the file, so identification must
// not fail on them.
func readDescriptorJSON(reader io.Reader, value any) error {
data, err := io.ReadAll(reader)
if err != nil {
return err
}
return unmarshalDescriptor(data, value)
}
// unmarshalDescriptor decodes descriptor bytes with the same tolerance.
func unmarshalDescriptor(raw []byte, value any) error {
return json.Unmarshal(escapeJSONControlCharacters(raw), value)
}
// escapeJSONControlCharacters rewrites raw control characters inside JSON
// string literals as escape sequences. Bytes outside strings and escaped
// characters are copied unchanged.
func escapeJSONControlCharacters(raw []byte) []byte {
escaped := make([]byte, 0, len(raw))
inString := false
afterBackslash := false
for _, b := range raw {
if !inString {
if b == '"' {
inString = true
}
escaped = append(escaped, b)
continue
}
if afterBackslash {
afterBackslash = false
escaped = append(escaped, b)
continue
}
switch b {
case '\\':
afterBackslash = true
escaped = append(escaped, b)
case '"':
inString = false
escaped = append(escaped, b)
case '\n':
escaped = append(escaped, '\\', 'n')
case '\r':
escaped = append(escaped, '\\', 'r')
case '\t':
escaped = append(escaped, '\\', 't')
default:
if b < 0x20 {
escaped = append(escaped, fmt.Sprintf("\\u%04x", b)...)
continue
}
escaped = append(escaped, b)
}
}
return escaped
}
package artifact
import (
"crypto/sha1"
"fmt"
"io"
"os"
)
// File is an artifact file on disk. It implements upstream.ArtifactFingerprint.
type File struct {
Path string
}
func (f File) SHA1() ([sha1.Size]byte, error) {
file, err := os.Open(f.Path)
if err != nil {
return [sha1.Size]byte{}, fmt.Errorf("open artifact: %w", err)
}
defer file.Close()
hasher := sha1.New()
if _, err := io.Copy(hasher, file); err != nil {
return [sha1.Size]byte{}, fmt.Errorf("hash artifact: %w", err)
}
return [sha1.Size]byte(hasher.Sum(nil)), nil
}
// MurmurHash computes the CurseForge MurmurHash2 fingerprint of the file
// at Path; see MurmurHashBytes.
func (f File) MurmurHash() (uint32, error) {
data, err := os.ReadFile(f.Path)
if err != nil {
return 0, fmt.Errorf("read artifact: %w", err)
}
return MurmurHashBytes(data), nil
}
// MurmurHashBytes computes CurseForge's custom MurmurHash2 fingerprint.
// It strips whitespace bytes (0x09, 0x0A, 0x0D, 0x20) before mixing.
func MurmurHashBytes(data []byte) uint32 {
const multiplex uint32 = 1540483477
normalizedLen := uint32(0)
for _, value := range data {
if !isCurseForgeWhitespace(value) {
normalizedLen++
}
}
hash := uint32(1) ^ normalizedLen
var pending uint32
var pendingBits uint32
for _, value := range data {
if isCurseForgeWhitespace(value) {
continue
}
pending |= uint32(value) << pendingBits
pendingBits += 8
if pendingBits == 32 {
word := pending * multiplex
word = (word ^ word>>24) * multiplex
hash = hash*multiplex ^ word
pending = 0
pendingBits = 0
}
}
if pendingBits > 0 {
hash = (hash ^ pending) * multiplex
}
hash = (hash ^ hash>>13) * multiplex
return hash ^ hash>>15
}
func isCurseForgeWhitespace(b byte) bool {
return b == 0x09 || b == 0x0A || b == 0x0D || b == 0x20
}
package artifact
import (
"archive/zip"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
// InstallerKind identifies the installer tool that produces an archive.
type InstallerKind string
const (
InstallerForge InstallerKind = "forge-installer"
InstallerNeoForge InstallerKind = "neoforge-installer"
InstallerFabric InstallerKind = "fabric-installer"
InstallerQuilt InstallerKind = "quilt-installer"
)
// Installer is the declaration an installer archive carries about itself.
// LoaderVersion and Minecraft are empty for generic installers that do not
// declare a target.
type Installer struct {
Kind InstallerKind
Product server.Product
LoaderVersion version.Version
Minecraft version.Version
FilePath string
}
const (
installerProfilePath = "install_profile.json"
installerVersionPath = "version.json"
fabricInstallerMainClass = "net.fabricmc.installer.Main"
quiltInstallerMainClass = "org.quiltmc.installer.Main"
fabricInstallerMainEntry = "net/fabricmc/installer/Main.class"
quiltInstallerMainEntry = "org/quiltmc/installer/Main.class"
)
// ReadInstaller identifies a supported installer archive from its contents.
//
// The archive name and extension are not evidence. A caller that scans a
// directory can log an error and continue: a non-archive or an archive without
// installer metadata yields no error.
func ReadInstaller(filePath string) (inst Installer, found bool, err error) {
archive, err := zip.OpenReader(filePath)
if err != nil {
if errors.Is(err, zip.ErrFormat) {
return Installer{}, false, nil
}
return Installer{}, false, fmt.Errorf("open installer archive: %w", err)
}
defer archive.Close()
raw, err := readZipEntryBytes(&archive.Reader, installerProfilePath)
if err != nil {
return Installer{}, false, fmt.Errorf("read installer profile: %w", err)
}
if raw != nil {
return readInstallerProfile(&archive.Reader, raw, filePath)
}
attributes, err := readManifestAttributes(
&archive.Reader,
fsutil.MaxZipEntryBytes,
)
if err != nil {
return Installer{}, false, fmt.Errorf("read installer manifest: %w", err)
}
kind, product, identified := installerManifestKind(
&archive.Reader,
attributes,
)
if !identified {
return Installer{}, false, nil
}
return Installer{Kind: kind, Product: product, FilePath: filePath}, true, nil
}
// installerProfile is an install_profile.json declaration. Spec 0 and spec 1
// keep the identifying fields at the top level. Installers that predate the
// spec nest the same fields under install.
type installerProfile struct {
Spec int `json:"spec"`
Profile string `json:"profile"`
Version string `json:"version"`
Minecraft string `json:"minecraft"`
JSON string `json:"json"`
Path string `json:"path"`
Install installerLegacyInstall `json:"install"`
}
// installerLegacyInstall is the declaration that installers before the install
// profile spec write. Upstream reads these fields in place of the top-level
// ones.
type installerLegacyInstall struct {
ProfileName string `json:"profileName"`
Version string `json:"version"`
Minecraft string `json:"minecraft"`
JSON string `json:"json"`
Path string `json:"path"`
}
// installerDeclaration is the identifying part of an install profile with
// both declaration shapes unified.
type installerDeclaration struct {
Product string
Version string
Minecraft string
VersionJSON string
Path string
legacy bool
}
// declaration unifies the top-level declaration and the legacy nested one.
func (profile installerProfile) declaration() installerDeclaration {
if profile.Install.ProfileName != "" {
return installerDeclaration{
Product: profile.Install.ProfileName,
Version: profile.Install.Version,
Minecraft: profile.Install.Minecraft,
VersionJSON: profile.Install.JSON,
Path: profile.Install.Path,
legacy: true,
}
}
return installerDeclaration{
Product: profile.Profile,
Version: profile.Version,
Minecraft: profile.Minecraft,
VersionJSON: profile.JSON,
Path: profile.Path,
}
}
// installerVersionProfile is the launcher profile that an install profile
// names. Only the fields that identify the target are relevant.
type installerVersionProfile struct {
InheritsFrom string `json:"inheritsFrom"`
Arguments struct {
Game []jsontext.Value `json:"game"`
} `json:"arguments"`
}
func readInstallerProfile(
zipRdr *zip.Reader,
raw []byte,
filePath string,
) (Installer, bool, error) {
var profile installerProfile
if err := json.Unmarshal(raw, &profile); err != nil {
return Installer{}, false, fmt.Errorf("decode installer profile: %w", err)
}
declaration := profile.declaration()
// Forge uses spec 1 for the current declaration and spec 0 for the one
// before it. A legacy declaration carries no spec.
if !declaration.legacy && profile.Spec != 0 && profile.Spec != 1 {
return Installer{}, false, nil
}
product, ok := installerProduct(declaration.Product)
if !ok {
return Installer{}, false, nil
}
minecraft := declaration.Minecraft
versionProfile, err := readInstallerVersionProfile(
zipRdr,
declaration.VersionJSON,
)
if err != nil {
return Installer{}, false, err
}
if minecraft == "" && versionProfile != nil {
minecraft = versionProfile.InheritsFrom
}
loaderVersion := installerLoaderVersion(
declaration,
versionProfile,
minecraft,
product,
)
kind := installerKind(product)
return Installer{
Kind: kind,
Product: product,
LoaderVersion: loaderVersion,
Minecraft: version.Version(minecraft),
FilePath: filePath,
}, true, nil
}
func installerProduct(name string) (server.Product, bool) {
switch {
case strings.EqualFold(name, "neoforge"):
return server.ProductNeoForge, true
case strings.EqualFold(name, "forge"):
return server.ProductForge, true
default:
return server.ProductUnknown, false
}
}
func installerKind(product server.Product) InstallerKind {
switch product {
case server.ProductForge:
return InstallerForge
case server.ProductNeoForge:
return InstallerNeoForge
case server.ProductFabric:
return InstallerFabric
case server.ProductQuilt:
return InstallerQuilt
default:
return ""
}
}
// readInstallerVersionProfile reads the launcher profile that the install
// profile names. A missing entry is not an error because legacy profiles keep
// the same data in install_profile.json.
func readInstallerVersionProfile(
zipRdr *zip.Reader,
name string,
) (*installerVersionProfile, error) {
if name == "" {
name = installerVersionPath
}
name = strings.TrimPrefix(name, "/")
raw, err := readZipEntryBytes(zipRdr, name)
if err != nil {
return nil, fmt.Errorf("read installer version profile: %w", err)
}
if raw == nil {
return nil, nil
}
var profile installerVersionProfile
if err := json.Unmarshal(raw, &profile); err != nil {
return nil, fmt.Errorf("decode installer version profile: %w", err)
}
return &profile, nil
}
// installerLoaderVersion resolves the loader version in declaration order:
// launch arguments, the declared profile version, then Maven coordinates. A
// source that names no concrete version does not stop the search.
func installerLoaderVersion(
declaration installerDeclaration,
versionProfile *installerVersionProfile,
minecraft string,
product server.Product,
) version.Version {
candidates := []string{
installerArgumentValue(versionProfile, installerLoaderArgument(product)),
installerVersionFromDeclaration(declaration.Version, product),
installerVersionFromCoordinates(declaration.Path, minecraft, product),
}
for _, candidate := range candidates {
if concrete := concreteInstallerVersion(candidate); concrete != "" {
return concrete
}
}
return ""
}
func installerLoaderArgument(product server.Product) string {
switch product {
case server.ProductNeoForge:
return "--fml.neoForgeVersion"
case server.ProductForge:
return "--fml.forgeVersion"
default:
return ""
}
}
// installerArgumentValue returns the token after name. The launcher stores
// each argument as a separate string, and an object argument carries no
// loader version, so this scan ignores tokens that are not strings.
func installerArgumentValue(
profile *installerVersionProfile,
name string,
) string {
if profile == nil || name == "" {
return ""
}
tokens := make([]string, 0, len(profile.Arguments.Game))
for _, raw := range profile.Arguments.Game {
var token string
if err := json.Unmarshal(raw, &token); err != nil {
continue
}
tokens = append(tokens, token)
}
for index := 0; index+1 < len(tokens); index++ {
if tokens[index] == name {
return tokens[index+1]
}
}
return ""
}
// installerVersionFromDeclaration parses the loader version from the id that
// the installer declares. NeoForge ids are neoforge-<v>. Modern Forge ids are
// <minecraft>-forge-<v>. Legacy ids use the path field instead.
func installerVersionFromDeclaration(
declared string,
product server.Product,
) string {
declared = strings.TrimSpace(declared)
switch product {
case server.ProductNeoForge:
const prefix = "neoforge-"
if len(declared) > len(prefix) &&
strings.EqualFold(declared[:len(prefix)], prefix) {
return declared[len(prefix):]
}
case server.ProductForge:
const infix = "-forge-"
if index := strings.Index(strings.ToLower(declared), infix); index >= 0 {
return declared[index+len(infix):]
}
}
return ""
}
// installerVersionFromCoordinates parses the loader version from a Maven
// coordinate in the path field: group:artifact:version[:classifier]. Forge
// writes the version as <minecraft>-<loader>; NeoForge writes the loader
// version alone.
func installerVersionFromCoordinates(
coordinates string,
minecraft string,
product server.Product,
) string {
parts := strings.Split(coordinates, ":")
if len(parts) < 3 {
return ""
}
versionPart := parts[2]
if len(parts) > 3 {
versionPart = parts[len(parts)-2]
}
if minecraft != "" {
versionPart = strings.TrimPrefix(versionPart, minecraft+"-")
} else if product == server.ProductForge {
if index := strings.IndexByte(versionPart, '-'); index >= 0 {
versionPart = versionPart[index+1:]
}
}
return versionPart
}
// concreteInstallerVersion rejects values that name no exact version.
func concreteInstallerVersion(raw string) version.Version {
concrete := version.Version(strings.TrimSpace(raw))
if concrete == "" || concrete.IsInvalid() {
return ""
}
return concrete
}
// installerManifestKind identifies a generic Fabric or Quilt installer. Both
// the main class and its class file must match, so a mod that only copies the
// manifest attribute does not qualify.
func installerManifestKind(
zipRdr *zip.Reader,
attributes map[string]string,
) (InstallerKind, server.Product, bool) {
switch mainClass := manifestAttribute(attributes, "Main-Class"); mainClass {
case fabricInstallerMainClass:
if archiveContainsEntry(zipRdr, fabricInstallerMainEntry) {
return InstallerFabric, server.ProductFabric, true
}
case quiltInstallerMainClass:
if archiveContainsEntry(zipRdr, quiltInstallerMainEntry) {
return InstallerQuilt, server.ProductQuilt, true
}
}
return "", server.ProductUnknown, false
}
func archiveContainsEntry(zipRdr *zip.Reader, name string) bool {
for _, file := range zipRdr.File {
if file.Name == name {
return true
}
}
return false
}
package artifact
import (
"archive/zip"
"bytes"
"encoding/json/v2"
"fmt"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/version"
)
const jarjarMetadataPath = "META-INF/jarjar/metadata.json"
// readJarjarMetadata parses the JarJar metadata shared by Forge and NeoForge.
// Module analysis must reject malformed metadata, because the loaders refuse
// the archive and its bundled identities never load. A missing file is valid.
func readJarjarMetadata(zipRdr *zip.Reader) (*fileschema.FileJarjar, error) {
raw, err := readZipEntryBytes(zipRdr, jarjarMetadataPath)
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
var meta fileschema.FileJarjar
if err := json.Unmarshal(raw, &meta); err != nil {
return nil, fmt.Errorf("decode JarJar metadata: %w", err)
}
return &meta, nil
}
// jarjarNestedPaths lists the archives JarJar adds to the loader's module
// layer.
func jarjarNestedPaths(meta *fileschema.FileJarjar) []string {
if meta == nil {
return nil
}
paths := make([]string, 0, len(meta.Jars))
for _, jar := range meta.Jars {
paths = append(paths, jar.Path)
}
return paths
}
// jarjarEmbeddedModIDs reads the module identities of bundled archives.
// readDescriptor decodes the nested archive with the loader's precedence.
func jarjarEmbeddedModIDs(
zipRdr *zip.Reader,
meta *fileschema.FileJarjar,
readDescriptor func(*zip.Reader) (*decodedModsToml, error),
) map[string]bool {
if meta == nil {
return nil
}
byName := make(map[string]*zip.File, len(zipRdr.File))
for _, file := range zipRdr.File {
byName[file.Name] = file
}
modIDs := make(map[string]bool)
for _, entry := range meta.Jars {
file, ok := byName[entry.Path]
if !ok {
continue
}
reader, err := file.Open()
if err != nil {
continue
}
jarBytes, err := fsutil.CopyBytes(reader, fsutil.MaxZipEntryBytes)
_ = reader.Close()
if err != nil {
continue
}
nested, err := zip.NewReader(
bytes.NewReader(jarBytes),
int64(len(jarBytes)),
)
if err != nil {
continue
}
descriptor, err := readDescriptor(nested)
if err != nil || descriptor == nil {
continue
}
for _, mod := range descriptor.Identifier.Mods {
if mod.ModID != "" {
modIDs[mod.ModID] = true
}
}
}
return modIDs
}
// jarjarEmbeddedDependencies lists the Maven coordinates JarJar resolves.
func jarjarEmbeddedDependencies(
meta *fileschema.FileJarjar,
) ([]Dependency, error) {
if meta == nil {
return nil, nil
}
dependencies := make([]Dependency, 0, len(meta.Jars))
for _, entry := range meta.Jars {
constraint, err := version.ParseConstraint(
entry.Version.Range,
version.DialectMaven,
)
if err != nil {
return nil, err
}
dependencies = append(
dependencies,
Dependency{
Ref: catalog.VersionedRef{
Ref: catalog.Ref{
Name: input.ToProjectName(
entry.Identifier.Group + ":" +
entry.Identifier.Artifact,
),
Provider: catalog.ProviderUnknown,
},
Ecosystem: catalog.EcosystemUnspecified,
},
Constraint: constraint,
Mandatory: true,
Origin: catalog.DependencyEmbedded,
},
)
}
return dependencies, nil
}
package artifact
import (
"archive/zip"
"bytes"
"strings"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/version"
)
const manifestPath = "META-INF/MANIFEST.MF"
// readManifestAttributes parses the main attributes of the archive manifest.
// Attribute names are case-insensitive, so the returned map is keyed by
// lowercased names. An attribute value wraps onto following lines that start
// with one space; the space is removed and the parts join without a separator,
// as the JAR specification defines.
func readManifestAttributes(
zipRdr *zip.Reader,
maxBytes int64,
) (map[string]string, error) {
raw, found, err := fsutil.ReadZipEntry(zipRdr, manifestPath, maxBytes)
if err != nil {
return nil, err
}
if !found {
return map[string]string{}, nil
}
return manifestAttributes(raw), nil
}
func manifestAttributes(manifest []byte) map[string]string {
attributes := map[string]string{}
key := ""
for len(manifest) > 0 {
line := manifest
if end := bytes.IndexAny(manifest, "\r\n"); end >= 0 {
line = manifest[:end]
manifest = manifest[end+1:]
if len(line) == 0 {
// The main section ends at the first blank line.
break
}
if len(manifest) > 0 && manifest[0] == '\n' {
manifest = manifest[1:]
}
} else {
manifest = nil
}
if strings.HasPrefix(string(line), " ") {
if key != "" {
attributes[key] += string(line[1:])
}
continue
}
name, value, found := bytes.Cut(line, []byte(": "))
if !found {
name, value, found = bytes.Cut(line, []byte(":"))
if !found {
key = ""
continue
}
}
key = strings.ToLower(string(name))
attributes[key] = strings.TrimPrefix(string(value), " ")
}
return attributes
}
// manifestAttribute returns the value of a main manifest attribute. Names are
// case-insensitive, so the lookup normalizes the requested name.
func manifestAttribute(attributes map[string]string, name string) string {
return attributes[strings.ToLower(name)]
}
// readManifestImplementationVersion returns Unknown for a missing manifest or
// attribute. Read failures remain distinguishable for callers that reject them.
func readManifestImplementationVersion(
zipRdr *zip.Reader,
maxBytes int64,
) (version.Version, error) {
raw, found, err := fsutil.ReadZipEntry(zipRdr, manifestPath, maxBytes)
if err != nil {
return version.Unknown, err
}
if !found {
return version.Unknown, nil
}
return manifestImplementationVersion(raw), nil
}
func manifestImplementationVersion(manifest []byte) version.Version {
const versionField = "Implementation-Version: "
for len(manifest) > 0 {
line := manifest
if end := bytes.IndexAny(manifest, "\r\n"); end >= 0 {
line, manifest = manifest[:end], manifest[end+1:]
} else {
manifest = nil
}
if value, found := bytes.CutPrefix(line, []byte(versionField)); found {
return version.Version(value)
}
}
return version.Unknown
}
package artifact
import (
"archive/zip"
"bytes"
"context"
"fmt"
"os/exec"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fsutil"
)
// ReadModules keeps each descriptor identity and nested container location
// intact. Without a server version it reads the descriptor an inventory reader
// reports; callers that select for a server use ReadModulesFor.
func ReadModules(ctx context.Context, filename string, loader catalog.Ecosystem) ([]catalog.DescriptorModule, error) {
return ReadModulesFor(ctx, filename, loader, "")
}
// ReadModulesFor keeps each descriptor identity and nested container location
// intact, selecting version-dependent descriptors for minecraft.
func ReadModulesFor(
ctx context.Context,
filename string,
loader catalog.Ecosystem,
minecraft string,
) ([]catalog.DescriptorModule, error) {
modules, err := readModulesFor(ctx, filename, loader, minecraft, nil)
if err != nil {
return nil, err
}
return normalizeModules(modules), nil
}
// descriptorSideResult distinguishes an unknown side from a descriptor that
// permits the server to load the artifact.
func descriptorSideResult(modules []catalog.DescriptorModule) (clientOnly, known bool) {
if len(modules) == 0 {
return false, false
}
for _, module := range modules {
if module.Side != catalog.SideClient {
// Forge and NeoForge descriptors carry no mod-level side, and a
// Fabric or Quilt parent without an environment stays server-side.
return false, true
}
}
return true, true
}
func readModulesFor(
ctx context.Context,
filename string,
loader catalog.Ecosystem,
minecraft string,
inputs *descriptorInputs,
) ([]catalog.DescriptorModule, error) {
if strings.EqualFold(filepath.Ext(filename), ".py") {
return inspectPython(ctx, filename)
}
z, err := zip.OpenReader(filename)
if err != nil {
// Content-addressed storage names an object by its digest, not the
// artifact's filename. An MCDR plugin source is not an archive, so
// fall back to its static metadata when the extension is absent.
if loader == catalog.EcosystemMCDR {
if modules, pythonErr := inspectPython(ctx, filename); pythonErr == nil {
return modules, nil
}
}
return nil, err
}
defer z.Close()
return inspectArchive(&z.Reader, loader, "", 0, minecraft, inputs)
}
// normalizeModules makes descriptor order independent of map iteration. The
// lock and plan hashes depend on this order.
func normalizeModules(modules []catalog.DescriptorModule) []catalog.DescriptorModule {
modules = applyClientOnlyIdentities(modules)
for i := range modules {
slices.Sort(modules[i].Provides)
slices.Sort(modules[i].ClientOnly)
normalizeDescriptorDependencies(modules[i].Dependencies)
}
sort.Slice(modules, func(i, j int) bool {
return compareDescriptorModule(modules[i], modules[j]) < 0
})
return modules
}
// applyClientOnlyIdentities drops client-only declarations from the server
// inventory and records their identities on the modules that remain. A loader
// excludes those candidates from a dedicated server, so a requirement whose
// only candidate is client-only is filtered rather than reported missing.
func applyClientOnlyIdentities(
modules []catalog.DescriptorModule,
) []catalog.DescriptorModule {
var kept []catalog.DescriptorModule
var clientOnly []string
for _, module := range modules {
if module.Side != catalog.SideClient {
kept = append(kept, module)
continue
}
clientOnly = append(clientOnly, descriptorModuleNames(module)...)
}
if len(clientOnly) == 0 {
return modules
}
if len(kept) == 0 {
return nil
}
for i := range kept {
kept[i].ClientOnly = mergeModuleNames(kept[i].ClientOnly, clientOnly)
}
return kept
}
func descriptorModuleNames(module catalog.DescriptorModule) []string {
names := make([]string, 0, len(module.Provides)+2)
if module.ID != "" {
names = append(names, module.ID)
}
names = append(names, module.Provides...)
if module.Group != "" && module.ID != "" {
names = append(names, module.Group+":"+module.ID)
}
return names
}
func mergeModuleNames(existing, added []string) []string {
merged := append(append([]string(nil), existing...), added...)
slices.Sort(merged)
return slices.Compact(merged)
}
func normalizeDescriptorDependencies(deps []catalog.DescriptorDependency) {
sort.Slice(deps, func(a, b int) bool {
return compareDescriptorDependency(deps[a], deps[b]) < 0
})
for i := range deps {
normalizeDescriptorDependencies(deps[i].AnyOf)
normalizeDescriptorDependencies(deps[i].AllOf)
normalizeDescriptorDependencies(deps[i].Unless)
}
}
func compareDescriptorModule(a, b catalog.DescriptorModule) int {
if n := strings.Compare(a.NestedPath, b.NestedPath); n != 0 {
return n
}
if n := strings.Compare(a.DescriptorPath, b.DescriptorPath); n != 0 {
return n
}
if n := strings.Compare(a.ID, b.ID); n != 0 {
return n
}
if n := strings.Compare(string(a.Version), string(b.Version)); n != 0 {
return n
}
return strings.Compare(string(a.Ecosystem), string(b.Ecosystem))
}
func compareDescriptorDependency(a, b catalog.DescriptorDependency) int {
if n := strings.Compare(string(a.Kind), string(b.Kind)); n != 0 {
return n
}
if n := strings.Compare(a.ID, b.ID); n != 0 {
return n
}
if n := strings.Compare(a.Constraint, b.Constraint); n != 0 {
return n
}
if n := strings.Compare(a.Ordering, b.Ordering); n != 0 {
return n
}
if n := strings.Compare(a.Phase, b.Phase); n != 0 {
return n
}
if n := strings.Compare(a.Load, b.Load); n != 0 {
return n
}
if a.JoinClasspath != b.JoinClasspath {
if a.JoinClasspath {
return 1
}
return -1
}
if n := strings.Compare(string(a.Provider), string(b.Provider)); n != 0 {
return n
}
if n := strings.Compare(a.ProjectID, b.ProjectID); n != 0 {
return n
}
return strings.Compare(a.ModuleID, b.ModuleID)
}
func nativeEntry(z *zip.Reader, name string) ([]byte, error) {
raw, _, err := fsutil.ReadZipEntry(
z,
name,
fsutil.MaxNestedZipEntryBytes,
)
return raw, err
}
// descriptorDecoders maps each descriptor ecosystem to its decoder.
var descriptorDecoders = map[catalog.Ecosystem]func(
*zip.Reader,
string,
string,
*descriptorInputs,
) (*decodedDescriptor, error){
catalog.EcosystemQuilt: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeQuiltDescriptor(z, member, false, inputs)
},
catalog.EcosystemFabric: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeFabricDescriptor(z, member, false, inputs)
},
catalog.EcosystemForge: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeForgeDescriptor(z, member, false, inputs)
},
catalog.EcosystemNeoForge: func(
z *zip.Reader,
member, minecraft string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeNeoForgeDescriptor(z, member, false, minecraft, inputs)
},
catalog.EcosystemBukkit: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeBukkitDescriptor(z, member, inputs)
},
catalog.EcosystemPaper: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeBukkitDescriptor(z, member, inputs)
},
catalog.EcosystemMCDR: func(
z *zip.Reader,
member, _ string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
return decodeMCDRDescriptor(z, member, inputs)
},
}
// inspectArchive reads one archive with the descriptor precedence of loader
// and decodes every nested archive the descriptor bundles.
func inspectArchive(
z *zip.Reader,
loader catalog.Ecosystem,
member string,
depth int,
minecraft string,
inputs *descriptorInputs,
) ([]catalog.DescriptorModule, error) {
if depth > 16 {
return nil, fmt.Errorf("nested archive depth exceeds 16")
}
decoded, err := decodeArchiveDescriptor(z, loader, member, minecraft, inputs)
if err != nil {
return nil, err
}
if decoded == nil {
return nil, nil
}
modules := decoded.catalogModules()
if decoded.SkipNested {
return modules, nil
}
for _, jar := range decoded.Nested {
raw, err := nativeEntry(z, jar)
if err != nil {
return nil, err
}
if raw == nil {
return nil, fmt.Errorf("missing nested JAR %s", jar)
}
nested, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, err
}
path := jar
if member != "" {
path = member + "/" + path
}
nestedModules, err := inspectArchive(
nested,
loader,
path,
depth+1,
minecraft,
nil,
)
if err != nil {
return nil, err
}
modules = append(modules, nestedModules...)
}
return modules, nil
}
// decodeArchiveDescriptor reads the first descriptor ecosystem in the loader's
// precedence order that the archive carries.
func decodeArchiveDescriptor(
z *zip.Reader,
loader catalog.Ecosystem,
member string,
minecraft string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
for _, ecosystem := range loader.Loads() {
decoder, ok := descriptorDecoders[ecosystem]
if !ok {
continue
}
decoded, err := decoder(z, member, minecraft, inputs)
if err != nil {
return nil, err
}
if decoded != nil {
return decoded, nil
}
}
return nil, nil
}
func inspectPython(
ctx context.Context,
path string,
) ([]catalog.DescriptorModule, error) {
code := `import ast,json,sys
m=ast.parse(open(sys.argv[1],encoding="utf-8").read())
for n in m.body:
if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=="PLUGIN_METADATA" for t in n.targets):
print(json.dumps(ast.literal_eval(n.value)));break
else: raise ValueError("missing static PLUGIN_METADATA")`
data, err := exec.CommandContext(ctx, "python3", "-c", code, path).Output()
if err != nil {
return nil, fmt.Errorf("inspect Python plugin metadata: %w", err)
}
descriptor, err := parseMCDRPluginFile(data)
if err != nil {
return nil, err
}
decoded, err := mcdrDecodedDescriptor(nil, descriptor, "")
if err != nil {
return nil, err
}
return decoded.catalogModules(), nil
}
func ModuleProvides(m catalog.DescriptorModule, id string) bool {
if m.Ecosystem == catalog.EcosystemBukkit {
return strings.EqualFold(m.ID, id) || slices.ContainsFunc(m.Provides, func(p string) bool { return strings.EqualFold(p, id) })
}
return m.ID == id || slices.Contains(m.Provides, id)
}
package artifact
import (
"encoding/json/v2"
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/version"
)
const quiltModPath = "quilt.mod.json"
// validateQuiltDescriptor rejects schema versions this reader cannot
// interpret instead of guessing at a newer layout.
func validateQuiltDescriptor(descriptor *quiltModFile) error {
if descriptor.SchemaVersion != 1 {
return fmt.Errorf(
"unsupported Quilt schema_version %d",
descriptor.SchemaVersion,
)
}
if descriptor.Loader.ID == "" {
return fmt.Errorf("Quilt descriptor is missing quilt_loader.id")
}
return nil
}
// quiltModFile is the schema_version 1 quilt.mod.json document. The schema
// keeps dependency, license, and contributor values in several shapes, so the
// flexible fields decode into any and are interpreted through the helpers in
// this file.
type quiltModFile struct {
SchemaVersion int `json:"schema_version"`
Loader quiltLoader `json:"quilt_loader"`
Minecraft struct {
Environment string `json:"environment"`
} `json:"minecraft"`
}
type quiltLoader struct {
Group string `json:"group"`
ID string `json:"id"`
Version string `json:"version"`
Provides []quiltProvided `json:"provides"`
Jars []string `json:"jars"`
Depends []quiltDependencyEntry `json:"depends"`
Breaks []quiltDependencyEntry `json:"breaks"`
Metadata *quiltMetadata `json:"metadata"`
}
type quiltMetadata struct {
Name string `json:"name"`
Description string `json:"description"`
Contributors map[string]any `json:"contributors"`
Contact map[string]string `json:"contact"`
License quiltLicense `json:"license"`
}
// quiltProvided accepts the string shorthand and the object form of a
// provides entry. Version is empty when the entry omits it, which means the
// providing module's own version applies.
type quiltProvided struct {
ID string
Version version.Version
}
func (p *quiltProvided) UnmarshalJSON(data []byte) error {
var id string
if err := json.Unmarshal(data, &id); err == nil {
p.ID = id
return nil
}
var object struct {
ID string `json:"id"`
Version string `json:"version"`
}
if err := json.Unmarshal(data, &object); err != nil {
return fmt.Errorf("invalid Quilt provides entry: %w", err)
}
if object.ID == "" {
return fmt.Errorf("Quilt provides entry is missing an id")
}
p.ID = object.ID
p.Version = version.Version(object.Version)
return nil
}
// quiltLicense collapses the string, array, and object license forms into the
// single display string catalog.Metadata carries.
type quiltLicense string
func (l *quiltLicense) UnmarshalJSON(data []byte) error {
var single string
if err := json.Unmarshal(data, &single); err == nil {
*l = quiltLicense(single)
return nil
}
var many []quiltLicense
if err := json.Unmarshal(data, &many); err == nil {
parts := make([]string, 0, len(many))
for _, license := range many {
if license != "" {
parts = append(parts, string(license))
}
}
*l = quiltLicense(strings.Join(parts, ", "))
return nil
}
var object struct {
Name string `json:"name"`
ID string `json:"id"`
}
if err := json.Unmarshal(data, &object); err != nil {
return fmt.Errorf("invalid Quilt license: %w", err)
}
switch {
case object.ID != "":
*l = quiltLicense(object.ID)
case object.Name != "":
*l = quiltLicense(object.Name)
}
return nil
}
// quiltDependencyEntry models one element of a Quilt depends or breaks array.
// An element is a mod id string, a dependency object, or an array of
// dependency objects, and the two latter shapes may nest.
type quiltDependencyEntry struct {
ID string
Versions any
Optional bool
// Environment is the Minecraft game provider option. A dependency that
// applies only to the physical client does not constrain a server.
Environment string
Unless *quiltDependencyEntry
Elements []quiltDependencyEntry
array bool
}
func (e *quiltDependencyEntry) UnmarshalJSON(data []byte) error {
var id string
if err := json.Unmarshal(data, &id); err == nil {
e.ID = id
return nil
}
var elements []quiltDependencyEntry
if err := json.Unmarshal(data, &elements); err == nil {
e.Elements = elements
e.array = true
return nil
}
var object struct {
ID string `json:"id"`
Versions any `json:"versions"`
Optional bool `json:"optional"`
Environment string `json:"environment"`
Unless *quiltDependencyEntry `json:"unless"`
}
if err := json.Unmarshal(data, &object); err != nil {
return fmt.Errorf("invalid Quilt dependency entry: %w", err)
}
if object.ID == "" {
return fmt.Errorf("Quilt dependency object is missing an id")
}
e.ID = object.ID
e.Versions = object.Versions
e.Optional = object.Optional
e.Environment = object.Environment
e.Unless = object.Unless
return nil
}
// alternatives flattens nested dependency arrays into the alternatives their
// enclosing entry offers. depends arrays match when any alternative matches.
func (e quiltDependencyEntry) alternatives() []quiltDependencyEntry {
if !e.array {
return []quiltDependencyEntry{e}
}
var alternatives []quiltDependencyEntry
for _, element := range e.Elements {
alternatives = append(alternatives, element.alternatives()...)
}
return alternatives
}
// serverAlternatives drops alternatives that apply only to the physical
// client. The Minecraft game provider adds the environment option, and a
// dedicated server does not enforce client-only dependencies.
func (e quiltDependencyEntry) serverAlternatives() []quiltDependencyEntry {
alternatives := e.alternatives()
applicable := alternatives[:0]
for _, alternative := range alternatives {
if quiltDependencyAppliesToServer(alternative) {
applicable = append(applicable, alternative)
}
}
return applicable
}
func quiltDependencyAppliesToServer(entry quiltDependencyEntry) bool {
switch strings.ToLower(strings.TrimSpace(entry.Environment)) {
case "", "*", "any", "both", "server", "dedicated_server":
return true
default:
return false
}
}
// quiltVersionNode converts one versions value into a descriptor dependency
// node. Quilt states every version condition as a range: the deprecated array
// and the any form are alternatives, and the all form is a conjunction. Both
// lower to one constraint, because the module carries the Quilt dialect that
// spells alternatives with || and a conjunction with spaces. The nesting keeps
// each alternative's conjunction intact, which a dependency node cannot.
func quiltVersionNode(
raw any,
id string,
kind catalog.DependencyKind,
) (catalog.DescriptorDependency, error) {
clauses, err := quiltVersionClauses(raw)
if err != nil {
return catalog.DescriptorDependency{}, err
}
return catalog.DescriptorDependency{
ID: id,
Kind: kind,
Constraint: quiltConstraint(clauses),
}, nil
}
// quiltVersionClauses returns the disjunctive normal form of a versions value:
// alternatives, each a conjunction of range terms. An absent value accepts
// every version.
func quiltVersionClauses(raw any) ([][]string, error) {
switch value := raw.(type) {
case nil:
return [][]string{{}}, nil
case string:
return quiltRangeClauses(value), nil
case []any:
return quiltAnyClauses(value)
case map[string]any:
if len(value) != 1 {
return nil, fmt.Errorf(
"Quilt versions object must hold exactly one of any or all",
)
}
if anyRaw, ok := value["any"]; ok {
return quiltAnyClauses(quiltVersionItems(anyRaw))
}
if allRaw, ok := value["all"]; ok {
return quiltAllClauses(quiltVersionItems(allRaw))
}
return nil, fmt.Errorf(
"Quilt versions object must hold exactly one of any or all",
)
default:
return nil, fmt.Errorf("invalid Quilt versions value %T", raw)
}
}
func quiltVersionItems(raw any) []any {
if items, ok := raw.([]any); ok {
return items
}
return []any{raw}
}
// quiltAnyClauses concatenates the alternatives of every item.
func quiltAnyClauses(items []any) ([][]string, error) {
if len(items) == 0 {
return [][]string{{}}, nil
}
clauses := make([][]string, 0, len(items))
for _, item := range items {
itemClauses, err := quiltVersionClauses(item)
if err != nil {
return nil, err
}
clauses = append(clauses, itemClauses...)
}
return clauses, nil
}
// quiltAllClauses multiplies the alternatives of every item into conjunctions.
func quiltAllClauses(items []any) ([][]string, error) {
clauses := [][]string{{}}
for _, item := range items {
itemClauses, err := quiltVersionClauses(item)
if err != nil {
return nil, err
}
clauses = quiltConjunction(clauses, itemClauses)
}
return clauses, nil
}
// quiltRangeClauses splits one range into its alternatives. Each alternative
// stays a conjunction the Quilt grammar spells with spaces.
func quiltRangeClauses(raw string) [][]string {
alternatives := strings.Split(raw, "||")
clauses := make([][]string, 0, len(alternatives))
for _, alternative := range alternatives {
alternative = strings.TrimSpace(alternative)
if alternative == "" {
continue
}
clauses = append(clauses, []string{alternative})
}
return clauses
}
func quiltConjunction(left, right [][]string) [][]string {
product := make([][]string, 0, len(left)*len(right))
for _, leftClause := range left {
for _, rightClause := range right {
clause := make([]string, 0, len(leftClause)+len(rightClause))
clause = append(clause, leftClause...)
clause = append(clause, rightClause...)
product = append(product, clause)
}
}
return product
}
// quiltConstraint joins the normal form back into a Quilt range. An empty
// conjunction accepts every version, so it imposes no constraint.
func quiltConstraint(clauses [][]string) string {
alternatives := make([]string, 0, len(clauses))
for _, clause := range clauses {
terms := make([]string, 0, len(clause))
for _, term := range clause {
if term = strings.TrimSpace(term); term != "" {
terms = append(terms, term)
}
}
if len(terms) == 0 {
return ""
}
alternatives = append(alternatives, strings.Join(terms, " "))
}
return strings.Join(alternatives, " || ")
}
func quiltRole(value any) string {
switch roles := value.(type) {
case string:
return roles
case []any:
parts := make([]string, 0, len(roles))
for _, role := range roles {
if text, ok := role.(string); ok && text != "" {
parts = append(parts, text)
}
}
return strings.Join(parts, ", ")
default:
return ""
}
}
package artifact
import (
"archive/zip"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/version"
"go.yaml.in/yaml/v4"
)
const (
bukkitPluginDescriptorPath = "plugin.yml"
paperPluginDescriptorPath = "paper-plugin.yml"
)
type bukkitReader struct{}
var _ Reader = (*bukkitReader)(nil)
type bukkitPluginDescriptor struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
Main string `yaml:"main"`
Description string `yaml:"description"`
Author string `yaml:"author"`
Authors []string `yaml:"authors"`
Website string `yaml:"website"`
APIVersion string `yaml:"api-version"`
API []string `yaml:"api"`
Provides []string `yaml:"provides"`
Depend []string `yaml:"depend"`
SoftDepend []string `yaml:"softdepend"`
LoadBefore []string `yaml:"loadbefore"`
Libraries []string `yaml:"libraries"`
FoliaSupported bool `yaml:"folia-supported"`
PaperPluginLoader string `yaml:"paper-plugin-loader"`
Dependencies map[string]map[string]struct {
Required *bool `yaml:"required"`
Load string `yaml:"load"`
JoinClasspath *bool `yaml:"join-classpath"`
} `yaml:"dependencies"`
}
func newBukkitReader() Reader { return &bukkitReader{} }
func (r *bukkitReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *bukkitReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeBukkitPackageDescriptor(zipRdr, "", inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
// decodeBukkitPackageDescriptor reads plugin.yml for the metadata reader view.
func decodeBukkitPackageDescriptor(
zipRdr *zip.Reader,
member string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, name, err := readBukkitPluginDescriptor(
zipRdr,
bukkitPluginDescriptorPath,
inputs,
)
if err != nil || descriptor == nil {
return nil, err
}
return bukkitDecodedDescriptor(descriptor, name, member, true)
}
// decodeBukkitDescriptor reads the modules a Bukkit or Paper runtime loads. A
// paper-plugin.yml descriptor takes precedence over plugin.yml, and both
// loaders record the module as Bukkit.
func decodeBukkitDescriptor(
zipRdr *zip.Reader,
member string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, name, err := readBukkitPluginDescriptor(
zipRdr,
paperPluginDescriptorPath,
inputs,
)
if err != nil {
return nil, err
}
if descriptor == nil {
descriptor, name, err = readBukkitPluginDescriptor(
zipRdr,
bukkitPluginDescriptorPath,
inputs,
)
if err != nil {
return nil, err
}
}
if descriptor == nil {
return nil, nil
}
return bukkitDecodedDescriptor(descriptor, name, member, false)
}
func readBukkitPluginDescriptor(
zipRdr *zip.Reader,
name string,
inputs *descriptorInputs,
) (*bukkitPluginDescriptor, string, error) {
descriptor, err := descriptorInput(inputs, name, func() (*bukkitPluginDescriptor, error) {
return parseBukkitPluginDescriptor(zipRdr, name)
})
return descriptor, name, err
}
func parseBukkitPluginDescriptor(zipRdr *zip.Reader, name string) (*bukkitPluginDescriptor, error) {
raw, err := readZipEntryBytes(zipRdr, name)
if err != nil || raw == nil {
return nil, err
}
descriptor := &bukkitPluginDescriptor{}
if err := yaml.Unmarshal(raw, descriptor); err != nil {
return nil, err
}
return descriptor, nil
}
func bukkitDecodedDescriptor(
descriptor *bukkitPluginDescriptor,
descriptorPath string,
member string,
requireMain bool,
) (*decodedDescriptor, error) {
if requireMain &&
(strings.TrimSpace(descriptor.Name) == "" ||
strings.TrimSpace(descriptor.Version) == "" ||
strings.TrimSpace(descriptor.Main) == "") {
return nil, nil
}
platform := detectBukkitPluginPlatform(descriptor)
module := catalog.DescriptorModule{
ID: descriptor.Name,
Version: version.Version(descriptor.Version),
Ecosystem: catalog.EcosystemBukkit,
VersionDialect: version.DialectOpaque,
NestedPath: member,
DescriptorPath: descriptorPath,
APIVersion: descriptor.APIVersion,
FoliaSupported: descriptor.FoliaSupported,
Provides: descriptor.Provides,
Dependencies: bukkitModuleDependencies(descriptor),
}
packageDependencies := bukkitPackageDependencies(descriptor, platform)
decoded := decodedModule{
Module: module,
PackageEcosystem: platform,
PackageVersion: version.Version(strings.TrimSpace(descriptor.Version)),
PackageDependencies: packageDependencies,
Metadata: catalog.Metadata{
Title: strings.TrimSpace(descriptor.Name),
Description: strings.TrimSpace(descriptor.Description),
Authors: bukkitDescriptorAuthors(
descriptor.Author,
descriptor.Authors,
),
URLs: bukkitDescriptorURLs(descriptor.Website),
},
Compatibility: Compatibility{
FoliaSupported: descriptor.FoliaSupported,
},
}
return &decodedDescriptor{Modules: []decodedModule{decoded}}, nil
}
func bukkitModuleDependencies(
descriptor *bukkitPluginDescriptor,
) []catalog.DescriptorDependency {
dependencies := make(
[]catalog.DescriptorDependency,
0,
len(descriptor.Depend)+len(descriptor.SoftDepend)+
len(descriptor.LoadBefore),
)
dependencies = appendBukkitModuleDependencies(
dependencies,
descriptor.Depend,
catalog.DependencyKindRequired,
"AFTER",
)
dependencies = appendBukkitModuleDependencies(
dependencies,
descriptor.SoftDepend,
catalog.DependencyKindOptional,
"AFTER",
)
dependencies = appendBukkitModuleDependencies(
dependencies,
descriptor.LoadBefore,
catalog.DependencyKindOptional,
"BEFORE",
)
for phase, deps := range descriptor.Dependencies {
for id, dep := range deps {
kind := catalog.DependencyKindRequired
if dep.Required != nil && !*dep.Required {
kind = catalog.DependencyKindOptional
}
join := dep.JoinClasspath == nil || *dep.JoinClasspath
dependencies = append(
dependencies,
catalog.DescriptorDependency{
ID: id,
Kind: kind,
Phase: phase,
Load: dep.Load,
JoinClasspath: join,
},
)
}
}
return dependencies
}
func appendBukkitModuleDependencies(
dependencies []catalog.DescriptorDependency,
names []string,
kind catalog.DependencyKind,
ordering string,
) []catalog.DescriptorDependency {
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" {
continue
}
dependencies = append(
dependencies,
catalog.DescriptorDependency{
ID: name,
Kind: kind,
Ordering: ordering,
},
)
}
return dependencies
}
// bukkitPackageDependencies keeps the reader view to plugin.yml's depend and
// softdepend lists.
func bukkitPackageDependencies(
descriptor *bukkitPluginDescriptor,
platform catalog.Ecosystem,
) []Dependency {
dependencies := make(
[]Dependency,
0,
len(descriptor.Depend)+len(descriptor.SoftDepend),
)
dependencies = appendBukkitPackageDependencies(
dependencies,
platform,
descriptor.Depend,
true,
)
dependencies = appendBukkitPackageDependencies(
dependencies,
platform,
descriptor.SoftDepend,
false,
)
return dependencies
}
func appendBukkitPackageDependencies(
dependencies []Dependency,
platform catalog.Ecosystem,
names []string,
mandatory bool,
) []Dependency {
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" {
continue
}
dependencies = append(
dependencies,
Dependency{
Ref: catalog.VersionedRef{
Ref: catalog.Ref{
Name: input.ToProjectName(name),
Provider: catalog.ProviderUnknown,
},
Ecosystem: platform,
},
Mandatory: mandatory,
},
)
}
return dependencies
}
func detectBukkitPluginPlatform(
descriptor *bukkitPluginDescriptor,
) catalog.Ecosystem {
if descriptor.PaperPluginLoader != "" || len(descriptor.Libraries) > 0 {
return catalog.EcosystemPaper
}
for _, list := range [][]string{
descriptor.API,
descriptor.Depend,
descriptor.SoftDepend,
} {
for _, entry := range list {
switch strings.ToLower(strings.TrimSpace(entry)) {
case "paper", "folia", "leaves":
return catalog.EcosystemPaper
}
}
}
return catalog.EcosystemBukkit
}
func bukkitDescriptorAuthors(author string, authors []string) []catalog.Person {
people := make([]catalog.Person, 0, len(authors)+1)
if trimmed := strings.TrimSpace(author); trimmed != "" {
people = append(people, catalog.Person{Name: trimmed})
}
for _, item := range authors {
if trimmed := strings.TrimSpace(item); trimmed != "" {
people = append(people, catalog.Person{Name: trimmed})
}
}
return people
}
func bukkitDescriptorURLs(website string) []catalog.URL {
website = strings.TrimSpace(website)
if website == "" {
return nil
}
return []catalog.URL{
{
Name: "Website",
Type: catalog.URLHome,
URL: website,
},
}
}
package artifact
import (
"archive/zip"
"bytes"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/internal/fn"
"github.com/mclucy/lucy/version"
)
type fabricReader struct{}
var _ Reader = (*fabricReader)(nil)
func newFabricReader() Reader { return &fabricReader{} }
func (r *fabricReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *fabricReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeFabricDescriptor(zipRdr, "", true, inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
// decodeFabricDescriptor reads fabric.mod.json and returns nil when the
// archive does not carry it. packageView adds the metadata ReadInfo reports.
func decodeFabricDescriptor(
zipRdr *zip.Reader,
member string,
packageView bool,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
modInfo, err := descriptorInput(inputs, "fabric.mod.json", func() (*fileschema.FileFabricModIdentifier, error) {
return readFabricDescriptor(zipRdr)
})
if err != nil || modInfo == nil {
return nil, err
}
module := catalog.DescriptorModule{
ID: modInfo.ID,
Version: version.Version(modInfo.Version),
Ecosystem: catalog.EcosystemFabric,
VersionDialect: version.DialectFabric,
NestedPath: member,
DescriptorPath: "fabric.mod.json",
Provides: modInfo.Provides,
Side: catalog.ParseSide(string(modInfo.Environment)),
}
if inputs != nil {
module.Provides = slices.Clone(module.Provides)
}
var origins map[string]catalog.DependencyOrigin
var embeddedNames map[string]struct{}
if packageView {
embeddedNames, err = fabricEmbeddedModNames(zipRdr, modInfo)
if err != nil {
return nil, err
}
origins = make(map[string]catalog.DependencyOrigin)
}
for _, group := range []struct {
dependencies map[string]fn.SingleOrSlice[string]
kind catalog.DependencyKind
}{
{modInfo.Depends, catalog.DependencyKindRequired},
{modInfo.Recommends, catalog.DependencyKindRecommended},
{modInfo.Suggests, catalog.DependencyKindSuggested},
{modInfo.Breaks, catalog.DependencyKindIncompatible},
{modInfo.Conflicts, catalog.DependencyKindConflict},
} {
for id, ranges := range group.dependencies {
module.Dependencies = append(
module.Dependencies,
catalog.DescriptorDependency{
ID: id,
Kind: group.kind,
Constraint: strings.Join(ranges, " || "),
},
)
if packageView {
origins[id] = fabricDependencyOrigin(id, embeddedNames)
}
}
}
nested := make([]string, 0, len(modInfo.Jars))
for _, jar := range modInfo.Jars {
nested = append(nested, jar.File)
}
decoded := decodedModule{
Module: module,
Origins: origins,
}
if packageView {
decoded.Metadata = fabricArtifactMetadata(modInfo)
decoded.PackageEcosystem = catalog.EcosystemFabric
}
return &decodedDescriptor{
Modules: []decodedModule{decoded},
Nested: nested,
SkipNested: module.Side == catalog.SideClient,
}, nil
}
func readFabricDescriptor(
zipRdr *zip.Reader,
) (*fileschema.FileFabricModIdentifier, error) {
raw, err := readZipEntryBytes(zipRdr, "fabric.mod.json")
if err != nil || raw == nil {
return nil, err
}
modInfo := &fileschema.FileFabricModIdentifier{}
if err := unmarshalDescriptor(raw, modInfo); err != nil {
return nil, err
}
return modInfo, nil
}
func fabricDependencyOrigin(
id string,
embeddedNames map[string]struct{},
) catalog.DependencyOrigin {
switch id {
case "minecraft", "java", "fabricloader":
return catalog.DependencyServerProvided
}
if _, embedded := embeddedNames[string(input.ToProjectName(id))]; embedded {
return catalog.DependencyEmbedded
}
return catalog.DependencyRegular
}
func fabricArtifactMetadata(
modInfo *fileschema.FileFabricModIdentifier,
) catalog.Metadata {
return catalog.Metadata{
Title: modInfo.Name,
Description: modInfo.Description,
License: strings.Join(modInfo.License, ", "),
Authors: fabricArtifactAuthors(modInfo.Authors),
URLs: fabricArtifactURLs(modInfo.Contact),
}
}
func fabricEmbeddedModNames(
zipRdr *zip.Reader,
modInfo *fileschema.FileFabricModIdentifier,
) (map[string]struct{}, error) {
depNames := make([]string, 0, len(modInfo.Depends))
for id := range modInfo.Depends {
depNames = append(depNames, id)
}
names := make(map[string]struct{}, len(modInfo.Jars))
for _, jar := range modInfo.Jars {
nestedInfo, err := fabricNestedModInfo(zipRdr, jar.File)
if err != nil {
return nil, err
}
if nestedInfo != nil {
fabricRecordEmbeddedName(names, nestedInfo.ID)
for _, provided := range nestedInfo.Provides {
fabricRecordEmbeddedName(names, provided)
}
continue
}
base := jar.File
if _, tail, ok := strings.CutLast(base, "/"); ok {
base = tail
}
base = strings.TrimSuffix(base, ".jar")
for _, dep := range depNames {
if base == dep || strings.HasPrefix(base, dep+"-") {
names[dep] = struct{}{}
break
}
}
}
return names, nil
}
func fabricNestedModInfo(
zipRdr *zip.Reader,
filePath string,
) (*fileschema.FileFabricModIdentifier, error) {
raw, err := readZipEntryBytes(zipRdr, filePath)
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
nestedZip, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, err
}
return readFabricDescriptor(nestedZip)
}
func fabricRecordEmbeddedName(names map[string]struct{}, id string) {
if id == "" {
return
}
names[string(input.ToProjectName(id))] = struct{}{}
}
func fabricArtifactAuthors(authors []fileschema.FabricAuthor) []catalog.Person {
translated := make([]catalog.Person, len(authors))
for i, author := range authors {
translated[i] = catalog.Person{Name: string(author)}
}
return translated
}
func fabricArtifactURLs(contact map[string]string) []catalog.URL {
urlSpecs := []struct {
key string
name string
urlType catalog.URLType
}{
{key: "homepage", name: "Homepage", urlType: catalog.URLHome},
{key: "sources", name: "Source", urlType: catalog.URLSource},
{key: "issues", name: "Issues", urlType: catalog.URLIssues},
}
urls := make([]catalog.URL, 0, len(urlSpecs))
for _, spec := range urlSpecs {
url := contact[spec.key]
if url == "" {
continue
}
urls = append(
urls,
catalog.URL{
Name: spec.name,
Type: spec.urlType,
URL: url,
},
)
}
return urls
}
package artifact
import (
"archive/zip"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/version"
)
const forgeModsTomlPath = "META-INF/mods.toml"
type forgeReader struct{}
var _ Reader = (*forgeReader)(nil)
func newForgeReader() Reader { return &forgeReader{} }
func (r *forgeReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *forgeReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeForgeDescriptor(zipRdr, "", true, inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
// decodedModsToml is the parsed shared Forge and NeoForge descriptor.
type decodedModsToml struct {
Identifier fileschema.FileModLoaderIdentifier
Path string
}
// readModsToml parses one mods.toml entry. It returns nil when the entry is
// absent.
func readModsToml(
zipRdr *zip.Reader,
name string,
inputs *descriptorInputs,
) (*decodedModsToml, error) {
return descriptorInput(inputs, name, func() (*decodedModsToml, error) {
return parseModsToml(zipRdr, name)
})
}
func parseModsToml(zipRdr *zip.Reader, name string) (*decodedModsToml, error) {
raw, err := readZipEntryBytes(zipRdr, name)
if err != nil || raw == nil {
return nil, err
}
identifier, err := fileschema.ParseFileModLoaderIdentifier(raw)
if err != nil {
return nil, err
}
return &decodedModsToml{Identifier: identifier, Path: name}, nil
}
// decodeForgeDescriptor reads META-INF/mods.toml and every archive Forge adds
// from it. Forge ignores neoforge.mods.toml, so a jar carrying both descriptors
// stays a Forge mod. A library or language-provider jar may have no descriptor;
// its JarJar children still carry modules. A jar with an
// Embedded-Dependencies-Mod attribute contributes that archive, as Connector's
// locator does.
func decodeForgeDescriptor(
zipRdr *zip.Reader,
member string,
packageView bool,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, err := readModsToml(zipRdr, forgeModsTomlPath, inputs)
if err != nil {
return nil, err
}
jarjarMeta, err := readJarjarMetadata(zipRdr)
if err != nil {
return nil, err
}
nested := jarjarNestedPaths(jarjarMeta)
attributes, err := readManifestAttributes(
zipRdr,
fsutil.MaxNestedZipEntryBytes,
)
if err != nil {
return nil, err
}
service := forgeServiceProvider(zipRdr)
if service {
// Connector's locator names its mod archive here; FML itself reads
// only JarJar metadata.
if embedded := manifestAttribute(attributes, "Embedded-Dependencies-Mod"); embedded != "" {
nested = append(nested, embedded)
}
}
if descriptor == nil {
if !forgeLoadsWithoutDescriptor(manifestAttribute(attributes, "FMLModType")) && !service {
return nil, nil
}
if !service && len(nested) == 0 {
return nil, nil
}
return &decodedDescriptor{Nested: nested}, nil
}
var origins map[string]catalog.DependencyOrigin
var embeddedDependencies []Dependency
if packageView {
embeddedModIDs := jarjarEmbeddedModIDs(
zipRdr,
jarjarMeta,
func(nested *zip.Reader) (*decodedModsToml, error) {
return readModsToml(nested, forgeModsTomlPath, nil)
},
)
origins = make(map[string]catalog.DependencyOrigin, len(embeddedModIDs))
for id := range embeddedModIDs {
origins[id] = catalog.DependencyEmbedded
}
embeddedDependencies, err = jarjarEmbeddedDependencies(jarjarMeta)
if err != nil {
return nil, err
}
}
decoded, err := forgeDecodedDescriptor(
zipRdr,
descriptor,
member,
catalog.EcosystemForge,
packageView,
origins,
embeddedDependencies,
)
if err != nil {
return nil, err
}
decoded.Nested = nested
return decoded, nil
}
// forgeLoadsWithoutDescriptor reports whether FML keeps a jar that has no
// mods.toml. Every mod file type except MOD is accepted without one.
func forgeLoadsWithoutDescriptor(modType string) bool {
switch modType {
case "LIBRARY", "GAMELIBRARY", "LANGPROVIDER":
return true
default:
return false
}
}
// forgeServiceProvider reports whether the jar supplies a ModLauncher or FML
// service. FML loads such a jar into its service layer and excludes it from
// the mods-folder scan, so the jar itself is not a mod. Connector uses this
// path and points at its mod archive through Embedded-Dependencies-Mod.
func forgeServiceProvider(zipRdr *zip.Reader) bool {
for _, file := range zipRdr.File {
switch file.Name {
case "META-INF/services/cpw.mods.modlauncher.api.ITransformationService",
"META-INF/services/net.minecraftforge.forgespi.locating.IModLocator",
"META-INF/services/net.minecraftforge.forgespi.locating.IDependencyLocator",
"META-INF/services/net.minecraftforge.fml.loading.ImmediateWindowProvider":
return true
}
}
return false
}
// extras lists reader-only dependencies added beyond the descriptor, such as
// JarJar containers.
func forgeDecodedDescriptor(
zipRdr *zip.Reader,
descriptor *decodedModsToml,
member string,
ecosystem catalog.Ecosystem,
packageView bool,
packageOrigins map[string]catalog.DependencyOrigin,
extras []Dependency,
) (*decodedDescriptor, error) {
modules := make([]decodedModule, 0, len(descriptor.Identifier.Mods))
for _, mod := range descriptor.Identifier.Mods {
value := version.Version(mod.Version)
if value == "${file.jarVersion}" {
manifestVersion, err := readManifestImplementationVersion(
zipRdr,
fsutil.MaxNestedZipEntryBytes,
)
if err != nil {
return nil, err
}
value = manifestVersion
}
module := catalog.DescriptorModule{
ID: mod.ModID,
Version: value,
Ecosystem: ecosystem,
VersionDialect: version.DialectMaven,
NestedPath: member,
DescriptorPath: descriptor.Path,
Side: forgeModuleSide(
descriptor.Identifier.ClientSideOnly || mod.ClientSideOnly,
),
Dependencies: []catalog.DescriptorDependency{},
}
var metadata catalog.Metadata
if packageView {
metadata = catalog.Metadata{
Title: mod.DisplayName,
Description: mod.Description,
Authors: forgeAuthors(mod.Authors),
License: descriptor.Identifier.License,
URLs: []catalog.URL{
{
Name: "URL",
Type: catalog.URLHome,
URL: mod.DisplayURL,
},
{
Name: "Issue Tracker",
Type: catalog.URLIssues,
URL: descriptor.Identifier.IssueTrackerURL,
},
},
}
}
dependencies, packageDependencies, err := forgeDependencies(
descriptor.Identifier,
mod.ModID,
ecosystem,
packageView,
packageOrigins,
)
if err != nil {
return nil, err
}
module.Dependencies = dependencies
decoded := decodedModule{
Module: module,
SkipPackage: forgeLoaderModID(ecosystem) == mod.ModID,
}
if packageView {
decoded.Metadata = metadata
decoded.PackageDependencies = append(
packageDependencies,
extras...,
)
}
modules = append(modules, decoded)
}
return &decodedDescriptor{Modules: modules}, nil
}
func forgeLoaderModID(ecosystem catalog.Ecosystem) string {
if ecosystem == catalog.EcosystemNeoForge {
return "neoforge"
}
return "forge"
}
// forgeModuleSide maps a descriptor's clientSideOnly flag. Forge skips a
// client-only mod on a dedicated server, so its dependencies do not apply.
func forgeModuleSide(clientSideOnly bool) catalog.Side {
if clientSideOnly {
return catalog.SideClient
}
return catalog.SideUnknown
}
// forgeDependencies translates one mod's dependency list into the resolver
// view and, when requested, the reader view. Client-only entries do not
// constrain a dedicated server.
// forgeAuthors keeps every declared author. FML does not read the field, but
// package metadata presents it.
func forgeAuthors(authors fileschema.FileModLoaderAuthors) []catalog.Person {
people := make([]catalog.Person, 0, len(authors))
for _, author := range authors {
if name := strings.TrimSpace(author); name != "" {
people = append(people, catalog.Person{Name: name})
}
}
return people
}
func forgeDependencies(
identifier fileschema.FileModLoaderIdentifier,
modID string,
ecosystem catalog.Ecosystem,
packageView bool,
origins map[string]catalog.DependencyOrigin,
) ([]catalog.DescriptorDependency, []Dependency, error) {
deps := identifier.Dependencies[modID]
moduleDependencies := make([]catalog.DescriptorDependency, 0, len(deps))
packageDependencies := make([]Dependency, 0, len(deps))
for _, dep := range deps {
if catalog.ParseSide(dep.Side) != catalog.SideClient {
kind := catalog.ParseDependencyKind(dep.Type)
if kind == catalog.DependencyKindUnknown {
kind = catalog.DependencyKindOptional
if dep.Mandatory {
kind = catalog.DependencyKindRequired
}
}
moduleDependencies = append(
moduleDependencies,
catalog.DescriptorDependency{
ID: dep.ModID,
Constraint: dep.VersionRange,
Kind: kind,
Ordering: dep.Ordering,
},
)
}
if !packageView {
continue
}
if ecosystem == catalog.EcosystemNeoForge {
if dep.Type == "incompatible" ||
catalog.ParseSide(dep.Side) == catalog.SideClient ||
isLoaderDependencyID(dep.ModID) {
continue
}
}
constraint, err := version.ParseConstraint(
dep.VersionRange,
version.DialectMaven,
)
if err != nil {
return nil, nil, err
}
mandatory := dep.Mandatory
if ecosystem == catalog.EcosystemNeoForge {
mandatory = dep.Type == "required" || dep.Mandatory
}
origin := catalog.DependencyRegular
if mapped, ok := origins[dep.ModID]; ok {
origin = mapped
}
packageDependencies = append(packageDependencies, Dependency{
Ref: catalog.VersionedRef{
Ref: catalog.Ref{
Name: input.ToProjectName(dep.ModID),
Provider: catalog.ProviderUnknown,
},
Ecosystem: ecosystem,
},
Constraint: constraint,
Mandatory: mandatory,
Origin: origin,
})
}
return moduleDependencies, packageDependencies, nil
}
func isLoaderDependencyID(id string) bool {
switch id {
case "neoforge", "forge", "minecraft", "java":
return true
default:
return false
}
}
package artifact
import (
"archive/zip"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/version"
)
type forgeLegacyReader struct{}
func newForgeLegacyReader() Reader {
return &forgeLegacyReader{}
}
func (r *forgeLegacyReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
for _, f := range zipRdr.File {
if f.Name != "mcmod.info" {
continue
}
rc, err := f.Open()
if err != nil {
return nil, err
}
var mods fileschema.FileForgeModIdentifierOld
decodeErr := readDescriptorJSON(rc, &mods)
closeErr := rc.Close()
if decodeErr != nil {
return nil, decodeErr
}
if closeErr != nil {
return nil, closeErr
}
infos := make([]PackageInfo, 0, len(mods))
for _, m := range mods {
if m.ModId == "forge" || m.ModId == "minecraft" || m.ModId == "mcp" {
continue
}
info := PackageInfo{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(m.ModId), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemForge, Version: version.Version(m.Version)},
FilePath: filePath,
}
if len(m.Dependencies) > 0 {
deps := make([]Dependency, 0, len(m.Dependencies))
for _, rawDep := range m.Dependencies {
depStr, ok := rawDep.(string)
if !ok || depStr == "" {
continue
}
deps = append(
deps, Dependency{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(depStr), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemForge},
Mandatory: true,
},
)
}
if len(deps) > 0 {
info.Dependencies = deps
}
}
infos = append(infos, info)
}
return infos, nil
}
return nil, nil
}
package artifact
import (
"archive/zip"
"encoding/json/jsontext"
"encoding/json/v2"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fn"
"github.com/mclucy/lucy/version"
)
type mcdrReader struct{}
var _ Reader = (*mcdrReader)(nil)
func newMcdrReader() Reader {
return &mcdrReader{}
}
func (r *mcdrReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *mcdrReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeMCDRDescriptor(zipRdr, "", inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
func decodeMCDRDescriptor(
zipRdr *zip.Reader,
member string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, err := descriptorInput(inputs, "mcdreforged.plugin.json", func() (*mcdrPluginFile, error) {
raw, err := readZipEntryBytes(zipRdr, "mcdreforged.plugin.json")
if err != nil || raw == nil {
return nil, err
}
return parseMCDRPluginFile(raw)
})
if err != nil || descriptor == nil {
return nil, err
}
return mcdrDecodedDescriptor(zipRdr, descriptor, member)
}
// mcdrDescription is the plugin description. MCDR accepts one string or a map
// from language to text.
type mcdrDescription struct {
EnUs string
ZhCn string
}
func (d *mcdrDescription) UnmarshalJSON(data []byte) error {
var text string
if err := json.Unmarshal(data, &text); err == nil {
d.EnUs = text
return nil
}
var localized map[string]string
if err := json.Unmarshal(data, &localized); err != nil {
// The loader ignores a description it cannot read.
return nil
}
d.EnUs = localized["en_us"]
d.ZhCn = localized["zh_cn"]
return nil
}
type mcdrPluginFile struct {
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
Description mcdrDescription `json:"description"`
Author fn.SingleOrSlice[string] `json:"author"`
Link string `json:"link"`
Dependencies map[string]string `json:"dependencies"`
Requirements []string `json:"requirements"`
RequirementsFile jsontext.Value `json:"requirements_file"`
}
func parseMCDRPluginFile(raw []byte) (*mcdrPluginFile, error) {
descriptor := &mcdrPluginFile{}
if err := unmarshalDescriptor(raw, descriptor); err != nil {
return nil, err
}
return descriptor, nil
}
func mcdrDecodedDescriptor(zipRdr *zip.Reader, descriptor *mcdrPluginFile, member string) (*decodedDescriptor, error) {
module := catalog.DescriptorModule{
ID: descriptor.ID,
Version: version.Version(descriptor.Version),
Ecosystem: catalog.EcosystemMCDR,
VersionDialect: version.DialectMCDR,
NestedPath: member,
DescriptorPath: "mcdreforged.plugin.json",
Dependencies: []catalog.DescriptorDependency{},
}
for id, rangeText := range descriptor.Dependencies {
module.Dependencies = append(module.Dependencies, catalog.DescriptorDependency{
ID: id,
Kind: catalog.DependencyKindRequired,
Constraint: rangeText,
})
}
for _, requirement := range descriptor.Requirements {
module.Dependencies = append(module.Dependencies, catalog.DescriptorDependency{
ID: requirement,
Kind: catalog.DependencyKindPython,
})
}
if zipRdr != nil {
files, err := mcdrRequirementFiles(descriptor.RequirementsFile)
if err != nil {
return nil, err
}
if len(files) == 0 {
files = []string{"requirements.txt"}
}
for _, name := range files {
content, err := readZipEntryBytes(zipRdr, name)
if err != nil {
return nil, err
}
if content == nil {
continue
}
for _, requirement := range mcdrRequirements(content) {
module.Dependencies = append(
module.Dependencies,
catalog.DescriptorDependency{
ID: requirement,
Kind: catalog.DependencyKindPython,
},
)
}
}
}
decoded := decodedModule{
Module: module,
PackageEcosystem: catalog.EcosystemMCDR,
Metadata: mcdrMetadata(descriptor),
}
return &decodedDescriptor{Modules: []decodedModule{decoded}}, nil
}
func mcdrMetadata(descriptor *mcdrPluginFile) catalog.Metadata {
authors := make([]catalog.Person, len(descriptor.Author))
for i, author := range descriptor.Author {
authors[i] = catalog.Person{Name: author}
}
urls := make([]catalog.URL, 0, 1)
if descriptor.Link != "" {
urls = append(
urls,
catalog.URL{
Name: "Link",
Type: catalog.URLSource,
URL: descriptor.Link,
},
)
}
return catalog.Metadata{
Title: descriptor.Name,
Description: descriptor.Description.EnUs,
Authors: authors,
URLs: urls,
}
}
func mcdrRequirementFiles(raw jsontext.Value) ([]string, error) {
if len(raw) == 0 {
return nil, nil
}
var one string
if err := json.Unmarshal(raw, &one); err == nil {
if one == "" {
return nil, nil
}
return []string{one}, nil
}
var many []string
if err := json.Unmarshal(raw, &many); err != nil {
return nil, err
}
return many, nil
}
func mcdrRequirements(content []byte) []string {
var requirements []string
for line := range strings.SplitSeq(string(content), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "-") {
continue
}
requirements = append(requirements, line)
}
return requirements
}
package artifact
import (
"archive/zip"
"strconv"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
neoforgeModsTomlPath = "META-INF/neoforge.mods.toml"
legacyNeoforgeModsTomlPath = "META-INF/mods.toml"
)
type neoforgeReader struct{}
var _ Reader = (*neoforgeReader)(nil)
func newNeoforgeReader() Reader {
return &neoforgeReader{}
}
func (r *neoforgeReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *neoforgeReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeNeoForgeDescriptor(zipRdr, "", true, "", inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
// decodeNeoForgeDescriptor reads the NeoForge descriptor and its JarJar
// containers. requireMarker restricts the legacy shared mods.toml to files
// that name the NeoForge loader.
func decodeNeoForgeDescriptor(
zipRdr *zip.Reader,
member string,
packageView bool,
minecraft string,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, err := readNeoforgeDescriptor(zipRdr, minecraft, inputs)
if err != nil {
return nil, err
}
jarjarMeta, err := readJarjarMetadata(zipRdr)
if err != nil {
return nil, err
}
nested := jarjarNestedPaths(jarjarMeta)
attributes, err := readManifestAttributes(
zipRdr,
fsutil.MaxNestedZipEntryBytes,
)
if err != nil {
return nil, err
}
service := neoforgeServiceProvider(zipRdr)
if service {
if embedded := manifestAttribute(attributes, "Embedded-Dependencies-Mod"); embedded != "" {
nested = append(nested, embedded)
}
}
if descriptor == nil {
if !forgeLoadsWithoutDescriptor(manifestAttribute(attributes, "FMLModType")) && !service {
return nil, nil
}
if !service && len(nested) == 0 {
return nil, nil
}
return &decodedDescriptor{Nested: nested}, nil
}
var origins map[string]catalog.DependencyOrigin
var embeddedDependencies []Dependency
if packageView {
embeddedModIDs := jarjarEmbeddedModIDs(
zipRdr,
jarjarMeta,
func(nested *zip.Reader) (*decodedModsToml, error) {
return readNeoforgeDescriptor(nested, minecraft, nil)
},
)
origins = make(map[string]catalog.DependencyOrigin, len(embeddedModIDs))
for id := range embeddedModIDs {
origins[id] = catalog.DependencyEmbedded
}
embeddedDependencies, err = jarjarEmbeddedDependencies(jarjarMeta)
if err != nil {
return nil, err
}
}
decoded, err := forgeDecodedDescriptor(
zipRdr,
descriptor,
member,
catalog.EcosystemNeoForge,
packageView,
origins,
embeddedDependencies,
)
if err != nil {
return nil, err
}
decoded.Nested = nested
return decoded, nil
}
// neoforgeServiceProvider reports whether the jar supplies a ModLauncher or
// NeoForge service. FML loads such a jar into its service layer and excludes it
// from the mods-folder scan, so the jar itself is not a mod.
func neoforgeServiceProvider(zipRdr *zip.Reader) bool {
for _, file := range zipRdr.File {
switch file.Name {
case "META-INF/services/cpw.mods.modlauncher.api.ITransformationService",
"META-INF/services/net.neoforged.neoforgespi.locating.IModLocator",
"META-INF/services/net.neoforged.neoforgespi.locating.IDependencyLocator",
"META-INF/services/net.neoforged.neoforgespi.locating.IModFileCandidateLocator",
"META-INF/services/net.neoforged.fml.loading.ImmediateWindowProvider":
return true
}
}
return false
}
// readNeoforgeDescriptor selects the descriptor path of this FML line. FML 3
// (Minecraft 1.20.6) probes neoforge.mods.toml; earlier lines probe the shared
// mods.toml. Without a server version, report whichever descriptor the jar
// carries.
func readNeoforgeDescriptor(
zipRdr *zip.Reader,
minecraft string,
inputs *descriptorInputs,
) (*decodedModsToml, error) {
if minecraft == "" {
descriptor, err := readModsToml(zipRdr, neoforgeModsTomlPath, inputs)
if err != nil || descriptor != nil {
return descriptor, err
}
return readModsToml(zipRdr, legacyNeoforgeModsTomlPath, inputs)
}
if neoforgeReadsNeoDescriptor(minecraft) {
return readModsToml(zipRdr, neoforgeModsTomlPath, inputs)
}
return readModsToml(zipRdr, legacyNeoforgeModsTomlPath, inputs)
}
// neoforgeReadsNeoDescriptor reports whether the FML line for minecraft
// probes META-INF/neoforge.mods.toml. FML 3 starts with Minecraft 1.20.6.
func neoforgeReadsNeoDescriptor(minecraft string) bool {
major, minor, patch, ok := minecraftVersion(minecraft)
if !ok {
return true
}
if major != 1 {
return major > 1
}
if minor != 20 {
return minor > 20
}
return patch >= 6
}
func minecraftVersion(raw string) (major, minor, patch int, ok bool) {
parts := strings.Split(raw, ".")
if len(parts) < 2 {
return 0, 0, 0, false
}
numbers := make([]int, 3)
for i := 0; i < len(numbers) && i < len(parts); i++ {
value, err := strconv.Atoi(parts[i])
if err != nil {
return 0, 0, 0, false
}
numbers[i] = value
}
return numbers[0], numbers[1], numbers[2], true
}
package artifact
import (
"archive/zip"
"bytes"
"fmt"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/version"
)
// quiltReader reads schema_version 1 quilt.mod.json descriptors.
type quiltReader struct{}
var _ Reader = (*quiltReader)(nil)
func newQuiltReader() Reader { return &quiltReader{} }
func (r *quiltReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
return r.readWithInputs(zipRdr, filePath, nil)
}
func (r *quiltReader) readWithInputs(zipRdr *zip.Reader, filePath string, inputs *descriptorInputs) ([]PackageInfo, error) {
decoded, err := decodeQuiltDescriptor(zipRdr, "", true, inputs)
if err != nil {
return nil, err
}
return packageInfosFromDecoded(filePath, decoded)
}
// decodeQuiltDescriptor reads quilt.mod.json and returns nil when the archive
// does not carry it. packageView adds the metadata ReadInfo reports.
func decodeQuiltDescriptor(
zipRdr *zip.Reader,
member string,
packageView bool,
inputs *descriptorInputs,
) (*decodedDescriptor, error) {
descriptor, err := descriptorInput(inputs, quiltModPath, func() (*quiltModFile, error) {
return readQuiltDescriptor(zipRdr)
})
if err != nil || descriptor == nil {
return nil, err
}
loader := &descriptor.Loader
module, err := quiltModule(descriptor, member)
if err != nil {
return nil, err
}
decoded := decodedModule{Module: *module}
if packageView {
embeddedNames, err := quiltEmbeddedNames(zipRdr, loader)
if err != nil {
return nil, err
}
decoded.Metadata = quiltArtifactMetadata(loader.Metadata)
decoded.Origins = quiltDependencyOrigins(
module.Dependencies,
embeddedNames,
)
decoded.PackageNames = quiltDependencyPackageNames(
module.Dependencies,
)
decoded.PackageEcosystem = catalog.EcosystemQuilt
}
return &decodedDescriptor{
Modules: []decodedModule{decoded},
Nested: loader.Jars,
SkipNested: module.Side == catalog.SideClient,
}, nil
}
func readQuiltDescriptor(zipRdr *zip.Reader) (*quiltModFile, error) {
raw, err := readZipEntryBytes(zipRdr, quiltModPath)
if err != nil || raw == nil {
return nil, err
}
descriptor := &quiltModFile{}
if err := unmarshalDescriptor(raw, descriptor); err != nil {
return nil, err
}
if err := validateQuiltDescriptor(descriptor); err != nil {
return nil, err
}
return descriptor, nil
}
// quiltModule converts one quilt_loader descriptor into the module the
// resolver indexes.
func quiltModule(
descriptor *quiltModFile,
member string,
) (*catalog.DescriptorModule, error) {
loader := &descriptor.Loader
side := catalog.ParseSide(quiltEnvironment(descriptor.Minecraft.Environment))
provides := make([]string, 0, len(loader.Provides))
var providedVersions map[string]version.Version
for _, provided := range loader.Provides {
if provided.ID == "" {
continue
}
provides = append(provides, provided.ID)
if provided.Version != "" {
if providedVersions == nil {
providedVersions = map[string]version.Version{}
}
providedVersions[provided.ID] = provided.Version
}
}
dependencies, err := quiltDescriptorDependencies(loader)
if err != nil {
return nil, err
}
return &catalog.DescriptorModule{
ID: loader.ID,
Version: version.Version(loader.Version),
Ecosystem: catalog.EcosystemQuilt,
VersionDialect: version.DialectQuilt,
NestedPath: member,
DescriptorPath: quiltModPath,
Group: loader.Group,
Provides: provides,
ProvidedVersions: providedVersions,
Side: side,
Dependencies: dependencies,
}, nil
}
func quiltEnvironment(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "dedicated_server", "server":
return "server"
default:
return raw
}
}
// quiltDescriptorDependencies translates depends and breaks. A nested array in
// depends offers any-of alternatives, and a nested array in breaks applies
// every entry.
func quiltDescriptorDependencies(
loader *quiltLoader,
) ([]catalog.DescriptorDependency, error) {
dependencies := make(
[]catalog.DescriptorDependency,
0,
len(loader.Depends)+len(loader.Breaks),
)
for _, entry := range loader.Depends {
alternatives := entry.serverAlternatives()
if len(alternatives) == 0 {
continue
}
// A depends array is any-of. Each alternative keeps its own optional
// flag: an absent optional alternative satisfies the group, while an
// absent required alternative does not.
converted := make([]catalog.DescriptorDependency, 0, len(alternatives))
for _, alternative := range alternatives {
kind := catalog.DependencyKindRequired
if alternative.Optional {
kind = catalog.DependencyKindOptional
}
dependency, err := quiltDescriptorDependency(alternative, kind)
if err != nil {
return nil, err
}
converted = append(converted, dependency)
}
primary := converted[0]
primary.AnyOf = append(primary.AnyOf, converted[1:]...)
dependencies = append(dependencies, primary)
}
for _, entry := range loader.Breaks {
alternatives := entry.serverAlternatives()
if len(alternatives) == 0 {
continue
}
converted := make([]catalog.DescriptorDependency, 0, len(alternatives))
for _, alternative := range alternatives {
dependency, err := quiltDescriptorDependency(
alternative,
catalog.DependencyKindIncompatible,
)
if err != nil {
return nil, err
}
converted = append(converted, dependency)
}
primary := converted[0]
primary.AllOf = append(primary.AllOf, converted[1:]...)
dependencies = append(dependencies, primary)
}
return dependencies, nil
}
func quiltDescriptorDependency(
entry quiltDependencyEntry,
kind catalog.DependencyKind,
) (catalog.DescriptorDependency, error) {
dependency, err := quiltVersionNode(entry.Versions, entry.ID, kind)
if err != nil {
return catalog.DescriptorDependency{}, err
}
dependency.Unless, err = quiltDescriptorConditions(entry.Unless)
if err != nil {
return catalog.DescriptorDependency{}, err
}
return dependency, nil
}
func quiltDescriptorConditions(
entry *quiltDependencyEntry,
) ([]catalog.DescriptorDependency, error) {
if entry == nil {
return nil, nil
}
var conditions []catalog.DescriptorDependency
for _, alternative := range entry.serverAlternatives() {
condition, err := quiltVersionNode(
alternative.Versions,
alternative.ID,
catalog.DependencyKindRequired,
)
if err != nil {
return nil, err
}
condition.Unless, err = quiltDescriptorConditions(alternative.Unless)
if err != nil {
return nil, err
}
conditions = append(conditions, condition)
}
return conditions, nil
}
func quiltDependencyOrigins(
dependencies []catalog.DescriptorDependency,
embeddedNames map[string]struct{},
) map[string]catalog.DependencyOrigin {
origins := make(map[string]catalog.DependencyOrigin, len(dependencies))
for _, dependency := range dependencies {
if quiltDependencyServerID(quiltDependencyName(dependency.ID)) {
origins[dependency.ID] = catalog.DependencyServerProvided
continue
}
if quiltEmbeddedName(embeddedNames, dependency.ID) {
origins[dependency.ID] = catalog.DependencyEmbedded
}
}
return origins
}
func quiltDependencyPackageNames(
dependencies []catalog.DescriptorDependency,
) map[string]string {
names := make(map[string]string, len(dependencies))
for _, dependency := range dependencies {
names[dependency.ID] = quiltDependencyName(dependency.ID)
}
return names
}
// quiltDependencyName returns the project identity a dependency names. Quilt
// allows a maven group prefix, but upstream projects and package identities
// are keyed by the mod id alone.
func quiltDependencyName(id string) string {
if _, name, ok := strings.Cut(id, ":"); ok && name != "" {
return name
}
return id
}
func quiltDependencyServerID(name string) bool {
switch name {
case "minecraft", "java", "quilt_loader", "fabricloader":
return true
default:
return false
}
}
// quiltEmbeddedName reports whether a nested jar declares the dependency
// identity. The raw id and its group-free project name are both recorded.
func quiltEmbeddedName(names map[string]struct{}, id string) bool {
if _, ok := names[id]; ok {
return true
}
_, ok := names[quiltDependencyName(id)]
return ok
}
func quiltArtifactMetadata(metadata *quiltMetadata) catalog.Metadata {
if metadata == nil {
return catalog.Metadata{}
}
return catalog.Metadata{
Title: metadata.Name,
Description: metadata.Description,
License: string(metadata.License),
Authors: quiltArtifactAuthors(metadata.Contributors),
URLs: quiltArtifactURLs(metadata.Contact),
}
}
func quiltArtifactAuthors(contributors map[string]any) []catalog.Person {
names := make([]string, 0, len(contributors))
for name := range contributors {
names = append(names, name)
}
sort.Strings(names)
authors := make([]catalog.Person, 0, len(names))
for _, name := range names {
authors = append(authors, catalog.Person{
Name: name,
Role: quiltRole(contributors[name]),
})
}
return authors
}
func quiltArtifactURLs(contact map[string]string) []catalog.URL {
urlSpecs := []struct {
key string
name string
urlType catalog.URLType
}{
{key: "homepage", name: "Homepage", urlType: catalog.URLHome},
{key: "sources", name: "Source", urlType: catalog.URLSource},
{key: "issues", name: "Issues", urlType: catalog.URLIssues},
}
urls := make([]catalog.URL, 0, len(urlSpecs))
for _, spec := range urlSpecs {
url := contact[spec.key]
if url == "" {
continue
}
urls = append(
urls,
catalog.URL{Name: spec.name, Type: spec.urlType, URL: url},
)
}
return urls
}
// quiltEmbeddedNames lists the identities the jars field bundles. Nested jars
// carry their own descriptor, and a jar without one falls back to the filename
// convention used by Fabric wrappers.
func quiltEmbeddedNames(
zipRdr *zip.Reader,
loader *quiltLoader,
) (map[string]struct{}, error) {
dependencyNames := make([]string, 0, len(loader.Depends))
for _, entry := range loader.Depends {
for _, alternative := range entry.serverAlternatives() {
dependencyNames = append(
dependencyNames,
quiltDependencyName(alternative.ID),
)
}
}
names := make(map[string]struct{}, len(loader.Jars))
for _, jar := range loader.Jars {
raw, err := readZipEntryBytes(zipRdr, jar)
if err != nil {
return nil, err
}
if raw == nil {
return nil, fmt.Errorf("missing nested Quilt JAR %s", jar)
}
nested, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
if err != nil {
return nil, err
}
recorded, err := quiltRecordNestedNames(nested, names)
if err != nil {
return nil, err
}
if recorded {
continue
}
base := jar
if _, tail, ok := strings.CutLast(base, "/"); ok {
base = tail
}
base = strings.TrimSuffix(base, ".jar")
for _, name := range dependencyNames {
if base == name || strings.HasPrefix(base, name+"-") {
names[name] = struct{}{}
break
}
}
}
return names, nil
}
func quiltRecordNestedNames(
nested *zip.Reader,
names map[string]struct{},
) (bool, error) {
descriptor, err := readQuiltDescriptor(nested)
if err != nil {
return false, err
}
if descriptor != nil {
quiltRecordNames(names, descriptor.Loader.ID)
for _, provided := range descriptor.Loader.Provides {
quiltRecordNames(names, provided.ID)
}
return true, nil
}
raw, err := readZipEntryBytes(nested, "fabric.mod.json")
if err != nil {
return false, err
}
if raw == nil {
return false, nil
}
fabric := &fileschema.FileFabricModIdentifier{}
if err := unmarshalDescriptor(raw, fabric); err != nil {
return false, err
}
quiltRecordNames(names, fabric.ID)
for _, provided := range fabric.Provides {
quiltRecordNames(names, provided)
}
return true, nil
}
func quiltRecordNames(names map[string]struct{}, id string) {
if id == "" {
return
}
names[id] = struct{}{}
names[quiltDependencyName(id)] = struct{}{}
}
package artifact
import (
"archive/zip"
"errors"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/internal/fn"
"github.com/mclucy/lucy/version"
)
const spongePluginMetadataPath = "META-INF/sponge_plugins.json"
type spongeReader struct{}
func newSpongeReader() Reader {
return &spongeReader{}
}
func (r *spongeReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
for _, f := range zipRdr.File {
if f.Name != spongePluginMetadataPath {
continue
}
rc, err := f.Open()
if err != nil {
return nil, err
}
var metadata fileschema.FileSpongePluginsIdentifier
decodeErr := readDescriptorJSON(rc, &metadata)
if err := errors.Join(decodeErr, rc.Close()); err != nil {
return nil, err
}
if !validSpongeMetadata(&metadata) {
return []PackageInfo{}, nil
}
infos := make([]PackageInfo, 0, len(metadata.Plugins))
for _, plugin := range metadata.Plugins {
info, ok, err := translateSpongePlugin(&metadata, plugin, filePath)
if err != nil {
return nil, err
}
if !ok {
continue
}
infos = append(infos, info)
}
if len(infos) == 0 {
return []PackageInfo{}, nil
}
return infos, nil
}
return nil, nil
}
func validSpongeMetadata(metadata *fileschema.FileSpongePluginsIdentifier) bool {
if strings.TrimSpace(metadata.Loader.Name) == "" ||
strings.TrimSpace(metadata.Loader.Version) == "" ||
len(metadata.Plugins) == 0 {
return false
}
for _, plugin := range metadata.Plugins {
if hasConcreteSpongePluginIdentity(metadata, plugin) {
return true
}
}
return false
}
func hasConcreteSpongePluginIdentity(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
) bool {
if strings.TrimSpace(plugin.ID) == "" || strings.TrimSpace(plugin.Entrypoint) == "" {
return false
}
return strings.TrimSpace(resolveSpongePluginVersion(metadata, plugin)) != ""
}
func translateSpongePlugin(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
localPath string,
) (PackageInfo, bool, error) {
if !hasConcreteSpongePluginIdentity(metadata, plugin) {
return PackageInfo{}, false, nil
}
v := resolveSpongePluginVersion(metadata, plugin)
info := PackageInfo{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(plugin.ID), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemSponge, Version: version.Version(v)},
FilePath: localPath,
Metadata: catalog.Metadata{
Title: fn.Ternary(plugin.Name != "", plugin.Name, plugin.ID),
Description: plugin.Description,
License: strings.Join(metadata.License, ", "),
Authors: translateSpongeContributors(
resolveSpongePluginContributors(metadata, plugin),
),
URLs: translateSpongeLinks(
resolveSpongePluginLinks(metadata, plugin),
),
},
}
deps, err := translateSpongeDependencies(
resolveSpongePluginDependencies(metadata, plugin),
)
if err != nil {
return PackageInfo{}, false, err
}
if len(deps) > 0 {
info.Dependencies = deps
}
return info, true, nil
}
func resolveSpongePluginVersion(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
) string {
if v := strings.TrimSpace(plugin.Version); v != "" {
return v
}
return strings.TrimSpace(metadata.Global.Version)
}
func resolveSpongePluginLinks(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
) struct {
Homepage string
Source string
Issues string
} {
links := struct {
Homepage string
Source string
Issues string
}{
Homepage: metadata.Global.Links.Homepage,
Source: metadata.Global.Links.Source,
Issues: metadata.Global.Links.Issues,
}
if strings.TrimSpace(plugin.Links.Homepage) != "" {
links.Homepage = plugin.Links.Homepage
}
if strings.TrimSpace(plugin.Links.Source) != "" {
links.Source = plugin.Links.Source
}
if strings.TrimSpace(plugin.Links.Issues) != "" {
links.Issues = plugin.Links.Issues
}
return links
}
func resolveSpongePluginContributors(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
) []struct {
Name string
Description string
} {
contributors := metadata.Global.Contributors
if len(plugin.Contributors) > 0 {
contributors = plugin.Contributors
}
resolved := make(
[]struct {
Name string
Description string
}, 0, len(contributors),
)
for _, contributor := range contributors {
resolved = append(
resolved, struct {
Name string
Description string
}{
Name: contributor.Name,
Description: contributor.Description,
},
)
}
return resolved
}
func resolveSpongePluginDependencies(
metadata *fileschema.FileSpongePluginsIdentifier,
plugin fileschema.FileSpongePluginMetadata,
) []struct {
ID string
Version string
LoadOrder string
Optional bool
} {
deps := metadata.Global.Dependencies
if len(plugin.Dependencies) > 0 {
deps = plugin.Dependencies
}
resolved := make(
[]struct {
ID string
Version string
LoadOrder string
Optional bool
}, 0, len(deps),
)
for _, dep := range deps {
resolved = append(
resolved, struct {
ID string
Version string
LoadOrder string
Optional bool
}{
ID: dep.ID,
Version: dep.Version,
LoadOrder: dep.LoadOrder,
Optional: dep.Optional,
},
)
}
return resolved
}
func translateSpongeContributors(
contributors []struct {
Name string
Description string
},
) []catalog.Person {
people := make([]catalog.Person, 0, len(contributors))
for _, contributor := range contributors {
if strings.TrimSpace(contributor.Name) == "" {
continue
}
people = append(
people, catalog.Person{
Name: contributor.Name,
Role: contributor.Description,
},
)
}
return people
}
func translateSpongeLinks(
links struct {
Homepage string
Source string
Issues string
},
) []catalog.URL {
urls := make([]catalog.URL, 0, 3)
if homepage := strings.TrimSpace(links.Homepage); homepage != "" {
urls = append(
urls,
catalog.URL{Name: "Homepage", Type: catalog.URLHome, URL: homepage},
)
}
if source := strings.TrimSpace(links.Source); source != "" {
urls = append(
urls,
catalog.URL{Name: "Source", Type: catalog.URLSource, URL: source},
)
}
if issues := strings.TrimSpace(links.Issues); issues != "" {
urls = append(
urls,
catalog.URL{Name: "Issues", Type: catalog.URLIssues, URL: issues},
)
}
return urls
}
func translateSpongeDependencies(
deps []struct {
ID string
Version string
LoadOrder string
Optional bool
},
) ([]Dependency, error) {
translated := make([]Dependency, 0, len(deps))
for _, dep := range deps {
id := strings.TrimSpace(dep.ID)
v := strings.TrimSpace(dep.Version)
if id == "" || v == "" || strings.EqualFold(id, "spongeapi") {
continue
}
constraint, err := version.ParseConstraint(v, version.DialectMaven)
if err != nil {
return nil, err
}
translated = append(
translated, Dependency{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(id), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemSponge},
Constraint: constraint,
Mandatory: !dep.Optional,
},
)
}
return translated, nil
}
package artifact
import (
"archive/zip"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/version"
"go.yaml.in/yaml/v4"
)
type velocityReader struct{}
type bungeeCordReader struct{}
type velocityPluginDescriptor struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Authors []string `json:"authors"`
URL string `json:"url"`
}
type bungeeCordPluginDescriptor struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
Description string `yaml:"description"`
Author string `yaml:"author"`
Authors []string `yaml:"authors"`
Website string `yaml:"website"`
}
func newVelocityReader() Reader {
return &velocityReader{}
}
func newBungeeCordReader() Reader {
return &bungeeCordReader{}
}
func (r *velocityReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
for _, f := range zipRdr.File {
if f.Name != "velocity-plugin.json" {
continue
}
rc, err := f.Open()
if err != nil {
return nil, err
}
descriptor := &velocityPluginDescriptor{}
decodeErr := readDescriptorJSON(rc, descriptor)
closeErr := rc.Close()
if decodeErr != nil {
return nil, decodeErr
}
if closeErr != nil {
return nil, closeErr
}
authors := make([]catalog.Person, 0, len(descriptor.Authors))
for _, author := range descriptor.Authors {
authors = append(authors, catalog.Person{Name: author})
}
urls := make([]catalog.URL, 0, 1)
if descriptor.URL != "" {
urls = append(
urls, catalog.URL{
Name: "Homepage",
Type: catalog.URLHome,
URL: descriptor.URL,
},
)
}
return []PackageInfo{
{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(descriptor.ID), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemVelocity, Version: version.Version(descriptor.Version)},
FilePath: filePath,
Metadata: catalog.Metadata{
Title: descriptor.Name,
Description: descriptor.Description,
Authors: authors,
URLs: urls,
},
},
}, nil
}
return nil, nil
}
func (r *bungeeCordReader) Read(
zipRdr *zip.Reader,
filePath string,
) ([]PackageInfo, error) {
for _, f := range zipRdr.File {
if f.Name != "bungee.yml" {
continue
}
rc, err := f.Open()
if err != nil {
return nil, err
}
descriptor := &bungeeCordPluginDescriptor{}
if err := yaml.NewDecoder(rc).Decode(descriptor); err != nil {
_ = rc.Close()
return nil, err
}
if err := rc.Close(); err != nil {
return nil, err
}
authors := make([]catalog.Person, 0, len(descriptor.Authors)+1)
if descriptor.Author != "" {
authors = append(authors, catalog.Person{Name: descriptor.Author})
}
for _, author := range descriptor.Authors {
authors = append(authors, catalog.Person{Name: author})
}
urls := make([]catalog.URL, 0, 1)
if descriptor.Website != "" {
urls = append(
urls, catalog.URL{
Name: "Website",
Type: catalog.URLHome,
URL: descriptor.Website,
},
)
}
return []PackageInfo{
{
Ref: catalog.VersionedRef{Ref: catalog.Ref{Name: input.ToProjectName(descriptor.Name), Provider: catalog.ProviderUnknown}, Ecosystem: catalog.EcosystemBungeeCord, Version: version.Version(descriptor.Version)},
FilePath: filePath,
Metadata: catalog.Metadata{
Title: descriptor.Name,
Description: descriptor.Description,
Authors: authors,
URLs: urls,
},
},
}, nil
}
return nil, nil
}
package artifact
import (
"archive/zip"
"github.com/mclucy/lucy/internal/fsutil"
)
// readZipEntryBytes returns the contents of a named ZIP entry, or nil if missing.
func readZipEntryBytes(zipRdr *zip.Reader, name string) ([]byte, error) {
data, _, err := fsutil.ReadZipEntry(
zipRdr,
name,
fsutil.MaxZipEntryBytes,
)
return data, err
}
// Package artifactstore owns the durable per-user store for installed
// artifacts. It is separate from the network cache: entries survive cache
// expiration and clearing, and each registered workspace's lock retains the
// objects its installation pins.
package artifactstore
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/appdata"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
// DirectoryName is the artifact store's directory inside Lucy's per-user
// data root.
DirectoryName = "artifacts"
operationsDirectoryName = "operations"
)
// Directory reports the per-user artifact store directory without creating it.
func Directory() (string, error) {
root, err := appdata.Root()
if err != nil {
return "", err
}
return filepath.Join(root, DirectoryName), nil
}
// Open opens the per-user store, creating its private namespaces when absent.
func Open() (*Store, error) {
directory, err := Directory()
if err != nil {
return nil, fmt.Errorf("locate artifact store: %w", err)
}
return OpenAt(directory)
}
// OpenAt opens a store at an explicit directory. It creates the same private
// object, staging, and operation namespaces as the per-user store.
func OpenAt(directory string) (*Store, error) {
store, err := cas.New(directory)
if err != nil {
return nil, fmt.Errorf("open artifact store: %w", err)
}
operations := filepath.Join(directory, operationsDirectoryName)
if err := createOperations(operations); err != nil {
return nil, errors.Join(fmt.Errorf("open artifact store operations: %w", err), store.Close())
}
snapshots := filepath.Join(directory, snapshotsDirectoryName)
if err := createSnapshots(snapshots); err != nil {
return nil, errors.Join(fmt.Errorf("open artifact store snapshots: %w", err), store.Close())
}
return &Store{Store: store, operations: operations, snapshots: snapshots}, nil
}
// Store is the artifact store's content-addressed storage. Object names never
// carry a consumer's filename or extension; consumers give meaning to a digest
// through their locks.
type Store struct {
*cas.Store
operations string
snapshots string
}
// createOperations creates the private directory that holds the operation gate
// and leases, separate from the content store's staging namespace.
func createOperations(directory string) error {
if err := fsutil.MkdirAllPrivate(directory); err != nil {
return err
}
info, err := os.Lstat(directory)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("operations namespace must be a regular directory")
}
return nil
}
package artifactstore
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/serverregistry"
)
// Report describes one garbage collection. Bytes counts the reclaimed object
// contents, not staging files cleaned separately. SnapshotsRemoved counts
// bootstrap snapshots no registered lock references, including unreadable ones.
type Report struct {
Removed int `json:"removed"`
Bytes int64 `json:"bytes"`
SnapshotsRemoved int `json:"snapshots_removed"`
}
// GC removes objects that no registered server's lock pins. It refuses to
// delete anything when an operation lease is active, when the registry or any
// registered workspace cannot report a complete reference set, when another
// Lucy operation owns a registered workspace, or when a lock names an artifact
// without a usable sha256 digest.
//
// Locks are acquired in one order everywhere: operation gate, workspace writer
// locks, registry mutation lock, then the content store lock. An operation
// creates its lease before taking its workspace lock. A sweep holds the
// operation gate from the lease check through the last removal, so no
// acquisition can start while references are read or objects are deleted.
func (s *Store) GC(registry *serverregistry.Registry) (Report, error) {
if registry == nil {
return Report{}, errors.New("server registry is unavailable")
}
gate, err := s.beginCollection()
if err != nil {
return Report{}, err
}
defer func() { _ = gate.Close() }()
entries, err := registry.List()
if err != nil {
return Report{}, fmt.Errorf("inspect server registry: %w", err)
}
validated, err := validatedEntries(entries)
if err != nil {
return Report{}, err
}
workspaceLocks, err := lockWorkspaces(validated)
if err != nil {
return Report{}, err
}
defer func() {
for i := len(workspaceLocks) - 1; i >= 0; i-- {
_ = workspaceLocks[i].Close()
}
}()
registryLock, err := registry.Lock()
if err != nil {
return Report{}, fmt.Errorf("lock server registry: %w", err)
}
defer func() { _ = registryLock.Close() }()
refreshed, err := registry.List()
if err != nil {
return Report{}, fmt.Errorf("refresh server registry: %w", err)
}
if !sameRegistrySet(validated, refreshed) {
return Report{}, errors.New("registered server set changed during collection; retry")
}
referenced, snapshotKeys, err := lockReferences(validated)
if err != nil {
return Report{}, err
}
snapshotReferences, snapshotsRemoved, err := s.SnapshotReferences(context.Background(), snapshotKeys)
if err != nil {
return Report{}, err
}
for digest := range snapshotReferences {
referenced[digest] = struct{}{}
}
var report Report
report.SnapshotsRemoved = snapshotsRemoved
removed, bytes, err := s.Store.Sweep(func() (map[cas.Digest]struct{}, func() error, error) {
return referenced, nil, nil
})
report.Removed = removed
report.Bytes = bytes
if err != nil {
return report, fmt.Errorf("collect artifact store: %w", err)
}
if err := s.Cleanup(); err != nil {
return report, fmt.Errorf("clean artifact store staging: %w", err)
}
return report, nil
}
// validatedEntries rejects every state whose references cannot be determined
// and returns one entry per canonical path. Lock-only entries are valid: a
// lock-only installation is still a registered server whose lock pins
// artifacts.
func validatedEntries(entries []serverregistry.Entry) ([]serverregistry.Entry, error) {
validated := make([]serverregistry.Entry, 0, len(entries))
seen := make(map[string]struct{}, len(entries))
for _, entry := range entries {
switch entry.State {
case serverregistry.StateAvailable, serverregistry.StateLockOnly:
default:
problem := entry.Problem
if problem == "" {
problem = "the workspace cannot be inspected"
}
if entry.State == serverregistry.StateMissing {
return nil, fmt.Errorf(
"registered server %s is missing: %s; if its directory no longer exists, remove the entry with `lucy server forget <path>`",
displayEntry(entry), problem,
)
}
return nil, fmt.Errorf(
"registered server %s is %s: %s",
displayEntry(entry), entry.State, problem,
)
}
if _, duplicate := seen[entry.Path]; duplicate {
continue
}
seen[entry.Path] = struct{}{}
validated = append(validated, entry)
}
sort.Slice(validated, func(i, j int) bool {
return validated[i].Path < validated[j].Path
})
return validated, nil
}
// lockWorkspaces takes every registered workspace's writer lock without
// creating or changing workspace state. An active operation is a reason to
// refuse collection, not a reason to wait: reference state would keep moving
// while it completed.
func lockWorkspaces(entries []serverregistry.Entry) ([]*fsutil.FileLock, error) {
locks := make([]*fsutil.FileLock, 0, len(entries))
fail := func(reason error) ([]*fsutil.FileLock, error) {
for i := len(locks) - 1; i >= 0; i-- {
_ = locks[i].Close()
}
return nil, reason
}
for _, entry := range entries {
lock, err := lockWorkspace(entry.Path)
if err != nil {
return fail(fmt.Errorf(
"registered server %s cannot be held still: %w",
displayEntry(entry), err,
))
}
locks = append(locks, lock)
}
return locks, nil
}
func lockWorkspace(root string) (*fsutil.FileLock, error) {
relative := ".lucy/" + workspacewrite.LockFileName
if err := workspacewrite.SafePath(root, relative); err != nil {
return nil, err
}
file, err := os.OpenFile(filepath.Join(root, filepath.FromSlash(relative)), os.O_RDWR, 0)
if errors.Is(err, os.ErrNotExist) {
return nil, errors.New("workspace writer lock is missing")
}
if err != nil {
return nil, err
}
lock, err := fsutil.LockOpenedFile(file, false)
if errors.Is(err, fsutil.ErrLocked) {
return nil, errors.New("another Lucy operation is active")
}
return lock, err
}
func sameRegistrySet(expected, current []serverregistry.Entry) bool {
currentByPath := make(map[string]string, len(current))
for _, entry := range current {
currentByPath[entry.Path] = entry.State
}
for _, entry := range expected {
if state, ok := currentByPath[entry.Path]; !ok || state != entry.State {
return false
}
}
return len(currentByPath) == len(expected)
}
func displayEntry(entry serverregistry.Entry) string {
if entry.Name != "" {
return fmt.Sprintf("%q (%s)", entry.Name, entry.Path)
}
return entry.Path
}
func lockReferences(entries []serverregistry.Entry) (map[cas.Digest]struct{}, map[cas.Digest]struct{}, error) {
referenced := make(map[cas.Digest]struct{})
snapshotKeys := make(map[cas.Digest]struct{})
for _, entry := range entries {
journal := filepath.Join(entry.Path, workspacewrite.InstallJournalName)
if _, err := os.Lstat(journal); err == nil {
return nil, nil, fmt.Errorf("registered server %s has an interrupted installation; run `lucy install` in that workspace before collecting", displayEntry(entry))
} else if !errors.Is(err, os.ErrNotExist) {
return nil, nil, fmt.Errorf("inspect installation journal for registered server %s: %w", displayEntry(entry), err)
}
locked, err := document.LockFile(entry.Path).Read()
if errors.Is(err, os.ErrNotExist) {
// A registered workspace without a lock pins no artifacts.
continue
}
if err != nil {
return nil, nil, fmt.Errorf(
"registered server %s has an unreadable lock: %w",
displayEntry(entry), err,
)
}
if err := addLockReferences(referenced, entry, locked); err != nil {
return nil, nil, err
}
key, err := snapshot.Key(locked.Server)
if err != nil {
return nil, nil, fmt.Errorf(
"server %s: bootstrap recipe key: %w",
displayEntry(entry), err,
)
}
snapshotKeys[key] = struct{}{}
}
return referenced, snapshotKeys, nil
}
func addLockReferences(
referenced map[cas.Digest]struct{},
entry serverregistry.Entry,
locked *document.Lock,
) error {
owner := displayEntry(entry)
if err := addArtifactReference(referenced, owner, "server core", locked.Server.Artifact); err != nil {
return err
}
for _, input := range locked.Server.Inputs {
if err := addArtifactReference(referenced, owner, "bootstrap input "+input.ProjectID, input); err != nil {
return err
}
}
for _, pkg := range locked.Packages {
name := "package " + pkg.ProjectID
if pkg.Version != "" {
name += "@" + pkg.Version.String()
}
if err := addArtifactReference(referenced, owner, name, pkg.Artifact); err != nil {
return err
}
}
return nil
}
func addArtifactReference(
referenced map[cas.Digest]struct{},
owner, name string,
artifact catalog.Artifact,
) error {
if artifact.Embedded != "" {
// Embedded inputs are extracted from their pinned parent object.
return nil
}
value := strings.ToLower(strings.TrimSpace(artifact.Hashes["sha256"]))
if value == "" {
return fmt.Errorf(
"server %s: %s has no sha256 digest; its store object cannot be determined",
owner, name,
)
}
digest, err := cas.ParseDigest("sha256:" + value)
if err != nil {
return fmt.Errorf(
"server %s: %s has an invalid sha256 digest %q: %w",
owner, name, value, err,
)
}
referenced[digest] = struct{}{}
return nil
}
package artifactstore
import (
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
operationsLockName = "operations.lock"
operationPrefix = "operation-"
operationSuffix = ".lease"
)
// Lease marks one in-flight operation that may acquire artifacts before it has
// registered a workspace. It is global to the per-user store and survives
// process boundaries through a private file lock. Hold it from before the
// first artifact access through registration, installation, or planning so a
// collection sweep preserves bytes the operation is still using.
type Lease struct {
file *os.File
lock *fsutil.FileLock
name string
closeOnce sync.Once
closeErr error
}
// AcquireOperation acquires a lease on the per-user artifact store.
func AcquireOperation() (*Lease, error) {
store, err := Open()
if err != nil {
return nil, err
}
defer store.Close()
return store.AcquireLease()
}
// AcquireLease creates and locks a unique operation lease. Lease creation is
// serialized by the same gate a collection uses, so a sweep either observes
// the lease before deleting or waits for the lease to exist.
func (s *Store) AcquireLease() (*Lease, error) {
gate, err := fsutil.LockFile(s.operationPath(operationsLockName))
if err != nil {
return nil, fmt.Errorf("lock artifact store operations: %w", err)
}
defer func() { _ = gate.Close() }()
for {
name := s.operationPath(operationPrefix + rand.Text() + operationSuffix)
file, err := os.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600)
if errors.Is(err, os.ErrExist) {
continue
}
if err != nil {
return nil, fmt.Errorf("create artifact store lease: %w", err)
}
lock, err := fsutil.LockOpenedFile(file, false)
if err != nil {
return nil, errors.Join(
fmt.Errorf("lock artifact store lease: %w", err),
os.Remove(name),
)
}
return &Lease{file: file, lock: lock, name: name}, nil
}
}
// Close releases the lease and removes its file. It is idempotent.
func (l *Lease) Close() error {
if l == nil {
return nil
}
l.closeOnce.Do(func() {
var result error
if l.lock != nil {
result = l.lock.Close()
}
if l.file != nil && l.lock == nil {
result = errors.Join(result, l.file.Close())
}
if err := os.Remove(l.name); err != nil && !errors.Is(err, os.ErrNotExist) {
result = errors.Join(result, err)
}
l.closeErr = result
})
return l.closeErr
}
// beginCollection keeps the operation gate held through the sweep so
// operations wait to acquire artifacts until after the last removal.
func (s *Store) beginCollection() (*fsutil.FileLock, error) {
gate, err := fsutil.LockFile(s.operationPath(operationsLockName))
if err != nil {
return nil, fmt.Errorf("lock artifact store operations: %w", err)
}
entries, err := os.ReadDir(s.operations)
if err != nil {
return nil, errors.Join(err, gate.Close())
}
for _, entry := range entries {
name := entry.Name()
if !strings.HasPrefix(name, operationPrefix) || !strings.HasSuffix(name, operationSuffix) {
continue
}
path := s.operationPath(name)
if !entry.Type().IsRegular() {
return nil, errors.Join(
fmt.Errorf("artifact store operation lease %s is not a regular file", path),
gate.Close(),
)
}
file, err := os.OpenFile(path, os.O_RDWR, 0)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, errors.Join(err, gate.Close())
}
lock, lockErr := fsutil.LockOpenedFile(file, false)
if errors.Is(lockErr, fsutil.ErrLocked) {
return nil, errors.Join(
errors.New("another Lucy operation is acquiring or using artifacts"),
gate.Close(),
)
}
if lockErr != nil {
return nil, errors.Join(lockErr, gate.Close())
}
closeErr := lock.Close()
removeErr := os.Remove(path)
if closeErr != nil || removeErr != nil {
return nil, errors.Join(closeErr, removeErr, gate.Close())
}
}
return gate, nil
}
func (s *Store) operationPath(name string) string {
return filepath.Join(s.operations, name)
}
package artifactstore
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
snapshotsDirectoryName = "snapshots"
snapshotManifestSuffix = ".json"
// snapshotManifestLimit bounds a manifest read so a damaged file cannot
// exhaust memory.
snapshotManifestLimit = 32 * 1024 * 1024
)
// LookupSnapshot reads the manifest for key. A missing or unreadable manifest
// reports a miss; the caller then stages the bootstrap from scratch.
func (s *Store) LookupSnapshot(ctx context.Context, key cas.Digest) (snapshot.Snapshot, bool, error) {
if err := ctx.Err(); err != nil {
return snapshot.Snapshot{}, false, err
}
raw, ok, err := s.readSnapshotManifest(key)
if err != nil || !ok {
return snapshot.Snapshot{}, ok, err
}
var snap snapshot.Snapshot
if err := json.Unmarshal(raw, &snap); err != nil {
return snapshot.Snapshot{}, false, fmt.Errorf("decode bootstrap snapshot %s: %w", key.Hex(), err)
}
if snap.Key != key {
return snapshot.Snapshot{}, false, fmt.Errorf(
"bootstrap snapshot %s names a different key %s",
key.Hex(), snap.Key.Hex(),
)
}
if err := snap.Validate(); err != nil {
return snapshot.Snapshot{}, false, fmt.Errorf("invalid bootstrap snapshot %s: %w", key.Hex(), err)
}
return snap, true, nil
}
// SaveSnapshot publishes every entry's contents to the store, then writes the
// manifest. A failure before the manifest write leaves the published objects
// unreferenced.
func (s *Store) SaveSnapshot(ctx context.Context, snap snapshot.Snapshot, sourceDir string) error {
if err := snap.Validate(); err != nil {
return err
}
snap.Entries = slices.Clone(snap.Entries)
slices.SortFunc(snap.Entries, func(a, b snapshot.Entry) int {
return strings.Compare(a.Path, b.Path)
})
for _, entry := range snap.Entries {
if err := ctx.Err(); err != nil {
return err
}
digest, err := cas.ParseDigest("sha256:" + strings.ToLower(entry.SHA256))
if err != nil {
return fmt.Errorf("snapshot entry %s: %w", entry.Path, err)
}
source := filepath.Join(sourceDir, filepath.FromSlash(entry.Path))
if err := s.storeObject(digest, source); err != nil {
return fmt.Errorf("snapshot entry %s: %w", entry.Path, err)
}
}
raw, err := json.Marshal(snap)
if err != nil {
return fmt.Errorf("encode bootstrap snapshot: %w", err)
}
return s.writeSnapshotManifest(snap.Key, raw)
}
// storeObject publishes source at the digest address unless the object is
// already present. Contents are addressed by digest, so a present object needs
// no second read; a corrupt object is replaced when a later writer publishes
// verified bytes at the same address.
func (s *Store) storeObject(digest cas.Digest, source string) error {
if info, err := os.Lstat(s.Path(digest)); err == nil {
if !info.Mode().IsRegular() {
return fmt.Errorf("store object %s is not a regular file", digest.Hex())
}
return nil
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
file, err := os.Open(source)
if err != nil {
return err
}
defer file.Close()
if _, err := s.Store.Put(file, &digest); err != nil {
return err
}
return nil
}
// RestoreSnapshot materializes every entry into destination with link. Each
// stored object is verified against its digest before it is materialized,
// because a clone or a hardlink places bytes that no copy reads. The caller
// owns destination; a failed restore leaves it incomplete, and the caller
// removes it before a cold start.
func (s *Store) RestoreSnapshot(
ctx context.Context,
snap snapshot.Snapshot,
destination string,
link fsutil.LinkMode,
) error {
if err := snap.Validate(); err != nil {
return err
}
if err := os.MkdirAll(destination, 0o755); err != nil {
return fmt.Errorf("create snapshot destination: %w", err)
}
var recoverable error
for _, entry := range snap.Entries {
if err := ctx.Err(); err != nil {
return err
}
digest, err := cas.ParseDigest("sha256:" + strings.ToLower(entry.SHA256))
if err != nil {
return fmt.Errorf("snapshot entry %s: %w", entry.Path, err)
}
if err := s.restoreEntry(digest, entry, destination, link); err != nil {
failure := fmt.Errorf("restore %s: %w", entry.Path, err)
if errors.Is(err, cas.ErrCorrupt) {
// Drop every corrupt object in this restore so one cold
// prepare can republish all of them from checked output.
if _, removeErr := s.Remove(digest); removeErr != nil {
return errors.Join(recoverable, failure, removeErr)
}
} else if !errors.Is(err, os.ErrNotExist) {
return errors.Join(recoverable, failure)
}
recoverable = errors.Join(recoverable, failure)
}
}
return recoverable
}
func (s *Store) restoreEntry(
digest cas.Digest,
entry snapshot.Entry,
destination string,
link fsutil.LinkMode,
) error {
if err := s.verifyObject(digest); err != nil {
return err
}
mode := os.FileMode(entry.Mode)
if mode == 0 {
mode = 0o644
}
target := filepath.Join(destination, filepath.FromSlash(entry.Path))
return fsutil.Materialize(s.Path(digest), target, link.Perm(mode), link)
}
// verifyObject hashes a stored object before a restore places it, because a
// clone or a hardlink never reads the bytes it publishes.
func (s *Store) verifyObject(digest cas.Digest) error {
reader, err := s.Open(digest)
if err != nil {
return err
}
_, copyErr := io.Copy(io.Discard, reader)
return errors.Join(copyErr, reader.Close())
}
// SnapshotKeys lists the keys whose manifests are present, in ascending order.
func (s *Store) SnapshotKeys() ([]cas.Digest, error) {
entries, err := os.ReadDir(s.snapshots)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
keys := make([]cas.Digest, 0, len(entries))
for _, entry := range entries {
key, ok := manifestKey(entry.Name())
if !ok || !entry.Type().IsRegular() {
continue
}
keys = append(keys, key)
}
slices.SortFunc(keys, func(a, b cas.Digest) int {
return strings.Compare(a.Hex(), b.Hex())
})
return keys, nil
}
// RemoveSnapshot deletes one manifest. Its contents stay until a collection
// sweep finds them unreferenced.
func (s *Store) RemoveSnapshot(key cas.Digest) error {
err := os.Remove(filepath.Join(s.snapshots, key.Hex()+snapshotManifestSuffix))
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
// SnapshotReferences reads every retained manifest and reports the object
// digests its entries need.
func (s *Store) SnapshotReferences(
ctx context.Context,
retained map[cas.Digest]struct{},
) (map[cas.Digest]struct{}, int, error) {
keys, err := s.SnapshotKeys()
if err != nil {
return nil, 0, err
}
referenced := make(map[cas.Digest]struct{})
removed := 0
for _, key := range keys {
if err := ctx.Err(); err != nil {
return nil, removed, err
}
if _, keep := retained[key]; !keep {
if err := s.RemoveSnapshot(key); err != nil {
return nil, removed, fmt.Errorf("remove unreferenced bootstrap snapshot %s: %w", key.Hex(), err)
}
removed++
continue
}
snap, ok, err := s.LookupSnapshot(ctx, key)
if err != nil || !ok {
if removeErr := s.RemoveSnapshot(key); removeErr != nil {
return nil, removed, errors.Join(err, removeErr)
}
removed++
continue
}
for _, entry := range snap.Entries {
digest, parseErr := cas.ParseDigest("sha256:" + strings.ToLower(entry.SHA256))
if parseErr != nil {
return nil, removed, fmt.Errorf(
"bootstrap snapshot %s entry %s: %w",
key.Hex(), entry.Path, parseErr,
)
}
referenced[digest] = struct{}{}
}
}
return referenced, removed, nil
}
func (s *Store) readSnapshotManifest(key cas.Digest) ([]byte, bool, error) {
path := filepath.Join(s.snapshots, key.Hex()+snapshotManifestSuffix)
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
if !info.Mode().IsRegular() {
return nil, false, fmt.Errorf("bootstrap snapshot %s is not a regular file", key.Hex())
}
file, err := os.Open(path)
if err != nil {
return nil, false, err
}
defer file.Close()
raw, err := io.ReadAll(io.LimitReader(file, snapshotManifestLimit+1))
if err != nil {
return nil, false, err
}
if len(raw) > snapshotManifestLimit {
return nil, false, fmt.Errorf("bootstrap snapshot %s exceeds %d bytes", key.Hex(), snapshotManifestLimit)
}
return raw, true, nil
}
func (s *Store) writeSnapshotManifest(key cas.Digest, raw []byte) error {
file, err := os.CreateTemp(s.snapshots, ".snapshot-*")
if err != nil {
return err
}
temporary := file.Name()
complete := false
defer func() {
if !complete {
_ = os.Remove(temporary)
}
}()
if err := file.Chmod(0o600); err != nil {
return errors.Join(err, file.Close())
}
if _, err := file.Write(raw); err != nil {
return errors.Join(err, file.Close())
}
if err := file.Close(); err != nil {
return err
}
if err := os.Rename(temporary, filepath.Join(s.snapshots, key.Hex()+snapshotManifestSuffix)); err != nil {
return err
}
complete = true
return nil
}
func manifestKey(name string) (cas.Digest, bool) {
hex, ok := strings.CutSuffix(name, snapshotManifestSuffix)
if !ok {
return cas.Digest{}, false
}
digest, err := cas.ParseDigest("sha256:" + hex)
if err != nil {
return cas.Digest{}, false
}
return digest, true
}
// createSnapshots creates the private namespace that holds snapshot manifests.
func createSnapshots(directory string) error {
if err := fsutil.MkdirAllPrivate(directory); err != nil {
return err
}
info, err := os.Lstat(directory)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("snapshots namespace must be a regular directory")
}
return nil
}
package bootstrap
import (
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/document"
serverpkg "github.com/mclucy/lucy/server"
)
// OutputPolicy defines the lifecycle and ownership of an output file.
type OutputPolicy string
const (
// PolicyManaged designates outputs that Lucy owns, manages, and protects
// against local user modifications.
PolicyManaged OutputPolicy = "managed"
// PolicySeed designates output files initialized only when missing;
// subsequent content is user-owned and never clobbered or pruned.
PolicySeed OutputPolicy = "seed"
// PolicyDiscard designates outputs generated in staging for execution
// purposes that must never be committed to the workspace runtime.
PolicyDiscard OutputPolicy = "discard"
)
// MaterialRole defines the operational purpose of input or staging material.
type MaterialRole string
const (
// RoleRuntime designates material intended for runtime execution.
RoleRuntime MaterialRole = "runtime"
// RoleBootstrapOnly designates material required only during installation
// or bootstrap execution, not to be retained in runtime output.
RoleBootstrapOnly MaterialRole = "bootstrap-only"
)
// OutputOrigin indicates whether an output is generated by the bootstrap method
// or supplied as a locked input.
type OutputOrigin string
const (
// OriginGenerated designates outputs generated or extracted by bootstrap execution.
OriginGenerated OutputOrigin = "generated"
// OriginInput designates inputs supplied from locked artifacts.
OriginInput OutputOrigin = "input"
)
// OutputSpec describes a declared exact output path or bounded directory scope.
type OutputSpec struct {
// Path is the server-relative exact path (if exact).
Path string
// Scope is the server-relative bounded directory prefix (if dynamic).
Scope string
// Policy is the ownership policy for matching files.
Policy OutputPolicy
// Role is the material role for matching files.
Role MaterialRole
// Origin indicates whether the path originates from a locked input or generated output.
Origin OutputOrigin
}
// Output describes a file in the staged image.
type Output struct {
// Path is the workspace-relative path (e.g. "server.jar" or "server/server.jar").
Path string
// ServerPath is the server-relative path (e.g. "server.jar").
ServerPath string
// SHA256 is the hexadecimal SHA-256 digest of the file contents.
SHA256 string
// Mode is the file permission bits.
Mode uint32
// Policy is the ownership policy (managed, seed, discard).
Policy OutputPolicy
// Role is the material role (runtime, bootstrap-only).
Role MaterialRole
}
// validateContract checks the locked server's bootstrap method, locked inputs, and declared outputs.
// It detects and rejects:
// - Unsupported bootstrap methods.
// - Collisions between locked inputs or with generated outputs, such as a loader library.
// - Overlaps where an exact input or output conflicts with a scope policy or role.
// - Overlaps between scopes with conflicting policies or roles.
func validateContract(locked document.LockedServer) (map[string]OutputSpec, []OutputSpec, error) {
var generated []OutputSpec
var scopes []OutputSpec
switch locked.Bootstrap {
case serverpkg.BootstrapMethodVanilla:
generated = []OutputSpec{
{Path: "server.jar", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
}
case serverpkg.BootstrapMethodPaperclip:
generated = []OutputSpec{
{Path: "server.jar", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
}
scopes = []OutputSpec{
{Scope: "versions/", Policy: PolicyManaged, Role: RoleRuntime},
{Scope: "libraries/", Policy: PolicyManaged, Role: RoleRuntime},
{Scope: "cache/", Policy: PolicyManaged, Role: RoleRuntime},
}
case serverpkg.BootstrapMethodFabric:
loaderPath, err := fabricLoaderPath(locked.CoreVersion.String())
if err != nil {
return nil, nil, fmt.Errorf("resolving Fabric loader path: %w", err)
}
generated = []OutputSpec{
{Path: "run.sh", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "run.bat", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "fabric-server-launch.jar", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "fabric-server-launcher.properties", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: loaderPath, Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
}
scopes = []OutputSpec{
{Scope: "libraries/", Policy: PolicyManaged, Role: RoleRuntime},
}
case serverpkg.BootstrapMethodQuilt:
loaderPath, err := quiltLoaderPath(locked.CoreVersion.String())
if err != nil {
return nil, nil, fmt.Errorf("resolving Quilt loader path: %w", err)
}
generated = []OutputSpec{
{Path: "quilt-server-launch.jar", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "quilt-server-launcher.properties", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: loaderPath, Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
}
scopes = []OutputSpec{
{Scope: "libraries/", Policy: PolicyManaged, Role: RoleRuntime},
}
case serverpkg.BootstrapMethodForge:
generated = []OutputSpec{
{Path: "run.sh", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "run.bat", Policy: PolicyManaged, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "user_jvm_args.txt", Policy: PolicySeed, Role: RoleRuntime, Origin: OriginGenerated},
{Path: "README.txt", Policy: PolicySeed, Role: RoleRuntime, Origin: OriginGenerated},
}
scopes = []OutputSpec{
{Scope: ".bootstrap-data/", Policy: PolicyDiscard, Role: RoleBootstrapOnly},
{Scope: "libraries/", Policy: PolicyManaged, Role: RoleRuntime},
}
default:
return nil, nil, fmt.Errorf("unsupported bootstrap method %q", locked.Bootstrap)
}
for i := range scopes {
sc := filepath.ToSlash(filepath.Clean(scopes[i].Scope))
if !strings.HasSuffix(sc, "/") {
sc += "/"
}
scopes[i].Scope = sc
}
placed, err := inputPaths(locked)
if err != nil {
return nil, nil, err
}
exact := make(map[string]OutputSpec, len(generated)+len(placed))
for i := range generated {
gen := &generated[i]
gen.Path = filepath.ToSlash(filepath.Clean(gen.Path))
exact[gen.Path] = *gen
}
for _, clean := range placed {
// A Maven input can land on the generated loader library.
if gen, ok := exact[clean]; ok {
return nil, nil, fmt.Errorf(
"collision between locked input and generated bootstrap output claiming %q "+
"(input policy %s vs generated policy %s)",
clean, PolicyManaged, gen.Policy,
)
}
policy := PolicyManaged
role := RoleRuntime
if locked.Bootstrap == serverpkg.BootstrapMethodForge && isForgeDiscardInput(clean) {
policy = PolicyDiscard
role = RoleBootstrapOnly
}
for _, sc := range scopes {
if strings.HasPrefix(clean, sc.Scope) {
if policy != sc.Policy || role != sc.Role {
return nil, nil, fmt.Errorf("locked input %q (%s/%s) conflicts with bootstrap scope %q (%s/%s)", clean, policy, role, sc.Scope, sc.Policy, sc.Role)
}
}
}
exact[clean] = OutputSpec{
Path: clean,
Policy: policy,
Role: role,
Origin: OriginInput,
}
}
for _, gen := range generated {
for _, sc := range scopes {
if strings.HasPrefix(gen.Path, sc.Scope) {
if gen.Policy != sc.Policy || gen.Role != sc.Role {
return nil, nil, fmt.Errorf("generated output %q (%s/%s) conflicts with bootstrap scope %q (%s/%s)", gen.Path, gen.Policy, gen.Role, sc.Scope, sc.Policy, sc.Role)
}
}
}
}
for i := range scopes {
for j := i + 1; j < len(scopes); j++ {
s1 := scopes[i]
s2 := scopes[j]
if strings.HasPrefix(s1.Scope, s2.Scope) || strings.HasPrefix(s2.Scope, s1.Scope) {
if s1.Policy != s2.Policy || s1.Role != s2.Role {
return nil, nil, fmt.Errorf("conflicting overlapping bootstrap scopes: %q (%s/%s) vs %q (%s/%s)", s1.Scope, s1.Policy, s1.Role, s2.Scope, s2.Policy, s2.Role)
}
}
}
}
return exact, scopes, nil
}
// OutputSpecs reports the declared output paths and bounded scopes of a locked server.
func OutputSpecs(locked document.LockedServer) []OutputSpec {
exact, scopes, err := validateContract(locked)
if err != nil {
return nil
}
specs := make([]OutputSpec, 0, len(exact)+len(scopes))
for _, spec := range exact {
specs = append(specs, spec)
}
specs = append(specs, scopes...)
slices.SortFunc(specs, func(a, b OutputSpec) int {
if a.Path != "" && b.Path != "" {
return strings.Compare(a.Path, b.Path)
}
if a.Path != "" {
return -1
}
if b.Path != "" {
return 1
}
return strings.Compare(a.Scope, b.Scope)
})
return specs
}
package bootstrap
import (
"archive/zip"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
)
// prepareFabric places the Fabric loader on the classpath and generates the
// launch scripts and shim JAR that start it.
func prepareFabric(root string, server document.LockedServer, corePath string, link fsutil.LinkMode) error {
loaderPath, err := fabricLoaderPath(server.CoreVersion.String())
if err != nil {
return err
}
placed, err := inputPaths(server)
if err != nil {
return err
}
if err := placeArtifact(corePath, filepath.Join(root, filepath.FromSlash(loaderPath)), link); err != nil {
return err
}
classpath := loaderClasspath(loaderPath, placed)
unix := strings.Join(classpath, ":")
windows := strings.Join(classpath, ";")
if err := os.WriteFile(filepath.Join(root, "run.sh"), []byte("#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec java -cp '"+unix+"' "+fabricLauncherMainClass+" nogui \"$@\"\n"), 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(root, "run.bat"), []byte("@echo off\r\ncd /d %~dp0\r\njava -cp \""+windows+"\" "+fabricLauncherMainClass+" nogui %*\r\n"), 0o644); err != nil {
return err
}
if err := writeFabricShimJar(filepath.Join(root, "fabric-server-launch.jar"), classpath); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(root, "fabric-server-launcher.properties"), []byte("serverJar=server.jar\n"), 0o644); err != nil {
return err
}
return nil
}
const (
// fabricLauncherMainClass is the entry point of the Fabric launcher JAR.
fabricLauncherMainClass = "net.fabricmc.loader.impl.launch.server.FabricServerLauncher"
// fabricKnotMainClass is the server main class the launcher starts.
fabricKnotMainClass = "net.fabricmc.loader.impl.launch.knot.KnotServer"
)
func writeFabricShimJar(path string, classpath []string) error {
return writeLauncherShimJar(
path,
"fabric-server-launch.properties",
fabricLauncherMainClass,
fabricKnotMainClass,
classpath,
)
}
// writeLauncherShimJar writes the manifest-only launcher JAR shared by the
// loader methods. The embedded properties entry selects the server main class.
func writeLauncherShimJar(path, propertiesEntry, mainClass, launchMainClass string, classpath []string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
writer := zip.NewWriter(file)
defer writer.Close()
manifest := "Manifest-Version: 1.0\nMain-Class: " + mainClass + "\n" +
wrapLongLine("Class-Path: "+strings.Join(classpath, " "), 70) + "\n"
manifestEntry, err := writer.Create("META-INF/MANIFEST.MF")
if err != nil {
return err
}
if _, err := manifestEntry.Write([]byte(manifest)); err != nil {
return err
}
propertiesEntryWriter, err := writer.Create(propertiesEntry)
if err != nil {
return err
}
_, err = propertiesEntryWriter.Write([]byte("launch.mainClass=" + launchMainClass + "\n"))
return err
}
func wrapLongLine(line string, width int) string {
if len(line) <= width {
return line
}
var builder strings.Builder
for len(line) > width {
builder.WriteString(line[:width])
builder.WriteByte('\n')
builder.WriteByte(' ')
line = line[width:]
}
builder.WriteString(line)
return builder.String()
}
package bootstrap
import (
"archive/zip"
"context"
"crypto/sha1"
"encoding/hex"
"encoding/json/v2"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/maven"
"github.com/mclucy/lucy/internal/workspacewrite"
)
// prepareForgeInstaller runs the processors of a Forge or NeoForge installer
// profile and materializes the server launch scripts they generate.
func prepareForgeInstaller(ctx context.Context, root string, server document.LockedServer, corePath string, z *zip.Reader, java string, output io.Writer, progress Progress) error {
profile, err := readForgeProfile(z)
if err != nil {
return err
}
if profile.Path != "" {
if err := extractProfileArtifact(root, z, profile.Path); err != nil {
return err
}
}
vars, err := forgeVars(root, corePath, server, profile.Data)
if err != nil {
return err
}
for key, value := range profile.Data {
if !strings.HasPrefix(value.Server, "/") {
continue
}
if err := extractLockedEntry(
z, strings.TrimPrefix(value.Server, "/"), vars[key],
); err != nil {
return err
}
}
expand := func(value string) (string, error) {
return expandForgeValue(root, vars, value)
}
serverProcessors := 0
for _, proc := range profile.Processors {
if serverSideProcessor(proc.Sides) {
serverProcessors++
}
}
processorStart := time.Now()
processed := 0
if serverProcessors > 0 {
progress.started("processors")
}
for _, proc := range profile.Processors {
if len(proc.Sides) > 0 {
if !serverSideProcessor(proc.Sides) {
continue
}
}
args := make([]string, len(proc.Args))
for i, arg := range proc.Args {
args[i], err = expand(arg)
if err != nil {
return err
}
}
mappingTask := false
var mappingOutput string
for i, arg := range args {
if arg == "DOWNLOAD_MOJMAPS" {
mappingTask = true
}
if arg == "--output" && i+1 < len(args) {
mappingOutput = args[i+1]
}
}
if mappingTask {
if mappingOutput == "" {
return fmt.Errorf("mojang mappings processor has no output")
}
relative, err := filepath.Rel(root, mappingOutput)
if err != nil || !filepath.IsLocal(relative) {
return fmt.Errorf("installer mapping output %q escapes staging", mappingOutput)
}
if err := workspacewrite.SafePath(root, relative); err != nil {
return err
}
if err := fsutil.AtomicCopyFile(filepath.Join(root, "server-mappings.txt"), mappingOutput, 0o644); err != nil {
return err
}
processed++
progress.progressed("processors", processed, serverProcessors)
continue
}
p, err := safeForgeMavenPath(proc.Jar)
if err != nil {
return err
}
processorJar := filepath.Join(root, "libraries", p)
main, err := jarMain(processorJar)
if err != nil {
return err
}
classpath := []string{processorJar}
for _, coordinate := range proc.Classpath {
p, err := safeForgeMavenPath(coordinate)
if err != nil {
return err
}
classpath = append(classpath, filepath.Join(root, "libraries", p))
}
commandArgs := []string{
"-cp",
strings.Join(classpath, string(os.PathListSeparator)),
main,
}
commandArgs = append(commandArgs, args...)
if err := requireJava(java, "installer processor "+proc.Jar); err != nil {
return err
}
cmd := exec.CommandContext(ctx, java, commandArgs...)
cmd.Dir = root
if err := runLockedProcess(cmd, output); err != nil {
return fmt.Errorf("installer processor %s: %w", proc.Jar, err)
}
for name, expected := range proc.Outputs {
destination, err := expand(name)
if err != nil {
return err
}
expected, err = expand(expected)
if err != nil {
return err
}
if err := checkProcessorOutput(destination, expected); err != nil {
return err
}
}
processed++
progress.progressed("processors", processed, serverProcessors)
}
if serverProcessors > 0 {
progress.done("processors", time.Since(processorStart), processed, serverProcessors)
}
// Profile extraction processors generate the native server launch scripts.
argsPath := forgeArgsPath(server.Product, server.Minecraft.String(), server.CoreVersion.String())
if _, err := os.Stat(filepath.Join(root, "run.sh")); err != nil {
if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(argsPath))); err != nil {
return fmt.Errorf("installer did not generate server launch arguments: %w", err)
}
if err := os.WriteFile(filepath.Join(root, "run.sh"), []byte("#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec java @user_jvm_args.txt @"+argsPath+" \"$@\"\n"), 0o755); err != nil {
return err
}
}
if _, err := os.Stat(filepath.Join(root, "run.bat")); os.IsNotExist(err) {
winArgsPath := forgeWinArgsPath(server.Product, server.Minecraft.String(), server.CoreVersion.String())
argsForBat := winArgsPath
if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(winArgsPath))); err != nil {
argsForBat = argsPath
}
if err := os.WriteFile(filepath.Join(root, "run.bat"), []byte("@echo off\r\ncd /d %~dp0\r\njava @user_jvm_args.txt @"+argsForBat+" %*\r\n"), 0o644); err != nil {
return err
}
}
if _, err := os.Stat(filepath.Join(root, "user_jvm_args.txt")); os.IsNotExist(err) {
if err := os.WriteFile(filepath.Join(root, "user_jvm_args.txt"), nil, 0o644); err != nil {
return err
}
}
return nil
}
// extractProfileArtifact writes the launch artifact an installer profile
// names. The installer bundles it under maven/, mirroring the repository path
// it would otherwise download, and extracts it to the server root under its
// filename. Shim-era Forge profiles name the root shim here.
func extractProfileArtifact(root string, z *zip.Reader, coordinate string) error {
rel, err := maven.Path(coordinate)
if err != nil {
return fmt.Errorf("installer profile artifact: %w", err)
}
if err := document.SafeRelativePath(rel); err != nil || !filepath.IsLocal(rel) {
return fmt.Errorf("invalid installer profile artifact %q", coordinate)
}
return extractLockedEntry(
z,
"maven/"+rel,
filepath.Join(root, filepath.Base(rel)),
)
}
func safeForgeMavenPath(coordinate string) (string, error) {
p, err := maven.Path(coordinate)
if err != nil {
return "", err
}
if err := document.SafeRelativePath(p); err != nil || !filepath.IsLocal(p) {
return "", fmt.Errorf("invalid installer coordinate %q", coordinate)
}
return p, nil
}
func readLockedEntry(z *zip.Reader, name string) ([]byte, error) {
raw, found, err := fsutil.ReadZipEntry(
z,
name,
fsutil.MaxNestedZipEntryBytes,
)
if err != nil {
return nil, err
}
if !found {
return nil, fmt.Errorf("missing installer metadata %s", name)
}
return raw, nil
}
func jarMain(p string) (string, error) {
z, err := zip.OpenReader(p)
if err != nil {
return "", err
}
defer z.Close()
raw, err := readLockedEntry(&z.Reader, "META-INF/MANIFEST.MF")
if err != nil {
return "", err
}
for line := range strings.SplitSeq(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n") {
if v, ok := strings.CutPrefix(line, "Main-Class: "); ok {
return strings.TrimSpace(v), nil
}
}
return "", fmt.Errorf("processor JAR has no Main-Class")
}
func checkProcessorOutput(filename, expected string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
h := sha1.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
if actual := hex.EncodeToString(h.Sum(nil)); actual != expected {
return fmt.Errorf("processor output %s: expected sha1 %s, got %s", filename, expected, actual)
}
return nil
}
// serverSideProcessor reports whether a profile processor runs for the server
// side. A processor that declares no sides runs for both.
func serverSideProcessor(sides []string) bool {
if len(sides) == 0 {
return true
}
return slices.Contains(sides, "server")
}
// forgeInstallProfile is the subset of a Forge or NeoForge install profile
// that Lucy executes and verifies.
type forgeInstallProfile struct {
// Path names the launch artifact the installer extracts from its bundled
// Maven tree. Shim-era Forge profiles name the root shim.
Path string `json:"path"`
Data map[string]forgeProfileSide `json:"data"`
Processors []forgeProcessor `json:"processors"`
}
type forgeProfileSide struct {
Server string `json:"server"`
}
type forgeProcessor struct {
Sides []string `json:"sides"`
Jar string `json:"jar"`
Classpath []string `json:"classpath"`
Args []string `json:"args"`
Outputs map[string]string `json:"outputs"`
}
func readForgeProfile(z *zip.Reader) (forgeInstallProfile, error) {
raw, err := readLockedEntry(z, "install_profile.json")
if err != nil {
return forgeInstallProfile{}, err
}
var profile forgeInstallProfile
if err := json.Unmarshal(raw, &profile); err != nil {
return forgeInstallProfile{}, err
}
return profile, nil
}
// forgeVars maps profile tokens to server-side values. A value that names a
// file inside the installer resolves to the staging path the extractor writes,
// so the same map expands execution arguments and verification paths.
func forgeVars(
root, installer string,
server document.LockedServer,
data map[string]forgeProfileSide,
) (map[string]string, error) {
vars := map[string]string{
"SIDE": "server",
"ROOT": root,
"LIBRARY_DIR": filepath.Join(root, "libraries"),
"INSTALLER": installer,
"MINECRAFT_VERSION": server.Minecraft.String(),
"MINECRAFT_JAR": filepath.Join(root, "server.jar"),
}
for key, value := range data {
if strings.HasPrefix(value.Server, "/") {
if key == "" || key == "." || key == ".." || strings.ContainsAny(key, "/\\") {
return nil, fmt.Errorf("invalid installer data key %q", key)
}
vars[key] = filepath.Join(root, ".bootstrap-data", key)
continue
}
vars[key] = value.Server
}
return vars, nil
}
// expandForgeValue resolves one install-profile token, quoted literal, or
// Maven coordinate against root and vars.
func expandForgeValue(root string, vars map[string]string, value string) (string, error) {
if strings.HasPrefix(value, "'") && strings.HasSuffix(value, "'") {
return strings.Trim(value, "'"), nil
}
if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") {
p, err := safeForgeMavenPath(value[1 : len(value)-1])
return filepath.Join(root, "libraries", p), err
}
for range 16 {
start := strings.IndexByte(value, '{')
if start < 0 {
return value, nil
}
end := strings.IndexByte(value[start:], '}')
if end < 0 {
return "", fmt.Errorf("invalid processor token %q", value)
}
end += start
key := value[start+1 : end]
replacement, ok := vars[key]
if !ok {
return "", fmt.Errorf("unknown processor variable %s", key)
}
if strings.HasPrefix(replacement, "[") {
var err error
replacement, err = expandForgeValue(root, vars, replacement)
if err != nil {
return "", err
}
} else {
replacement = strings.Trim(replacement, "'")
}
value = value[:start] + replacement + value[end+1:]
}
return "", fmt.Errorf("recursive installer variable expansion")
}
package bootstrap
import (
"cmp"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/fs"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/mclucy/lucy/document"
)
// StagedImage classifies and digests every file a method produced under the
// server root of stageRoot. The result is the runtime image of the recipe:
// each file with its policy and role from the method's declared outputs,
// sorted by path. Stage-only material is listed with its policy so the
// commit discards it.
//
// The method is the only writer of the stage, so the image needs no proof
// beyond its declaration. A file outside every declared output or a missing
// exact output is a method defect and fails the build.
func StagedImage(stageRoot string, locked document.LockedServer) ([]Output, error) {
exact, scopes, err := validateContract(locked)
if err != nil {
return nil, fmt.Errorf("invalid bootstrap output contract: %w", err)
}
optional := optionalOutputs(locked)
serverRoot, err := stagedServerRoot(stageRoot, locked.Directory)
if err != nil {
return nil, err
}
outputs := make([]Output, 0, len(exact))
produced := make(map[string]bool, len(exact))
type stagedFile struct {
path string
rel string
spec OutputSpec
mode uint32
}
var files []stagedFile
err = filepath.WalkDir(serverRoot, func(p string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if p == serverRoot {
return nil
}
rel, err := filepath.Rel(serverRoot, p)
if err != nil {
return err
}
rel = filepath.ToSlash(filepath.Clean(rel))
if entry.IsDir() {
return nil
}
if entry.Type()&fs.ModeSymlink != 0 {
return fmt.Errorf("bootstrap method %s wrote symlink %s", locked.Bootstrap, rel)
}
if !entry.Type().IsRegular() {
return fmt.Errorf("bootstrap method %s wrote non-regular file %s", locked.Bootstrap, rel)
}
spec, declared := classifyOutput(rel, exact, optional, scopes)
if !declared {
return fmt.Errorf("bootstrap method %s wrote undeclared file %s", locked.Bootstrap, rel)
}
info, err := entry.Info()
if err != nil {
return err
}
produced[rel] = true
files = append(files, stagedFile{
path: p,
rel: rel,
spec: spec,
mode: uint32(info.Mode().Perm()),
})
return nil
})
if err != nil {
return nil, err
}
digests := make([]string, len(files))
digestErrs := make([]error, len(files))
workers := min(len(files), 4)
var next atomic.Int64
var group sync.WaitGroup
for range workers {
group.Go(func() {
for {
index := int(next.Add(1)) - 1
if index >= len(files) {
return
}
digests[index], digestErrs[index] = fileSHA256(files[index].path)
}
})
}
group.Wait()
for _, err := range digestErrs {
if err != nil {
return nil, err
}
}
for i, file := range files {
outputs = append(outputs, Output{
Path: filepath.ToSlash(filepath.Join(locked.Directory, file.rel)),
ServerPath: file.rel,
SHA256: digests[i],
Mode: file.mode,
Policy: file.spec.Policy,
Role: file.spec.Role,
})
}
for _, rel := range slices.Sorted(maps.Keys(exact)) {
spec := exact[rel]
if spec.Policy != PolicyManaged || produced[rel] {
continue
}
return nil, fmt.Errorf("bootstrap method %s did not produce %s", locked.Bootstrap, rel)
}
slices.SortFunc(outputs, func(a, b Output) int {
return strings.Compare(a.Path, b.Path)
})
return outputs, nil
}
// optionalOutputs declares the server-root files a method writes outside its
// exact paths and scopes. A shim-era Forge installer extracts its profile
// launch artifact at the server root. Later installer generations write no
// root shim, so the path is classified when present and never required.
func optionalOutputs(locked document.LockedServer) map[string]OutputSpec {
shim := forgeRootShimPath(locked)
if shim == "" {
return nil
}
return map[string]OutputSpec{
shim: {
Path: shim,
Policy: PolicyManaged,
Role: RoleRuntime,
Origin: OriginGenerated,
},
}
}
// scopeOutput returns the declaration of the longest scope that bounds rel.
func scopeOutput(rel string, scopes []OutputSpec) (OutputSpec, bool) {
var matched OutputSpec
found := false
for _, scope := range scopes {
if !strings.HasPrefix(rel, scope.Scope) {
continue
}
if !found || len(scope.Scope) > len(matched.Scope) {
matched, found = scope, true
}
}
return matched, found
}
// stagedServerRoot rejects a symlink or non-directory in the staged server path.
func stagedServerRoot(stage, directory string) (string, error) {
relative := filepath.FromSlash(cmp.Or(directory, "."))
if err := document.SafeRelativePath(relative); err != nil {
return "", err
}
relative = filepath.Clean(relative)
root := filepath.Clean(stage)
for {
info, err := os.Lstat(root)
if err != nil {
return "", fmt.Errorf("inspect staged server directory: %w", err)
}
if !info.IsDir() {
return "", fmt.Errorf("staged server path %s is not a directory", root)
}
if relative == "." || relative == "" {
return root, nil
}
part, rest, _ := strings.Cut(relative, string(filepath.Separator))
root = filepath.Join(root, part)
relative = rest
}
}
func fileSHA256(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
// ClassifyOutput returns the declaration of the method of locked that covers
// the server-relative path rel. The second result is false for a path the
// method does not write.
func ClassifyOutput(locked document.LockedServer, rel string) (OutputSpec, bool, error) {
exact, scopes, err := validateContract(locked)
if err != nil {
return OutputSpec{}, false, fmt.Errorf("invalid bootstrap output contract: %w", err)
}
spec, declared := classifyOutput(rel, exact, optionalOutputs(locked), scopes)
return spec, declared, nil
}
// classifyOutput matches an exact output first, then an optional output, then
// the longest scope.
func classifyOutput(
rel string,
exact, optional map[string]OutputSpec,
scopes []OutputSpec,
) (OutputSpec, bool) {
if spec, ok := exact[rel]; ok {
return spec, true
}
if spec, ok := optional[rel]; ok {
return spec, true
}
return scopeOutput(rel, scopes)
}
package bootstrap
import (
"fmt"
"path"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/maven"
serverpkg "github.com/mclucy/lucy/server"
)
// CorePath returns the server-relative path where the method keeps the core
// artifact unchanged, or an empty path when it keeps no copy.
func CorePath(locked document.LockedServer) (string, error) {
switch locked.Bootstrap {
case serverpkg.BootstrapMethodVanilla, serverpkg.BootstrapMethodPaperclip:
return "server.jar", nil
case serverpkg.BootstrapMethodFabric:
return fabricLoaderPath(locked.CoreVersion.String())
case serverpkg.BootstrapMethodQuilt:
return quiltLoaderPath(locked.CoreVersion.String())
case serverpkg.BootstrapMethodForge:
return "", nil
default:
return "", locked.Bootstrap.Validate()
}
}
// InputPath places one locked input in the server tree of method. The lock
// records what an input is; this function owns where it lands. Libraries
// follow the Maven layout under libraries/. The Mojang server jar lands where
// the method's launcher or patcher reads it.
func InputPath(method serverpkg.BootstrapMethod, input catalog.Artifact) (string, error) {
var placed string
switch {
case input.Provider == catalog.ProviderMaven:
p, err := maven.Path(input.ProjectID)
if err != nil {
return "", err
}
placed = path.Join("libraries", p)
if !strings.HasPrefix(placed, "libraries/") {
return "", fmt.Errorf("library %s escapes libraries/", input.ProjectID)
}
case input.Provider == catalog.ProviderMojang && input.ProjectID == "minecraft":
placed = "server.jar"
if method == serverpkg.BootstrapMethodPaperclip {
// Paperclip reads the Mojang jar from the cache name its download
// context declares; routing verifies that name matches this one.
v := input.Version.String()
if v == "" || strings.ContainsAny(v, "/\\") || strings.Contains(v, "..") {
return "", fmt.Errorf("invalid Mojang server version %q", v)
}
placed = "cache/mojang_" + v + ".jar"
}
case input.Provider == catalog.ProviderMojang && input.ProjectID == "server-mappings":
placed = "server-mappings.txt"
default:
return "", fmt.Errorf(
"bootstrap input %s:%s has no place in a %s server tree",
input.Provider, input.ProjectID, method,
)
}
if err := document.SafeRelativePath(placed); err != nil {
return "", err
}
return placed, nil
}
// inputPaths places every locked input of server in input order.
func inputPaths(server document.LockedServer) ([]string, error) {
paths := make([]string, len(server.Inputs))
seen := make(map[string]bool, len(server.Inputs))
for i, input := range server.Inputs {
placed, err := InputPath(server.Bootstrap, input)
if err != nil {
return nil, err
}
if seen[placed] {
return nil, fmt.Errorf("two locked inputs land at %s", placed)
}
seen[placed] = true
paths[i] = placed
}
return paths, nil
}
package bootstrap
import (
"context"
"errors"
"fmt"
"io"
"os/exec"
"github.com/mclucy/lucy/artifact"
versionpkg "github.com/mclucy/lucy/version"
)
// ErrInstallerUnsupported reports an identified installer whose native method
// this package cannot execute yet.
var ErrInstallerUnsupported = errors.New("installer execution is not supported")
// InstallerSupported reports whether RunInstaller can execute kind natively.
// Callers use it before selecting Java for an installer they cannot run.
func InstallerSupported(kind artifact.InstallerKind) bool {
switch kind {
case artifact.InstallerForge, artifact.InstallerNeoForge:
return true
default:
return false
}
}
// RunInstaller executes an identified installer with its native entry point
// in root. It requires a Java executable for every supported installer.
func RunInstaller(
ctx context.Context,
root string,
installer artifact.Installer,
java string,
output io.Writer,
) error {
switch installer.Kind {
case artifact.InstallerForge, artifact.InstallerNeoForge:
if err := requireJava(java, fmt.Sprintf("%s installer", installer.Kind)); err != nil {
return err
}
cmd := exec.CommandContext(ctx, java, "-jar", installer.FilePath, "--installServer")
cmd.Dir = root
if err := runLockedProcess(cmd, output); err != nil {
return fmt.Errorf("%s installer: %w", installer.Kind, err)
}
return nil
default:
return fmt.Errorf("%w: %s", ErrInstallerUnsupported, installer.Kind)
}
}
// nativeInstallerJava is the Java major version a Forge-family native
// installer needs. It does not depend on the Minecraft version the installer
// provisions.
const nativeInstallerJava = 17
// InstallerJavaAdvisory returns the Java major version an installer for the
// given Minecraft version needs. A version whose release line is unknown
// answers the native installer's own minimum.
func InstallerJavaAdvisory(installer artifact.Installer) int {
parsed, err := versionpkg.ParseVersion(
installer.Minecraft,
versionpkg.DialectMinecraft,
)
if err != nil {
return nativeInstallerJava
}
minecraft, ok := parsed.(*versionpkg.MinecraftVersion)
if !ok || minecraft.Post26 {
// A snapshot or a year-scheme release names no line this table
// covers, so only the installer's own minimum is known.
return nativeInstallerJava
}
switch {
case minecraft.Year == 1 &&
(minecraft.Update > 20 || minecraft.Update == 20 && minecraft.Hotfix >= 5):
return 21
case minecraft.Year == 1 && minecraft.Update >= 18:
return 17
case minecraft.Year == 1 && minecraft.Update >= 17:
return 16
default:
return 8
}
}
package bootstrap
import (
"fmt"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/maven"
serverpkg "github.com/mclucy/lucy/server"
)
// fabricLoaderPath returns the library path the Fabric method installs the
// locked loader to.
func fabricLoaderPath(version string) (string, error) {
return loaderLibraryPath("net.fabricmc:fabric-loader", "Fabric", version)
}
// quiltLoaderPath returns the library path the Quilt method installs the
// locked loader to.
func quiltLoaderPath(version string) (string, error) {
return loaderLibraryPath("org.quiltmc:quilt-loader", "Quilt", version)
}
// loaderLibraryPath returns the Maven-layout library path of a pinned loader.
func loaderLibraryPath(coordinate, loader, version string) (string, error) {
if version == "" || version == "." || version == ".." || strings.ContainsAny(version, "/\\") {
return "", fmt.Errorf("invalid %s loader version %q", loader, version)
}
p, err := maven.Path(coordinate + ":" + version)
if err != nil {
return "", err
}
return filepath.ToSlash(filepath.Join("libraries", p)), nil
}
// loaderClasspath returns the launcher classpath: the loader library followed
// by every pinned library input in lock order.
func loaderClasspath(loaderPath string, placed []string) []string {
classpath := make([]string, 1, 1+len(placed))
classpath[0] = loaderPath
for _, rel := range placed {
if strings.HasPrefix(rel, "libraries/") {
classpath = append(classpath, rel)
}
}
return classpath
}
// forgeArgsPath returns the UniX launch arguments file generated for the
// locked Forge or NeoForge installation.
func forgeArgsPath(product serverpkg.Product, mcVersion, coreVersion string) string {
return forgeVersionedPath(product, mcVersion, coreVersion, "unix_args.txt")
}
// forgeWinArgsPath returns the Windows launch arguments file generated for the
// locked Forge or NeoForge installation.
func forgeWinArgsPath(product serverpkg.Product, mcVersion, coreVersion string) string {
return forgeVersionedPath(product, mcVersion, coreVersion, "win_args.txt")
}
// forgeVersionedPath returns the Maven-layout path of one generated file under
// the locked Forge or NeoForge version directory.
func forgeVersionedPath(product serverpkg.Product, mcVersion, coreVersion, name string) string {
prefix := "net/neoforged/neoforge/"
version := coreVersion
if product == serverpkg.ProductForge {
prefix = "net/minecraftforge/forge/"
version = mcVersion + "-" + coreVersion
}
return "libraries/" + prefix + version + "/" + name
}
// forgeRootShimPath returns the server-relative shim a shim-era Forge
// installer writes at the server root and run.sh invokes for its Java check.
// NeoForge and earlier Forge branches write no root shim.
func forgeRootShimPath(locked document.LockedServer) string {
if locked.Product != serverpkg.ProductForge {
return ""
}
return "forge-" + locked.Minecraft.String() + "-" + locked.CoreVersion.String() + "-shim.jar"
}
// isForgeDiscardInput reports whether a locked Forge input exists only for
// installer processor execution.
func isForgeDiscardInput(cleanPath string) bool {
return cleanPath == "server-mappings.txt" ||
cleanPath == "server.jar" ||
strings.HasPrefix(cleanPath, ".bootstrap-data/")
}
package bootstrap
import (
"archive/zip"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
serverpkg "github.com/mclucy/lucy/server"
)
// PrepareLocked builds the server tree of a locked server in stage. inputs
// holds the local file of each locked input at the same index; an embedded
// input has an empty entry because it is extracted from the installer. link
// selects how the core and the inputs share content with their store copies.
// java is the Java executable for the bootstrap steps that run Java; it may be
// empty when no runtime is installed, and only those steps fail then.
// progress reports bounded stages such as the Forge processor count.
func PrepareLocked(
ctx context.Context,
stage string,
server document.LockedServer,
corePath string,
inputs []string,
link fsutil.LinkMode,
java string,
output io.Writer,
progress Progress,
) error {
for _, part := range []string{server.Minecraft.String(), server.CoreVersion.String()} {
if part == "" || part == "." || part == ".." || strings.ContainsAny(part, "/\\") {
return fmt.Errorf("invalid locked server version %q", part)
}
}
if err := document.SafeRelativePath(server.Directory); err != nil {
return err
}
root := filepath.Join(stage, server.Directory)
if err := os.MkdirAll(root, 0o755); err != nil {
return err
}
if len(inputs) != len(server.Inputs) {
return fmt.Errorf("got %d input files for %d locked inputs", len(inputs), len(server.Inputs))
}
placed, err := inputPaths(server)
if err != nil {
return err
}
var installer *zip.ReadCloser
if server.Bootstrap == serverpkg.BootstrapMethodForge {
installer, err = zip.OpenReader(corePath)
if err != nil {
return err
}
defer installer.Close()
}
for i, input := range server.Inputs {
dst := filepath.Join(root, filepath.FromSlash(placed[i]))
if input.Embedded != "" {
if installer == nil {
return fmt.Errorf("embedded input requires an installer")
}
if err := extractLockedEntry(&installer.Reader, input.Embedded, dst); err != nil {
return err
}
continue
}
if inputs[i] == "" {
return fmt.Errorf("missing locked bootstrap input %s", input.ProjectID)
}
if err := placeArtifact(inputs[i], dst, link); err != nil {
return err
}
}
switch server.Bootstrap {
case serverpkg.BootstrapMethodVanilla:
return placeArtifact(corePath, filepath.Join(root, "server.jar"), link)
case serverpkg.BootstrapMethodPaperclip:
return preparePaperclip(ctx, root, corePath, link, java, output)
case serverpkg.BootstrapMethodFabric:
return prepareFabric(root, server, corePath, link)
case serverpkg.BootstrapMethodQuilt:
return prepareQuilt(root, server, corePath, link)
case serverpkg.BootstrapMethodForge:
return prepareForgeInstaller(ctx, root, server, corePath, &installer.Reader, java, output, progress)
default:
return fmt.Errorf("unsupported bootstrap method %q", server.Bootstrap)
}
}
// placeArtifact places a stored artifact in the server tree. Methods only read
// placed artifacts, so a hardlink mode may share the store inode.
func placeArtifact(src, dst string, link fsutil.LinkMode) error {
return fsutil.Materialize(src, dst, link.Perm(0o644), link)
}
func extractLockedEntry(z *zip.Reader, name, dst string) error {
for _, f := range z.File {
if f.Name != name {
continue
}
r, err := f.Open()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return errors.Join(err, r.Close())
}
out, err := os.Create(dst)
if err != nil {
return errors.Join(err, r.Close())
}
_, err = io.Copy(out, r)
if err != nil {
return errors.Join(err, r.Close(), out.Close())
}
return errors.Join(r.Close(), out.Close())
}
return fmt.Errorf("missing pinned installer entry %s", name)
}
// runLockedProcess streams a subprocess's combined output to output, which
// already retains the evidence the failure report needs. An output that marks
// sections also records the command line that introduced the run.
func runLockedProcess(cmd *exec.Cmd, output io.Writer) error {
if output == nil {
output = io.Discard
}
if marker, ok := output.(interface{ Section(label string) }); ok {
marker.Section(cmd.String())
}
cmd.Stdout = output
cmd.Stderr = output
return cmd.Run()
}
// ErrNoJava reports a bootstrap step that runs Java when no Java runtime is
// installed.
var ErrNoJava = errors.New("no Java runtime is installed")
func requireJava(java, step string) error {
if java == "" {
return fmt.Errorf("%s needs a Java runtime: %w", step, ErrNoJava)
}
return nil
}
package bootstrap
import (
"slices"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/server"
)
// Launch describes how a prepared server tree starts.
type Launch struct {
// Command runs the server from its directory.
Command string
// Handler is the MCDReforged log handler that parses the server stream.
Handler string
}
// LaunchFor reports the start command and log handler of a bootstrap method.
// Methods that generate no launcher of their own start server.jar directly.
func LaunchFor(method server.BootstrapMethod) Launch {
launch := Launch{Command: "java -jar server.jar nogui", Handler: "vanilla_handler"}
switch method {
case server.BootstrapMethodFabric:
launch.Command = "sh run.sh"
case server.BootstrapMethodQuilt:
launch.Command = "java -jar quilt-server-launch.jar nogui"
case server.BootstrapMethodForge:
launch.Command = "sh run.sh"
launch.Handler = "forge_handler"
case server.BootstrapMethodPaperclip:
launch.Handler = "bukkit_handler"
}
return launch
}
// Outputs reports the known server-relative managed paths of a method.
// Preflight validation and staged output classification share this contract.
func Outputs(locked document.LockedServer) ([]string, error) {
exact, _, err := validateContract(locked)
if err != nil {
return nil, err
}
var paths []string
for _, spec := range exact {
if spec.Policy != PolicyManaged {
continue
}
paths = append(paths, spec.Path)
}
slices.Sort(paths)
return paths, nil
}
package bootstrap
import (
"context"
"fmt"
"io"
"os/exec"
"path/filepath"
"github.com/mclucy/lucy/internal/fsutil"
)
// preparePaperclip copies the locked core and lets the Paperclip patcher
// materialize its patched server in place.
func preparePaperclip(
ctx context.Context,
root string,
corePath string,
link fsutil.LinkMode,
java string,
output io.Writer,
) error {
if err := placeArtifact(corePath, filepath.Join(root, "server.jar"), link); err != nil {
return err
}
if err := requireJava(java, "Paperclip patching"); err != nil {
return err
}
cmd := exec.CommandContext(ctx, java, "-Dpaperclip.patchonly=true", "-jar", "server.jar")
cmd.Dir = root
if err := runLockedProcess(cmd, output); err != nil {
return fmt.Errorf("Paperclip patching: %w", err)
}
return nil
}
package bootstrap
import "time"
// Progress receives preparation facts from a bootstrap method. A zero-value
// callback reports nothing; the caller decides how to present them.
type Progress struct {
PhaseStarted func(name string)
PhaseProgress func(name string, count, total int)
PhaseDone func(name string, elapsed time.Duration, count, total int)
}
func (p Progress) started(name string) {
if p.PhaseStarted != nil {
p.PhaseStarted(name)
}
}
func (p Progress) progressed(name string, count, total int) {
if p.PhaseProgress != nil {
p.PhaseProgress(name, count, total)
}
}
func (p Progress) done(name string, elapsed time.Duration, count, total int) {
if p.PhaseDone != nil {
p.PhaseDone(name, elapsed, count, total)
}
}
package bootstrap
import (
"os"
"path/filepath"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
// quiltLauncherMainClass is the entry point of the generated Quilt launcher JAR.
quiltLauncherMainClass = "org.quiltmc.loader.impl.launch.server.QuiltServerLauncher"
// quiltKnotMainClass is the server main class the launcher runs through its
// embedded launch properties.
quiltKnotMainClass = "org.quiltmc.loader.impl.launch.knot.KnotServer"
)
// prepareQuilt places the Quilt loader on the launcher classpath and generates
// the launcher JAR and the properties that select the vanilla server JAR.
func prepareQuilt(root string, server document.LockedServer, corePath string, link fsutil.LinkMode) error {
loaderPath, err := quiltLoaderPath(server.CoreVersion.String())
if err != nil {
return err
}
placed, err := inputPaths(server)
if err != nil {
return err
}
if err := placeArtifact(corePath, filepath.Join(root, filepath.FromSlash(loaderPath)), link); err != nil {
return err
}
classpath := loaderClasspath(loaderPath, placed)
if err := writeLauncherShimJar(
filepath.Join(root, "quilt-server-launch.jar"),
"quilt-server-launch.properties",
quiltLauncherMainClass,
quiltKnotMainClass,
classpath,
); err != nil {
return err
}
return os.WriteFile(
filepath.Join(root, "quilt-server-launcher.properties"),
[]byte("serverJar=server.jar\n"),
0o644,
)
}
// Package snapshot identifies reusable bootstrap output trees and describes
// their contents independently of any one workspace. It computes the recipe
// key, validates a manifest, and defines the storage contract that the
// artifact store implements. It never decides ownership, runs a bootstrap
// method, or encodes a method's file layout.
package snapshot
import (
"context"
"crypto/sha256"
"fmt"
"hash"
"path/filepath"
"strings"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/buildid"
"github.com/mclucy/lucy/internal/fsutil"
)
// Entry describes one runtime-zone or seed-zone file of a bootstrap output.
// Policy and Role keep their bootstrap package words as opaque labels; this
// package does not interpret them.
type Entry struct {
Path string `json:"path"`
SHA256 string `json:"sha256"`
Mode uint32 `json:"mode"`
Policy string `json:"policy"`
Role string `json:"role"`
}
// Snapshot is one stored bootstrap output set addressed by its recipe key.
// The key covers the Lucy build, so the manifest encoding needs no version.
type Snapshot struct {
Key cas.Digest `json:"key"`
Entries []Entry `json:"entries"`
}
// Store persists snapshot manifests and their file contents. The artifact
// store implements it; installation wires it. A lookup miss is not an error.
// RestoreSnapshot places each entry with link and verifies its digest.
type Store interface {
LookupSnapshot(ctx context.Context, key cas.Digest) (Snapshot, bool, error)
SaveSnapshot(ctx context.Context, snap Snapshot, sourceDir string) error
RestoreSnapshot(ctx context.Context, snap Snapshot, destination string, link fsutil.LinkMode) error
}
// Key computes the recipe identity of a locked server: H(Lucy build, method,
// product, Minecraft version, core version, core digest, each input identity
// and digest in lock order). Input order is part of the recipe because a
// method can derive a classpath from it. The workspace directory, URLs,
// filenames, Java runtime, and package set are absent: they do not change the
// output bytes.
func Key(locked document.LockedServer) (cas.Digest, error) {
if err := locked.Bootstrap.Validate(); err != nil {
return cas.Digest{}, err
}
build, err := buildid.Identity()
if err != nil {
return cas.Digest{}, err
}
core, err := artifactReference("core artifact", locked.Artifact.Hashes)
if err != nil {
return cas.Digest{}, err
}
hasher := sha256.New()
writeField(hasher, "lucy-bootstrap-snapshot")
writeField(hasher, build)
writeField(hasher, string(locked.Bootstrap))
writeField(hasher, string(locked.Product))
writeField(hasher, locked.Minecraft.String())
// The method derives launch paths from the core version, so two locks
// with the same core bytes but a different declared version generate
// different launchers.
writeField(hasher, locked.CoreVersion.String())
writeField(hasher, core)
for _, input := range locked.Inputs {
reference, err := inputReference(input)
if err != nil {
return cas.Digest{}, err
}
writeField(hasher, string(input.Provider)+":"+input.ProjectID+"@"+input.Version.String())
writeField(hasher, reference)
}
var key cas.Digest
hasher.Sum(key[:0])
return key, nil
}
// inputReference identifies one locked input. An embedded input is addressed by
// its parent installer's digest plus the entry name, so a lock that omits an
// embedded digest still has a stable recipe.
func inputReference(input catalog.Artifact) (string, error) {
if input.Embedded != "" && !hasDigest(input.Hashes) {
if err := document.SafeRelativePath(input.Embedded); err != nil {
return "", fmt.Errorf("embedded bootstrap input %s: %w", input.ProjectID, err)
}
return "embedded:" + filepath.ToSlash(filepath.Clean(input.Embedded)), nil
}
return artifactReference("bootstrap input "+input.ProjectID, input.Hashes)
}
func hasDigest(hashes map[string]string) bool {
for _, algorithm := range []string{"sha256", "sha512", "sha1", "md5"} {
if strings.TrimSpace(hashes[algorithm]) != "" {
return true
}
}
return false
}
// artifactReference names the strongest digest a lock pins for one artifact.
// SHA-256 is preferred, and a weaker pin still yields a stable identity rather
// than silently dropping the input from the key.
func artifactReference(name string, hashes map[string]string) (string, error) {
for _, algorithm := range []string{"sha256", "sha512", "sha1", "md5"} {
value := strings.ToLower(strings.TrimSpace(hashes[algorithm]))
if value != "" {
return algorithm + ":" + value, nil
}
}
return "", fmt.Errorf("%s has no digest to identify the bootstrap recipe", name)
}
func writeField(hasher hash.Hash, value string) {
fmt.Fprintf(hasher, "%d:", len(value))
_, _ = hasher.Write([]byte(value))
_, _ = hasher.Write([]byte{'\n'})
}
// Validate rejects a manifest whose entries could escape the destination,
// collide, or name content that is not addressed by SHA-256.
func (s Snapshot) Validate() error {
if _, err := cas.ParseDigest(s.Key.String()); err != nil {
return fmt.Errorf("invalid snapshot key: %w", err)
}
seen := make(map[string]bool, len(s.Entries))
for i, entry := range s.Entries {
if err := ValidateEntry(entry); err != nil {
return fmt.Errorf("snapshot entry %d: %w", i, err)
}
if seen[entry.Path] {
return fmt.Errorf("snapshot entry %d repeats path %q", i, entry.Path)
}
seen[entry.Path] = true
}
return nil
}
// ValidateEntry rejects one entry that cannot be restored safely.
func ValidateEntry(entry Entry) error {
path := filepath.FromSlash(entry.Path)
if entry.Path == "" || entry.Path == "." || filepath.IsAbs(path) ||
filepath.ToSlash(filepath.Clean(path)) != entry.Path {
return fmt.Errorf("path %q is not a canonical server-relative path", entry.Path)
}
if err := document.SafeRelativePath(path); err != nil {
return err
}
if _, err := cas.ParseDigest("sha256:" + strings.ToLower(entry.SHA256)); err != nil {
return fmt.Errorf("path %q has an invalid sha256 digest %q", entry.Path, entry.SHA256)
}
if entry.Mode > 0o777 {
return fmt.Errorf("path %q has unsupported mode %#o", entry.Path, entry.Mode)
}
return nil
}
package snapshot
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
)
// managedPolicy is the entry policy whose permission bits belong to its
// identity.
const managedPolicy = "managed"
// Comparison classifies snapshot entries by the state of their path below a
// directory. Every entry lands in exactly one list, in entry order. Files in
// the directory that no entry names are outside the comparison.
type Comparison struct {
// Matching entries name a regular file with the entry's digest. A managed
// entry also compares the read and execute bits of its mode, because a
// read-only copy or hard link runs the same as a writable one. A seed file
// belongs to the user once it exists, so its mode is never compared.
// Matching entries carry the observed permission bits.
Matching []Entry
// Differing entries name a path that holds other content: other bytes or
// a non-regular file.
Differing []Entry
// OtherPermissions entries name a managed regular file with the entry's
// digest but other read or execute bits. They carry the observed
// permission bits.
OtherPermissions []Entry
// Missing entries name an absent path.
Missing []Entry
}
// Complete reports whether every entry matches.
func (c Comparison) Complete() bool {
return len(c.Differing) == 0 && len(c.OtherPermissions) == 0 && len(c.Missing) == 0
}
// Compare digests each entry's path below dir. It refuses a path that leaves
// dir or traverses a symlink, so a hostile tree cannot redirect the read.
func Compare(dir string, entries []Entry) (Comparison, error) {
return CompareCached(dir, entries, nil)
}
// compareResult is one entry's outcome. Observations are kept so a caller can
// record the evidence without a second walk.
type compareResult struct {
entry Entry
differing bool
otherPermissions bool
missing bool
err error
}
// CompareCached digests each entry's path below dir, reusing a digest the memo
// already proved for an unchanged file. Files hash on a bounded pool; entry
// order decides the first error and the result lists.
func CompareCached(
dir string,
entries []Entry,
memo *fileidentity.Memo,
) (Comparison, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return Comparison{}, err
}
defer root.Close()
results := make([]compareResult, len(entries))
workers := min(len(entries), 4)
if workers < 1 {
workers = 1
}
var next atomic.Int64
var group sync.WaitGroup
for range workers {
group.Go(func() {
for {
index := int(next.Add(1)) - 1
if index >= len(entries) {
return
}
results[index] = compareEntry(root, entries[index], memo)
}
})
}
group.Wait()
var comparison Comparison
for _, result := range results {
switch {
case result.err != nil:
return Comparison{}, result.err
case result.missing:
comparison.Missing = append(comparison.Missing, result.entry)
case result.differing:
comparison.Differing = append(comparison.Differing, result.entry)
case result.otherPermissions:
comparison.OtherPermissions = append(comparison.OtherPermissions, result.entry)
default:
comparison.Matching = append(comparison.Matching, result.entry)
}
}
return comparison, nil
}
func compareEntry(
root *os.Root,
entry Entry,
memo *fileidentity.Memo,
) compareResult {
result := compareResult{entry: entry}
rel := filepath.FromSlash(entry.Path)
if err := document.SafeRelativePath(rel); err != nil {
result.err = fmt.Errorf("snapshot entry %s: %w", entry.Path, err)
return result
}
info, err := lstatWithin(root, rel)
switch {
case errors.Is(err, fs.ErrNotExist):
result.missing = true
return result
case err != nil:
result.err = err
return result
}
if !info.Mode().IsRegular() {
result.differing = true
return result
}
observation, err := memo.ObserveRootInfo(root, rel, info, nil)
if err != nil {
result.err = err
return result
}
digest := observation.Hashes["sha256"]
if !strings.EqualFold(digest, entry.SHA256) {
result.differing = true
return result
}
result.entry.Mode = uint32(info.Mode().Perm())
result.entry.SHA256 = digest
if entry.Policy == managedPolicy && entry.Mode != 0 &&
info.Mode().Perm()&0o555 != os.FileMode(entry.Mode)&0o555 {
result.otherPermissions = true
}
return result
}
// VerifyRestored classifies entries against a tree a verified restore
// materialized. It checks presence, regular-file type, and the managed mode,
// but never reads content the caller already verified.
func VerifyRestored(dir string, entries []Entry) (Comparison, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return Comparison{}, err
}
defer root.Close()
var comparison Comparison
for _, entry := range entries {
rel := filepath.FromSlash(entry.Path)
if err := document.SafeRelativePath(rel); err != nil {
return Comparison{}, fmt.Errorf("snapshot entry %s: %w", entry.Path, err)
}
info, err := lstatWithin(root, rel)
switch {
case errors.Is(err, fs.ErrNotExist):
comparison.Missing = append(comparison.Missing, entry)
continue
case err != nil:
return Comparison{}, err
}
if !info.Mode().IsRegular() {
comparison.Differing = append(comparison.Differing, entry)
continue
}
observed := entry
observed.Mode = uint32(info.Mode().Perm())
if entry.Policy == managedPolicy && entry.Mode != 0 &&
info.Mode().Perm()&0o555 != os.FileMode(entry.Mode)&0o555 {
comparison.OtherPermissions = append(comparison.OtherPermissions, observed)
continue
}
comparison.Matching = append(comparison.Matching, observed)
}
return comparison, nil
}
// lstatWithin reports the entry at rel below root without following a symlink
// in any component. A symlink above the leaf is an error, and a leaf symlink
// is returned as a non-regular file.
func lstatWithin(root *os.Root, rel string) (fs.FileInfo, error) {
parts := strings.Split(filepath.ToSlash(rel), "/")
current := ""
for i, part := range parts {
if part == "" || part == "." {
continue
}
current = filepath.Join(current, part)
info, err := root.Lstat(current)
if err != nil {
return nil, err
}
if i == len(parts)-1 {
return info, nil
}
if info.Mode()&fs.ModeSymlink != 0 {
return nil, fmt.Errorf("snapshot path %s traverses symlink %s", rel, current)
}
if !info.IsDir() {
return nil, fs.ErrNotExist
}
}
return nil, fs.ErrNotExist
}
// Package cache owns request metadata and expiration policy over reusable CAS
// storage. Its objects have a separate lifecycle from project-local backups.
package cache
import (
"errors"
"io"
"net/http"
"os"
"path/filepath"
"sync"
"github.com/mclucy/lucy/log"
)
// ErrNoHTTPClient reports a cache client constructed without a transport.
var ErrNoHTTPClient = errors.New("cache client has no http client")
// DefaultRoot reports the per-user directory the network cache lives in. It is
// a path helper for the construction boundary, not a cache instance.
func DefaultRoot() string {
dir, err := os.UserCacheDir()
if err != nil {
dir = os.TempDir()
}
return filepath.Join(dir, "lucy", "network")
}
// Client is one configured network cache: a content-addressed store, its
// index and expiration policy, and the HTTP transport used for requests.
//
// Construction is lazy. The store and index open on first use, so a missing or
// unusable root disables caching for this client while requests continue
// uncached; construction itself never touches the filesystem.
type Client struct {
root string
config Config
httpClient *http.Client
logger *log.Logger
lifetime sync.RWMutex
closed bool
once sync.Once
handler *handler
}
// New constructs a cache client rooted at root. A nil logger records nothing.
// httpClient must be supplied: a nil client makes network helpers fail rather
// than falling back to a process-wide default.
func New(
root string,
config Config,
httpClient *http.Client,
logger *log.Logger,
) *Client {
return &Client{
root: root,
config: config,
httpClient: httpClient,
logger: logger,
}
}
// Do executes a request through the configured transport so callers that fetch
// uncached bytes share the same HTTP configuration.
func (c *Client) Do(request *http.Request) (*http.Response, error) {
if c.httpClient == nil {
return nil, ErrNoHTTPClient
}
start := c.logger.WaitStart()
response, err := c.httpClient.Do(request)
c.logger.WaitDone(log.WaitHTTP, start)
return response, err
}
// Close waits for cache operations and closes the store if it was opened.
// It is safe to call repeatedly and never initializes an unused store.
func (c *Client) Close() error {
c.lifetime.Lock()
defer c.lifetime.Unlock()
if c.closed {
return nil
}
c.closed = true
c.once.Do(func() {
c.handler = &handler{logger: c.logger}
})
c.handler.on = false
if c.handler.store != nil {
return c.handler.store.Close()
}
return nil
}
func (c *Client) cache() *handler {
c.once.Do(func() {
c.handler = newHandler(c.root, c.config, c.logger)
})
return c.handler
}
// All returns every live index entry in key order.
func (c *Client) All() []*Entry {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().all()
}
// ClearAll empties the index and reports the objects it collected.
func (c *Client) ClearAll() (ResetReport, error) {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().clearAll()
}
// Get keeps a reader alive independently of later index replacements. The
// caller must Close it.
func (c *Client) Get(k string) (
hit bool,
reader io.ReadCloser,
filename string,
err error,
) {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
hit, reader, filename, _, err = c.cache().get(k)
return hit, reader, filename, err
}
func (c *Client) GetBytes(k string) (hit bool, data []byte, err error) {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().getBytes(k)
}
// Exist reports whether k names a live entry.
func (c *Client) Exist(k string) bool {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().exist(k)
}
// Remove drops the entry for k and reclaims unreferenced objects.
func (c *Client) Remove(k string) error {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().remove(k)
}
// Flush publishes the in-memory index under the cache lock.
func (c *Client) Flush() error {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
return c.cache().flush()
}
package cache
import (
"crypto/sha256"
"errors"
"fmt"
"hash"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/log"
)
// byteStage can finish a buffered response without requiring temporary disk space.
type byteStage struct {
writer *cas.Writer
hasher hash.Hash
logger *log.Logger
}
func (c *Client) newByteStage() *byteStage {
writer, err := c.cache().newWriter()
if err == nil {
return &byteStage{writer: writer, logger: c.logger}
}
if !errors.Is(err, ErrDisabled) {
c.logger.Warn(fmt.Errorf("cache staging unavailable: %w", err))
}
return &byteStage{hasher: sha256.New(), logger: c.logger}
}
func (s *byteStage) detach() error {
hasher, err := s.writer.DetachHash()
if err != nil {
return err
}
if err := s.writer.Abort(); err != nil {
s.logger.Warn(fmt.Errorf("remove failed cache stage: %w", err))
}
s.hasher = hasher
s.writer = nil
return nil
}
func (s *byteStage) Write(data []byte) (int, error) {
if s.writer == nil {
return s.hasher.Write(data)
}
count, err := s.writer.Write(data)
if err == nil {
return count, nil
}
s.logger.Warn(fmt.Errorf("cache write failed, retaining buffered response: %w", err))
if err := s.detach(); err != nil {
return count, err
}
rest, err := s.hasher.Write(data[count:])
return count + rest, err
}
func (s *byteStage) seal() (cas.Object, error) {
if s.writer != nil {
object, err := s.writer.Seal(nil)
if err == nil {
return object, nil
}
s.logger.Warn(fmt.Errorf("cache sync failed, retaining buffered response: %w", err))
if err := s.detach(); err != nil {
return cas.Object{}, err
}
}
var digest cas.Digest
s.hasher.Sum(digest[:0])
return cas.Object{Digest: digest}, nil
}
func (s *byteStage) Close() error {
if s.writer != nil {
return s.writer.Abort()
}
return nil
}
package cache
import (
"fmt"
"time"
)
type Config struct {
Enabled bool `json:"enabled"`
DownloadMaxSize int64 `json:"download_max_size"`
DownloadKeepFor time.Duration `json:"download_keep_for"`
IndexMaxSize int64 `json:"index_max_size"`
IndexRefreshAfter time.Duration `json:"index_refresh_after"`
}
func DefaultCacheConfig() Config {
return Config{
Enabled: true,
DownloadMaxSize: 2 * 1024 * 1024 * 1024, // 2 GB
DownloadKeepFor: 7 * 24 * time.Hour, // 7 days
IndexMaxSize: 50 * 1024 * 1024, // 50 MB
IndexRefreshAfter: 4 * time.Hour, // 4 hours
}
}
func (c *Config) Validate() error {
if !c.Enabled {
return nil
}
if c.DownloadMaxSize <= 0 {
return fmt.Errorf("download_max_size must be positive, got %d", c.DownloadMaxSize)
}
if c.DownloadKeepFor <= 0 {
return fmt.Errorf("download_keep_for must be positive, got %s", c.DownloadKeepFor)
}
if c.IndexMaxSize <= 0 {
return fmt.Errorf("index_max_size must be positive, got %d", c.IndexMaxSize)
}
if c.IndexRefreshAfter <= 0 {
return fmt.Errorf("index_refresh_after must be positive, got %s", c.IndexRefreshAfter)
}
return nil
}
func (c *Config) toPolicy() Policy {
return Policy{
Metadata: PolicyConfig{
MaxSize: c.IndexMaxSize,
TTL: c.IndexRefreshAfter,
},
Artifact: PolicyConfig{
MaxSize: c.DownloadMaxSize,
TTL: c.DownloadKeepFor,
},
}
}
package cache
import "time"
// EntryKind distinguishes artifact entries (large, immutable binaries like
// server JARs and mods) from metadata entries (small, frequently refreshed
// manifests and version indexes).
type EntryKind uint8
const (
KindMetadata EntryKind = iota
KindArtifact
)
func (k EntryKind) String() string {
switch k {
case KindMetadata:
return "metadata"
case KindArtifact:
return "artifact"
default:
return "unknown"
}
}
// HashAlgorithm identifies the hash function used for integrity verification.
// Different upstream sources provide different algorithms: Mojang uses SHA-1,
// Modrinth provides SHA-1 and SHA-512, and Lucy uses SHA-256 internally for
// content addressing.
type HashAlgorithm uint8
const (
HashNone HashAlgorithm = iota
HashSHA1
HashSHA256
HashSHA512
)
func (h HashAlgorithm) String() string {
switch h {
case HashSHA1:
return "sha1"
case HashSHA256:
return "sha256"
case HashSHA512:
return "sha512"
default:
return "none"
}
}
// IntegrityState tracks whether a cached entry's content has been verified
// against an expected digest from an upstream source.
type IntegrityState uint8
const (
// IntegrityUnverified means no expected digest was available or verification
// has not run.
IntegrityUnverified IntegrityState = iota
// IntegrityVerified means the entry's content matched the expected
// digest at cache-add time.
IntegrityVerified
)
// Integrity holds the expected or actual digest of a cache entry along with
// its verification state. When Expected is empty, the entry operates in
// unverified mode (best-effort caching without integrity guarantees).
type Integrity struct {
Algorithm HashAlgorithm `json:"algorithm"`
Expected string `json:"expected,omitempty"`
Actual string `json:"actual,omitempty"`
State IntegrityState `json:"state"`
}
// Entry is the metadata record for one cached blob. ContentHash
// (always SHA-256) addresses the blob in the store; Integrity carries the
// upstream-provided digest, which may use a different algorithm (see
// HashAlgorithm).
type Entry struct {
Kind EntryKind `json:"kind"`
Filename string `json:"filename"`
Size int64 `json:"size"`
ContentHash string `json:"content_hash"`
Integrity Integrity `json:"integrity"`
Expiration time.Time `json:"expiration"`
Key string `json:"key"`
CreatedAt time.Time `json:"created_at"`
}
package cache
import (
"bytes"
"context"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"maps"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/fsutil"
)
// DownloadOptions controls artifact caching and downloading. The URL passed to
// CachedDownload is the cache identity; RequestURL, when set, is used only for
// the network request.
type DownloadOptions struct {
Kind EntryKind
ExpectedHash string
HashAlgorithm HashAlgorithm
Filename string
RequestURL string
WrapReader func(io.Reader, int64) io.Reader
OnCacheHit func()
OnResolvedFilename func(string)
TTL time.Duration
FileMode os.FileMode
// MaxBytes rejects content larger than this many bytes on a download or a
// cache hit. Zero accepts any size.
MaxBytes int64
}
// ErrDownloadTooLarge reports content beyond a download's MaxBytes limit.
var ErrDownloadTooLarge = errors.New("download exceeds size limit")
type BytesRequestOptions struct {
Kind EntryKind
Headers http.Header
ExpectedHash string
HashAlgorithm HashAlgorithm
TTL time.Duration
MaxBytes int64
}
type BytesResponse struct {
StatusCode int
Data []byte
CacheHit bool
// Header is the network response header, nil on a cache hit. Callers
// retrying a failed request read Retry-After from it.
Header http.Header
}
type DownloadResult struct {
File *os.File
CacheHit bool
Verified bool
}
// CachedDownload downloads a file from url into dir, using the cache for
// deduplication. On cache hit the indexed bytes are copied atomically into
// dir and OnCacheHit (if set) is called. On miss the response body is
// streamed once through an optional WrapReader (for progress tracking) into
// a cache stage, verified, and only then written to the destination and
// published to the cache.
func (c *Client) CachedDownload(
ctx context.Context,
url, dir string,
opts DownloadOptions,
) (*DownloadResult, error) {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
if err := ctx.Err(); err != nil {
return nil, err
}
if err := validateDownloadURL(url); err != nil {
return nil, err
}
requestURL := url
if opts.RequestURL != "" {
requestURL = opts.RequestURL
}
if err := validateDownloadURL(requestURL); err != nil {
return nil, err
}
if opts.FileMode == 0 {
opts.FileMode = 0o640
}
hit, cachedReader, cachedFilename, _, err := c.cache().get(url)
if err != nil {
c.logger.Warn(
fmt.Errorf(
"cache lookup failed, proceeding with download: %w",
err,
),
)
}
if hit && cachedReader != nil {
result, copyErr := copyCachedFile(
ctx,
cachedReader,
cachedFilename,
dir,
opts,
)
closeErr := cachedReader.Close()
if copyErr == nil {
if closeErr != nil {
return nil, errors.Join(closeErr, result.File.Close())
}
return result, nil
}
copyErr = errors.Join(copyErr, closeErr)
if !errors.Is(copyErr, cas.ErrCorrupt) &&
!errors.Is(copyErr, cas.ErrRead) {
return nil, copyErr
}
c.logger.Warn(
fmt.Errorf(
"cached contents unreadable, refetching %s: %w",
url,
copyErr,
),
)
}
return c.downloadAndCache(ctx, url, requestURL, dir, opts)
}
// copyCachedFile materializes a cache hit under dir. cas.ErrCorrupt and
// cas.ErrRead mean the stored bytes are unusable and the caller must treat
// the hit as a miss; the atomic copy leaves the destination untouched.
func copyCachedFile(
ctx context.Context,
reader io.Reader,
cachedFilename string,
dir string,
opts DownloadOptions,
) (*DownloadResult, error) {
resolvedName := sanitizeFilename(cachedFilename, "artifact")
if opts.OnResolvedFilename != nil {
opts.OnResolvedFilename(resolvedName)
}
destPath := filepath.Join(dir, resolvedName)
if !containedUnder(dir, destPath) {
return nil, fmt.Errorf(
"cached filename %q escapes destination directory",
resolvedName,
)
}
destFile, err := copyFileContext(
ctx,
limitDownloadReader(reader, opts.MaxBytes),
destPath,
opts.FileMode,
)
if err != nil {
return nil, fmt.Errorf(
"failed to copy cached file to destination: %w",
err,
)
}
if opts.OnCacheHit != nil {
opts.OnCacheHit()
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, destFile.Close())
}
return &DownloadResult{
File: destFile,
CacheHit: true,
Verified: false,
}, nil
}
// limitDownloadReader fails once a stream produces more than limit bytes.
// A non-positive limit leaves the reader unbounded.
func limitDownloadReader(reader io.Reader, limit int64) io.Reader {
if limit <= 0 {
return reader
}
return &limitedDownloadReader{reader: reader, limit: limit}
}
type limitedDownloadReader struct {
reader io.Reader
limit int64
total int64
}
func (r *limitedDownloadReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
r.total += int64(n)
if r.total > r.limit {
return n, fmt.Errorf(
"%w: %d bytes exceeds %d",
ErrDownloadTooLarge,
r.total,
r.limit,
)
}
return n, err
}
// ProgressReader reports the cumulative bytes read from reader. It is the
// counting half of a DownloadOptions.WrapReader, whose size argument is the
// transfer total the response announced.
func ProgressReader(
reader io.Reader,
total int64,
report func(read, total int64),
) io.Reader {
if report == nil {
return reader
}
return &progressReader{reader: reader, total: total, report: report}
}
type progressReader struct {
reader io.Reader
total int64
read int64
report func(read, total int64)
}
func (r *progressReader) Read(p []byte) (int, error) {
n, err := r.reader.Read(p)
r.read += int64(n)
if n > 0 {
r.report(r.read, r.total)
}
return n, err
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.reader.Read(p)
if ctxErr := r.ctx.Err(); ctxErr != nil {
return n, ctxErr
}
return n, err
}
func copyFileContext(ctx context.Context, reader io.Reader, path string, mode os.FileMode) (file *os.File, resultErr error) {
dir := filepath.Dir(path)
if err := fsutil.MkdirAllPrivate(dir); err != nil {
return nil, err
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, root.Close()) }()
if err := fsutil.WriteRoot(root, filepath.Base(path), contextReader{ctx, reader}, fsutil.WriteOptions{
Mode: mode, Replace: true, Check: ctx.Err,
}); err != nil {
return nil, err
}
return os.Open(path)
}
// CachedGetBytes fetches bytes from url, using the cache for deduplication.
// On cache hit the bytes are returned directly. On miss the response body is
// read into memory with a size limit, staged for content addressing, verified
// against the optional upstream digest, and then cached.
func (c *Client) CachedGetBytes(
ctx context.Context,
url string,
opts BytesRequestOptions,
) ([]byte, error) {
res, err := c.CachedGetRequest(ctx, url, opts)
if err != nil {
return nil, err
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("fetch failed: status %d", res.StatusCode)
}
return res.Data, nil
}
// CachedGetRequest fetches bytes from url. Non-2xx responses are not cached
// and retain their status and headers even if reading the body fails.
func (c *Client) CachedGetRequest(
ctx context.Context,
url string,
opts BytesRequestOptions,
) (*BytesResponse, error) {
return c.cachedBytesRequest(ctx, http.MethodGet, url, nil, url, 0, opts, nil)
}
// CachedPostRequest fetches bytes from url with a read-only POST body.
// Non-2xx responses retain their status and headers even if reading fails.
// Pass all request headers explicitly. Use provider-issued API tokens, not
// passwords. The key partitions responses by URL, body, and headers; it does
// not authenticate a caller. Only a validated 200 response is cached.
func (c *Client) CachedPostRequest(
ctx context.Context,
url string,
body []byte,
opts BytesRequestOptions,
validate func([]byte) error,
) (*BytesResponse, error) {
return c.cachedBytesRequest(
ctx,
http.MethodPost,
url,
body,
postRequestCacheKey(url, body, opts.Headers),
http.StatusOK,
opts,
validate,
)
}
// postRequestCacheKey digests every request input that changes what the server
// answers. All headers participate so credentials and content negotiation are
// isolated between cache entries.
func postRequestCacheKey(url string, body []byte, headers http.Header) string {
digest := sha256.New()
write := func(data []byte) {
var length [8]byte
binary.LittleEndian.PutUint64(length[:], uint64(len(data)))
digest.Write(length[:])
digest.Write(data)
}
write([]byte(http.MethodPost))
write([]byte(url))
write(body)
for _, name := range slices.Sorted(maps.Keys(headers)) {
write([]byte(strings.ToLower(name)))
var count [8]byte
binary.LittleEndian.PutUint64(count[:], uint64(len(headers[name])))
digest.Write(count[:])
for _, value := range headers[name] {
write([]byte(value))
}
}
return "post:" + hex.EncodeToString(digest.Sum(nil))
}
// cachedBytesRequest is the shared fetch-and-cache path for cached GET and
// opt-in read-only POST requests. cacheKey identifies the stored response;
// cacheStatus, when nonzero, admits only that response status to the cache.
func (c *Client) cachedBytesRequest(
ctx context.Context,
method, url string,
body []byte,
cacheKey string,
cacheStatus int,
opts BytesRequestOptions,
validate func([]byte) error,
) (*BytesResponse, error) {
c.lifetime.RLock()
defer c.lifetime.RUnlock()
if err := ctx.Err(); err != nil {
return nil, err
}
if err := validateDownloadURL(url); err != nil {
return nil, err
}
maxBytes := opts.MaxBytes
if maxBytes == 0 {
maxBytes = 50 * 1024 * 1024
}
hit, data, digest, err := c.cache().getBytesContext(ctx, cacheKey)
if err := ctx.Err(); err != nil {
return nil, err
}
if err != nil {
c.logger.Warn(
fmt.Errorf(
"cache lookup failed, proceeding with fetch: %w",
err,
),
)
}
if hit && data != nil {
if int64(len(data)) > maxBytes {
return nil, fmt.Errorf(
"response too large: exceeded %d bytes",
maxBytes,
)
}
if c.verifyCachedBytes(opts, url, data, digest) == nil &&
(validate == nil || validate(data) == nil) {
return &BytesResponse{
StatusCode: http.StatusOK,
Data: data,
CacheHit: true,
}, nil
}
// Refetch when the stored response fails either integrity or validation.
}
var requestBody io.Reader
if body != nil {
requestBody = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, url, requestBody)
if err != nil {
return nil, fmt.Errorf("create fetch request failed: %w", err)
}
for key, values := range opts.Headers {
for _, value := range values {
req.Header.Add(key, value)
}
}
resp, err := c.Do(req)
if err != nil {
return nil, fmt.Errorf("fetch failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
errorBody, err := readLimitedBytes(contextReader{ctx, resp.Body}, maxBytes)
if err == nil {
err = ctx.Err()
}
return &BytesResponse{
StatusCode: resp.StatusCode,
Data: errorBody,
Header: resp.Header,
}, err
}
stage := c.newByteStage()
defer func() {
if err := stage.Close(); err != nil {
c.logger.Warn(fmt.Errorf("remove download stage: %w", err))
}
}()
writers := []io.Writer{stage}
integrityHasher := newIntegrityHasher(opts.HashAlgorithm, opts.ExpectedHash)
if integrityHasher != nil {
writers = append(writers, integrityHasher)
}
var bodyBuf bytes.Buffer
writers = append(writers, &bodyBuf)
limitedReader := io.LimitReader(contextReader{ctx, resp.Body}, min(maxBytes, math.MaxInt64-1)+1)
if _, err := io.Copy(io.MultiWriter(writers...), limitedReader); err != nil {
return nil, fmt.Errorf("read failed: %w", err)
}
responseBody := bodyBuf.Bytes()
if int64(len(responseBody)) > maxBytes {
return nil, fmt.Errorf(
"response too large: exceeded %d bytes",
maxBytes,
)
}
object, err := stage.seal()
if err != nil {
return nil, err
}
contentDigest := object.Digest
integrity, _, err := c.verifyIntegrity(
integrityActual(opts.HashAlgorithm, contentDigest, integrityHasher),
opts.HashAlgorithm,
opts.ExpectedHash,
url,
)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if resp.StatusCode == cacheStatus && validate != nil {
if err := validate(responseBody); err != nil {
return nil, err
}
}
if stage.writer != nil &&
(cacheStatus == 0 || resp.StatusCode == cacheStatus) {
if err := c.cache().commitEntryContext(
ctx,
stage.writer, "", cacheKey, opts.Kind, integrity, opts.TTL,
); err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
c.logger.Warn(fmt.Errorf("failed to cache bytes: %w", err))
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
return &BytesResponse{
StatusCode: resp.StatusCode,
Data: responseBody,
CacheHit: false,
Header: resp.Header,
}, nil
}
func (c *Client) verifyCachedBytes(
opts BytesRequestOptions,
url string,
data []byte,
digest cas.Digest,
) error {
if opts.ExpectedHash == "" {
return nil
}
// The store already verified the content address as it read the bytes.
hasher := newIntegrityHasher(opts.HashAlgorithm, opts.ExpectedHash)
if hasher != nil {
hasher.Write(data)
}
_, _, err := c.verifyIntegrity(
integrityActual(opts.HashAlgorithm, digest, hasher),
opts.HashAlgorithm,
opts.ExpectedHash,
url,
)
return err
}
func readLimitedBytes(reader io.Reader, maxBytes int64) ([]byte, error) {
bytes, err := fsutil.CopyBytes(reader, maxBytes)
if err != nil {
return nil, fmt.Errorf("read failed: %w", err)
}
return bytes, nil
}
// downloadAndCache streams requestURL into dir. The destination write and
// the cache commit happen only after the staged SHA-256 digest and any
// upstream integrity check pass, so a rejected response reaches neither.
func (c *Client) downloadAndCache(
ctx context.Context,
url, requestURL, dir string,
opts DownloadOptions,
) (*DownloadResult, error) {
if err := validateDownloadURL(url); err != nil {
return nil, err
}
if err := validateDownloadURL(requestURL); err != nil {
return nil, err
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
if err != nil {
return nil, fmt.Errorf("download failed: %w", err)
}
resp, err := c.Do(request)
if err != nil {
return nil, fmt.Errorf("download failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("download failed: status %d", resp.StatusCode)
}
filename := opts.Filename
if filename == "" {
filename = speculateFilename(resp)
}
if opts.OnResolvedFilename != nil && filename != "" {
opts.OnResolvedFilename(filename)
}
stage, err := c.newDownloadStage()
if err != nil {
return nil, err
}
defer func() {
if err := stage.Close(); err != nil {
c.logger.Warn(fmt.Errorf("remove download stage: %w", err))
}
}()
writers := []io.Writer{stage}
integrityHasher := newIntegrityHasher(opts.HashAlgorithm, opts.ExpectedHash)
if integrityHasher != nil {
writers = append(writers, integrityHasher)
}
var reader io.Reader = resp.Body
if opts.WrapReader != nil {
reader = opts.WrapReader(reader, resp.ContentLength)
}
if opts.MaxBytes > 0 && resp.ContentLength > opts.MaxBytes {
return nil, fmt.Errorf(
"%w: %d bytes exceeds %d",
ErrDownloadTooLarge,
resp.ContentLength,
opts.MaxBytes,
)
}
reader = limitDownloadReader(reader, opts.MaxBytes)
if _, err := io.Copy(io.MultiWriter(writers...), contextReader{ctx, reader}); err != nil {
return nil, fmt.Errorf("download stream failed: %w", err)
}
object, err := stage.seal()
if err != nil {
return nil, err
}
contentDigest := object.Digest
integrity, verified, err := c.verifyIntegrity(
integrityActual(opts.HashAlgorithm, contentDigest, integrityHasher),
opts.HashAlgorithm,
opts.ExpectedHash,
url,
)
if err != nil {
return nil, err
}
filename = sanitizeFilename(filename, contentDigest.Hex())
destPath := filepath.Join(dir, filename)
if !containedUnder(dir, destPath) {
return nil, fmt.Errorf(
"downloaded filename %q escapes destination directory",
filename,
)
}
if err := stage.writer.Rewind(); err != nil {
return nil, fmt.Errorf("rewind staged download: %w", err)
}
destFile, err := copyFileContext(ctx, stage.writer, destPath, opts.FileMode)
if err != nil {
return nil, fmt.Errorf("write downloaded file: %w", err)
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, destFile.Close())
}
if stage.cacheable {
if err := c.cache().commitEntryContext(
ctx,
stage.writer, filename, url, opts.Kind, integrity, opts.TTL,
); err != nil {
if ctx.Err() != nil {
return nil, errors.Join(ctx.Err(), destFile.Close())
}
c.logger.Warn(fmt.Errorf("failed to cache downloaded file: %w", err))
}
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, destFile.Close())
}
return &DownloadResult{
File: destFile,
CacheHit: false,
Verified: verified,
}, nil
}
// newIntegrityHasher creates the hasher for an upstream digest, or nil when
// the content SHA-256 already covers that expectation or none was supplied.
func newIntegrityHasher(algorithm HashAlgorithm, expectedHash string) hash.Hash {
if expectedHash == "" || algorithm == HashNone || algorithm == HashSHA256 {
return nil
}
switch algorithm {
case HashSHA1:
return sha1.New()
case HashSHA512:
return sha512.New()
default:
return nil
}
}
// integrityActual reports the digest compared against the upstream
// expectation: the content digest for SHA-256, the separate hasher otherwise.
func integrityActual(
algorithm HashAlgorithm,
content cas.Digest,
hasher hash.Hash,
) string {
if algorithm == HashSHA256 {
return content.Hex()
}
if hasher != nil {
return hex.EncodeToString(hasher.Sum(nil))
}
return ""
}
func (c *Client) verifyIntegrity(
actualHash string,
algorithm HashAlgorithm,
expectedHash string,
url string,
) (Integrity, bool, error) {
integrity := Integrity{State: IntegrityUnverified}
verified := false
if expectedHash != "" && actualHash != "" {
if actualHash != expectedHash {
return integrity, false, fmt.Errorf(
"integrity verification failed (%s): expected %s, got %s",
algorithm, expectedHash, actualHash,
)
}
integrity = Integrity{
Algorithm: algorithm,
Expected: expectedHash,
Actual: actualHash,
State: IntegrityVerified,
}
verified = true
c.logger.Debug(
fmt.Sprintf(
"integrity verified (%s): %s",
algorithm,
url,
),
)
}
return integrity, verified, nil
}
func validateDownloadURL(rawURL string) error {
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("invalid download URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf(
"unsupported URL scheme %q (only http/https)",
u.Scheme,
)
}
return nil
}
package cache
import (
"mime"
"net/http"
"net/url"
"path/filepath"
"strings"
)
func speculateFilename(resp *http.Response) string {
if filename, ok := getFilenameFromHeader(resp); ok {
return filename
}
filename := getFilenameFromURL(resp.Request.URL.String())
return filename
}
func getFilenameFromHeader(resp *http.Response) (string, bool) {
contentDisposition := resp.Header.Get("Content-Disposition")
if contentDisposition == "" {
return "", false
}
_, params, err := mime.ParseMediaType(contentDisposition)
if err != nil {
return "", false
}
filename, ok := params["filename"]
return filename, ok
}
func getFilenameFromURL(urlString string) string {
u, err := url.Parse(urlString)
if err != nil {
return ""
}
_, filename, found := strings.CutLast(u.Path, "/")
if !found {
return u.Path
}
return filename
}
// sanitizeFilename prevents path traversal by stripping directory components.
func sanitizeFilename(name, fallback string) string {
name = filepath.Base(name)
if !filepath.IsLocal(name) || name == "." || name == ".." || name == "/" || name == string(filepath.Separator) {
return fallback
}
return name
}
// containedUnder reports whether child is strictly inside parent.
func containedUnder(parent, child string) bool {
absParent, err := filepath.Abs(parent)
if err != nil {
return false
}
absChild, err := filepath.Abs(child)
if err != nil {
return false
}
prefix := absParent
if !strings.HasSuffix(prefix, string(filepath.Separator)) {
prefix += string(filepath.Separator)
}
return strings.HasPrefix(absChild, prefix)
}
package cache
import (
"context"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"slices"
"sync"
"time"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/log"
)
var ErrDisabled = errors.New("cache is disabled")
// missingObjectRetries bounds how often get reloads the index after the
// object of an entry vanished.
const missingObjectRetries = 2
type handler struct {
mu sync.Mutex
on bool
dir string
store *cas.Store
index *index
policy Policy
logger *log.Logger
}
func newHandler(root string, cfg Config, logger *log.Logger) *handler {
h := &handler{
on: cfg.Enabled,
dir: root,
policy: cfg.toPolicy(),
logger: logger,
}
if !h.on {
return h
}
if err := h.initialize(cfg); err != nil {
logger.Warn(fmt.Errorf("disable cache at %s: %w", root, err))
h.on = false
if h.store != nil {
if err := h.store.Close(); err != nil {
logger.Warn(err)
}
h.store = nil
}
}
return h
}
func (h *handler) initialize(cfg Config) (resultErr error) {
if err := cfg.Validate(); err != nil {
return err
}
if err := fsutil.MkdirAllPrivate(h.dir); err != nil {
return err
}
lock, err := h.acquireIndexLock()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
h.store, err = cas.New(filepath.Join(h.dir, "cas"))
if err != nil {
return err
}
h.index = newIndex(filepath.Join(h.dir, manifestFilename))
if _, err = h.index.load(); err != nil {
return err
}
removed, _, err := h.maintainLocked(nil)
if err != nil {
return err
}
if len(removed) != 0 {
if err := h.index.flush(); err != nil {
return err
}
}
if err := h.collectAllLocked(nil); err != nil {
return err
}
return h.store.Cleanup()
}
func (h *handler) acquireIndexLock() (*fsutil.FileLock, error) {
start := h.logger.WaitStart()
lock, err := fsutil.LockFile(h.dir + ".lock")
h.logger.WaitDone(log.WaitFileLock, start)
return lock, err
}
func (h *handler) lockIndex() (*fsutil.FileLock, error) {
if !h.on {
return nil, ErrDisabled
}
lock, err := h.acquireIndexLock()
if err != nil {
return nil, err
}
reset, err := h.index.load()
if err == nil && reset {
err = h.collectAllLocked(nil)
}
if err != nil {
return nil, errors.Join(err, lock.Close())
}
return lock, nil
}
// refresh reloads the index only when another process published a change.
// A read that finds the published identity unchanged costs one stat and no
// file lock, because this process holds the same entries it last loaded.
func (h *handler) refresh() (resultErr error) {
if !h.on {
return ErrDisabled
}
changed, err := h.index.changed()
if err != nil || !changed {
return err
}
lock, err := h.acquireIndexLock()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
reset, err := h.index.load()
if err != nil {
return err
}
if reset {
return h.collectAllLocked(nil)
}
return nil
}
func (h *handler) newWriter() (*cas.Writer, error) {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return nil, ErrDisabled
}
return h.store.NewWriter()
}
func (h *handler) commitEntryContext(ctx context.Context, writer *cas.Writer, filename, k string, kind EntryKind, integrity Integrity, expiration time.Duration) (resultErr error) {
h.mu.Lock()
defer h.mu.Unlock()
lock, err := h.lockIndex()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return err
}
object, err := writer.Commit(nil)
if err != nil {
return err
}
if expiration == 0 {
expiration = h.policy.ConfigFor(kind).TTL
}
ckey := canonicalizeKey(k)
now := time.Now()
created := now
contentHash := object.Digest.String()
var removed []cas.Digest
if old, ok := h.index.get(ckey); ok {
created = old.CreatedAt
if old.ContentHash != contentHash {
digest, err := cas.ParseDigest(old.ContentHash)
if err != nil {
return err
}
removed = append(removed, digest)
}
}
h.index.put(ckey, &Entry{
Kind: kind,
Filename: sanitizeFilename(filename, object.Digest.Hex()),
Size: object.Size,
ContentHash: contentHash,
Integrity: integrity,
Expiration: now.Add(expiration),
Key: string(ckey),
CreatedAt: created,
})
removed, dropped, err := h.maintainLocked(removed)
if err != nil {
return err
}
// Publish the entry and the maintenance deletions with one append. The
// new entry may itself be the one maintenance dropped.
records := make([]journalRecord, 0, len(dropped)+1)
if entry, ok := h.index.get(ckey); ok {
records = append(records, journalRecord{
Op: journalOpPut,
Key: ckey,
Entry: entry,
})
}
for _, k := range dropped {
records = append(records, journalRecord{Op: journalOpDelete, Key: k})
}
if err := h.index.publishRecords(records); err != nil {
return err
}
return h.collectCandidatesLocked(removed)
}
func (h *handler) flush() (resultErr error) {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return nil
}
lock, err := h.lockIndex()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
return h.index.flush()
}
func (h *handler) exist(k string) bool {
hit, reader, _, _, err := h.get(k)
if err != nil {
h.logger.Warn(err)
return false
}
if reader != nil {
if err := reader.Close(); err != nil {
h.logger.Warn(err)
return false
}
}
return hit
}
func (h *handler) get(k string) (
hit bool,
reader io.ReadCloser,
filename string,
digest cas.Digest,
resultErr error,
) {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return false, nil, "", cas.Digest{}, nil
}
if err := h.refresh(); err != nil {
return false, nil, "", cas.Digest{}, err
}
defer func() {
if resultErr != nil && reader != nil {
resultErr = errors.Join(resultErr, reader.Close())
hit, reader, filename, digest = false, nil, "", cas.Digest{}
}
}()
var err error
for attempt := 0; ; attempt++ {
entry, ok := h.index.get(canonicalizeKey(k))
if !ok || !entry.Expiration.After(time.Now()) {
return false, nil, "", cas.Digest{}, nil
}
digest, err = cas.ParseDigest(entry.ContentHash)
if err != nil {
return false, nil, "", cas.Digest{}, err
}
reader, err = h.store.Open(digest)
if err == nil {
return true, reader, entry.Filename, digest, nil
}
// Another process publishes a replacement entry before it reclaims
// the old object, so a refresh after a missing object finds it.
if !errors.Is(err, os.ErrNotExist) || attempt == missingObjectRetries {
return false, nil, "", cas.Digest{}, err
}
if err := h.refresh(); err != nil {
return false, nil, "", cas.Digest{}, err
}
}
}
func (h *handler) getBytes(k string) (bool, []byte, error) {
hit, data, _, err := h.getBytesContext(context.Background(), k)
return hit, data, err
}
func (h *handler) getBytesContext(ctx context.Context, k string) (
hit bool,
data []byte,
digest cas.Digest,
resultErr error,
) {
hit, reader, _, digest, err := h.get(k)
if err != nil || !hit {
return false, nil, cas.Digest{}, err
}
defer func() { resultErr = errors.Join(resultErr, reader.Close()) }()
data, err = io.ReadAll(contextReader{ctx, reader})
if err != nil {
return false, nil, cas.Digest{}, err
}
return true, data, digest, nil
}
func (h *handler) remove(k string) (resultErr error) {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return nil
}
lock, err := h.lockIndex()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
entry, ok := h.index.get(canonicalizeKey(k))
if !ok {
return nil
}
digest, err := cas.ParseDigest(entry.ContentHash)
if err != nil {
return err
}
h.index.delete(canonicalizeKey(k))
if err := h.index.publishRecords([]journalRecord{{
Op: journalOpDelete,
Key: canonicalizeKey(k),
}}); err != nil {
return err
}
return h.collectCandidatesLocked([]cas.Digest{digest})
}
func (h *handler) all() []*Entry {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return nil
}
if err := h.refresh(); err != nil {
h.logger.Warn(err)
return nil
}
keys := slices.Sorted(maps.Keys(h.index.entries))
entries := make([]*Entry, 0, len(keys))
for _, k := range keys {
entry := *h.index.entries[k]
entries = append(entries, &entry)
}
return entries
}
func (h *handler) clearAll() (report ResetReport, resultErr error) {
h.mu.Lock()
defer h.mu.Unlock()
if !h.on {
return report, nil
}
lock, err := h.lockIndex()
if err != nil {
return report, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
h.index.entries = make(map[key]*Entry)
if err := h.index.flush(); err != nil {
return report, err
}
if err := h.collectAllLocked(&report); err != nil {
return report, err
}
return report, h.store.Cleanup()
}
package cache
import (
"bytes"
"encoding/json/v2"
"errors"
"fmt"
"os"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/fsutil"
)
const indexVersion = 3
const (
// journalSuffix names the append-only record log published beside the
// snapshot. A process replays it after loading the snapshot.
journalSuffix = ".journal"
// journalEntryLimit and journalByteLimit bound the replay a reader pays
// before the next publish compacts the journal into the snapshot.
journalEntryLimit = 256
journalByteLimit = 1 << 20
)
const (
journalOpPut = "put"
journalOpDelete = "delete"
)
type indexManifest struct {
Version int `json:"version"`
Entries map[key]*Entry `json:"entries"`
}
// journalRecord is one durable index change. A snapshot rewrite replaces the
// whole journal, so records only describe changes made after the snapshot.
type journalRecord struct {
Op string `json:"op"`
Key key `json:"key"`
Entry *Entry `json:"entry,omitempty"`
}
// index holds the cache index in memory for the process. A process takes the
// cache file lock to load changes another process published and to publish its
// own changes; a read only stats the snapshot and journal and reloads when
// their identity changed.
type index struct {
path string
journal string
entries map[key]*Entry
// info and journalInfo are the stat identities the in-memory state was
// loaded from. A write that replaces the snapshot changes its inode, and
// an append changes the journal size.
info os.FileInfo
journalInfo os.FileInfo
journalRecords int
}
func newIndex(path string) *index {
return &index{
path: path,
journal: path + journalSuffix,
entries: make(map[key]*Entry),
}
}
// load brings the in-memory index up to date with the published snapshot and
// journal. It runs under cache ownership when it may repair a broken index.
func (idx *index) load() (bool, error) {
changed, err := idx.changed()
if err != nil {
return false, err
}
if !changed {
return false, nil
}
reset, err := idx.loadSnapshot()
if err != nil {
return false, err
}
if reset {
idx.entries = make(map[key]*Entry)
if err := idx.writeSnapshot(); err != nil {
return false, err
}
if err := idx.removeJournal(); err != nil {
return false, err
}
return true, nil
}
if err := idx.replayJournal(); err != nil {
return false, err
}
return false, nil
}
// changed reports whether the published state differs from the state this
// process holds. It only stats both files. A missing snapshot counts as a
// change, because a loaded index always has one.
func (idx *index) changed() (bool, error) {
info, err := os.Stat(idx.path)
if errors.Is(err, os.ErrNotExist) {
return true, nil
}
if err != nil {
return true, nil
}
if idx.info == nil || !sameFileStamp(info, idx.info) {
return true, nil
}
journalInfo, journalErr := os.Stat(idx.journal)
if errors.Is(journalErr, os.ErrNotExist) {
return idx.journalInfo != nil, nil
}
if journalErr != nil {
return true, nil
}
if idx.journalInfo == nil || !sameFileStamp(journalInfo, idx.journalInfo) {
return true, nil
}
return false, nil
}
// sameFileStamp matches the identity a file was loaded from against its
// current stat.
func sameFileStamp(current, cached os.FileInfo) bool {
return cached != nil && current != nil &&
os.SameFile(current, cached) &&
current.Size() == cached.Size() &&
current.ModTime().Equal(cached.ModTime())
}
// loadSnapshot replaces the in-memory entries with the published snapshot. A
// missing, unreadable, or invalid snapshot resets the index and reports it.
func (idx *index) loadSnapshot() (bool, error) {
file, err := os.Open(idx.path)
if errors.Is(err, os.ErrNotExist) {
idx.entries = make(map[key]*Entry)
idx.info = nil
return true, nil
}
if err != nil {
return false, err
}
var manifest indexManifest
decodeErr := json.UnmarshalRead(file, &manifest)
info, statErr := file.Stat()
closeErr := file.Close()
if statErr != nil || closeErr != nil {
return false, errors.Join(statErr, closeErr)
}
if decodeErr != nil || !validIndex(manifest) {
idx.entries = make(map[key]*Entry)
idx.info = nil
return true, nil
}
idx.info = info
idx.entries = manifest.Entries
return false, nil
}
func validIndex(manifest indexManifest) bool {
if manifest.Version != indexVersion || manifest.Entries == nil {
return false
}
for k, entry := range manifest.Entries {
if !validEntry(k, entry) {
return false
}
}
return true
}
func validEntry(k key, entry *Entry) bool {
if entry == nil || entry.Size < 0 || entry.Kind > KindArtifact || entry.Key != string(k) {
return false
}
digest, err := cas.ParseDigest(entry.ContentHash)
return err == nil &&
entry.Filename != "" &&
sanitizeFilename(entry.Filename, digest.Hex()) == entry.Filename
}
// replayJournal applies the records published after the snapshot. A torn or
// invalid tail is discarded, so a crashed writer costs at most the entries it
// had not finished publishing.
func (idx *index) replayJournal() error {
idx.journalRecords = 0
data, err := os.ReadFile(idx.journal)
if errors.Is(err, os.ErrNotExist) {
idx.journalInfo = nil
return nil
}
if err != nil {
return err
}
offset := 0
for offset < len(data) {
end := bytes.IndexByte(data[offset:], '\n')
if end < 0 {
break
}
var record journalRecord
line := data[offset : offset+end]
if json.Unmarshal(line, &record) != nil || !applyJournalRecord(idx.entries, record) {
break
}
offset += end + 1
idx.journalRecords++
}
if offset < len(data) {
if err := os.Truncate(idx.journal, int64(offset)); err != nil {
return err
}
}
info, err := os.Stat(idx.journal)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
idx.journalInfo = nil
return nil
}
return err
}
idx.journalInfo = info
return nil
}
func applyJournalRecord(entries map[key]*Entry, record journalRecord) bool {
switch record.Op {
case journalOpPut:
if !validEntry(record.Key, record.Entry) {
return false
}
entries[record.Key] = record.Entry
case journalOpDelete:
delete(entries, record.Key)
default:
return false
}
return true
}
// flush publishes the whole in-memory index as a new snapshot and drops the
// journal that is now redundant.
func (idx *index) flush() error {
if err := idx.writeSnapshot(); err != nil {
return err
}
return idx.removeJournal()
}
func (idx *index) writeSnapshot() error {
data, err := json.Marshal(indexManifest{
Version: indexVersion,
Entries: idx.entries,
})
if err != nil {
idx.info = nil
return fmt.Errorf("encode cache index: %w", err)
}
if err := fsutil.AtomicWrite(idx.path, data, 0o600); err != nil {
idx.info = nil
return fmt.Errorf("publish cache index: %w", err)
}
idx.info, err = os.Stat(idx.path)
return err
}
func (idx *index) removeJournal() error {
idx.journalRecords = 0
idx.journalInfo = nil
if err := os.Remove(idx.journal); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("clear cache journal: %w", err)
}
return nil
}
// publishRecords appends records for changes already applied in memory. When
// the journal outgrows its replay bound, the same call compacts it.
func (idx *index) publishRecords(records []journalRecord) error {
idx.journalRecords += len(records)
if err := idx.appendJournal(records); err != nil {
return err
}
if idx.journalRecords >= journalEntryLimit ||
idx.journalInfo != nil && idx.journalInfo.Size() >= journalByteLimit {
return idx.flush()
}
return nil
}
// appendJournal writes one batch of records. The caller holds the cache lock,
// so records from different processes never interleave.
func (idx *index) appendJournal(records []journalRecord) error {
if len(records) == 0 {
return nil
}
var buffer bytes.Buffer
for _, record := range records {
line, err := json.Marshal(record)
if err != nil {
return fmt.Errorf("encode cache journal record: %w", err)
}
buffer.Write(line)
buffer.WriteByte('\n')
}
file, err := os.OpenFile(
idx.journal,
os.O_WRONLY|os.O_CREATE|os.O_APPEND,
0o600,
)
if err != nil {
return fmt.Errorf("open cache journal: %w", err)
}
_, writeErr := file.Write(buffer.Bytes())
info, statErr := file.Stat()
closeErr := file.Close()
if err := errors.Join(writeErr, statErr, closeErr); err != nil {
return fmt.Errorf("append cache journal: %w", err)
}
idx.journalInfo = info
return nil
}
func (idx *index) get(k key) (*Entry, bool) {
entry, ok := idx.entries[k]
return entry, ok
}
func (idx *index) put(k key, entry *Entry) {
idx.entries[k] = entry
}
func (idx *index) delete(k key) {
delete(idx.entries, k)
}
package cache
import (
"time"
"github.com/mclucy/lucy/cas"
)
const manifestFilename = "cache.json"
type key string
// ResetReport counts unique objects actually removed, collapsing shared URL references.
// Removed lists the paths of those objects.
type ResetReport struct {
TotalFreedSize int64
FileCount int
Removed []string
}
func (h *handler) maintainLocked(removed []cas.Digest) ([]cas.Digest, []key, error) {
var dropped []key
for _, k := range expiredEntries(h.index.entries, time.Now()) {
digest, err := cas.ParseDigest(h.index.entries[k].ContentHash)
if err != nil {
return nil, nil, err
}
removed = append(removed, digest)
dropped = append(dropped, k)
h.index.delete(k)
}
for _, target := range evictionCandidates(h.index.entries, h.policy) {
digest, err := cas.ParseDigest(h.index.entries[target.key].ContentHash)
if err != nil {
return nil, nil, err
}
removed = append(removed, digest)
dropped = append(dropped, target.key)
h.index.delete(target.key)
}
return removed, dropped, nil
}
func (h *handler) referencedLocked(digest cas.Digest) bool {
value := digest.String()
for _, entry := range h.index.entries {
if entry.ContentHash == value {
return true
}
}
return false
}
func (h *handler) collectCandidatesLocked(digests []cas.Digest) error {
for _, digest := range digests {
if h.referencedLocked(digest) {
continue
}
if _, err := h.store.Remove(digest); err != nil {
return err
}
}
return nil
}
func (h *handler) collectAllLocked(report *ResetReport) error {
references := make(map[cas.Digest]struct{}, len(h.index.entries))
for _, entry := range h.index.entries {
digest, err := cas.ParseDigest(entry.ContentHash)
if err != nil {
return err
}
references[digest] = struct{}{}
}
return h.store.Walk(func(object cas.Object) error {
if _, ok := references[object.Digest]; ok {
return nil
}
freed, err := h.store.Remove(object.Digest)
if err != nil {
return err
}
if report != nil {
report.TotalFreedSize += freed
report.FileCount++
report.Removed = append(report.Removed, h.store.Path(object.Digest))
}
return nil
})
}
package cache
import "time"
type PolicyConfig struct {
MaxSize int64 `json:"max_size"`
TTL time.Duration `json:"ttl"`
}
type Policy struct {
Metadata PolicyConfig `json:"metadata"`
Artifact PolicyConfig `json:"artifact"`
}
func (p *Policy) ConfigFor(kind EntryKind) PolicyConfig {
switch kind {
case KindMetadata:
return p.Metadata
case KindArtifact:
return p.Artifact
default:
return p.Artifact
}
}
package cache
import (
"errors"
"fmt"
"os"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/log"
)
// downloadStage retains the stream when optional cache storage cannot accept it.
type downloadStage struct {
writer *cas.Writer
cacheable bool
temporary *cas.Store
directory string
logger *log.Logger
}
func (c *Client) newDownloadStage() (*downloadStage, error) {
writer, err := c.cache().newWriter()
stage := &downloadStage{
writer: writer,
cacheable: err == nil,
logger: c.logger,
}
if err == nil {
return stage, nil
}
if !errors.Is(err, ErrDisabled) {
c.logger.Warn(fmt.Errorf("cache staging unavailable: %w", err))
}
if err := stage.fallback(); err != nil {
return nil, err
}
return stage, nil
}
func (s *downloadStage) fallback() error {
directory, err := os.MkdirTemp("", "lucy-download-")
if err != nil {
return err
}
store, err := cas.New(directory)
if err != nil {
return errors.Join(err, os.RemoveAll(directory))
}
var writer *cas.Writer
if s.writer == nil {
writer, err = store.NewWriter()
} else {
writer, err = s.writer.MoveTo(store)
}
if err != nil {
return errors.Join(err, store.Close(), os.RemoveAll(directory))
}
if s.writer != nil {
if err := s.writer.Abort(); err != nil {
s.logger.Warn(fmt.Errorf("remove failed cache stage: %w", err))
}
}
s.writer = writer
s.cacheable = false
s.temporary = store
s.directory = directory
return nil
}
func (s *downloadStage) Write(data []byte) (int, error) {
count, err := s.writer.Write(data)
if err == nil || !s.cacheable {
return count, err
}
s.logger.Warn(fmt.Errorf("cache stage write failed, retaining uncached download: %w", err))
if err := s.fallback(); err != nil {
return count, err
}
rest, err := s.writer.Write(data[count:])
return count + rest, err
}
func (s *downloadStage) seal() (cas.Object, error) {
object, err := s.writer.Seal(nil)
if err == nil || !s.cacheable {
return object, err
}
s.logger.Warn(fmt.Errorf("cache stage sync failed, retaining uncached download: %w", err))
if err := s.fallback(); err != nil {
return cas.Object{}, err
}
return s.writer.Seal(nil)
}
func (s *downloadStage) Close() error {
result := s.writer.Abort()
if s.temporary != nil {
result = errors.Join(result, s.temporary.Close(), os.RemoveAll(s.directory))
}
return result
}
package cache
import (
"cmp"
"maps"
"net/url"
"path"
"slices"
"strings"
"time"
)
// expiredEntries uses the same boundary as cache lookups: an entry is dead
// once its expiration is reached.
func expiredEntries(entries map[key]*Entry, now time.Time) []key {
var expired []key
for k, entry := range entries {
if !entry.Expiration.After(now) {
expired = append(expired, k)
}
}
return expired
}
type evictionTarget struct {
key key
exp time.Time
}
func evictionCandidates(
entries map[key]*Entry,
policy Policy,
) []evictionTarget {
type objectKey struct {
kind EntryKind
hash string
}
totals := map[EntryKind]int64{}
references := make(map[objectKey]int, len(entries))
targets := make([]evictionTarget, 0, len(entries))
for k, entry := range entries {
object := objectKey{kind: entry.Kind, hash: entry.ContentHash}
if references[object] == 0 {
totals[entry.Kind] += entry.Size
}
references[object]++
targets = append(targets, evictionTarget{key: k, exp: entry.Expiration})
}
slices.SortFunc(targets, func(a, b evictionTarget) int {
if c := a.exp.Compare(b.exp); c != 0 {
return c
}
return cmp.Compare(a.key, b.key)
})
var result []evictionTarget
for _, target := range targets {
entry := entries[target.key]
if totals[entry.Kind] <= policy.ConfigFor(entry.Kind).MaxSize {
continue
}
result = append(result, target)
object := objectKey{kind: entry.Kind, hash: entry.ContentHash}
references[object]--
if references[object] == 0 {
totals[entry.Kind] -= entry.Size
}
}
return result
}
func canonicalizeKey(k string) key {
u, err := url.Parse(k)
if err != nil || u.Scheme == "" {
return key(k)
}
u.Scheme = strings.ToLower(u.Scheme)
u.Host = strings.ToLower(u.Host)
host := u.Hostname()
port := u.Port()
if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") {
u.Host = host
}
if u.Path != "" {
u.Path = path.Clean(u.Path)
}
if u.RawQuery != "" {
params := u.Query()
keys := slices.Sorted(maps.Keys(params))
var parts []string
for _, k := range keys {
vals := slices.Clone(params[k])
slices.Sort(vals)
for _, v := range vals {
parts = append(parts, url.QueryEscape(k)+"="+url.QueryEscape(v))
}
}
u.RawQuery = strings.Join(parts, "&")
}
u.Fragment = ""
u.RawFragment = ""
return key(u.String())
}
// Package cas stores immutable contents independently of consumer metadata.
package cas
import (
"crypto/sha256"
"encoding/hex"
"fmt"
)
// Digest is an SHA-256 address. Its serialized form includes the algorithm name.
type Digest [sha256.Size]byte
// ParseDigest accepts only the canonical sha256:<lowercase-hex> representation.
func ParseDigest(value string) (Digest, error) {
var digest Digest
if len(value) != 7+sha256.Size*2 || value[:7] != "sha256:" {
return digest, fmt.Errorf("expected sha256:<64 lowercase hexadecimal characters>")
}
for i := range digest {
high, highOK := hexDigit(value[7+i*2])
low, lowOK := hexDigit(value[8+i*2])
if !highOK || !lowOK {
return Digest{}, fmt.Errorf("invalid sha256 digest")
}
digest[i] = high<<4 | low
}
return digest, nil
}
func hexDigit(value byte) (byte, bool) {
switch {
case value >= '0' && value <= '9':
return value - '0', true
case value >= 'a' && value <= 'f':
return value - 'a' + 10, true
default:
return 0, false
}
}
func (d Digest) String() string {
var text [7 + sha256.Size*2]byte
copy(text[:], "sha256:")
hex.Encode(text[7:], d[:])
return string(text[:])
}
// Hex is the filename-safe digest without its algorithm prefix.
func (d Digest) Hex() string {
return hex.EncodeToString(d[:])
}
func (d Digest) MarshalText() ([]byte, error) {
text := make([]byte, 7+sha256.Size*2)
copy(text, "sha256:")
hex.Encode(text[7:], d[:])
return text, nil
}
func (d *Digest) UnmarshalText(text []byte) error {
parsed, err := ParseDigest(string(text))
if err != nil {
return err
}
*d = parsed
return nil
}
// Object records storage facts alone; filenames and retention policies belong to consumers.
type Object struct {
Digest Digest `json:"digest"`
Size int64 `json:"size"`
}
package cas
import (
"errors"
"fmt"
"hash"
"io"
"os"
)
type verifiedReader struct {
file *os.File
expected Digest
hash hash.Hash
finished bool
err error
}
func (r *verifiedReader) Read(data []byte) (int, error) {
if r.finished {
return 0, r.err
}
count, err := r.file.Read(data)
if count > 0 {
if _, hashErr := r.hash.Write(data[:count]); hashErr != nil {
return count, errors.Join(ErrRead, hashErr)
}
}
if errors.Is(err, io.EOF) {
r.finished = true
var actual Digest
r.hash.Sum(actual[:0])
if actual != r.expected {
r.err = fmt.Errorf("%w: expected %s, got %s", ErrCorrupt, r.expected.String(), actual.String())
} else {
r.err = io.EOF
}
return count, r.err
}
if err != nil {
return count, errors.Join(ErrRead, err)
}
return count, nil
}
func (r *verifiedReader) Close() error {
return r.file.Close()
}
package cas
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/internal/fsutil"
)
var (
ErrCorrupt = errors.New("cas contents do not match their digest")
ErrRead = errors.New("cannot read cas contents")
)
// Store owns one private filesystem root; consumers keep their own metadata.
// Close it after its writers finish; open readers own their file handles.
// A Commit orders its writes with fsutil.Barrier, so a power loss before the
// next device flush leaves an object complete or missing, never partial.
type Store struct {
root *os.Root
directory string
}
// New rejects a symlink store root and creates private object and staging namespaces.
func New(path string) (*Store, error) {
if err := fsutil.MkdirAllPrivate(path); err != nil {
return nil, fmt.Errorf("create cas root: %w", err)
}
info, err := os.Lstat(path)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return nil, errors.Join(fmt.Errorf("cas root must be a regular directory"), err)
}
root, err := os.OpenRoot(path)
if err != nil {
return nil, fmt.Errorf("open cas root: %w", err)
}
for _, name := range []string{"objects", "objects/sha256", "tmp"} {
if err := root.Mkdir(name, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
return nil, errors.Join(err, root.Close())
}
info, err := root.Lstat(name)
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return nil, errors.Join(fmt.Errorf("invalid cas namespace %s", name), err, root.Close())
}
}
return &Store{root: root, directory: path}, nil
}
func (s *Store) Close() error {
return s.root.Close()
}
// Path reports the filesystem path of a published object. It does not check
// that the object exists; callers open it through their own filesystem view.
func (s *Store) Path(digest Digest) string {
return filepath.Join(s.directory, filepath.FromSlash(objectPath(digest)))
}
func (s *Store) lock() (*fsutil.FileLock, error) {
if info, err := s.root.Lstat("cas.lock"); err == nil && !info.Mode().IsRegular() {
return nil, fmt.Errorf("cas lock must be a regular file")
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
file, err := s.root.OpenFile("cas.lock", os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
return fsutil.LockOpenedFile(file, true)
}
func objectPath(digest Digest) string {
hex := digest.Hex()
return "objects/sha256/" + hex[:2] + "/" + hex
}
// Open verifies the digest as the stream reaches EOF. Discard copied bytes on error.
func (s *Store) Open(digest Digest) (io.ReadCloser, error) {
name := objectPath(digest)
info, err := s.root.Lstat(name)
if err != nil {
return nil, fmt.Errorf("open cas object: %w", err)
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("%w: object is not a regular file", ErrCorrupt)
}
file, err := s.root.Open(name)
if err != nil {
return nil, errors.Join(ErrRead, err)
}
return &verifiedReader{
file: file,
expected: digest,
hash: sha256.New(),
}, nil
}
// Put computes the address while writing and never publishes a failed stream.
func (s *Store) Put(reader io.Reader, expected *Digest) (object Object, resultErr error) {
writer, err := s.NewWriter()
if err != nil {
return object, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Abort()) }()
if _, err := io.Copy(writer, reader); err != nil {
return object, fmt.Errorf("ingest cas contents: %w", err)
}
return writer.Commit(expected)
}
// Walk visits physical objects once. Consumers must coordinate retention with their metadata.
func (s *Store) Walk(visit func(Object) error) error {
return fs.WalkDir(s.root.FS(), "objects/sha256", func(name string, entry fs.DirEntry, err error) error {
if err != nil || entry.IsDir() {
return err
}
if !entry.Type().IsRegular() {
return nil
}
digest, err := ParseDigest("sha256:" + filepath.Base(name))
if err != nil || filepath.ToSlash(name) != objectPath(digest) {
return nil
}
info, err := entry.Info()
if err != nil {
return err
}
return visit(Object{Digest: digest, Size: info.Size()})
})
}
// Remove is for consumer-approved reclamation, not automatic retention.
// Readers already opened on systems that allow to unlink can finish reading their handles.
func (s *Store) Remove(digest Digest) (size int64, resultErr error) {
lock, err := s.lock()
if err != nil {
return 0, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
return s.removeLocked(digest)
}
func (s *Store) removeLocked(digest Digest) (int64, error) {
name := objectPath(digest)
info, err := s.root.Lstat(name)
if errors.Is(err, os.ErrNotExist) {
return 0, nil
}
if err != nil {
return 0, err
}
if !info.Mode().IsRegular() {
return 0, fmt.Errorf("refuse to remove non-regular cas object")
}
garbage := "tmp/gc-" + rand.Text()
if err := fsutil.RenameRoot(s.root, name, garbage); err != nil {
return 0, err
}
if err := s.removePrivateFile(garbage); err != nil {
return 0, fmt.Errorf("remove reclaimed cas contents: %w", err)
}
return info.Size(), nil
}
// Sweep holds the store lock while plan determines the retained digests and
// locks the state those references came from, then removes every other object.
// No writer can publish from the moment the lock is acquired through the last
// removal, so an object published by an operation that started after plan has
// not run cannot be collected. plan may return a release function for state it
// locked; Sweep runs it before releasing the store lock. A nil reference set is
// rejected rather than read as "delete all", and a plan or enumeration error
// removes nothing.
func (s *Store) Sweep(plan func() (map[Digest]struct{}, func() error, error)) (removed int, bytes int64, resultErr error) {
if plan == nil {
return 0, 0, fmt.Errorf("sweep requires a plan")
}
lock, err := s.lock()
if err != nil {
return 0, 0, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
referenced, release, err := plan()
if release != nil {
defer func() { resultErr = errors.Join(resultErr, release()) }()
}
if err != nil {
return 0, 0, err
}
if referenced == nil {
return 0, 0, fmt.Errorf("sweep requires a reference set")
}
var objects []Object
if err := s.Walk(func(object Object) error {
objects = append(objects, object)
return nil
}); err != nil {
return 0, 0, err
}
var failures []error
for _, object := range objects {
if _, kept := referenced[object.Digest]; kept {
continue
}
size, err := s.removeLocked(object.Digest)
if err != nil {
failures = append(failures, err)
continue
}
removed++
bytes += size
}
return removed, bytes, errors.Join(failures...)
}
// Cleanup removes only stages whose lease is no longer held by a writer.
func (s *Store) Cleanup() (resultErr error) {
lock, err := s.lock()
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
directory, err := s.root.Open("tmp")
if err != nil {
return err
}
entries, err := directory.ReadDir(-1)
if closeErr := directory.Close(); err != nil || closeErr != nil {
return errors.Join(err, closeErr)
}
for _, entry := range entries {
if strings.HasPrefix(entry.Name(), "gc-") && entry.Type().IsRegular() {
if err := s.removePrivateFile("tmp/" + entry.Name()); err != nil {
return err
}
continue
}
if strings.HasPrefix(entry.Name(), "stage-") && strings.HasSuffix(entry.Name(), ".data") {
dataName := "tmp/" + entry.Name()
leaseName := strings.TrimSuffix(dataName, ".data") + ".lease"
if _, err := s.root.Lstat(leaseName); errors.Is(err, os.ErrNotExist) {
if err := s.removePrivateFile(dataName); err != nil {
return err
}
} else if err != nil {
return err
}
continue
}
if !strings.HasPrefix(entry.Name(), "stage-") || !strings.HasSuffix(entry.Name(), ".lease") {
continue
}
if !entry.Type().IsRegular() {
continue
}
leaseName := "tmp/" + entry.Name()
file, err := s.root.OpenFile(leaseName, os.O_RDWR, 0)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
lease, err := fsutil.LockOpenedFile(file, false)
if errors.Is(err, fsutil.ErrLocked) {
continue
}
if err != nil {
return err
}
if err := lease.Close(); err != nil {
return err
}
dataName := strings.TrimSuffix(leaseName, ".lease") + ".data"
for _, name := range []string{dataName, leaseName} {
if err := s.removePrivateFile(name); err != nil {
return err
}
}
}
return nil
}
func (s *Store) removePrivateFile(name string) error {
info, err := s.root.Lstat(name)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("refuse non-regular cas cleanup path")
}
return s.root.Remove(name)
}
package cas
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"github.com/mclucy/lucy/internal/fsutil"
)
type writerState uint8
const (
writerOpen writerState = iota
writerSealed
writerTransferred
writerClosedStage
writerFinished
)
// Writer has one owner. Seal prevents further writes; Abort releases an unpublished stage.
type Writer struct {
store *Store
file *os.File
lease *fsutil.FileLock
dataName string
leaseName string
hash hash.Hash
size int64
state writerState
object Object
}
// NewWriter leases a unique stage so cleanup cannot remove active writes.
func (s *Store) NewWriter() (*Writer, error) {
return s.newWriter(sha256.New())
}
func (s *Store) newWriter(hasher hash.Hash) (writer *Writer, resultErr error) {
lock, err := s.lock()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
name := "tmp/stage-" + rand.Text()
leaseName := name + ".lease"
leaseFile, err := s.root.OpenFile(leaseName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
lease, err := fsutil.LockOpenedFile(leaseFile, false)
if err != nil {
return nil, errors.Join(err, s.root.Remove(leaseName))
}
file, err := s.root.OpenFile(name+".data", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o600)
if err != nil {
return nil, errors.Join(err, lease.Close(), s.root.Remove(leaseName))
}
return &Writer{store: s, file: file, lease: lease, dataName: name + ".data", leaseName: leaseName, hash: hasher}, nil
}
func (w *Writer) Write(data []byte) (int, error) {
if w.state != writerOpen {
return 0, fmt.Errorf("cas writer is closed for writes")
}
count, err := w.file.Write(data)
if count > 0 {
if _, hashErr := w.hash.Write(data[:count]); hashErr != nil {
return count, errors.Join(err, hashErr)
}
w.size += int64(count)
}
return count, err
}
// Seal checks an optional expected digest and makes the stage readable without publishing it.
func (w *Writer) Seal(expected *Digest) (Object, error) {
if w.state != writerOpen && w.state != writerSealed {
return Object{}, os.ErrClosed
}
if w.state == writerOpen {
var digest Digest
w.hash.Sum(digest[:0])
w.object = Object{Digest: digest, Size: w.size}
if err := fsutil.Barrier(w.file); err != nil {
return Object{}, fmt.Errorf("sync cas stage: %w", err)
}
w.state = writerSealed
}
if expected != nil && w.object.Digest != *expected {
return Object{}, fmt.Errorf("%w: expected %s, got %s", ErrCorrupt, expected.String(), w.object.Digest.String())
}
return w.object, nil
}
// Rewind is available only after Seal; reading does not hash or copy the stage again.
func (w *Writer) Rewind() error {
if w.state != writerSealed && w.state != writerTransferred {
return fmt.Errorf("cas stage must be sealed before reading")
}
_, err := w.file.Seek(0, io.SeekStart)
return err
}
func (w *Writer) Read(data []byte) (int, error) {
if w.state != writerSealed && w.state != writerTransferred {
return 0, fmt.Errorf("cas stage must be sealed before reading")
}
return w.file.Read(data)
}
// Commit publishes only the sealed contents. It can repair corrupt bytes at the same address.
func (w *Writer) Commit(expected *Digest) (object Object, resultErr error) {
object, err := w.Seal(expected)
if err != nil {
return Object{}, err
}
lock, err := w.store.lock()
if err != nil {
return Object{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
name := objectPath(object.Digest)
if info, err := w.store.root.Lstat(name); err == nil {
if !info.Mode().IsRegular() {
return Object{}, fmt.Errorf("invalid existing cas object")
}
} else if !errors.Is(err, os.ErrNotExist) {
return Object{}, err
}
if err := w.store.root.MkdirAll(filepath.Dir(name), 0o700); err != nil {
return Object{}, err
}
if err := w.file.Chmod(0o444); err != nil {
return Object{}, err
}
if err := fsutil.Barrier(w.file); err != nil {
return Object{}, err
}
w.state = writerClosedStage
if err := w.file.Close(); err != nil {
w.file = nil
return Object{}, err
}
w.file = nil
if err := fsutil.RenameRoot(w.store.root, w.dataName, name); err != nil {
return Object{}, fmt.Errorf("publish cas object: %w", err)
}
return object, w.cleanup()
}
// Abort is idempotent, including after a successful Commit.
func (w *Writer) Abort() (resultErr error) {
if w.state == writerFinished {
return nil
}
lock, err := w.store.lock()
if err != nil {
return errors.Join(err, w.closeFiles())
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
return w.cleanup()
}
func (w *Writer) closeFiles() error {
w.state = writerFinished
var result error
if w.file != nil {
result = w.file.Close()
w.file = nil
}
result = errors.Join(result, w.lease.Close())
w.lease = nil
return result
}
func (w *Writer) cleanup() error {
result := w.closeFiles()
if err := w.store.removePrivateFile(w.dataName); err != nil {
return errors.Join(result, err)
}
return errors.Join(result, w.store.removePrivateFile(w.leaseName))
}
// MoveTo preserves a written prefix and its hash state when staging must change filesystems.
// The original writer becomes read-only and must still be aborted by its owner.
func (w *Writer) MoveTo(destination *Store) (replacement *Writer, resultErr error) {
if (w.state != writerOpen && w.state != writerSealed) || destination == w.store {
return nil, fmt.Errorf("cas writer cannot move to that store")
}
replacement, err := destination.newWriter(w.hash)
if err != nil {
return nil, err
}
staged := replacement
complete := false
defer func() {
if !complete {
resultErr = errors.Join(resultErr, staged.Abort())
}
}()
if _, err := w.file.Seek(0, io.SeekStart); err != nil {
return nil, err
}
count, err := io.Copy(replacement.file, w.file)
if err != nil || count != w.size {
return nil, errors.Join(fmt.Errorf("cannot preserve cas stage prefix"), err)
}
var digest Digest
w.hash.Sum(digest[:0])
w.object = Object{Digest: digest, Size: w.size}
w.state = writerTransferred
replacement.size = w.size
complete = true
return replacement, nil
}
// DetachHash transfers a partial stream's hash state for a consumer's memory-only fallback.
// The original writer can only be aborted after this call.
func (w *Writer) DetachHash() (hash.Hash, error) {
if w.state != writerOpen && w.state != writerSealed {
return nil, os.ErrClosed
}
w.state = writerTransferred
return w.hash, nil
}
package catalog
import "github.com/mclucy/lucy/version"
// Artifact records one upstream file. Descriptor module identities do not
// replace its provider coordinates.
type Artifact struct {
Provider Provider `yaml:"provider" json:"provider"`
ProjectID string `yaml:"project_id,omitempty" json:"project_id,omitempty"`
ReleaseID string `yaml:"release_id,omitempty" json:"release_id,omitempty"`
FileID string `yaml:"file_id,omitempty" json:"file_id,omitempty"`
Version version.Version `yaml:"version" json:"version"`
Embedded string `yaml:"embedded,omitempty" json:"embedded,omitempty"`
Filename string `yaml:"filename" json:"filename"`
URL string `yaml:"url,omitempty" json:"url,omitempty"`
Hashes map[string]string `yaml:"hashes" json:"hashes"`
Modules []DescriptorModule `yaml:"modules,omitempty" json:"modules,omitempty"`
}
type DescriptorModule struct {
ID string `yaml:"id" json:"id"`
Version version.Version `yaml:"version" json:"version"`
Ecosystem Ecosystem `yaml:"ecosystem" json:"ecosystem"`
VersionDialect version.Dialect `yaml:"version_dialect,omitempty" json:"version_dialect,omitempty"`
NestedPath string `yaml:"nested_path,omitempty" json:"nested_path,omitempty"`
DescriptorPath string `yaml:"descriptor_path,omitempty" json:"descriptor_path,omitempty"`
// Group is the namespace the descriptor assigns to the module identity.
// Quilt descriptors require it and use it to qualify the mod id.
Group string `yaml:"group,omitempty" json:"group,omitempty"`
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"`
// ProvidedVersions records the version each provided identity exposes when
// it differs from this module's version. Providers that omit an entry
// expose Version, matching the descriptor default.
ProvidedVersions map[string]version.Version `yaml:"provided_versions,omitempty" json:"provided_versions,omitempty"`
// ClientOnly lists module identities this artifact declares for the
// client environment only. Loaders do not enforce a dependency whose only
// candidate is excluded from the dedicated server, so the resolver ignores
// such a requirement instead of reporting it missing.
ClientOnly []string `yaml:"client_only,omitempty" json:"client_only,omitempty"`
Side Side `yaml:"side,omitempty" json:"side,omitempty"`
FoliaSupported bool `yaml:"folia_supported,omitempty" json:"folia_supported,omitzero"`
APIVersion string `yaml:"api_version,omitempty" json:"api_version,omitempty"`
Dependencies []DescriptorDependency `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`
}
// ProvidedVersion returns the version this module exposes for the provided
// identity id. A provided identity without an explicit version exposes the
// module's own version.
func (m DescriptorModule) ProvidedVersion(id string) version.Version {
if provided, ok := m.ProvidedVersions[id]; ok && provided != "" {
return provided
}
return m.Version
}
type DescriptorDependency struct {
ID string `yaml:"id" json:"id"`
Constraint string `yaml:"constraint,omitempty" json:"constraint,omitempty"`
Kind DependencyKind `yaml:"kind" json:"kind"`
Ordering string `yaml:"ordering,omitempty" json:"ordering,omitempty"`
Phase string `yaml:"phase,omitempty" json:"phase,omitempty"`
Load string `yaml:"load,omitempty" json:"load,omitempty"`
JoinClasspath bool `yaml:"join_classpath,omitempty" json:"join_classpath,omitzero"`
Provider Provider `yaml:"provider,omitempty" json:"provider,omitempty"`
ProjectID string `yaml:"project_id,omitempty" json:"project_id,omitempty"`
ModuleID string `yaml:"module_id,omitempty" json:"module_id,omitempty"`
// AnyOf lists alternative identities that satisfy this dependency in
// place of ID. ID and Constraint describe the first alternative, and the
// alternatives are satisfied by any one match. Quilt dependency arrays
// produce them when their entries name different modules.
AnyOf []DescriptorDependency `yaml:"any_of,omitempty" json:"any_of,omitempty"`
// AllOf lists further conditions that must all match for this dependency
// to apply. Quilt breaks arrays are conjunctive: a break takes effect only
// when every listed dependency matches.
AllOf []DescriptorDependency `yaml:"all_of,omitempty" json:"all_of,omitempty"`
// Unless lists conditions that exempt this dependency. Any matching
// condition suppresses the dependency entirely. Empty means the
// dependency always applies.
Unless []DescriptorDependency `yaml:"unless,omitempty" json:"unless,omitempty"`
}
package catalog
import "github.com/mclucy/lucy/version"
// DependencyOrigin identifies how a dependency is satisfied.
type DependencyOrigin string
const (
DependencyRegular DependencyOrigin = "regular"
DependencyServerProvided DependencyOrigin = "server-provided"
DependencyEmbedded DependencyOrigin = "embedded"
)
func NormalizeDependencyOrigin(origin DependencyOrigin) DependencyOrigin {
if origin == "" {
return DependencyRegular
}
return origin
}
func (d Dependency) IsServerProvided() bool {
return NormalizeDependencyOrigin(d.Origin) == DependencyServerProvided
}
func (d Dependency) IsEmbedded() bool {
return NormalizeDependencyOrigin(d.Origin) == DependencyEmbedded
}
// Dependency is a package dependency request. Constraint is a 2D array whose
// outer array is OR and inner array is AND; nil or empty means no constraint.
// ID.Version is always empty because Constraint carries the version selector.
//
// DependencyOrigin records how the dependency is satisfied. Regular
// dependencies resolve through upstream providers, server-provided
// dependencies come from the server environment, and embedded dependencies
// are physically bundled inside the parent artifact.
type Dependency struct {
ID VersionedRef
Constraint version.Expr
Mandatory bool
Origin DependencyOrigin
}
package catalog
import "strings"
// DependencyKind is the relationship declared by a descriptor or provider.
type DependencyKind string
const (
DependencyKindUnknown DependencyKind = ""
DependencyKindRequired DependencyKind = "required"
DependencyKindOptional DependencyKind = "optional"
DependencyKindRecommended DependencyKind = "recommended"
DependencyKindSuggested DependencyKind = "suggested"
DependencyKindIncompatible DependencyKind = "incompatible"
DependencyKindConflict DependencyKind = "conflict"
DependencyKindPython DependencyKind = "python"
)
func ParseDependencyKind(s string) DependencyKind {
switch strings.ToLower(strings.TrimSpace(s)) {
case "required", "mandatory":
return DependencyKindRequired
case "optional", "recommends", "recommended":
return DependencyKindOptional
case "suggested", "suggests":
return DependencyKindSuggested
case "incompatible", "breaks":
return DependencyKindIncompatible
case "conflict", "conflicts", "discouraged":
return DependencyKindConflict
case "python":
return DependencyKindPython
default:
return DependencyKindUnknown
}
}
// Package catalog describes package identities, artifacts, compatibility,
// metadata, and dependencies independently of their source.
//
// Runtime observations, persisted workspace state, provider clients, and
// presentation belong to their owning packages, not catalog.
package catalog
import (
"slices"
"github.com/mclucy/lucy/version"
)
// Ecosystem identifies the compatibility surface a server can serve. It is a
// capability descriptor, not the server product itself.
type Ecosystem string
const (
EcosystemUnspecified Ecosystem = ""
EcosystemMinecraft Ecosystem = "minecraft"
EcosystemVanilla = EcosystemMinecraft
EcosystemFabric Ecosystem = "fabric"
EcosystemQuilt Ecosystem = "quilt"
EcosystemForge Ecosystem = "forge"
EcosystemNeoForge Ecosystem = "neoforge"
EcosystemBukkit Ecosystem = "bukkit"
EcosystemPaper Ecosystem = "paper"
EcosystemBungeeCord Ecosystem = "bungeecord"
EcosystemVelocity Ecosystem = "velocity"
EcosystemSponge Ecosystem = "sponge"
EcosystemMCDR Ecosystem = "mcdr"
)
// Family groups ecosystems whose packages deploy to the same kind of runtime.
// One deployable artifact never spans two families.
type Family uint8
const (
FamilyNone Family = iota
// FamilyMod is a mod loader that runs inside the game server.
FamilyMod
// FamilyPlugin is a plugin API that a game server implements.
FamilyPlugin
// FamilyProxy is a plugin API that a network proxy implements.
FamilyProxy
)
type ecosystemDefinition struct {
title string
searchable bool
family Family
// dialect is the version grammar of the ecosystem's descriptors.
dialect version.Dialect
// alsoLoads lists the other ecosystems whose packages a runtime of this
// ecosystem loads, in the order its loader prefers their descriptors
// after its own.
alsoLoads []Ecosystem
}
// ecosystemDefinitions is the single source of ecosystem traits. Only
// listed ecosystems are valid.
var ecosystemDefinitions = map[Ecosystem]ecosystemDefinition{
EcosystemUnspecified: {title: "Any"},
EcosystemMinecraft: {title: "Minecraft"},
EcosystemFabric: {
title: "Fabric",
searchable: true,
family: FamilyMod,
dialect: version.DialectFabric,
},
EcosystemQuilt: {
title: "Quilt",
searchable: true,
family: FamilyMod,
dialect: version.DialectQuilt,
alsoLoads: []Ecosystem{EcosystemFabric},
},
EcosystemForge: {
title: "Forge",
searchable: true,
family: FamilyMod,
dialect: version.DialectMaven,
},
EcosystemNeoForge: {
title: "NeoForge",
searchable: true,
family: FamilyMod,
dialect: version.DialectMaven,
},
EcosystemBukkit: {
title: "Bukkit",
searchable: true,
family: FamilyPlugin,
dialect: version.DialectOpaque,
},
EcosystemPaper: {
title: "Paper",
searchable: true,
family: FamilyPlugin,
dialect: version.DialectOpaque,
alsoLoads: []Ecosystem{EcosystemBukkit},
},
EcosystemBungeeCord: {title: "BungeeCord", family: FamilyProxy},
EcosystemVelocity: {title: "Velocity", family: FamilyProxy},
EcosystemSponge: {title: "Sponge"},
EcosystemMCDR: {title: "MCDR", dialect: version.DialectMCDR},
}
func (e Ecosystem) Title() string {
if definition, ok := ecosystemDefinitions[e]; ok {
return definition.title
}
return "Unknown"
}
func (e Ecosystem) String() string {
if e == EcosystemUnspecified {
return "any"
}
return string(e)
}
// Valid reports whether e is a defined ecosystem.
func (e Ecosystem) Valid() bool {
_, ok := ecosystemDefinitions[e]
return ok
}
func (e Ecosystem) IsSearchable() bool {
return ecosystemDefinitions[e].searchable
}
func (e Ecosystem) Family() Family {
return ecosystemDefinitions[e].family
}
func (e Ecosystem) IsModding() bool {
return e.Family() == FamilyMod
}
// VersionDialect returns the version grammar of e's descriptors, or
// version.DialectUnknown when e has no descriptor grammar.
func (e Ecosystem) VersionDialect() version.Dialect {
return ecosystemDefinitions[e].dialect
}
// Loads lists the ecosystems whose packages a runtime of e loads, e first.
// The order is the loader's descriptor precedence: when one artifact carries
// descriptors of several listed ecosystems, the loader reads the earliest.
func (e Ecosystem) Loads() []Ecosystem {
if e == EcosystemUnspecified {
return nil
}
return append([]Ecosystem{e}, ecosystemDefinitions[e].alsoLoads...)
}
// Satisfy reports whether a runtime of e loads packages of the required
// ecosystem. An unspecified requirement accepts any ecosystem.
func (e Ecosystem) Satisfy(required Ecosystem) bool {
if required == EcosystemUnspecified {
return true
}
return slices.Contains(e.Loads(), required)
}
// ModuleNamespace returns the ecosystem that scopes module identities of
// descriptor ecosystem d in a runtime of e. A loader that loads several
// ecosystems resolves all their modules in one graph, so each of them maps to
// e. Any other ecosystem keeps its own namespace.
func (e Ecosystem) ModuleNamespace(d Ecosystem) Ecosystem {
if e != EcosystemUnspecified && slices.Contains(e.Loads(), d) {
return e
}
return d
}
// LoadedAlongside lists e and every ecosystem that some runtime loads
// together with e. Their modules can share one namespace, so a dependency
// recorded under one of them can name a package recorded under another.
func (e Ecosystem) LoadedAlongside() []Ecosystem {
peers := []Ecosystem{e}
for runtime := range ecosystemDefinitions {
loads := runtime.Loads()
if !slices.Contains(loads, e) {
continue
}
for _, peer := range loads {
if !slices.Contains(peers, peer) {
peers = append(peers, peer)
}
}
}
slices.Sort(peers[1:])
return peers
}
// IsUnspecified reports whether the ecosystem is waiting for workspace
// context.
func (e Ecosystem) IsUnspecified() bool {
return e == EcosystemUnspecified
}
package catalog
// Metadata contains informational data about a package. Archive readers and
// upstream providers both produce it. It carries content only. The source of
// the data is part of the result types, for example upstream.Info.
type Metadata struct {
Title string `json:"title"`
Brief string `json:"brief,omitempty"`
Description string `json:"description,omitempty"`
DescriptionURL string `json:"description_url,omitempty"`
DescriptionIsMarkdown bool `json:"description_is_markdown,omitempty"`
Authors []Person `json:"authors,omitempty"`
URLs []URL `json:"urls,omitempty"`
License string `json:"license,omitempty"`
}
type Person struct {
Name string `json:"name"`
Role string `json:"role,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
type URL struct {
Name string `json:"name"`
Type URLType `json:"type"`
URL string `json:"url"`
}
func (p URLType) String() string {
switch p {
case URLFile:
return "File"
case URLHome:
return "Homepage"
case URLSource:
return "Source"
case URLWiki:
return "Wiki"
case URLForum:
return "Forum"
case URLIssues:
return "Issues"
case URLSponsor:
return "Sponsor"
case URLMisc:
return "URL"
default:
return "Unknown"
}
}
type URLType uint8
const (
URLFile URLType = iota
URLHome
URLSource
URLWiki
URLForum
URLIssues
URLSponsor
URLMisc
)
package catalog
import "strings"
// Provider identifies the execution layer that fetches metadata or artifacts.
type Provider string
const (
ProviderUnspecified Provider = ""
ProviderUnknown Provider = "unknown"
ProviderModrinth Provider = "modrinth"
ProviderCurseForge Provider = "curseforge"
ProviderHangar Provider = "hangar"
ProviderSpiget Provider = "spiget"
ProviderMCDR Provider = "mcdr"
ProviderGitHub Provider = "github"
ProviderMojang Provider = "mojang"
ProviderFabric Provider = "fabric"
ProviderQuilt Provider = "quilt"
ProviderForge Provider = "forge"
ProviderNeoForge Provider = "neoforge"
ProviderPaperMC Provider = "papermc"
ProviderPurpur Provider = "purpur"
ProviderMaven Provider = "maven"
ProviderPyPI Provider = "pypi"
)
// String returns the persisted provider key. The unspecified provider is
// rendered as "any" for display only; use the value itself for storage.
func (p Provider) String() string {
if p == ProviderUnspecified {
return "any"
}
return string(p)
}
// Title returns the human-facing provider name.
func (p Provider) Title() string {
switch p {
case ProviderModrinth:
return "Modrinth"
case ProviderCurseForge:
return "CurseForge"
case ProviderHangar:
return "Hangar"
case ProviderSpiget:
return "Spiget"
case ProviderMCDR:
return "MCDR"
case ProviderGitHub:
return "GitHub"
case ProviderMojang:
return "Mojang"
case ProviderFabric:
return "Fabric"
case ProviderQuilt:
return "Quilt"
case ProviderForge:
return "Forge"
case ProviderNeoForge:
return "NeoForge"
case ProviderPaperMC:
return "PaperMC"
case ProviderPurpur:
return "Purpur"
case ProviderMaven:
return "Maven"
case ProviderPyPI:
return "PyPI"
case ProviderUnspecified:
return "Any"
default:
return "Unknown"
}
}
// Registry returns the registry backed by p. Providers such as GitHub, Maven,
// and PyPI are execution layers without a registry.
func (p Provider) Registry() (Registry, bool) {
switch p {
case ProviderModrinth:
return RegistryModrinth, true
case ProviderCurseForge:
return RegistryCurseForge, true
case ProviderHangar:
return RegistryHangar, true
case ProviderSpiget:
return RegistrySpiget, true
case ProviderMCDR:
return RegistryMCDR, true
default:
return RegistryUnspecified, false
}
}
// ParseProvider maps a provider key to its typed value. The empty key means
// the unspecified provider, which lets routing choose.
func ParseProvider(s string) (Provider, bool) {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" {
return ProviderUnspecified, true
}
switch Provider(s) {
case ProviderUnknown,
ProviderModrinth,
ProviderCurseForge,
ProviderHangar,
ProviderSpiget,
ProviderMCDR,
ProviderGitHub,
ProviderMojang,
ProviderFabric,
ProviderQuilt,
ProviderForge,
ProviderNeoForge,
ProviderPaperMC,
ProviderPurpur,
ProviderMaven,
ProviderPyPI:
return Provider(s), true
default:
return ProviderUnknown, false
}
}
package catalog
import (
"strings"
"github.com/mclucy/lucy/version"
)
// Name is a package name. User input may be untrusted; normalize it
// before using it as an identity.
type Name string
func (n Name) String() string {
return string(n)
}
// PythonName formats the name as a Python distribution name.
func (n Name) PythonName() string {
return strings.ReplaceAll(string(n), "-", "_")
}
// Ref identifies one package supplied by a provider.
type Ref struct {
Name Name `json:"name" yaml:"name"`
Provider Provider `json:"provider,omitempty" yaml:"provider,omitempty"`
}
func (p Ref) String() string {
return p.StringBase()
}
func (p Ref) StringBase() string {
if p.Provider == ProviderUnspecified {
return p.Name.String()
}
return p.Provider.String() + ":" + p.Name.String()
}
// VersionedRef identifies a package selection for one ecosystem.
// Version may be a selector during resolution or an exact version after
// resolution.
type VersionedRef struct {
Ref `yaml:",inline"`
Ecosystem Ecosystem `json:"ecosystem" yaml:"ecosystem"`
Version version.Version `json:"version" yaml:"version"`
}
func (p VersionedRef) String() string {
suffix := ""
if p.Version != version.Any {
suffix = "@" + p.Version.String()
}
return p.Ref.String() + suffix
}
// StringBase is the stable provider-qualified package identity used by graph
// and provenance keys.
func (p VersionedRef) StringBase() string {
return p.Ref.StringBase()
}
// StringQualified is the human-facing label that also carries the ecosystem.
func (p VersionedRef) StringQualified() string {
return p.Ecosystem.String() + "/" + p.StringBase() + "@" + p.Version.String()
}
package catalog
import "strings"
// Registry identifies a package repository with search and package metadata.
// A registry is executed by a Provider.
type Registry string
const (
RegistryUnspecified Registry = ""
RegistryUnknown Registry = "unknown"
RegistryModrinth Registry = "modrinth"
RegistryCurseForge Registry = "curseforge"
RegistryHangar Registry = "hangar"
RegistrySpiget Registry = "spiget"
RegistryMCDR Registry = "mcdr"
)
func (r Registry) String() string {
if r == RegistryUnspecified {
return "any"
}
return string(r)
}
func (r Registry) Title() string {
switch r {
case RegistryModrinth:
return "Modrinth"
case RegistryCurseForge:
return "CurseForge"
case RegistryHangar:
return "Hangar"
case RegistrySpiget:
return "Spiget"
case RegistryMCDR:
return "MCDR"
case RegistryUnspecified:
return "Any"
default:
return "Unknown"
}
}
// Provider returns the execution layer that handles r.
func (r Registry) Provider() Provider {
switch r {
case RegistryModrinth:
return ProviderModrinth
case RegistryCurseForge:
return ProviderCurseForge
case RegistryHangar:
return ProviderHangar
case RegistrySpiget:
return ProviderSpiget
case RegistryMCDR:
return ProviderMCDR
default:
return ProviderUnknown
}
}
// ParseRegistry maps a registry key to its typed value. The empty key means
// all registries.
func ParseRegistry(s string) (Registry, bool) {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" {
return RegistryUnspecified, true
}
switch Registry(s) {
case RegistryUnknown,
RegistryModrinth,
RegistryCurseForge,
RegistryHangar,
RegistrySpiget,
RegistryMCDR:
return Registry(s), true
default:
return RegistryUnknown, false
}
}
package catalog
import "strings"
// Side identifies where a descriptor module is intended to run.
type Side string
const (
SideUnknown Side = ""
SideClient Side = "client"
SideServer Side = "server"
SideBoth Side = "both"
)
func ParseSide(s string) Side {
switch strings.ToLower(strings.TrimSpace(s)) {
case "client":
return SideClient
case "server":
return SideServer
case "*", "both", "any":
return SideBoth
default:
return SideUnknown
}
}
// Command cipher generates build-time embedded secret material.
//
// It never prints the plaintext secret. Output is four KEY=value lines for
// shell capture into linker-injected fragments.
//
// The secret is read from stdin only (never from argv), so it does not appear
// in process argument lists.
package main
import (
"encoding/hex"
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/mclucy/lucy/internal/cipher"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s -encrypt-stdin [options] < secret\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\nReads the plaintext secret from stdin, generates a fresh key, encrypts,\n")
fmt.Fprintf(os.Stderr, "and prints four fragment lines:\n")
fmt.Fprintf(os.Stderr, " cipher_key_a, cipher_key_b, cipher_ciphertext_a, cipher_ciphertext_b\n")
fmt.Fprintf(os.Stderr, "\nOptions:\n")
flag.PrintDefaults()
}
encryptStdin := flag.Bool("encrypt-stdin", false, "read plaintext secret from stdin (required)")
version := flag.String("version", "", "release version for AD binding (empty = unbound local)")
commit := flag.String("commit", "", "release commit for AD binding (empty = unbound local)")
flag.Parse()
if !*encryptStdin {
flag.Usage()
os.Exit(2)
}
secret, err := readSecret(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "cipher: read secret: %v\n", err)
os.Exit(1)
}
if secret == "" {
fmt.Fprintf(os.Stderr, "cipher: empty secret on stdin\n")
os.Exit(2)
}
key, err := cipher.GenerateKey()
if err != nil {
fmt.Fprintf(os.Stderr, "cipher: generate key: %v\n", err)
os.Exit(1)
}
ctHex, err := cipher.Encrypt(key, secret, *version, *commit)
if err != nil {
fmt.Fprintf(os.Stderr, "cipher: encrypt: %v\n", err)
os.Exit(1)
}
keyHex := hex.EncodeToString(key)
keyA, keyB, err := splitExactHalves(keyHex)
if err != nil {
fmt.Fprintf(os.Stderr, "cipher: split key: %v\n", err)
os.Exit(1)
}
ctA, ctB, err := splitExactHalves(ctHex)
if err != nil {
fmt.Fprintf(os.Stderr, "cipher: split ciphertext: %v\n", err)
os.Exit(1)
}
fmt.Printf("cipher_key_a=%s\n", keyA)
fmt.Printf("cipher_key_b=%s\n", keyB)
fmt.Printf("cipher_ciphertext_a=%s\n", ctA)
fmt.Printf("cipher_ciphertext_b=%s\n", ctB)
}
func readSecret(r io.Reader) (string, error) {
raw, err := io.ReadAll(r)
if err != nil {
return "", err
}
// Preserve internal content; only strip one trailing \n or \r\n so secrets
// are not altered beyond ordinary line-oriented stdin delivery.
s := string(raw)
s = strings.TrimSuffix(s, "\n")
s = strings.TrimSuffix(s, "\r")
if strings.TrimSpace(s) == "" {
return "", nil
}
return s, nil
}
func splitExactHalves(s string) (string, string, error) {
if len(s) == 0 {
return "", "", fmt.Errorf("empty string")
}
if len(s)%2 != 0 {
return "", "", fmt.Errorf("odd length %d", len(s))
}
mid := len(s) / 2
return s[:mid], s[mid:], nil
}
package cmd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"path/filepath"
"runtime/debug"
"strings"
"time"
"charm.land/fang/v2"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/config"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/agent"
"github.com/mclucy/lucy/internal/cipher"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/compile"
docscli "github.com/mclucy/lucy/internal/cli/docs"
"github.com/mclucy/lucy/internal/cli/file"
"github.com/mclucy/lucy/internal/cli/info"
"github.com/mclucy/lucy/internal/cli/search"
telemetrycli "github.com/mclucy/lucy/internal/cli/telemetry"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/javainstall"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/operation"
"github.com/mclucy/lucy/serverregistry"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
"github.com/mclucy/lucy/upstream/routing"
"github.com/spf13/cobra"
)
var (
version string
commit string
official string
telemetryRelease string
)
const agentInstructions = "Instructions for agents:\n" +
"The --help flag is human-oriented. Use `lucy docs list` to view all available documentation,\n" +
"`lucy docs grep` to search, and `lucy docs read` to read one or more articles. `--json-compact` and\n" +
"`--no-interactive` will be on by default for you. You can use tools like `jq` to process\n" +
"command outputs. Use `lucy schema` to list JSON result contracts, `lucy schema COMMAND` to\n" +
"read a result schema, and `lucy schema --error` to read the shared failure schema.\n" +
"If telemetry is off, a rejected agent report is not an error to repair. Never turn telemetry on\n" +
"without an explicit instruction from the user."
// RunnerOptions supplies the invocation directory, streams, and network transport.
// Directory must be absolute. A nil HTTPClient creates a client owned by the run.
type RunnerOptions struct {
Directory string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
HTTPClient *http.Client
}
// Runner owns one invocation: its command tree, JSON contracts, streams, and
// output state. Construct a runner per run; nothing is shared between runs.
type Runner struct {
root *cobra.Command
contracts *cli.JSONContracts
args []string
stdin io.Reader
stdout io.Writer
stderr io.Writer
executing *cobra.Command
loggingReady bool
selectedJSON cli.JSONRendering
machineResult bytes.Buffer
resultWriter io.Writer
flagParsingFailed bool
agentHelpInjected bool
invocation *cli.Invocation
dependencies *cli.Dependencies
httpClient *http.Client
ownsHTTPClient bool
directory string
telemetryState telemetrycli.State
runContext context.Context
setupStarted time.Time
commandStarted time.Time
}
// NewRunner prepares an isolated invocation with a fresh command tree, fresh
// JSON contracts, and the given streams.
func NewRunner(args []string, options RunnerOptions) *Runner {
r := &Runner{
contracts: cli.NewJSONContracts(),
args: args,
stdin: options.Stdin,
stdout: options.Stdout,
stderr: options.Stderr,
invocation: cli.NewInvocation(options.Directory, nil),
dependencies: &cli.Dependencies{},
httpClient: options.HTTPClient,
directory: options.Directory,
}
if r.httpClient == nil {
transport, ok := http.DefaultTransport.(*http.Transport)
if !ok {
transport = &http.Transport{Proxy: http.ProxyFromEnvironment}
}
r.httpClient = &http.Client{Transport: transport.Clone()}
r.ownsHTTPClient = true
}
r.root = NewRootCommand(r.contracts, r.invocation, r.dependencies)
r.registerTelemetryCommands()
r.root.SetArgs(r.args)
r.root.SetIn(r.stdin)
r.root.SetOut(r.stdout)
r.root.SetErr(r.stderr)
r.root.PersistentPreRunE = r.persistentPreRunE
return r
}
// NewRootCommand builds a fresh root with its persistent flags and
// subcommands bound to contracts.
func NewRootCommand(contracts *cli.JSONContracts, invocation *cli.Invocation, dependencies *cli.Dependencies) *cobra.Command {
root := &cobra.Command{
Use: "lucy",
Short: "The Minecraft server package manager",
}
cli.RegisterServerSelection(root)
root.PersistentFlags().String(
cli.FlagLogLevel,
"info",
"Level mirrored by --print-logs; the log file always records debug",
)
root.PersistentFlags().String(
cli.FlagLogFile,
log.DefaultFile(),
"Write diagnostic logs to this file",
)
root.PersistentFlags().Bool(
cli.FlagPrintLogs,
false,
"Mirror diagnostic logs to stderr; machine output keeps stderr clean",
)
root.PersistentFlags().Bool(
cli.FlagJSON,
false,
"Print JSON indented with 2 spaces",
)
root.PersistentFlags().Bool(
cli.FlagJSONCompact,
false,
"Print JSON without indentation; wins over --json",
)
root.PersistentFlags().Bool(
cli.FlagNoColor,
false,
"Disable colored output",
)
root.PersistentFlags().Bool(
cli.FlagNoInteractive,
false,
"Disable prompts and animated output; fail instead of asking",
)
root.PersistentFlags().Bool(
cli.FlagNoStyle,
false,
"Same as --no-color --no-interactive",
)
cli.AddPagerFlag(root, invocation)
displayVersion, displayCommit := buildVersion()
docs := docscli.NewCommand(invocation)
contracts.Ignore(docs)
root.AddCommand(
cli.NewAddCommand(contracts, invocation, dependencies),
cli.NewBisectCommand(contracts, invocation, dependencies),
cli.NewCacheCommand(contracts, invocation, dependencies),
cli.NewConfigCommand(contracts, invocation, dependencies),
cli.NewCreateCommand(contracts, invocation, dependencies),
cli.NewDeinitCommand(contracts, invocation, dependencies),
docs,
file.NewCommand(contracts, invocation, dependencies),
cli.NewImportCommand(contracts, invocation, dependencies),
cli.NewInitCommand(contracts, invocation, dependencies),
cli.NewInstallCommand(contracts, invocation, dependencies),
cli.NewJavaCommand(contracts, invocation, dependencies),
cli.NewLeavesCommand(contracts, invocation, dependencies),
cli.NewRemoveCommand(contracts, invocation, dependencies),
cli.NewServerCommand(contracts, invocation, dependencies),
cli.NewStoreCommand(contracts, invocation, dependencies),
cli.NewTreeCommand(contracts, invocation, dependencies),
cli.NewUpgradeCommand(contracts, invocation, dependencies),
compile.NewCommand(invocation),
info.NewCommand(contracts, invocation, dependencies),
cli.NewStatusCommand(contracts, invocation, dependencies),
search.NewCommand(contracts, invocation, dependencies),
cli.NewSchemaCommand(contracts, invocation),
cli.NewSelfUpdateCommand(
contracts,
invocation,
dependencies,
cli.BuildInfo{
Version: displayVersion,
Commit: displayCommit,
Official: isOfficialBuild(),
},
),
)
return root
}
func (r *Runner) persistentPreRunE(cmd *cobra.Command, args []string) error {
r.executing = cmd
mode := r.effectiveRendering(cmd)
r.selectedJSON = mode
r.configurePresentation(cmd)
if !filepath.IsAbs(r.directory) {
return fmt.Errorf("invocation directory must be absolute")
}
if telemetrycli.IsCommand(cmd) {
return nil
}
if err := r.configureLogging(cmd); err != nil {
return err
}
r.loggingReady = true
r.beginTelemetryObservation(cmd)
if err := r.configureServices(cmd); err != nil {
return err
}
r.completeSetupObservation()
if n := cmd.Name(); n != "__complete" && n != "__completeNoDesc" {
r.invocation.Logger.Info("action invoked", "action", cmd.CommandPath(), "directory", r.invocation.Directory)
if mode == cli.JSONNone && !r.contracts.Ignores(cmd) && r.invocation.TelemetryEnabled {
r.announceTelemetry(cmd)
}
}
r.startCommandObservation()
return nil
}
// announceTelemetry presents the one-time telemetry notice. The claim is
// recorded before the notice renders, so a machine presents it once even when
// several invocations start together, and a claim that cannot render stays
// claimed.
func (r *Runner) announceTelemetry(cmd *cobra.Command) {
if r.telemetryState.Client == nil || r.telemetryState.Err != nil {
return
}
claimed, err := r.telemetryState.Client.ClaimNotice()
if err != nil {
r.invocation.Logger.Debug("telemetry notice was not shown", "error", err)
return
}
if !claimed {
return
}
identity := "lucy"
if displayVersion, _ := buildVersion(); displayVersion != "" {
identity += " " + displayVersion
}
report.New(cmd.ErrOrStderr(), r.invocation.Theme).Info(
identity + " comes with opt-out telemetry. You can manage it with `lucy telemetry`. " +
"If you are using an agent with telemetry on, they will be instructed to write " +
"reports autonomously upon failure or difficulties. Your data will be used for " +
"improving lucy only. See <lucy.lc/docs/commands/telemetry> for more info.",
)
}
func (r *Runner) configurePresentation(cmd *cobra.Command) {
noStyle, _ := cmd.Flags().GetBool(cli.FlagNoStyle)
noColor, _ := cmd.Flags().GetBool(cli.FlagNoColor)
noInteractive, _ := cmd.Flags().GetBool(cli.FlagNoInteractive)
r.invocation.Theme = style.New(!noStyle && !noColor)
r.invocation.ASCII = noStyle
r.invocation.Interactive = r.effectiveRendering(cmd) == cli.JSONNone && !noStyle && !noInteractive
if r.effectiveRendering(cmd) == cli.JSONNone {
var input io.Reader
if r.invocation.Interactive {
input = r.stdin
}
r.invocation.Stdout, r.invocation.Stderr = style.DetectTerminals(input, r.stdout, r.stderr)
}
}
func (r *Runner) configureServices(cmd *cobra.Command) error {
registry, registryErr := serverregistry.New()
r.dependencies.Registry = registry
r.dependencies.RegistryError = registryErr
if cmd.Name() != "__complete" && cmd.Name() != "__completeNoDesc" &&
cmd.Root().PersistentFlags().Changed(cli.FlagServer) && registryErr != nil {
return registryErr
}
if err := cli.ResolveServer(cmd, registry, r.invocation); err != nil {
return err
}
settings, err := config.New(r.invocation.Directory, r.invocation.Logger)
if err != nil {
return err
}
proxy, proxyErr := settings.GitHubProxy()
key, keyErr := settings.CurseForgeAPIKey()
link, linkErr := configuredLinkMode(settings)
if err := errors.Join(proxyErr, keyErr, linkErr); err != nil {
if !toleratesUnreadableSettings(cmd) {
return fmt.Errorf("%w\nrun `lucy config` to inspect or repair machine settings", err)
}
r.invocation.Logger.Warn(err)
}
key = strings.TrimSpace(key)
configuredKey := key != ""
if key == "" {
embedded, err := cipher.Decode()
if err != nil {
r.invocation.Logger.Debug("embedded CurseForge key unavailable", "error", err)
} else {
key = strings.TrimSpace(embedded)
}
}
r.invocation.Logger.Debug(
"machine settings applied",
"github_proxy_configured", proxy != "",
"curseforge_key_configured", configuredKey,
)
network := cache.New(cache.DefaultRoot(), cache.DefaultCacheConfig(), r.httpClient, r.invocation.Logger)
router := routing.New(network, r.invocation.Logger, key)
files := filetrack.NewService(r.httpClient, r.invocation.Logger)
installer := install.NewService(
router,
network,
files,
install.NewPythonHost(r.invocation.Directory, r.invocation.Logger),
registry,
r.invocation.Logger,
proxy,
link,
)
r.dependencies.Network = network
r.dependencies.Router = router
r.dependencies.Files = files
r.dependencies.Operations = operation.NewService(installer, router, registry, r.invocation.Logger)
r.dependencies.JavaHost = javainstall.NewHost(network, r.invocation.Logger)
return nil
}
// configuredLinkMode reads store.link and names the key in a value the
// installer cannot use, so the command fails before it stages anything.
// Machine settings that cannot be read leave the default in place.
func configuredLinkMode(settings *config.Service) (fsutil.LinkMode, error) {
value, err := settings.Setting("store.link")
if err != nil {
return fsutil.LinkClone, err
}
link, err := fsutil.ParseLinkMode(strings.TrimSpace(value))
if err != nil {
return fsutil.LinkClone, fmt.Errorf("config store.link: %w", err)
}
return link, nil
}
// toleratesUnreadableSettings reports whether cmd stays runnable while machine
// settings are unreadable. These surfaces either repair the configuration or
// repair the binary.
func toleratesUnreadableSettings(cmd *cobra.Command) bool {
for current := cmd; current != nil; current = current.Parent() {
switch current.Name() {
case "config", "docs", "schema", "self-update",
"__complete", "__completeNoDesc":
return true
}
}
return false
}
func (r *Runner) configureLogging(cmd *cobra.Command) error {
flags := cmd.Root().PersistentFlags()
path, err := flags.GetString(cli.FlagLogFile)
if err != nil {
return err
}
level, err := flags.GetString(cli.FlagLogLevel)
if err != nil {
return err
}
printLogs, err := flags.GetBool(cli.FlagPrintLogs)
if err != nil {
return err
}
var mirror io.Writer
if printLogs && r.effectiveRendering(cmd) == cli.JSONNone {
mirror = r.stderr
}
if path != "" && !filepath.IsAbs(path) {
path = filepath.Join(r.directory, path)
}
if err := r.invocation.Logger.Close(); err != nil {
return err
}
r.invocation.Logger, err = log.New(path, level, mirror)
if err == nil && r.telemetryState.Client != nil && invocationTelemetryPolicy(cmd, nil).collect {
if enabled, stateErr := r.telemetryState.Client.Enabled(cmd.Context()); stateErr == nil && enabled {
r.invocation.TelemetryEnabled = true
r.invocation.Logger.CaptureStages()
}
}
return err
}
// applyAgentDefaults makes the non-interactive and compact-JSON behaviors
// implicit for detected agents. Explicit flags still win because parsing runs
// after these defaults are installed.
func (r *Runner) applyAgentDefaults() {
r.setPersistentBoolDefault(cli.FlagNoInteractive, false)
r.setPersistentBoolDefault(cli.FlagJSONCompact, false)
if !agent.Detected() {
return
}
r.setPersistentBoolDefault(cli.FlagNoInteractive, true)
if !r.contracts.Supports(r.invocationCommand()) {
return
}
if cli.JSONFlagsPresent(r.args) {
return
}
r.setPersistentBoolDefault(cli.FlagJSONCompact, true)
}
func (r *Runner) setPersistentBoolDefault(name string, value bool) {
flag := r.root.PersistentFlags().Lookup(name)
if flag == nil {
return
}
text := "false"
if value {
text = "true"
}
_ = flag.Value.Set(text)
flag.DefValue = text
}
// injectAgentInstructions adds the agent notice to every help text. Help is
// rendered from Long, so this works for both fang and Cobra help paths.
func (r *Runner) injectAgentInstructions() {
if r.agentHelpInjected || !agent.Detected() {
return
}
r.agentHelpInjected = true
block := "\n\n" + agentInstructions
if r.telemetryState.Client != nil {
if enabled, err := r.telemetryState.Client.Enabled(context.Background()); err == nil && enabled {
block += "\nWhen a Lucy command fails, panics, or returns a confusing result, report it once without asking:\n" +
"`lucy agent-report \"<text>\" --agent <your harness> --model <your model>`. Write one to three\n" +
"sentences: the command, the error code or observed behavior, and what you expected. Leave out\n" +
"secrets, absolute paths, logs, transcripts, and user data. Skip failures caused by your own wrong\n" +
"directory, wrong flag, or missing prerequisite; report unexpected behavior even when a workaround\n" +
"works. A rejected report needs no retry."
}
}
var walk func(*cobra.Command)
walk = func(cmd *cobra.Command) {
switch {
case cmd.Long != "":
cmd.Long += block
case cmd.Short != "":
cmd.Long = cmd.Short + block
}
for _, child := range cmd.Commands() {
walk(child)
}
}
walk(r.root)
}
// effectiveRendering reports the rendering requested by the actual
// invocation. Parsed flags win; otherwise the raw command line is inspected,
// so a failure that happens before Cobra parses flags still honors --json and
// --json-compact.
func (r *Runner) effectiveRendering(cmd *cobra.Command) cli.JSONRendering {
if r.contracts.Ignores(cmd) {
return cli.JSONNone
}
mode := cli.JSONModeFromArgs(cmd, r.args)
if cmd.Flags().Parsed() && !r.flagParsingFailed {
mode = cli.JSONMode(cmd)
} else if mode == cli.JSONNone && !cli.JSONFlagsPresent(r.args) {
if compact, _ := cmd.Root().PersistentFlags().GetBool(cli.FlagJSONCompact); compact {
mode = cli.JSONCompact
}
}
if mode == cli.JSONNone && r.contracts.IsNative(cmd) {
return cli.JSONPretty
}
return mode
}
// invocationCommand finds the command the raw command line addresses, even
// when Cobra stopped before recording the executing command.
func (r *Runner) invocationCommand() *cobra.Command {
if r.executing != nil {
return r.executing
}
command, _, _ := r.root.Find(r.args)
if command != nil {
return command
}
return r.root
}
// renderError keeps human failures readable: structured details render their
// own multi-line explanation, ordinary errors render on one line, and usage
// mistakes keep the framework's format with its --help hint. Machine mode
// defers rendering to the CLI boundary so the log file can close first and a
// close failure joins the same document.
func (r *Runner) renderError(w io.Writer, styles fang.Styles, err error) {
if err == nil {
return
}
var exitErr *cli.ExitError
if errors.As(err, &exitErr) && exitErr.Silent {
return
}
command := r.invocationCommand()
if mode := r.effectiveRendering(command); mode != cli.JSONNone {
r.selectedJSON = mode
return
}
var detail *report.Detail
if errors.As(err, &detail) && detail != nil {
report.RenderDetail(w, detail, r.invocation.Theme)
r.writeLogPath(w)
return
}
if cli.IsFrameworkUsageError(err) {
fang.DefaultErrorHandler(w, styles, err)
// The framework names the rejected flag but never what this command
// accepts, which is the fact the caller needs to retry.
if hint := cli.UsageHint(command, err); hint != "" {
fmt.Fprintf(w, " %s %s\n", r.invocation.Theme.Note("hint:"), hint)
}
return
}
report.New(w, r.invocation.Theme).Error(err)
r.writeLogPath(w)
}
func (r *Runner) writeLogPath(w io.Writer) {
if path := r.invocation.Logger.FilePath(); path != "" {
fmt.Fprintf(w, " %s %s\n", r.invocation.Theme.Muted("log:"), path)
}
}
// Close releases the invocation's diagnostics and owned HTTP connections.
func (r *Runner) Close() error {
var cacheErr error
if r.dependencies.Network != nil {
cacheErr = r.dependencies.Network.Close()
}
if r.ownsHTTPClient {
r.httpClient.CloseIdleConnections()
}
return errors.Join(cacheErr, r.invocation.Logger.Close())
}
// WriteError renders a failure through the same mode-aware funnel outside
// command execution. main uses it for a log file that fails to close.
func (r *Runner) WriteError(err error) {
if err == nil {
return
}
command := r.invocationCommand()
if mode := r.effectiveRendering(command); mode != cli.JSONNone {
r.selectedJSON = mode
}
output := cli.NewOperationOutput(command, r.invocation)
output.SetJSONRendering(r.selectedJSON)
output.WriteError(err, r.invocation.Logger.FilePath())
}
// JSONSelected reports whether the actual invocation selected machine output.
func (r *Runner) JSONSelected() bool {
return r.selectedJSON != cli.JSONNone
}
// FlushOutput publishes a machine result only after command cleanup succeeds.
func (r *Runner) FlushOutput() error {
if !r.JSONSelected() || r.resultWriter == nil {
return nil
}
if _, err := r.machineResult.WriteTo(r.resultWriter); err != nil {
return fmt.Errorf("write output: %w", err)
}
return nil
}
// panicError reports an unexpected panic through the ordinary failure
// funnel. The message stays stable for machine output; the stack goes to the
// diagnostic log.
type panicError struct {
value any
stack []byte
}
func (e *panicError) Error() string {
return fmt.Sprintf("internal error: %v", e.value)
}
// Execute runs the invocation. Per-run state is reset first, so a runner
// always starts from a clean parse result and output buffer.
func (r *Runner) Execute(ctx context.Context) (err error) {
r.runContext = ctx
r.setupStarted = time.Time{}
r.commandStarted = time.Time{}
started := r.startTelemetry()
defer func() { r.finishTelemetry(started, err) }()
defer func() {
recovered := recover()
if recovered == nil {
return
}
stack := debug.Stack()
err = &panicError{value: recovered, stack: stack}
path := r.root.CommandPath()
if r.executing != nil {
path = r.executing.CommandPath()
}
r.invocation.Logger.Error(fmt.Errorf("%s panicked: %v\n%s", path, recovered, stack))
}()
displayVersion, displayCommit := buildVersion()
r.executing = nil
r.loggingReady = false
r.flagParsingFailed = false
r.applyAgentDefaults()
r.injectAgentInstructions()
command := r.invocationCommand()
r.selectedJSON = r.effectiveRendering(command)
r.root.SetFlagErrorFunc(func(_ *cobra.Command, err error) error {
r.flagParsingFailed = true
return err
})
r.machineResult.Reset()
r.resultWriter = nil
if r.JSONSelected() {
r.resultWriter = r.root.OutOrStdout()
r.root.SetOut(&r.machineResult)
defer r.root.SetOut(r.resultWriter)
}
if r.JSONSelected() {
// Fang probes terminal colors before invoking its error handler.
// Machine mode must not emit those queries on the real stdout.
r.root.SilenceErrors = true
r.root.SilenceUsage = true
r.root.Version = displayVersion
_, err = r.root.ExecuteContextC(ctx)
} else {
err = fang.Execute(
ctx,
r.root,
fang.WithVersion(displayVersion),
fang.WithCommit(displayCommit),
fang.WithErrorHandler(r.renderError),
)
}
if err != nil {
command := r.executing
if command == nil {
var findErr error
command, _, findErr = r.root.Find(r.args)
if command == nil {
command = r.root
}
if findErr != nil {
// Unknown commands fail before Cobra parses the persistent
// flags. Keep the flag failure for the log without rendering a
// second human error.
if flagErr := r.root.ParseFlags(r.args); flagErr != nil {
err = errors.Join(err, flagErr)
}
}
if configureErr := r.configureLogging(command); configureErr != nil {
if !r.JSONSelected() {
report.New(r.stderr, r.invocation.Theme).Error(configureErr)
}
return errors.Join(err, configureErr)
}
r.loggingReady = true
}
if r.loggingReady {
var exitErr *cli.ExitError
if !errors.As(err, &exitErr) || !exitErr.Silent {
r.invocation.Logger.Error(fmt.Errorf("%s failed: %w", command.CommandPath(), err))
}
}
return err
}
if r.loggingReady && r.executing != nil {
if n := r.executing.Name(); n != "__complete" && n != "__completeNoDesc" {
r.invocation.Logger.Info("action completed", "action", r.executing.CommandPath())
}
}
return nil
}
package cmd
import (
"context"
"errors"
"fmt"
"os"
"runtime"
"strings"
"time"
"github.com/mclucy/lucy/internal/cli"
telemetrycli "github.com/mclucy/lucy/internal/cli/telemetry"
"github.com/mclucy/lucy/internal/telemetry"
"github.com/mclucy/lucy/terminal/report"
"github.com/spf13/cobra"
)
// registerTelemetryCommands attaches the telemetry control and agent report
// commands. Telemetry initialization stays with the runner: the commands read
// the state this method publishes through a live handle.
func (r *Runner) registerTelemetryCommands() {
r.root.AddCommand(
telemetrycli.NewCommand(r.contracts, r.invocation, &r.telemetryState),
telemetrycli.NewAgentReportCommand(r.contracts, r.invocation, &r.telemetryState),
)
}
func (r *Runner) startTelemetry() time.Time {
started := time.Now()
r.invocation.TelemetryEnabled = false
r.invocation.TelemetryObservation = nil
r.invocation.TelemetryContexts = nil
version, commit := buildVersion()
local := !isTelemetryRelease()
client, err := telemetry.New(telemetry.Config{
Disabled: local,
Endpoint: os.Getenv("LUCY_TELEMETRY_ENDPOINT"),
Channel: telemetryChannel(version),
LucyVersion: version,
LucyCommit: commit,
OS: runtime.GOOS,
Arch: runtime.GOARCH,
HTTPClient: r.httpClient,
})
r.telemetryState = telemetrycli.State{Client: client, Err: err, Local: local}
return started
}
// telemetryChannel derives the release channel from the build version. Only
// alpha and beta channels collect by default, so a stable release must not
// inherit the alpha default.
func telemetryChannel(version string) string {
lower := strings.ToLower(version)
switch {
case strings.Contains(lower, "beta"):
return "beta"
case strings.Contains(lower, "alpha"):
return "alpha"
default:
return "stable"
}
}
func (r *Runner) finishTelemetry(started time.Time, commandErr error) {
client := r.telemetryState.Client
if client == nil {
return
}
defer client.Close()
command := r.invocationCommand()
policy := invocationTelemetryPolicy(command, commandErr)
if !policy.collect {
return
}
ended := time.Now()
if ended.Before(started) {
ended = started
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
r.recordInvocation(ctx, command, started, ended, commandErr)
if !policy.flush {
r.invocation.Logger.Debug("telemetry flush skipped", "reason", "offline")
return
}
flush, flushErr := client.Flush(ctx)
r.logTelemetryFlush(flush, flushErr)
if flushErr == nil && flush.Attempted > 0 && !r.JSONSelected() && r.stderr != nil {
fmt.Fprintln(r.stderr, "Telemetry upload attempted; run `lucy telemetry stats` for local totals.")
}
}
type telemetryInvocationPolicy struct {
collect bool
flush bool
}
// invocationTelemetryPolicy governs automatic telemetry, not explicit
// telemetry commands. Failed guidance invocations remain observable, but a
// successful schema inspection is guidance and does not queue or flush.
func invocationTelemetryPolicy(command *cobra.Command, commandErr error) telemetryInvocationPolicy {
if cli.TelemetryExempt(command) {
return telemetryInvocationPolicy{}
}
for current := command; current.Parent() != nil; current = current.Parent() {
if current.Parent() == current.Root() {
switch current.Name() {
case "completion", "__complete", "__completeNoDesc", "help", "man":
return telemetryInvocationPolicy{}
case "schema":
if commandErr == nil {
return telemetryInvocationPolicy{}
}
}
}
}
if commandErr == nil {
if cli.IsHelpOnly(command) || !command.Runnable() {
return telemetryInvocationPolicy{}
}
for current := command; current != nil; current = current.Parent() {
for _, name := range []string{"help", "version"} {
if flag := current.Flags().Lookup(name); flag != nil && flag.Value.String() == "true" {
return telemetryInvocationPolicy{}
}
}
}
}
policy := telemetryInvocationPolicy{collect: true, flush: true}
if telemetryBoolFlag(command, "offline") {
policy.flush = false
}
return policy
}
// recordInvocation records the terminal event and, for failures, a diagnostic
// report. An unidentified build skips this call so harness traffic cannot pass
// as user activity, but it still flushes records queued by identified builds.
func (r *Runner) recordInvocation(ctx context.Context, command *cobra.Command, started, ended time.Time, commandErr error) {
client := r.telemetryState.Client
usageError := r.telemetryUsageError(commandErr)
outcome := telemetry.Outcome("success")
code := ""
reportKind := telemetry.ReportKind("")
if commandErr != nil {
outcome = telemetry.Outcome("failure")
code = cli.CodeCommandFailed
_, panicked := errors.AsType[*panicError](commandErr)
exit, hasExit := errors.AsType[*cli.ExitError](commandErr)
canceled := errors.Is(commandErr, context.Canceled) ||
errors.Is(commandErr, context.DeadlineExceeded)
switch {
case canceled:
outcome, code = telemetry.Outcome("canceled"), cli.CodeOperationCancelled
case usageError:
code = cli.CodeInvalidInvocation
case panicked:
reportKind = telemetry.ReportKind("panic")
case hasExit && exit != nil:
if !exit.Silent {
reportKind = telemetry.ReportKind("failure")
}
default:
reportKind = telemetry.ReportKind("failure")
}
if detail, ok := errors.AsType[*report.Detail](commandErr); ok && detail != nil && detail.Code != "" {
code = detail.Code
} else if code == cli.CodeCommandFailed {
if mapped := telemetryFailureCode(commandErr); mapped != "" {
code = mapped
}
}
}
r.completeCommandObservation(ended, commandErr)
localLog := r.telemetryLocalLog()
failureKind := r.telemetryFailureKind(commandErr, usageError)
cancelReason := r.telemetryCancelReason(commandErr)
id := telemetry.NewUUID()
if localLog {
r.invocation.Logger.Debug("telemetry invocation", "invocation_id", id)
}
event := telemetry.Event{
InvocationID: id,
Operation: strings.TrimPrefix(command.CommandPath(), "lucy "),
Duration: ended.Sub(started),
DurationMeasured: true,
Outcome: outcome,
ErrorCode: code,
OccurredAt: started,
Contexts: r.buildTelemetryContexts(
command,
usageError,
failureKind,
cancelReason,
ended,
),
}
submission, enqueueErr := client.RecordEvent(ctx, event)
r.logTelemetrySubmission("event", submission, enqueueErr)
if reportKind != "" {
body := cli.ReportBody{
Command: command.CommandPath(),
Code: code,
Stages: cli.StageCounts(r.invocation.Logger.Stages()),
Facts: cli.FailureFacts(commandErr),
}
if commandErr != nil {
body.Message = commandErr.Error()
}
if panicFailure, ok := errors.AsType[*panicError](commandErr); ok && panicFailure != nil {
body.Stack = telemetryPanicFunctions(panicFailure.stack)
}
reportSubmission, reportErr := client.SubmitReport(ctx, telemetry.Report{
Kind: reportKind,
InvocationID: id,
Body: body.Encode(),
})
r.logTelemetrySubmission("report", reportSubmission, reportErr)
}
}
func telemetryPanicFunctions(stack []byte) []string {
var functions []string
for _, line := range strings.Split(string(stack), "\n") {
if !strings.HasPrefix(line, "github.com/mclucy/lucy/") {
continue
}
name, _, found := strings.CutLast(line, "(")
if !found || len(name) > 160 {
continue
}
if strings.Trim(name, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._/-()*") != "" {
continue
}
functions = append(functions, name)
if len(functions) == 32 {
break
}
}
return functions
}
package cmd
import (
"math"
"strconv"
"strings"
"github.com/mclucy/lucy/internal/cli"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// The argument shape is bounded so one invocation cannot grow the event
// without limit. Names are long flag names or positional slots. Values are
// recorded only when the declaration opted into a closed semantic domain and
// the parsed value passes that domain's grammar.
const (
telemetryMaxArguments = 32
telemetryMaxArgumentName = 64
telemetryMaxArgumentValue = 64
telemetryMaxSafeInteger = 1<<53 - 1
telemetryKindBoolean = "boolean"
telemetryKindNumber = "number"
telemetryKindSelector = "selector"
telemetryKindVersion = "version"
telemetryKindText = "text"
telemetryKindList = "list"
)
// telemetryArgument is one replayable fragment of the command line. Value is
// present only for a boolean, a bounded number, or a value drawn from a closed
// selector/version vocabulary.
type telemetryArgument struct {
Name string `json:"name"`
Kind string `json:"kind"`
Value any `json:"value,omitempty"`
}
// telemetrySafeSelectors is a closed vocabulary of product, provider, channel,
// and policy choices. Matching is exact: an arbitrary string that happens to
// contain one of these words is still recorded without its value.
var telemetrySafeSelectors = map[string]struct{}{
"vanilla": {},
"paper": {},
"fabric": {},
"folia": {},
"purpur": {},
"forge": {},
"neoforge": {},
"quilt": {},
"spigot": {},
"bukkit": {},
"velocity": {},
"waterfall": {},
"modrinth": {},
"curseforge": {},
"hangar": {},
"github": {},
"release": {},
"snapshot": {},
"beta": {},
"alpha": {},
"stable": {},
"auto": {},
"latest": {},
"none": {},
"always": {},
"never": {},
"off": {},
"on": {},
}
// telemetryArguments projects the parsed command line into bounded arguments.
// It never reads raw argv: flag names and changed state come from Cobra, and
// positional and flag values are recorded only through annotated semantic
// declarations. Callers must skip it after a failed parse because Cobra leaves
// parsed state from an earlier execution in place.
func telemetryArguments(command *cobra.Command) []telemetryArgument {
if command == nil || !command.Flags().Parsed() {
return nil
}
flags := telemetrySetFlags(command)
arguments := make([]telemetryArgument, 0, min(len(flags)+len(command.Flags().Args()), telemetryMaxArguments))
for _, flag := range flags {
if len(arguments) >= telemetryMaxArguments {
return arguments
}
if argument, ok := telemetryFlagArgument(flag); ok {
arguments = append(arguments, argument)
}
}
for index, value := range command.Flags().Args() {
if len(arguments) >= telemetryMaxArguments {
break
}
position := index + 1
name := "arg-" + strconv.Itoa(position)
arguments = append(arguments, telemetryPositionalArgument(command, position, name, value))
}
return arguments
}
// telemetrySetFlags reads the parsed flag set after Cobra has merged inherited
// and root persistent flags. Visit yields only set flags, in name order.
func telemetrySetFlags(command *cobra.Command) []*pflag.Flag {
var flags []*pflag.Flag
command.Flags().Visit(func(flag *pflag.Flag) {
if flag == nil || flag.Hidden {
return
}
flags = append(flags, flag)
})
return flags
}
func telemetryFlagArgument(flag *pflag.Flag) (telemetryArgument, bool) {
if flag == nil || flag.Value == nil || !telemetryValidArgumentName(flag.Name) {
return telemetryArgument{}, false
}
kind, value := telemetryFlagValue(flag)
return telemetryArgument{Name: flag.Name, Kind: kind, Value: value}, true
}
func telemetryFlagValue(flag *pflag.Flag) (string, any) {
switch flag.Value.Type() {
case "bool":
value, err := strconv.ParseBool(flag.Value.String())
if err != nil {
return telemetryKindBoolean, nil
}
return telemetryKindBoolean, value
case "int", "int8", "int16", "int32", "int64", "count":
if value, err := strconv.ParseInt(flag.Value.String(), 10, 64); err == nil &&
telemetrySafeNumber(float64(value)) {
return telemetryKindNumber, value
}
return telemetryKindNumber, nil
case "uint", "uint8", "uint16", "uint32", "uint64":
if value, err := strconv.ParseUint(flag.Value.String(), 10, 64); err == nil &&
value <= telemetryMaxSafeInteger {
return telemetryKindNumber, int64(value)
}
return telemetryKindNumber, nil
case "float32", "float64":
if value, err := strconv.ParseFloat(flag.Value.String(), 64); err == nil &&
telemetrySafeNumber(value) {
return telemetryKindNumber, value
}
return telemetryKindNumber, nil
case "duration":
// A duration is numeric but has no lossless JSON-number spelling in
// this schema, so the kind is retained without a value.
return telemetryKindNumber, nil
case "string":
if kind, value, ok := telemetryAnnotatedValue(cli.TelemetryFlagArgumentKind(flag), flag.Value.String()); ok {
return kind, value
}
return telemetryKindText, nil
case "stringSlice", "stringArray", "intSlice", "int64Slice",
"uintSlice", "boolSlice", "float32Slice", "float64Slice",
"stringToString":
return telemetryKindList, nil
default:
return telemetryKindText, nil
}
}
func telemetryPositionalArgument(command *cobra.Command, position int, name, value string) telemetryArgument {
if kind, safe, ok := telemetryAnnotatedValue(
cli.TelemetryPositionArgumentKind(command, position),
value,
); ok {
return telemetryArgument{Name: name, Kind: kind, Value: safe}
}
return telemetryArgument{Name: name, Kind: telemetryKindText}
}
// telemetryAnnotatedValue validates a value only against the semantic domain
// its declaration opted into. An unmarked declaration is free text and never
// records its value, even when the spelling looks like a selector or version.
func telemetryAnnotatedValue(annotation, value string) (string, any, bool) {
if len(value) == 0 || len(value) > telemetryMaxArgumentValue {
return "", nil, false
}
switch annotation {
case cli.TelemetryArgumentSelector:
if safe, ok := telemetrySelectorValue(value); ok {
return telemetryKindSelector, safe, true
}
case cli.TelemetryArgumentVersion:
if telemetrySafeVersion(value) {
return telemetryKindVersion, value, true
}
if _, ok := telemetrySafeSelectors[value]; ok {
return telemetryKindSelector, value, true
}
}
return "", nil, false
}
// telemetrySelectorValue accepts a closed selector or a selector@version pair
// whose components each pass their own grammar. The pair is recorded as a
// selector because the product choice supplies its meaning.
func telemetrySelectorValue(value string) (string, bool) {
if _, ok := telemetrySafeSelectors[value]; ok {
return value, true
}
selector, version, found := strings.Cut(value, "@")
if !found || strings.Contains(version, "@") {
return "", false
}
if _, ok := telemetrySafeSelectors[selector]; !ok || !telemetrySafeVersion(version) {
return "", false
}
return value, true
}
// telemetrySafeVersion recognizes Mojang-style numeric segments and snapshot
// identifiers. Segments are ASCII digits only and no segment exceeds four
// digits; the snapshot form is exactly [0-9]{2}w[0-9]{2}[a-z].
func telemetrySafeVersion(value string) bool {
if len(value) == 0 || len(value) > 19 {
return false
}
if len(value) == 6 &&
telemetryDigit(value[0]) && telemetryDigit(value[1]) &&
value[2] == 'w' &&
telemetryDigit(value[3]) && telemetryDigit(value[4]) &&
value[5] >= 'a' && value[5] <= 'z' {
return true
}
segments := 1
digits := 0
for index := range len(value) {
switch {
case value[index] == '.':
if digits == 0 || digits > 4 {
return false
}
segments++
if segments > 4 {
return false
}
digits = 0
case telemetryDigit(value[index]):
digits++
if digits > 4 {
return false
}
default:
return false
}
}
return digits > 0
}
func telemetryDigit(value byte) bool {
return value >= '0' && value <= '9'
}
func telemetrySafeNumber(value float64) bool {
return !math.IsNaN(value) && !math.IsInf(value, 0) &&
math.Abs(value) <= telemetryMaxSafeInteger
}
// telemetryValidArgumentName enforces the wire name grammar without a list, so
// a newly registered flag appears in the shape as soon as it is parsed.
func telemetryValidArgumentName(name string) bool {
if len(name) == 0 || len(name) > telemetryMaxArgumentName {
return false
}
if !telemetryNameCharacter(name[0], true) {
return false
}
for index := 1; index < len(name); index++ {
if !telemetryNameCharacter(name[index], false) {
return false
}
}
return true
}
func telemetryNameCharacter(character byte, first bool) bool {
if (character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') {
return true
}
return character == '-' && !first
}
package cmd
import (
"context"
"errors"
"io/fs"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/internal/agent"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/telemetry"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type telemetryInvocation struct {
Intent string `json:"intent"`
Arguments []telemetryArgument `json:"arguments,omitempty"`
}
// beginTelemetryObservation starts the bounded observation only after the
// existing policy has enabled telemetry for this invocation. The observer is
// carried by the command context so prompt helpers can record their own wait.
func (r *Runner) beginTelemetryObservation(cmd *cobra.Command) {
if !r.invocation.TelemetryEnabled || r.invocation.TelemetryObservation != nil {
return
}
observation := cli.NewTelemetryObservation()
observation.AttachLogger(r.invocation.Logger)
r.invocation.TelemetryObservation = observation
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
cmd.SetContext(cli.WithTelemetryObservation(ctx, observation))
observation.PhaseStart("setup")
r.setupStarted = time.Now()
}
// completeSetupObservation closes the setup phase that covers service
// wiring. A failure leaves it active, which preserves the unfinished stage.
func (r *Runner) completeSetupObservation() {
observation := r.invocation.TelemetryObservation
if observation == nil || r.setupStarted.IsZero() {
return
}
observation.PhaseDone("setup", time.Since(r.setupStarted))
r.setupStarted = time.Time{}
}
// startCommandObservation begins the command parent phase immediately before
// the command body runs. Subphases may overlap it.
func (r *Runner) startCommandObservation() {
observation := r.invocation.TelemetryObservation
if observation == nil || !r.setupStarted.IsZero() {
return
}
observation.PhaseStart("command")
r.commandStarted = time.Now()
}
// completeCommandObservation closes the command phase only for a successful
// invocation. Failed and canceled traces keep the unfinished phase visible.
func (r *Runner) completeCommandObservation(ended time.Time, commandErr error) {
observation := r.invocation.TelemetryObservation
if observation == nil || r.commandStarted.IsZero() || commandErr != nil {
return
}
observation.PhaseDone("command", ended.Sub(r.commandStarted))
}
// telemetryFailureKind classifies a failed invocation without retaining its
// text. Usage is decided once by the caller so report and context agree.
func (r *Runner) telemetryFailureKind(commandErr error, usageError bool) string {
if commandErr == nil {
return ""
}
if usageError {
return "usage"
}
if _, panicked := errors.AsType[*panicError](commandErr); panicked {
return "panic"
}
if _, handled := errors.AsType[*cli.ExitError](commandErr); handled {
return "handled"
}
return "command"
}
// telemetryUsageError recognizes framework rejections and structured usage
// documents, including schema's invalid command path and unsupported output.
func (r *Runner) telemetryUsageError(err error) bool {
if r.flagParsingFailed || cli.IsUsageError(err) {
return true
}
detail, ok := errors.AsType[*report.Detail](err)
return ok && detail != nil && telemetryUsageCode(detail.Code)
}
func telemetryUsageCode(code string) bool {
return code == cli.CodeInvalidInvocation ||
code == "usage.unsupported_output" ||
strings.HasPrefix(code, "usage.")
}
// telemetryCancelReason distinguishes causes only when the boundary knows
// them. A typed signal cause is required before calling a cancellation an OS
// interruption; generic cancellation stays generic. A prompt abort keeps its
// identity because cli.ErrPromptAborted also matches context.Canceled.
func (r *Runner) telemetryCancelReason(commandErr error) string {
if commandErr == nil {
return ""
}
if !errors.Is(commandErr, context.Canceled) &&
!errors.Is(commandErr, context.DeadlineExceeded) {
return ""
}
if errors.Is(commandErr, cli.ErrPromptAborted) {
return "prompt_aborted"
}
if errors.Is(commandErr, context.DeadlineExceeded) ||
(r.runContext != nil && errors.Is(r.runContext.Err(), context.DeadlineExceeded)) {
return "deadline"
}
if telemetrySignalCanceled(r.runContext) {
return "interrupted"
}
return "context_canceled"
}
type telemetrySignalCause interface {
SignalCancellation()
}
func telemetrySignalCanceled(ctx context.Context) bool {
if ctx == nil {
return false
}
cause := context.Cause(ctx)
if cause == nil {
return false
}
var signal telemetrySignalCause
return errors.As(cause, &signal)
}
// telemetryFailureCode maps typed failure causes to the fixed event codes used
// by durable aggregation. An explicit report.Detail code is applied later and
// keeps precedence.
func telemetryFailureCode(err error) string {
if err == nil {
return ""
}
if selection, ok := errors.AsType[*discovery.SelectionError](err); ok && selection != nil {
switch selection.State {
case discovery.SelectionAmbiguous:
return "workspace.selection_ambiguous"
case discovery.SelectionUnmatched:
return "workspace.selection_unmatched"
case discovery.SelectionMissingDeclared:
return "workspace.missing_declared"
case discovery.SelectionInvalid, discovery.SelectionNone:
return "workspace.no_launchable_server"
}
}
if errors.Is(err, fsutil.ErrLocked) {
return "workspace.lock_busy"
}
if errors.Is(err, bootstrap.ErrNoJava) {
return "runtime.no_java"
}
if _, ok := errors.AsType[*resolve.SearchLimitError](err); ok {
return "resolve.search_limit"
}
if errors.Is(err, fs.ErrPermission) {
return "io.permission_denied"
}
return ""
}
func (r *Runner) invocationContext(command *cobra.Command, usageError bool) telemetry.Context {
intent := "command"
if usageError {
intent = "invalid_usage"
}
data := telemetryInvocation{Intent: intent}
if command != nil && command.Flags().Parsed() && !r.flagParsingFailed {
data.Arguments = telemetryArguments(command)
}
return telemetry.Context{
Kind: "invocation",
Status: telemetry.ContextPresent,
Data: data,
}
}
func telemetryFlagSource(command *cobra.Command, name string) *pflag.Flag {
if command == nil {
return nil
}
if flag := command.Flags().Lookup(name); flag != nil {
return flag
}
if flag := command.InheritedFlags().Lookup(name); flag != nil {
return flag
}
if root := command.Root(); root != nil {
return root.PersistentFlags().Lookup(name)
}
return nil
}
func telemetryBoolFlag(command *cobra.Command, name string) bool {
flag := telemetryFlagSource(command, name)
if flag == nil {
return false
}
value, err := strconv.ParseBool(flag.Value.String())
return err == nil && value
}
// buildTelemetryContexts assembles the bounded envelope. Contexts the command
// did not observe are explicit, and observation gaps are distinct from a
// failed observation.
func (r *Runner) buildTelemetryContexts(
command *cobra.Command,
usageError bool,
failureKind, cancelReason string,
ended time.Time,
) []telemetry.Context {
observation := r.invocation.TelemetryObservation
contexts := make([]telemetry.Context, 0, 8)
contexts = append(contexts, r.invocationContext(command, usageError))
if observation != nil {
if cancelReason != "" {
observation.SetCancelReason(cancelReason)
}
if failureKind != "" && cancelReason == "" {
observation.SetFailureKind(failureKind)
}
r.invocation.MergeWorkspacePackages(observation.Packages())
contexts = append(contexts, observation.Execution(ended))
} else {
contexts = append(contexts, telemetry.Context{
Kind: telemetry.ContextExecution,
Status: telemetry.ContextAbsent,
Reason: telemetry.ContextReasonNotReached,
})
}
seen := map[telemetry.ContextKind]bool{}
for _, observed := range r.invocation.TelemetryContexts {
contexts = append(contexts, normalizeObservedContext(observed))
seen[observed.Kind] = true
}
gapReason := telemetry.ContextReasonNotReached
if !r.commandStarted.IsZero() {
gapReason = telemetry.ContextReasonNotObserved
}
for _, kind := range []telemetry.ContextKind{"workspace", "java"} {
if seen[kind] {
continue
}
contexts = append(contexts, telemetry.Context{
Kind: kind,
Status: telemetry.ContextAbsent,
Reason: gapReason,
})
}
if r.invocation.TelemetryEnabled {
contexts = append(contexts, telemetry.Context{
Kind: "agent",
Status: telemetry.ContextPresent,
Data: struct {
Detected bool `json:"detected"`
}{Detected: agent.Detected()},
})
}
return contexts
}
// normalizeObservedContext fills the status-specific reason an older command
// projection left empty. Present contexts never carry a reason.
func normalizeObservedContext(observed telemetry.Context) telemetry.Context {
switch observed.Status {
case telemetry.ContextAbsent:
if observed.Reason == "" {
observed.Reason = telemetry.ContextReasonNoResult
}
case telemetry.ContextFailed:
if observed.Reason == "" {
observed.Reason = telemetry.ContextReasonObservationFailed
}
}
return observed
}
func (r *Runner) telemetryLocalLog() bool {
return r.invocation.Logger != nil && r.invocation.Logger.FilePath() != ""
}
func (r *Runner) logTelemetrySubmission(kind string, submission telemetry.Submission, err error) {
logger := r.invocation.Logger
if logger == nil {
return
}
switch {
case err != nil:
logger.Debug("telemetry " + kind + " enqueue failed")
case submission.Queued:
logger.Debug("telemetry " + kind + " queued")
case submission.Reason == telemetry.SkipDisabled,
submission.Reason == telemetry.SkipEnvironment:
logger.Debug("telemetry "+kind+" skipped", "reason", string(submission.Reason))
default:
logger.Debug("telemetry "+kind+" not queued", "reason", string(submission.Reason))
}
}
func (r *Runner) logTelemetryFlush(result telemetry.FlushResult, err error) {
logger := r.invocation.Logger
if logger == nil {
return
}
if err != nil {
logger.Debug("telemetry flush failed")
return
}
if result.Skipped {
logger.Debug("telemetry flush skipped", "reason", string(result.Reason))
return
}
logger.Debug(
"telemetry flush completed",
"attempted", result.Attempted,
"accepted", result.Accepted,
"rejected", result.Rejected,
"remaining", result.Remaining,
)
}
package cmd
import (
"runtime/debug"
"strings"
)
func buildVersion() (string, string) {
displayVersion, displayCommit := version, commit
info, ok := debug.ReadBuildInfo()
if !ok {
return displayVersion, displayCommit
}
revision := ""
for _, setting := range info.Settings {
switch setting.Key {
case "vcs.revision":
revision = setting.Value
}
}
if displayVersion == "" && revision == "" && info.Main.Version != "" && info.Main.Version != "(devel)" {
displayVersion = strings.TrimPrefix(info.Main.Version, "v")
}
if displayCommit == "" && revision != "" {
if len(revision) > 7 {
revision = revision[:7]
}
displayCommit = revision
}
return displayVersion, displayCommit
}
// isOfficialBuild reports whether the binary came from a published release
// archive. Development and go-install builds leave the linker marker empty.
func isOfficialBuild() bool {
return official == "true"
}
func isTelemetryRelease() bool {
if telemetryRelease == "true" {
return true
}
info, ok := debug.ReadBuildInfo()
return ok && info.Main.Sum != "" && info.Main.Version != "" && info.Main.Version != "(devel)"
}
// Package config manages machine-local global and workspace configuration.
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/log"
)
const WorkspaceFilename = ".lucy/config.yaml"
type Scope uint8
const (
WorkspaceScope Scope = iota
GlobalScope
)
type Service struct {
root string
globalPath string
globalErr error
logger *log.Logger
}
type WriteResult struct {
Path string `json:"path"`
Created bool `json:"created"`
}
// New builds the service for root. An unavailable user configuration directory
// only fails requests for the global scope, so Java selection still works in
// environments without a home directory.
func New(root string, logger *log.Logger) (*Service, error) {
absolute, err := filepath.Abs(root)
if err != nil {
return nil, fmt.Errorf("resolve workspace directory: %w", err)
}
service := &Service{root: absolute, logger: logger}
directory, err := os.UserConfigDir()
if err != nil {
service.globalErr = fmt.Errorf("locate global config directory: %w", err)
return service, nil
}
service.globalPath = filepath.Join(directory, "lucy", "config.yaml")
return service, nil
}
func configFile(path string) document.Service[Values] {
return document.NewService(path, document.Codec[Values]{
Decode: decodeValues,
Encode: encodeValues,
Merge: mergeConfigBytes,
}).WithMode(0o600)
}
func (s *Service) file(scope Scope) (document.Service[Values], error) {
switch scope {
case WorkspaceScope:
return configFile(filepath.Join(s.root, filepath.FromSlash(WorkspaceFilename))), nil
case GlobalScope:
if s.globalErr != nil {
return document.Service[Values]{}, s.globalErr
}
return configFile(s.globalPath), nil
default:
return document.Service[Values]{}, fmt.Errorf("unknown config scope")
}
}
func (s *Service) read(scope Scope, required bool) (*Values, error) {
file, err := s.file(scope)
if err != nil {
if scope == GlobalScope && !required {
return &Values{}, nil
}
return nil, err
}
values, err := file.Read()
if errors.Is(err, os.ErrNotExist) {
if !required {
return &Values{}, nil
}
command := "lucy config create"
if scope == GlobalScope {
command += " --global"
}
return nil, fmt.Errorf("config %s does not exist; run `%s` to create it: %w", file.Path(), command, err)
}
if err != nil {
return nil, fmt.Errorf("read config %s: %w", file.Path(), err)
}
return values, nil
}
func (s *Service) Get(key string, scope Scope) (any, error) {
selected, err := s.read(scope, true)
if err != nil {
return nil, err
}
global, workspace := selected, &Values{}
if scope == WorkspaceScope {
workspace = selected
global, err = s.read(GlobalScope, false)
if err != nil {
return nil, err
}
}
merged := mergeValues(global, workspace)
if key == "" {
return merged, nil
}
value, err := fieldValue(merged, key)
if err != nil {
return nil, err
}
if value.Kind() == reflect.Pointer {
return value.Elem().Interface(), nil
}
return value.Interface(), nil
}
// Setting returns one effective string setting. Missing layers are empty, and
// a workspace value overrides a global one.
func (s *Service) Setting(key string) (string, error) {
global, err := s.read(GlobalScope, false)
if err != nil {
return "", err
}
workspace, err := s.read(WorkspaceScope, false)
if err != nil {
return "", err
}
merged := mergeValues(global, workspace)
value, err := fieldValue(merged, key)
if err != nil {
return "", err
}
if value.Kind() != reflect.Pointer {
return "", fmt.Errorf("config key %q is not a string", key)
}
if value.IsNil() {
return "", nil
}
return value.Elem().String(), nil
}
// GitHubProxy returns the configured prefix proxy for GitHub release
// downloads. An empty prefix downloads directly. A hand-edited value must be
// an absolute HTTP(S) URL so an invalid value fails as an error up front.
func (s *Service) GitHubProxy() (string, error) {
value, err := s.Setting("github.proxy")
if err != nil {
return "", err
}
value = strings.TrimSpace(value)
if err := validateProxyURL(value); err != nil {
return "", err
}
return value, nil
}
// CurseForgeAPIKey returns the configured CurseForge API key. An empty key
// lets the provider use the key embedded in this build.
func (s *Service) CurseForgeAPIKey() (string, error) {
return s.Setting("curseforge.api_key")
}
// JavaHome resolves the selected path against the directory of its source
// scope. Missing config files still allow automatic runtime selection.
func (s *Service) JavaHome() (home string, sourcePath string, err error) {
global, err := s.read(GlobalScope, false)
if err != nil {
return "", "", err
}
workspace, err := s.read(WorkspaceScope, false)
if err != nil {
return "", "", err
}
selected, base, source := global.Java.Home, filepath.Dir(s.globalPath), s.globalPath
if workspace.Java.Home != nil {
selected, base, source = workspace.Java.Home, s.root, filepath.Join(s.root, WorkspaceFilename)
}
if selected == nil || *selected == "" {
return "", "", nil
}
home = *selected
if !filepath.IsAbs(home) {
home = filepath.Join(base, home)
}
if info, statErr := os.Stat(home); statErr == nil && !info.IsDir() {
home = filepath.Dir(filepath.Dir(home))
}
return filepath.Clean(home), source, nil
}
package config
import (
"reflect"
"strings"
)
// RedactedValue replaces a secret setting in configuration output.
const RedactedValue = "********"
// Secret reports whether a setting holds a credential that output must mask.
func Secret(key string) bool {
field, ok := schemaFieldByKey(key)
return ok && field.Tag.Get("secret") == "true"
}
// Redacted returns value with every secret setting masked, so the output is
// safe to share. A caller that needs one secret reads that setting by its exact
// key instead.
func Redacted(value any) any {
switch value := value.(type) {
case *Values:
if value == nil {
return value
}
copied := *value
redactSecrets(reflect.ValueOf(&copied).Elem())
return &copied
case CurseForge:
redactSecrets(reflect.ValueOf(&value).Elem())
return value
default:
return value
}
}
func schemaFieldByKey(key string) (reflect.StructField, bool) {
if key == "" {
return reflect.StructField{}, false
}
t := reflect.TypeFor[Values]()
var field reflect.StructField
for part := range strings.SplitSeq(key, ".") {
next, ok := schemaField(t, part)
if !ok {
return reflect.StructField{}, false
}
field, t = next, next.Type
}
return field, true
}
// redactSecrets masks the non-empty secret fields reachable from value in
// place. An empty secret keeps its empty value, which selects the fallback.
func redactSecrets(value reflect.Value) {
for value.Kind() == reflect.Pointer {
if value.IsNil() {
return
}
value = value.Elem()
}
if value.Kind() != reflect.Struct {
return
}
t := value.Type()
for i := range t.NumField() {
field := t.Field(i)
if !field.IsExported() {
continue
}
child := value.Field(i)
if field.Tag.Get("secret") == "true" &&
child.Kind() == reflect.Pointer &&
child.Type().Elem().Kind() == reflect.String &&
!child.IsNil() &&
child.Elem().String() != "" {
child.Elem().SetString(RedactedValue)
continue
}
redactSecrets(child)
}
}
package config
import (
"bytes"
"errors"
"fmt"
"io"
"reflect"
"strings"
"github.com/mclucy/lucy/document"
"go.yaml.in/yaml/v4"
)
// Values describes one configuration layer. A nil scalar inherits from the
// previous layer; an explicit empty value selects that setting's automatic
// behavior and masks an inherited value.
type Values struct {
Java Java `yaml:"java,omitempty" json:"java" description:"Java runtime selection."`
GitHub GitHub `yaml:"github,omitempty" json:"github" description:"GitHub access."`
CurseForge CurseForge `yaml:"curseforge,omitempty" json:"curseforge" description:"CurseForge access."`
Store Store `yaml:"store,omitempty" json:"store" description:"Artifact store use."`
}
type Java struct {
Home *string `yaml:"home,omitempty" json:"home" description:"Java home or executable. An empty value lets Lucy choose a runtime." example:"/path/to/java-home"`
}
type GitHub struct {
Proxy *string `yaml:"proxy,omitempty" json:"proxy" description:"Prefix proxy for GitHub release downloads. An empty value downloads directly." example:"https://ghfast.top/"`
}
type CurseForge struct {
APIKey *string `yaml:"api_key,omitempty" json:"api_key" secret:"true" description:"CurseForge API key. An empty value uses the key built into this Lucy build." example:"$2a$10$example"`
}
type Store struct {
Link *string `yaml:"link,omitempty" json:"link" description:"How installed files share content with the artifact store: clone (copy-on-write; a plain copy where the filesystem cannot clone) or hardlink (installed files share the stored copy and are read-only; a server that must rewrite a runtime file fails). An empty value selects clone. Windows installs plain copies with write bits because it cannot share a stored inode." example:"hardlink"`
}
func decodeValues(reader io.Reader) (*Values, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
decoder := yaml.NewDecoder(bytes.NewReader(data))
var node yaml.Node
if err := decoder.Decode(&node); errors.Is(err, io.EOF) {
return &Values{}, nil
} else if err != nil {
return nil, fmt.Errorf("decode config: %w", err)
}
var tail yaml.Node
if err := decoder.Decode(&tail); !errors.Is(err, io.EOF) {
if err != nil {
return nil, fmt.Errorf("decode config tail: %w", err)
}
return nil, fmt.Errorf("config must contain one YAML document")
}
if len(node.Content) == 0 {
return &Values{}, nil
}
if err := validateFields(node.Content[0], reflect.TypeFor[Values](), ""); err != nil {
return nil, err
}
values := &Values{}
if err := node.Decode(values); err != nil {
return nil, fmt.Errorf("decode config values: %w", err)
}
return values, nil
}
func encodeValues(values *Values) ([]byte, error) {
return document.NewCommenter(document.YAMLOptions{}).Render(values)
}
func (values *Values) PlainBytes() ([]byte, error) {
return document.NewCommenter(document.YAMLOptions{NoComments: true}).Render(values)
}
// mergeConfigBytes writes values into the configuration the file already
// holds. Comments the user wrote survive, and new keys arrive with the
// documentation declared by the config types.
func mergeConfigBytes(existing []byte, values *Values) ([]byte, error) {
if len(bytes.TrimSpace(existing)) == 0 {
return encodeValues(values)
}
if _, err := decodeValues(bytes.NewReader(existing)); err != nil {
return nil, err
}
return document.NewCommenter(document.YAMLOptions{}).Merge(existing, values)
}
func schemaField(t reflect.Type, name string) (reflect.StructField, bool) {
for i := range t.NumField() {
field := t.Field(i)
if field.IsExported() && yamlName(field) == name {
return field, true
}
}
return reflect.StructField{}, false
}
func yamlName(field reflect.StructField) string {
name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",")
return name
}
func validateFields(node *yaml.Node, t reflect.Type, prefix string) error {
if node.Kind == yaml.AliasNode {
node = node.Alias
}
if node.Tag == "!!null" {
return nil
}
if node.Kind != yaml.MappingNode {
return fmt.Errorf("config %s must be a mapping", strings.TrimSuffix(prefix, "."))
}
for i := 0; i < len(node.Content); i += 2 {
key, value := node.Content[i], node.Content[i+1]
field, ok := schemaField(t, key.Value)
if !ok {
return fmt.Errorf("unknown config key %q", prefix+key.Value)
}
if field.Type.Kind() == reflect.Struct {
if err := validateFields(value, field.Type, prefix+key.Value+"."); err != nil {
return err
}
continue
}
if value.Tag == "!!null" {
continue
}
if value.Kind == yaml.AliasNode {
value = value.Alias
}
if field.Type.Kind() != reflect.Pointer || field.Type.Elem().Kind() != reflect.String {
return fmt.Errorf("unsupported config schema field %q", prefix+key.Value)
}
if value.Kind != yaml.ScalarNode || value.Tag != "!!str" {
return fmt.Errorf("config %s must be a string", prefix+key.Value)
}
}
return nil
}
func fieldValue(values *Values, key string) (reflect.Value, error) {
value := reflect.ValueOf(values).Elem()
for part := range strings.SplitSeq(key, ".") {
if value.Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("unknown config key %q", key)
}
field, ok := schemaField(value.Type(), part)
if !ok {
return reflect.Value{}, fmt.Errorf("unknown config key %q", key)
}
value = value.FieldByIndex(field.Index)
}
return value, nil
}
func mergeValues(global, workspace *Values) *Values {
merged := &Values{}
mergeFields(reflect.ValueOf(merged).Elem(), reflect.ValueOf(global).Elem(), reflect.ValueOf(workspace).Elem())
return merged
}
func mergeFields(target, global, workspace reflect.Value) {
for i := range target.Type().NumField() {
field := target.Type().Field(i)
if !field.IsExported() {
continue
}
dst := target.FieldByIndex(field.Index)
left, right := global.FieldByIndex(field.Index), workspace.FieldByIndex(field.Index)
if dst.Kind() == reflect.Struct {
mergeFields(dst, left, right)
continue
}
switch {
case !right.IsNil():
dst.Set(right)
case !left.IsNil():
dst.Set(left)
default:
dst.Set(reflect.New(dst.Type().Elem()))
}
}
}
package config
import (
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspaceguard"
"github.com/mclucy/lucy/internal/workspacewrite"
)
func (s *Service) lock(scope Scope) (*fsutil.FileLock, error) {
if scope == WorkspaceScope {
if err := workspacewrite.SafePath(s.root, WorkspaceFilename); err != nil {
return nil, err
}
writer, err := workspacewrite.Lock(s.root, s.logger)
if err != nil {
return nil, err
}
if err := workspaceguard.RecoverInstall(s.root, s.logger); err != nil {
return nil, errors.Join(err, writer.Close())
}
return writer, nil
}
if scope != GlobalScope {
return nil, fmt.Errorf("unknown config scope")
}
if s.globalErr != nil {
return nil, s.globalErr
}
directory := filepath.Dir(s.globalPath)
if err := fsutil.MkdirAllPrivate(directory); err != nil {
return nil, err
}
return fsutil.TryLockFile(filepath.Join(directory, "writer.lock"))
}
// workspaceRoot opens the workspace directory that confines configuration IO.
// Global configuration has no such root because only this user can change its
// private directory.
func (s *Service) workspaceRoot(scope Scope) (*os.Root, error) {
if scope != WorkspaceScope {
return nil, nil
}
return os.OpenRoot(s.root)
}
// absent reports whether the configuration file is free. A workspace check runs
// through its root handle, so a replaced parent cannot answer for a foreign
// file.
func absent(file document.Service[Values], root *os.Root) (bool, error) {
var err error
if root == nil {
_, err = os.Lstat(file.Path())
} else {
_, err = root.Lstat(WorkspaceFilename)
}
switch {
case err == nil:
return false, nil
case errors.Is(err, os.ErrNotExist):
return true, nil
default:
return false, err
}
}
// readValues reads through root when the scope has one, so a replaced parent
// cannot feed a write with a foreign document.
func readValues(file document.Service[Values], root *os.Root) (*Values, error) {
if root == nil {
return file.Read()
}
return file.ReadRoot(root, WorkspaceFilename)
}
// writeValues publishes through root when the scope has one, keeping reading,
// staging, and renaming on the handle the writer lock verified.
func writeValues(file document.Service[Values], root *os.Root, values *Values, replace bool) error {
if root == nil {
if replace {
return file.Write(values)
}
return file.Create(values)
}
if replace {
return file.WriteRoot(root, WorkspaceFilename, values)
}
return file.CreateRoot(root, WorkspaceFilename, values)
}
// CreateWorkspace publishes a fresh workspace configuration when the file is
// absent and reports whether it wrote one. The write stays confined to the
// workspace root.
func CreateWorkspace(root string, plain bool) (created bool, resultErr error) {
files, err := os.OpenRoot(root)
if err != nil {
return false, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
file := configFile(filepath.Join(root, filepath.FromSlash(WorkspaceFilename)))
if plain {
file = file.WithEncoder((*Values).PlainBytes)
}
err = file.CreateRoot(files, WorkspaceFilename, &Values{})
if errors.Is(err, os.ErrExist) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
type CreateOptions struct {
Force bool
NoComments bool
}
func (s *Service) Create(scope Scope, options CreateOptions) (result *WriteResult, resultErr error) {
writer, err := s.lock(scope)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
file, err := s.file(scope)
if err != nil {
return nil, err
}
if options.NoComments {
file = file.WithEncoder((*Values).PlainBytes)
}
// Create replaces the file by definition: a forced create must not merge
// its empty template into the values it is discarding.
file = file.WithoutMerge()
root, err := s.workspaceRoot(scope)
if err != nil {
return nil, err
}
if root != nil {
defer func() { resultErr = errors.Join(resultErr, root.Close()) }()
}
created, err := absent(file, root)
if err != nil {
return nil, err
}
if !created && !options.Force {
return nil, fmt.Errorf("config %s already exists; use --force to replace it with a fresh config", file.Path())
}
if err := writeValues(file, root, &Values{}, options.Force); err != nil {
return nil, err
}
return &WriteResult{Path: file.Path(), Created: created}, nil
}
func validateSetting(key, text string) error {
switch key {
case "github.proxy":
return validateProxyURL(text)
default:
return nil
}
}
func validateProxyURL(text string) error {
if text == "" {
return nil
}
parsed, err := url.Parse(text)
if err != nil ||
(parsed.Scheme != "http" && parsed.Scheme != "https") ||
parsed.Host == "" ||
parsed.RawQuery != "" ||
parsed.Fragment != "" {
return fmt.Errorf("config github.proxy must be an absolute HTTP(S) URL without a query or fragment")
}
return nil
}
func (s *Service) Set(key, text string, scope Scope) (result *WriteResult, resultErr error) {
probe, err := fieldValue(&Values{}, key)
if err != nil {
return nil, err
}
if probe.Kind() != reflect.Pointer || probe.Type().Elem().Kind() != reflect.String {
return nil, fmt.Errorf("config key %q requires a field, not a section", key)
}
if strings.ContainsRune(text, '\x00') {
return nil, fmt.Errorf("config %s cannot contain a null character", key)
}
if err := validateSetting(key, text); err != nil {
return nil, err
}
writer, err := s.lock(scope)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
file, err := s.file(scope)
if err != nil {
return nil, err
}
root, err := s.workspaceRoot(scope)
if err != nil {
return nil, err
}
if root != nil {
defer func() { resultErr = errors.Join(resultErr, root.Close()) }()
}
values, err := readValues(file, root)
created := errors.Is(err, os.ErrNotExist)
if created {
values = &Values{}
} else if err != nil {
return nil, fmt.Errorf("read config %s: %w", file.Path(), err)
}
field, err := fieldValue(values, key)
if err != nil {
return nil, err
}
field.Set(reflect.ValueOf(new(text)))
if err := writeValues(file, root, values, !created); err != nil {
return nil, err
}
return &WriteResult{Path: file.Path(), Created: created}, nil
}
//go:build !docsarchive
package docs
import (
"embed"
"io/fs"
)
// Sources are the tracked page files, read directly by builds that do not pack
// the documentation archive.
//
//go:embed *.mdx agents/*.mdx commands/*.mdx file-tracking/*.mdx
var sources embed.FS
// Load returns the embedded pages sorted by slug.
func Load() ([]Page, error) {
var pages []Page
err := fs.WalkDir(sources, ".", func(name string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
slug, ok := pageName(name)
if !ok {
return nil
}
content, err := sources.ReadFile(name)
if err != nil {
return err
}
pages = append(pages, Page{Slug: slug, Content: content})
return nil
})
if err != nil {
return nil, err
}
sortPages(pages)
return pages, nil
}
// Package docs supplies the documentation pages embedded in lucy.
package docs
import (
"cmp"
"slices"
"strings"
)
// Page is one documentation page. Slug is the page path without the .mdx suffix.
type Page struct {
Slug string
Content []byte
}
// pageName reports the slug of a page path. Drafts are not pages.
func pageName(name string) (string, bool) {
if !strings.HasSuffix(name, ".mdx") || strings.HasSuffix(name, ".draft.mdx") {
return "", false
}
return strings.TrimSuffix(name, ".mdx"), true
}
func sortPages(pages []Page) {
slices.SortFunc(pages, func(a, b Page) int {
return cmp.Compare(a.Slug, b.Slug)
})
}
package document
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json/v2"
"fmt"
"io"
"slices"
"github.com/mclucy/lucy/catalog"
javapkg "github.com/mclucy/lucy/java"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
"go.yaml.in/yaml/v4"
)
const (
LockFilename = "lucy-lock.yaml"
LockSchemaVersion = 1
)
type Lock struct {
SchemaVersion int `yaml:"lock_version" json:"lock_version"`
ManifestFingerprint string `yaml:"manifest_fingerprint" json:"manifest_fingerprint"`
Server LockedServer `yaml:"server" json:"server"`
MCDR *LockedMCDR `yaml:"mcdr,omitempty" json:"mcdr,omitempty"`
Packages []Package `yaml:"packages" json:"packages"`
Files []TrackedFile `yaml:"files,omitempty" json:"files,omitempty"`
}
type LockedServer struct {
Directory string `yaml:"directory,omitempty" json:"directory"`
Minecraft version.Version `yaml:"minecraft" json:"minecraft"`
Product server.Product `yaml:"product" json:"product"`
CoreVersion version.Version `yaml:"core_version" json:"core_version"`
catalog.Artifact `yaml:",inline" json:",inline"`
Bootstrap server.BootstrapMethod `yaml:"bootstrap" json:"bootstrap"`
// Inputs are the artifacts the method consumes besides the core. The
// method decides where each input lands in the server tree.
Inputs []catalog.Artifact `yaml:"inputs,omitempty" json:"inputs"`
Java LockedJava `yaml:"java" json:"java"`
}
// LockedJava records the inputs of the Java requirement. Package requirements
// on Java stay in the package modules, so commands combine the inputs when
// they check a Java runtime.
type LockedJava struct {
// Advisory is the Java major version that Mojang recommends for the
// Minecraft version. Lucy treats it as a minimum.
Advisory int `yaml:"advisory" json:"advisory"`
// Version is the major version that the manifest pins; zero follows the
// advisory.
Version int `yaml:"version,omitempty" json:"version,omitempty"`
// Distribution is the distribution that the manifest pins; empty accepts
// any build.
Distribution javapkg.Distribution `yaml:"distribution,omitempty" json:"distribution,omitempty"`
}
// NewLockedJava records the Mojang advisory with the override that the
// manifest declares.
func NewLockedJava(advisory int, override *ManifestJava) LockedJava {
java := LockedJava{Advisory: advisory}
if override != nil {
java.Version = override.Version
java.Distribution = override.Distribution
}
return java
}
type LockedMCDR struct {
Directory string `yaml:"directory" json:"directory"`
Version version.Version `yaml:"version" json:"version"`
}
func (l *Lock) Validate() error {
if l.SchemaVersion != LockSchemaVersion {
return fmt.Errorf("unsupported lock version %d", l.SchemaVersion)
}
if l.ManifestFingerprint == "" {
return fmt.Errorf("manifest_fingerprint is required")
}
if l.Server.Directory == "" {
return fmt.Errorf("server.directory is required")
}
if err := SafeRelativePath(l.Server.Directory); err != nil {
return err
}
if err := validateVersion("server.minecraft", l.Server.Minecraft, false); err != nil {
return err
}
if l.Server.Product == server.ProductUnknown {
return fmt.Errorf("server.product is required")
}
if err := validateVersion("server.core_version", l.Server.CoreVersion, true); err != nil {
return err
}
if l.Server.Artifact.Version == "" {
return fmt.Errorf("server.artifact.version is required")
}
if l.Server.Artifact.Filename == "" {
return fmt.Errorf("server.artifact.filename is required")
}
if err := l.Server.Bootstrap.Validate(); err != nil {
return fmt.Errorf("server.bootstrap: %w", err)
}
if l.Server.Java.Advisory <= 0 {
return fmt.Errorf("server.java.advisory must be positive")
}
distribution, ok := javapkg.ParseDistribution(string(l.Server.Java.Distribution))
if !ok {
return fmt.Errorf("unknown server.java.distribution %q", l.Server.Java.Distribution)
}
l.Server.Java.Distribution = distribution
if l.MCDR != nil {
if l.MCDR.Directory == "" {
return fmt.Errorf("mcdr.directory is required")
}
if err := SafeRelativePath(l.MCDR.Directory); err != nil {
return err
}
if err := validateVersion("mcdr.version", l.MCDR.Version, false); err != nil {
return err
}
}
for i := range l.Packages {
if err := validateLockedPackage(&l.Packages[i]); err != nil {
return err
}
}
if err := NormalizeTrackedFiles(l.Files); err != nil {
return err
}
return nil
}
func validateVersion(field string, v version.Version, allowSelector bool) error {
if v == "" {
return fmt.Errorf("%s is required", field)
}
if !allowSelector && (v.CanInfer() || v.IsInvalid()) {
return fmt.Errorf("%s must be a concrete version", field)
}
return nil
}
func validateLockedPackage(pkg *Package) error {
switch pkg.Environment {
case server.EnvironmentServer, server.EnvironmentMCDR:
default:
return fmt.Errorf("package %s has unknown environment %q", pkg.Artifact.ProjectID, pkg.Environment)
}
if !pkg.Ecosystem.Valid() || pkg.Ecosystem == catalog.EcosystemUnspecified {
return fmt.Errorf("package %s has unknown ecosystem %q", pkg.Artifact.ProjectID, pkg.Ecosystem)
}
if pkg.Artifact.Provider == catalog.ProviderUnspecified || pkg.Artifact.Provider == catalog.ProviderUnknown {
return fmt.Errorf("package %s has no provider", pkg.Artifact.ProjectID)
}
if pkg.Artifact.Version == "" || pkg.Artifact.Version.CanInfer() || pkg.Artifact.Version.IsInvalid() {
return fmt.Errorf("package %s has no concrete version", pkg.Artifact.ProjectID)
}
if pkg.Artifact.Filename == "" {
return fmt.Errorf("package %s has no filename", pkg.Artifact.ProjectID)
}
if pkg.Artifact.Hashes["sha256"] == "" {
return fmt.Errorf("package %s has no sha256 hash", pkg.Artifact.ProjectID)
}
for j := range pkg.Modules {
module := &pkg.Modules[j]
if !module.VersionDialect.Valid() {
return fmt.Errorf(
"package %s module %s requires a known version dialect, got %q",
pkg.Artifact.ProjectID,
module.ID,
module.VersionDialect,
)
}
}
for j := range pkg.Requirements {
requirement := &pkg.Requirements[j]
if requirement.Reference == "" {
return fmt.Errorf("package %s has an empty requirement reference", pkg.Artifact.ProjectID)
}
if requirement.Selector == "" {
return fmt.Errorf("package %s has an empty requirement selector", pkg.Artifact.ProjectID)
}
}
return nil
}
// DecodeLock validates lock bytes from a reader.
func DecodeLock(reader io.Reader) (*Lock, error) {
l := &Lock{}
decoder := yaml.NewDecoder(reader)
decoder.KnownFields(true)
if err := decoder.Decode(l); err != nil {
return nil, fmt.Errorf("decode lock: %w", err)
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
if err == nil {
return nil, fmt.Errorf("lock must contain one YAML document")
}
return nil, fmt.Errorf("decode lock tail: %w", err)
}
if err := l.Validate(); err != nil {
return nil, err
}
return l, nil
}
// Fingerprint returns the identity of a lock's content. It validates a copy
// first, so the fingerprint describes what the lock says and not how it was
// spelled.
func (l *Lock) Fingerprint() (string, error) {
canonical, err := l.canonical()
if err != nil {
return "", err
}
data, err := json.Marshal(canonical, json.Deterministic(true))
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
func (l *Lock) canonical() (*Lock, error) {
if l == nil {
return nil, nil
}
clone := *l
clone.Files = slices.Clone(l.Files)
if err := clone.Validate(); err != nil {
return nil, err
}
return &clone, nil
}
// Snapshot returns the canonical bytes of the document. It writes nothing. A
// publisher that decides when and where the bytes land takes a snapshot first;
// Service.Write takes one and publishes it.
func (l *Lock) Snapshot() ([]byte, error) {
if err := l.Validate(); err != nil {
return nil, err
}
return NewCommenter(YAMLOptions{NoComments: true}).Render(l)
}
// MergeBytes writes l into existing and keeps the comments the existing lock
// carries. The lock declares no generated comments of its own.
func (l *Lock) MergeBytes(existing []byte) ([]byte, error) {
if len(bytes.TrimSpace(existing)) == 0 {
return l.Snapshot()
}
if _, err := DecodeLock(bytes.NewReader(existing)); err != nil {
return nil, err
}
if err := l.Validate(); err != nil {
return nil, err
}
return NewCommenter(YAMLOptions{NoComments: true}).Merge(existing, l)
}
// LookupReference expands a bare name against the package names in this lock.
// It returns an empty string when no package matches and an error when the
// name is ambiguous.
func (l *Lock) LookupReference(input string) (string, error) {
var match string
for _, pkg := range l.Packages {
if pkg.Artifact.ProjectID != input {
continue
}
ref := pkg.Artifact.Provider.String() + ":" + pkg.Artifact.ProjectID
if match != "" && match != ref {
return "", fmt.Errorf("ambiguous package name %q", input)
}
match = ref
}
return match, nil
}
package document
import (
"fmt"
"path/filepath"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
// RequirementBinding retains a declared reference's immutable project identity,
// including when the requirement is disabled.
type RequirementBinding struct {
Reference string `yaml:"reference" json:"reference"`
Selector version.Version `yaml:"selector" json:"selector"`
FilePattern string `yaml:"file_pattern,omitempty" json:"file_pattern,omitempty"`
Enabled bool `yaml:"enabled" json:"enabled"`
}
// PackageDependency is a relationship the selected release declares to
// another project.
type PackageDependency struct {
Provider catalog.Provider `yaml:"provider" json:"provider"`
ProjectID string `yaml:"project_id" json:"project_id"`
ReleaseID string `yaml:"release_id,omitempty" json:"release_id,omitempty"`
Kind catalog.DependencyKind `yaml:"kind" json:"kind"`
}
// Package records an artifact pin and its requirement bindings, not installed state.
type Package struct {
Environment server.Environment `yaml:"environment" json:"environment"`
Ecosystem catalog.Ecosystem `yaml:"ecosystem" json:"ecosystem"`
catalog.Artifact `yaml:",inline"`
Requirements []RequirementBinding `yaml:"requirements,omitempty" json:"requirements,omitempty"`
// Dependency records selection through another package's dependency.
Dependency bool `yaml:"dependency,omitempty" json:"dependency,omitzero"`
// DependencyOf keeps the required dependents that justify this pin.
DependencyOf []catalog.Ref `yaml:"dependency_of,omitempty" json:"dependency_of,omitempty"`
// Dependencies retains the release's declared project relationships, so a
// candidate restored from the lock keeps its demands and incompatibilities.
Dependencies []PackageDependency `yaml:"dependencies,omitempty" json:"dependencies,omitempty"`
// DependenciesUnknown records that the provider could not supply the
// release's dependency metadata.
DependenciesUnknown bool `yaml:"dependencies_unknown,omitempty" json:"dependencies_unknown,omitempty"`
// Channel records the selected release's stability channel, which the
// artifact does not carry. A candidate restored from the lock must satisfy
// the same selector checks as the catalogue candidate it replaces.
Channel upstream.ReleaseChannel `yaml:"channel,omitempty" json:"channel,omitempty"`
// ModulesSuperseded records that finalization dropped modules from
// Modules because another selected module answers their identity. Modules
// then lists only the surviving subset of the artifact's descriptors.
ModulesSuperseded bool `yaml:"modules_superseded,omitempty" json:"modules_superseded,omitempty"`
}
// Enabled reports whether p is selected for installation. Dependency demand
// overrides disabled direct bindings; an unbound package without dependents is ambient.
func (p *Package) Enabled() bool {
if p.Dependency || (len(p.Requirements) == 0 && len(p.DependencyOf) == 0) {
return true
}
for _, r := range p.Requirements {
if r.Enabled {
return true
}
}
return false
}
// PackageDirectory derives placement even for disabled or absent packages.
// MCDR packages require a wrapper runtime in the lock.
func (l *Lock) PackageDirectory(pkg *Package) (string, error) {
directory := l.Server.Directory
folder := "mods"
if pkg.Environment == server.EnvironmentMCDR {
if l.MCDR == nil {
return "", fmt.Errorf("MCDR package has no wrapper runtime")
}
directory, folder = l.MCDR.Directory, "plugins"
} else if pkg.Ecosystem == catalog.EcosystemBukkit ||
pkg.Ecosystem == catalog.EcosystemPaper {
folder = "plugins"
}
return filepath.Join(directory, folder), nil
}
// PackageDestination identifies a planned path, not filesystem existence or
// ownership. Nested filenames remain relative to the package directory.
func (l *Lock) PackageDestination(pkg *Package) (string, error) {
directory, err := l.PackageDirectory(pkg)
if err != nil {
return "", err
}
return filepath.Join(directory, pkg.Filename), nil
}
package document
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json/v2"
"fmt"
"io"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
"go.yaml.in/yaml/v4"
)
const (
ManifestFilename = "lucy.yaml"
ManifestSchemaVersion = 1
)
type Manifest struct {
SchemaVersion int `yaml:"manifest_version" json:"manifest_version" description:"Manifest schema version" example:"1"`
Name string `yaml:"name,omitempty" json:"name,omitempty" description:"Server name used to select and register the workspace" example:"survival"`
Server ManifestServer `yaml:"server" json:"server" description:"Declared Minecraft server"`
MCDR *ManifestMCDR `yaml:"mcdr,omitempty" json:"mcdr,omitempty" description:"Optional MCDReforged installation" example:"-"`
Files []TrackedFile `yaml:"files,omitempty" json:"files,omitempty" description:"Tracked files with an accepted digest and change policy" example:"-"`
}
type ManifestCore struct {
Product server.Product `yaml:"product" json:"product" description:"Server implementation product" example:"paper"`
ProductVersion version.Version `yaml:"product_version,omitempty" json:"product_version" description:"Server product version selector" example:"any"`
Repository string `yaml:"repository,omitempty" json:"repository,omitempty" description:"GitHub owner/repository for a product without built-in resolution" example:"owner/repository"`
FilePattern string `yaml:"file_pattern,omitempty" json:"file_pattern,omitempty" description:"Glob pattern matching the server artifact filename" example:"'*.jar'"`
}
type ManifestServer struct {
Minecraft version.Version `yaml:"minecraft" json:"minecraft" description:"Minecraft version the server runs" example:"1.21.4"`
Directory string `yaml:"directory,omitempty" json:"directory" description:"Workspace-relative server directory" example:"."`
Core ManifestCore `yaml:"core" json:"core" description:"Server implementation declaration"`
Java *ManifestJava `yaml:"java,omitempty" json:"java,omitempty" description:"Java version and distribution requirements"`
Packages map[catalog.Ecosystem]map[string]Requirement `yaml:"packages" json:"packages" description:"Package requirements grouped by ecosystem" example:"{}"`
}
type ManifestMCDR struct {
Directory string `yaml:"directory,omitempty" json:"directory" description:"Workspace-relative MCDReforged directory" example:"."`
Version version.Version `yaml:"version,omitempty" json:"version" description:"MCDReforged version selector" example:"latest"`
Packages map[string]Requirement `yaml:"packages" json:"packages" description:"MCDReforged plugin requirements by provider:project reference" example:"{}"`
}
type Requirement struct {
Selector version.Version `yaml:"selector,omitempty" json:"selector" description:"Version selector such as any, stable, beta, a tag, or an exact version" example:"stable"`
FilePattern string `yaml:"file_pattern,omitempty" json:"file_pattern,omitempty" description:"Glob pattern matching the upstream artifact filename" example:"'*.jar'"`
Enabled *bool `yaml:"enabled,omitempty" json:"enabled" description:"Whether the requirement is active in the resolved environment" example:"true"`
}
func (r Requirement) IsEnabled() bool { return r.Enabled == nil || *r.Enabled }
func (r *Requirement) UnmarshalYAML(n *yaml.Node) error {
if n.Kind == yaml.ScalarNode {
if n.Tag != "!!str" {
return fmt.Errorf("package selector must be a quoted string")
}
r.Selector = version.Version(n.Value)
return nil
}
if n.Kind != yaml.MappingNode {
return fmt.Errorf("package requirement must be a string or object")
}
for i := 0; i < len(n.Content); i += 2 {
switch n.Content[i].Value {
case "selector", "file_pattern", "enabled":
default:
return fmt.Errorf("unknown package requirement field %q", n.Content[i].Value)
}
}
type plain Requirement
return n.Decode((*plain)(r))
}
func (r Requirement) MarshalYAML() (any, error) {
if r.FilePattern == "" && r.IsEnabled() {
return r.Selector.String(), nil
}
type plain Requirement
return plain(r), nil
}
// ParseReference splits a versionless provider:project reference.
func ParseReference(ref string) (provider catalog.Provider, project string, err error) {
providerKey, project, ok := strings.Cut(ref, ":")
if !ok || project == "" || strings.Contains(ref, "@") {
return catalog.ProviderUnknown, "", fmt.Errorf("require provider:project reference, got %q", ref)
}
provider, ok = catalog.ParseProvider(providerKey)
if !ok || !isPackageProvider(provider) {
return catalog.ProviderUnknown, "", fmt.Errorf("unsupported package provider %q", providerKey)
}
return provider, project, nil
}
func isPackageProvider(provider catalog.Provider) bool {
switch provider {
case catalog.ProviderModrinth, catalog.ProviderCurseForge,
catalog.ProviderHangar, catalog.ProviderSpiget, catalog.ProviderMCDR:
return true
default:
return false
}
}
// NormalizeName trims and validates the user-facing name of a workspace.
// Names are visible selectors: printable text with normal interior spaces,
// without terminal control or format characters. The registry keys entries by
// canonical path, not by name.
func NormalizeName(value string) (string, error) {
name := strings.TrimSpace(value)
if name == "" {
return "", fmt.Errorf("server name must not be empty")
}
if !utf8.ValidString(name) {
return "", fmt.Errorf("server name must be valid UTF-8")
}
for _, character := range name {
if !unicode.IsPrint(character) {
return "", fmt.Errorf("server name must contain only printable characters")
}
}
return name, nil
}
// SafeRelativePath reports whether path is a workspace-relative path that
// stays inside the workspace.
func SafeRelativePath(path string) error {
if path == "" || filepath.IsAbs(path) {
return fmt.Errorf("path must be workspace-relative: %q", path)
}
clean := filepath.Clean(path)
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
return fmt.Errorf("path escapes workspace: %q", path)
}
return nil
}
func (m *Manifest) Normalize() error {
if m.SchemaVersion != ManifestSchemaVersion {
return fmt.Errorf("unsupported manifest version %d", m.SchemaVersion)
}
if m.Name != "" {
name, err := NormalizeName(m.Name)
if err != nil {
return err
}
m.Name = name
}
m.Server.Minecraft = version.Version(strings.TrimSpace(m.Server.Minecraft.String()))
if declared := m.Server.Minecraft; declared == "" || declared.CanInfer() || declared.IsInvalid() {
return fmt.Errorf("server.minecraft must specify a concrete Minecraft version")
}
m.Server.Core.Product = server.Product(strings.ToLower(strings.TrimSpace(m.Server.Core.Product.String())))
if m.Server.Core.Product == server.ProductUnknown {
return fmt.Errorf("server core product is required")
}
if product, known := server.ParseProduct(m.Server.Core.Product.String()); known {
m.Server.Core.Product = product
} else if m.Server.Core.Repository == "" {
return fmt.Errorf("unsupported server product %q; GitHub forks require core.repository", m.Server.Core.Product)
}
if m.Server.Core.ProductVersion == "" {
m.Server.Core.ProductVersion = version.Any
}
if m.Server.Directory == "" {
m.Server.Directory = "."
}
if err := SafeRelativePath(m.Server.Directory); err != nil {
return err
}
m.Server.Directory = filepath.ToSlash(filepath.Clean(m.Server.Directory))
if err := normalizeJava(&m.Server); err != nil {
return err
}
if m.Server.Packages == nil {
m.Server.Packages = map[catalog.Ecosystem]map[string]Requirement{}
}
for ecosystem, packages := range m.Server.Packages {
if !ecosystem.IsSearchable() {
return fmt.Errorf("unsupported package ecosystem %q", ecosystem)
}
for ref, requirement := range packages {
if err := normalizeRequirement(ref, &requirement); err != nil {
return err
}
packages[ref] = requirement
}
if len(packages) == 0 {
delete(m.Server.Packages, ecosystem)
}
}
if m.MCDR != nil {
if m.MCDR.Directory == "" {
m.MCDR.Directory = "."
}
if err := SafeRelativePath(m.MCDR.Directory); err != nil {
return err
}
m.MCDR.Directory = filepath.ToSlash(filepath.Clean(m.MCDR.Directory))
if m.MCDR.Version == "" {
m.MCDR.Version = version.Any
}
if m.MCDR.Packages == nil {
m.MCDR.Packages = map[string]Requirement{}
}
for ref, requirement := range m.MCDR.Packages {
if err := normalizeRequirement(ref, &requirement); err != nil {
return err
}
m.MCDR.Packages[ref] = requirement
}
}
if err := NormalizeTrackedFiles(m.Files); err != nil {
return err
}
return nil
}
func normalizeRequirement(ref string, requirement *Requirement) error {
if _, _, err := ParseReference(ref); err != nil {
return err
}
if requirement.Selector == "" {
requirement.Selector = version.Any
}
if requirement.Enabled == nil {
enabled := true
requirement.Enabled = &enabled
}
return nil
}
// DecodeManifest validates manifest bytes from a reader.
func DecodeManifest(reader io.Reader) (*Manifest, error) {
m := &Manifest{}
decoder := yaml.NewDecoder(reader)
decoder.KnownFields(true)
if err := decoder.Decode(m); err != nil {
return nil, fmt.Errorf("decode manifest: %w", err)
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
if err == nil {
return nil, fmt.Errorf("manifest must contain one YAML document")
}
return nil, fmt.Errorf("decode manifest tail: %w", err)
}
if err := m.Normalize(); err != nil {
return nil, err
}
return m, nil
}
func (m *Manifest) Fingerprint() (string, error) {
if err := m.Normalize(); err != nil {
return "", err
}
// Name is user-facing metadata: renaming a workspace must not force a
// dependency resolution. Copy shallowly so normalization still applies.
canonical := *m
canonical.Name = ""
data, err := json.Marshal(&canonical, json.Deterministic(true))
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
// ManifestSchemaURL is the hosted manifest schema. Lucy writes it into the
// schema header of every manifest it generates.
const ManifestSchemaURL = "https://lucy.lc/manifest.schema.json"
// CanonicalBytes includes field documentation and the YAML schema header.
func (m *Manifest) CanonicalBytes() ([]byte, error) {
return m.yamlBytes(YAMLOptions{SchemaURL: ManifestSchemaURL})
}
func (m *Manifest) PlainBytes() ([]byte, error) {
return m.yamlBytes(YAMLOptions{NoComments: true})
}
func (m *Manifest) yamlBytes(options YAMLOptions) ([]byte, error) {
if err := m.Normalize(); err != nil {
return nil, err
}
return NewCommenter(options).Render(m)
}
// MergeBytes writes m into existing. Comments the existing manifest carries
// survive, so a rewrite never replaces what a user wrote.
func (m *Manifest) MergeBytes(existing []byte) ([]byte, error) {
if len(bytes.TrimSpace(existing)) == 0 {
return m.CanonicalBytes()
}
if _, err := DecodeManifest(bytes.NewReader(existing)); err != nil {
return nil, err
}
if err := m.Normalize(); err != nil {
return nil, err
}
return NewCommenter(YAMLOptions{SchemaURL: ManifestSchemaURL}).Merge(existing, m)
}
package document
import (
"fmt"
"strconv"
"strings"
"github.com/mclucy/lucy/java"
"go.yaml.in/yaml/v4"
)
// JavaAuto is the value that keeps a Java field on auto. Lucy never writes it:
// an absent field means the same.
const JavaAuto = "auto"
// MinimumJava is the oldest Java major version that any Minecraft server
// release runs on.
const MinimumJava = 8
// ManifestJava overrides the Java runtime that the server runs on. A nil
// ManifestJava or a zero field keeps that part on auto: the version follows
// the Mojang advisory for the Minecraft version, and every distribution is
// accepted.
type ManifestJava struct {
Version int `yaml:"version,omitempty" json:"version,omitempty" description:"Java major version or auto to follow the Mojang advisory" example:"auto"`
Distribution java.Distribution `yaml:"distribution,omitempty" json:"distribution,omitempty" description:"Java distribution or auto to accept any distribution" example:"auto"`
}
// IsAuto reports whether j leaves both the version and the distribution on
// auto.
func (j *ManifestJava) IsAuto() bool {
return j == nil || *j == ManifestJava{}
}
// UnmarshalYAML accepts a major version or "auto" as a scalar, or a mapping
// with version and distribution keys.
func (j *ManifestJava) UnmarshalYAML(n *yaml.Node) error {
*j = ManifestJava{}
switch n.Kind {
case yaml.ScalarNode:
version, err := parseJavaVersion(n.Value)
if err != nil {
return fmt.Errorf("server.java: %w", err)
}
j.Version = version
return nil
case yaml.MappingNode:
for i := 0; i < len(n.Content); i += 2 {
key, value := n.Content[i].Value, n.Content[i+1]
if value.Kind != yaml.ScalarNode {
return fmt.Errorf("server.java.%s must be a scalar", key)
}
switch key {
case "version":
version, err := parseJavaVersion(value.Value)
if err != nil {
return fmt.Errorf("server.java.version: %w", err)
}
j.Version = version
case "distribution":
distribution, err := ParseJavaDistribution(value.Value)
if err != nil {
return fmt.Errorf("server.java.distribution: %w", err)
}
j.Distribution = distribution
default:
return fmt.Errorf("unknown server.java field %q", key)
}
}
return nil
default:
return fmt.Errorf("server.java must be a Java major version, %s, or an object", JavaAuto)
}
}
// MarshalYAML writes the short form when only the version is set.
func (j ManifestJava) MarshalYAML() (any, error) {
if j.Distribution == java.DistributionAny {
return j.Version, nil
}
type plain ManifestJava
return plain(j), nil
}
// ParseJavaDistribution reads a distribution key, where "auto" and "any" mean
// every distribution.
func ParseJavaDistribution(s string) (java.Distribution, error) {
if strings.EqualFold(strings.TrimSpace(s), JavaAuto) {
return java.DistributionAny, nil
}
distribution, ok := java.ParseDistribution(s)
if !ok {
names := make([]string, len(java.Distributions))
for i, known := range java.Distributions {
names[i] = string(known)
}
return java.DistributionAny, fmt.Errorf(
"unknown Java distribution %q; use one of %s",
s,
strings.Join(names, ", "),
)
}
return distribution, nil
}
func parseJavaVersion(s string) (int, error) {
s = strings.TrimSpace(s)
if strings.EqualFold(s, JavaAuto) {
return 0, nil
}
version, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("%q is not a Java major version or %s", s, JavaAuto)
}
if version < MinimumJava {
return 0, fmt.Errorf("major version must be %d or later, got %d", MinimumJava, version)
}
return version, nil
}
// normalizeJava drops an override that leaves everything on auto, so the
// manifest and its fingerprint stay the same as without the field.
func normalizeJava(s *ManifestServer) error {
if s.Java.IsAuto() {
s.Java = nil
return nil
}
if s.Java.Version != 0 && s.Java.Version < MinimumJava {
return fmt.Errorf("server.java.version must be %d or later", MinimumJava)
}
distribution, ok := java.ParseDistribution(string(s.Java.Distribution))
if !ok {
return fmt.Errorf("unknown Java distribution %q", s.Java.Distribution)
}
s.Java.Distribution = distribution
return nil
}
package document
import (
"fmt"
"net/url"
"sort"
"strings"
"github.com/mclucy/lucy/input"
)
// TrackedFile declares accepted contents and a change policy, not an observed file state.
type TrackedFile struct {
Path string `yaml:"path" json:"path" description:"Workspace-relative forward-slash path to the tracked file" example:"server.jar"`
Immutable bool `yaml:"immutable,omitempty" json:"immutable,omitzero" description:"Whether deviation from the accepted digest produces a warning" example:"true"`
Hash string `yaml:"hash,omitempty" json:"hash,omitempty" description:"Accepted SHA-256 digest in sha256:hex form" example:"sha256:64 lowercase hexadecimal characters"`
RecoverURL string `yaml:"recover_url,omitempty" json:"recover_url,omitempty" description:"HTTP(S) URL used to restore missing file contents" example:"https://example.com/server.jar"`
}
// NormalizeTrackedFiles makes declaration order irrelevant to manifest fingerprints.
func NormalizeTrackedFiles(files []TrackedFile) error {
seen := make(map[string]struct{}, len(files))
for i := range files {
file := &files[i]
normalized, err := input.TrackedPath(file.Path)
if err != nil {
return err
}
file.Path = normalized
key := strings.ToLower(normalized)
if _, exists := seen[key]; exists {
return fmt.Errorf("duplicate tracked path %q", normalized)
}
seen[key] = struct{}{}
if file.Immutable && file.Hash == "" {
return fmt.Errorf("immutable file %s requires an accepted hash", file.Path)
}
if file.Hash != "" {
if len(file.Hash) != 71 || !strings.HasPrefix(file.Hash, "sha256:") {
return fmt.Errorf("tracked file %s requires sha256:<64 lowercase hexadecimal characters>", file.Path)
}
for _, digit := range file.Hash[7:] {
if !((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f')) {
return fmt.Errorf("invalid accepted hash for %s", file.Path)
}
}
}
if file.RecoverURL != "" {
if file.Hash == "" {
return fmt.Errorf("recovery URL for %s requires an accepted hash", file.Path)
}
u, err := url.Parse(file.RecoverURL)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return fmt.Errorf("invalid recovery URL for %s", file.Path)
}
}
}
sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })
return nil
}
package document
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/mclucy/lucy/internal/fsutil"
)
// Codec decodes and encodes one persisted document type.
type Codec[T any] struct {
Decode func(io.Reader) (*T, error)
Encode func(*T) ([]byte, error)
// Merge writes value into an existing encoded document. It preserves the
// comments the existing document carries, so a write never replaces user
// comments. A nil Merge replaces the document with Encode.
Merge func(existing []byte, value *T) ([]byte, error)
}
// Service reads and writes one document path. It does not lock; callers that
// need a transaction own the workspace lock.
type Service[T any] struct {
path string
codec Codec[T]
mode os.FileMode
}
// NewService binds a codec to a path. New files use 0644 unless WithMode says
// otherwise.
func NewService[T any](path string, codec Codec[T]) Service[T] {
return Service[T]{path: path, codec: codec, mode: 0o644}
}
// WithMode returns a copy of the service that creates new files with mode.
func (s Service[T]) WithMode(mode os.FileMode) Service[T] {
s.mode = mode
return s
}
// WithEncoder replaces the encoder. The encoder also replaces any existing
// document, because a caller that chooses its own bytes, such as a plain
// comment-free write, does not ask to preserve the previous document.
func (s Service[T]) WithEncoder(encode func(*T) ([]byte, error)) Service[T] {
s.codec.Encode = encode
s.codec.Merge = nil
return s
}
// WithoutMerge returns a copy that always writes a fresh document.
func (s Service[T]) WithoutMerge() Service[T] {
s.codec.Merge = nil
return s
}
func (s Service[T]) Path() string { return s.path }
func (s Service[T]) Read() (*T, error) {
file, err := os.Open(s.path)
if err != nil {
return nil, err
}
value, decodeErr := s.codec.Decode(file)
return value, errors.Join(decodeErr, file.Close())
}
func (s Service[T]) Snapshot(value *T) ([]byte, error) {
return s.codec.Encode(value)
}
func (s Service[T]) Write(value *T) error {
data, err := s.writeBytes(value)
if err != nil {
return err
}
if err := fsutil.AtomicWrite(s.path, data, s.mode); err != nil {
return err
}
return nil
}
// writeBytes merges value into the document the path already holds. A missing
// document is encoded fresh.
func (s Service[T]) writeBytes(value *T) ([]byte, error) {
if s.codec.Merge == nil {
return s.Snapshot(value)
}
existing, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
return s.Snapshot(value)
}
if err != nil {
return nil, err
}
return s.codec.Merge(existing, value)
}
// writeRootBytes merges value into the document relative names inside root. A
// missing document is encoded fresh.
func (s Service[T]) writeRootBytes(root *os.Root, relative string, value *T) ([]byte, error) {
if s.codec.Merge == nil {
return s.Snapshot(value)
}
file, err := root.Open(relative)
if errors.Is(err, os.ErrNotExist) {
return s.Snapshot(value)
}
if err != nil {
return nil, err
}
existing, readErr := io.ReadAll(file)
closeErr := file.Close()
if err := errors.Join(readErr, closeErr); err != nil {
return nil, err
}
return s.codec.Merge(existing, value)
}
// Create publishes value only while the destination is still absent. A file
// that appears after the caller's check survives.
func (s Service[T]) Create(value *T) error {
data, err := s.Snapshot(value)
if err != nil {
return err
}
parent := filepath.Dir(s.path)
if err := fsutil.MkdirAllPrivate(parent); err != nil {
return fmt.Errorf("create file parent: %w", err)
}
root, err := os.OpenRoot(parent)
if err != nil {
return fmt.Errorf("open file parent: %w", err)
}
writeErr := fsutil.WriteRoot(
root,
filepath.Base(s.path),
bytes.NewReader(data),
fsutil.WriteOptions{Mode: s.mode, Replace: false},
)
if err := errors.Join(writeErr, root.Close()); err != nil {
return err
}
return nil
}
// ReadRoot reads relative inside root. The root confines every path component
// to root, so a replaced parent cannot redirect the read.
func (s Service[T]) ReadRoot(root *os.Root, relative string) (*T, error) {
file, err := root.Open(relative)
if err != nil {
return nil, err
}
value, decodeErr := s.codec.Decode(file)
return value, errors.Join(decodeErr, file.Close())
}
// WriteRoot replaces relative inside root with value and retains the
// permissions of the file it replaces.
func (s Service[T]) WriteRoot(root *os.Root, relative string, value *T) error {
return s.publishRoot(root, relative, value, true)
}
// CreateRoot publishes value at relative inside root only while the name is
// absent. A file that appears after the caller's check survives.
func (s Service[T]) CreateRoot(root *os.Root, relative string, value *T) error {
return s.publishRoot(root, relative, value, false)
}
// publishRoot keeps every operation of one publish on the same root handle.
// Callers use it while they hold the writer lock that SafePath checked.
func (s Service[T]) publishRoot(root *os.Root, relative string, value *T, replace bool) error {
var data []byte
var err error
if replace {
data, err = s.writeRootBytes(root, relative, value)
} else {
data, err = s.Snapshot(value)
}
if err != nil {
return err
}
mode := s.mode
info, statErr := root.Lstat(relative)
switch {
case statErr == nil:
if !info.Mode().IsRegular() {
return fmt.Errorf("write destination must be a regular file")
}
mode = info.Mode().Perm()
case !errors.Is(statErr, os.ErrNotExist):
return statErr
}
err = fsutil.WriteRoot(root, relative, bytes.NewReader(data), fsutil.WriteOptions{
Mode: mode,
Replace: replace,
})
if err != nil {
return err
}
return nil
}
// ManifestFile returns the service for lucy.yaml in root.
func ManifestFile(root string) Service[Manifest] {
service := NewService(filepath.Join(root, ManifestFilename), Codec[Manifest]{
Decode: DecodeManifest,
Encode: (*Manifest).CanonicalBytes,
Merge: func(existing []byte, m *Manifest) ([]byte, error) {
return m.MergeBytes(existing)
},
})
return service
}
// LockFile returns the service for lucy-lock.yaml in root.
func LockFile(root string) Service[Lock] {
service := NewService(filepath.Join(root, LockFilename), Codec[Lock]{
Decode: DecodeLock,
Encode: (*Lock).Snapshot,
Merge: func(existing []byte, l *Lock) ([]byte, error) {
return l.MergeBytes(existing)
},
})
return service
}
package document
import (
"bytes"
"errors"
"fmt"
"reflect"
"strings"
"go.yaml.in/yaml/v4"
)
const yamlSchemaDirective = "yaml-language-server:"
// YAMLOptions controls generated YAML comments.
type YAMLOptions struct {
// NoComments writes the document without generated comments.
NoComments bool
// SchemaURL adds the editor schema directive as the document header.
SchemaURL string
}
// Commenter applies the comments declared by serialized types. Descriptions
// and examples belong to the Go types, so no document has a hand-written
// commented template.
type Commenter struct {
options YAMLOptions
}
// NewCommenter configures a commenter for one document family.
func NewCommenter(options YAMLOptions) Commenter {
return Commenter{options: options}
}
// Render writes value as a fresh YAML document.
func (c Commenter) Render(value any) ([]byte, error) {
node, err := c.node(value, true)
if err != nil {
return nil, err
}
return c.marshal(node)
}
// Merge writes value into existing. Comments already present in existing are
// never replaced: new nodes adopt the comments declared by value's type, and
// blank comment slots on existing nodes are filled. A changed description
// therefore reaches new documents and new fields without rewriting the
// comments a user already has.
func (c Commenter) Merge(existing []byte, value any) ([]byte, error) {
incoming, err := c.node(value, false)
if err != nil {
return nil, err
}
var target yaml.Node
if err := yaml.Unmarshal(existing, &target); err != nil {
return nil, fmt.Errorf("decode existing yaml: %w", err)
}
root := documentRoot(&target)
if root == nil {
header := strings.TrimSpace(string(existing))
if header == "" {
return c.marshal(incoming)
}
// A document that held only comments keeps them as a document header,
// independent of the entries written below.
document := &yaml.Node{
Kind: yaml.DocumentNode,
HeadComment: header,
Content: []*yaml.Node{incoming},
}
return c.marshal(document)
}
mergeYAMLNode(root, incoming)
c.removeSchemaDirective(&target)
return c.marshal(&target)
}
// node encodes value and documents its fields. examples selects the template
// form, which also shows omitted fields as commented examples; a merge into an
// existing document documents only the fields it writes.
func (c Commenter) node(value any, examples bool) (*yaml.Node, error) {
var node yaml.Node
if err := node.Encode(value); err != nil {
return nil, err
}
if c.options.NoComments {
return &node, nil
}
t := reflect.TypeOf(value)
if t == nil {
return &node, nil
}
if err := validateYAMLDescriptions(t, map[reflect.Type]bool{}); err != nil {
return nil, err
}
if err := describeYAML(&node, t, examples); err != nil {
return nil, err
}
return &node, nil
}
func (c Commenter) marshal(node *yaml.Node) ([]byte, error) {
if node.Kind == yaml.MappingNode && len(node.Content) == 0 && node.FootComment != "" {
return commentBlock(node.FootComment), nil
}
data, err := marshalYAMLNode(node)
if err != nil {
return nil, err
}
if c.options.NoComments || c.options.SchemaURL == "" {
return data, nil
}
return append([]byte("# yaml-language-server: $schema="+c.options.SchemaURL+"\n"), data...), nil
}
// commentBlock renders a document that contains only generated examples.
func commentBlock(comment string) []byte {
var output strings.Builder
for line := range strings.SplitSeq(strings.TrimRight(comment, "\n"), "\n") {
if !strings.HasPrefix(line, "#") {
output.WriteString("# ")
}
output.WriteString(line)
output.WriteByte('\n')
}
return []byte(output.String())
}
// removeSchemaDirective drops the schema header the previous write added, so
// the next write can place the canonical one. User comments around it stay.
func (c Commenter) removeSchemaDirective(document *yaml.Node) {
if c.options.SchemaURL == "" {
return
}
var walk func(*yaml.Node)
walk = func(node *yaml.Node) {
node.HeadComment = withoutDirective(node.HeadComment)
for _, child := range node.Content {
walk(child)
}
}
walk(document)
}
func withoutDirective(comment string) string {
if comment == "" {
return ""
}
kept := make([]string, 0, strings.Count(comment, "\n")+1)
for line := range strings.SplitSeq(comment, "\n") {
text := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "#"))
if strings.HasPrefix(text, yamlSchemaDirective) {
continue
}
kept = append(kept, line)
}
return strings.Trim(strings.Join(kept, "\n"), "\n")
}
func documentRoot(node *yaml.Node) *yaml.Node {
if node.Kind == yaml.DocumentNode {
if len(node.Content) == 0 {
return nil
}
return node.Content[0]
}
if node.Kind == 0 {
return nil
}
return node
}
// mergeYAMLNode rewrites existing from incoming. Existing comments always win;
// incoming comments only fill empty slots or accompany new nodes.
func mergeYAMLNode(existing, incoming *yaml.Node) {
fillComments(existing, incoming)
if existing.Kind != incoming.Kind || existing.Tag != incoming.Tag {
replaceNode(existing, incoming)
return
}
switch existing.Kind {
case yaml.DocumentNode:
if len(existing.Content) == 0 || len(incoming.Content) == 0 {
replaceNode(existing, incoming)
return
}
mergeYAMLNode(existing.Content[0], incoming.Content[0])
case yaml.MappingNode:
if len(existing.Content) == 0 {
// An empty flow mapping such as {} carries no layout to preserve.
existing.Style = incoming.Style
}
mergeMappingNode(existing, incoming)
case yaml.SequenceNode:
if len(existing.Content) == 0 {
existing.Style = incoming.Style
}
mergeSequenceNode(existing, incoming)
case yaml.ScalarNode:
existing.Value = incoming.Value
existing.Style = incoming.Style
case yaml.AliasNode:
existing.Alias = incoming.Alias
existing.Value = incoming.Value
}
}
// mergeMappingNode keeps the existing entry order and appends new keys.
// Entries absent from incoming are removed.
func mergeMappingNode(existing, incoming *yaml.Node) {
pending := make(map[string]int, len(incoming.Content)/2)
for i := 0; i+1 < len(incoming.Content); i += 2 {
pending[incoming.Content[i].Value] = i
}
kept := make([]*yaml.Node, 0, len(existing.Content))
for i := 0; i+1 < len(existing.Content); i += 2 {
key := existing.Content[i]
position, ok := pending[key.Value]
if !ok {
continue
}
mergeYAMLNode(key, incoming.Content[position])
mergeYAMLNode(existing.Content[i+1], incoming.Content[position+1])
kept = append(kept, key, existing.Content[i+1])
delete(pending, key.Value)
}
for i := 0; i+1 < len(incoming.Content); i += 2 {
if _, ok := pending[incoming.Content[i].Value]; !ok {
continue
}
kept = append(kept, cloneYAMLNode(incoming.Content[i]), cloneYAMLNode(incoming.Content[i+1]))
}
existing.Content = kept
}
// mergeSequenceNode merges entries by a stable path key when both sequences
// have one, and by position otherwise. Declarations such as tracked files
// keep their comments when an entry is inserted or removed.
func mergeSequenceNode(existing, incoming *yaml.Node) {
if mergeSequenceByPath(existing, incoming) {
return
}
count := min(len(existing.Content), len(incoming.Content))
for i := range count {
mergeYAMLNode(existing.Content[i], incoming.Content[i])
}
if len(incoming.Content) > len(existing.Content) {
for _, node := range incoming.Content[count:] {
existing.Content = append(existing.Content, cloneYAMLNode(node))
}
return
}
existing.Content = existing.Content[:count]
}
// mergeSequenceByPath reports whether it merged the sequences. It requires
// every entry on both sides to be a mapping with a unique, non-empty string
// path, which is the identity tracked files and lock entries declare.
func mergeSequenceByPath(existing, incoming *yaml.Node) bool {
if _, ok := sequencePathIndex(existing); !ok {
return false
}
incomingIndex, ok := sequencePathIndex(incoming)
if !ok {
return false
}
kept := make([]*yaml.Node, 0, len(existing.Content))
for _, entry := range existing.Content {
path, _ := sequenceEntryPath(entry)
position, ok := incomingIndex[path]
if !ok {
continue
}
mergeYAMLNode(entry, incoming.Content[position])
kept = append(kept, entry)
delete(incomingIndex, path)
}
for _, entry := range incoming.Content {
path, _ := sequenceEntryPath(entry)
if _, ok := incomingIndex[path]; !ok {
continue
}
kept = append(kept, cloneYAMLNode(entry))
}
existing.Content = kept
return true
}
func sequencePathIndex(node *yaml.Node) (map[string]int, bool) {
if node.Kind != yaml.SequenceNode {
return nil, false
}
index := make(map[string]int, len(node.Content))
for i, entry := range node.Content {
path, ok := sequenceEntryPath(entry)
if !ok {
return nil, false
}
if _, exists := index[path]; exists {
return nil, false
}
index[path] = i
}
return index, true
}
func sequenceEntryPath(entry *yaml.Node) (string, bool) {
if entry.Kind != yaml.MappingNode {
return "", false
}
for i := 0; i+1 < len(entry.Content); i += 2 {
key, value := entry.Content[i], entry.Content[i+1]
if key.Value != "path" {
continue
}
if value.Kind != yaml.ScalarNode || value.Tag != "!!str" || value.Value == "" {
return "", false
}
return value.Value, true
}
return "", false
}
func fillComments(existing, incoming *yaml.Node) {
if existing.HeadComment == "" {
existing.HeadComment = incoming.HeadComment
}
if existing.LineComment == "" {
existing.LineComment = incoming.LineComment
}
if existing.FootComment == "" {
existing.FootComment = incoming.FootComment
}
}
// replaceNode adopts incoming's shape while keeping every comment existing
// carried.
func replaceNode(existing, incoming *yaml.Node) {
head, line, foot := existing.HeadComment, existing.LineComment, existing.FootComment
*existing = *cloneYAMLNode(incoming)
if head != "" {
existing.HeadComment = head
}
if line != "" {
existing.LineComment = line
}
if foot != "" {
existing.FootComment = foot
}
}
func cloneYAMLNode(node *yaml.Node) *yaml.Node {
copy := *node
copy.Content = make([]*yaml.Node, len(node.Content))
for i, child := range node.Content {
copy.Content[i] = cloneYAMLNode(child)
}
return ©
}
func marshalYAMLNode(node *yaml.Node) ([]byte, error) {
var output bytes.Buffer
encoder := yaml.NewEncoder(&output)
encoder.SetIndent(2)
encodeErr := encoder.Encode(node)
return output.Bytes(), errors.Join(encodeErr, encoder.Close())
}
func yamlFieldName(field reflect.StructField) string {
name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",")
return name
}
func validateYAMLDescriptions(t reflect.Type, seen map[reflect.Type]bool) error {
if t == nil || seen[t] {
return nil
}
seen[t] = true
switch t.Kind() {
case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map:
return validateYAMLDescriptions(t.Elem(), seen)
case reflect.Struct:
for i := range t.NumField() {
field := t.Field(i)
if !field.IsExported() || yamlFieldName(field) == "-" {
continue
}
if yamlFieldName(field) == "" || field.Tag.Get("description") == "" {
return fmt.Errorf("yaml field %s.%s requires a name and description", t.Name(), field.Name)
}
if err := validateYAMLDescriptions(field.Type, seen); err != nil {
return err
}
}
}
return nil
}
func describeYAML(node *yaml.Node, t reflect.Type, examples bool) error {
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
switch t.Kind() {
case reflect.Struct:
if node.Kind != yaml.MappingNode {
return nil // Custom marshalers can select a scalar shorthand.
}
var pending strings.Builder
for i := range t.NumField() {
field := t.Field(i)
if !field.IsExported() || yamlFieldName(field) == "-" {
continue
}
name := yamlFieldName(field)
index := yamlKeyIndex(node, name)
if index < 0 {
if !examples {
continue
}
example, err := yamlFieldExample(field)
if err != nil {
return err
}
if example == nil {
continue
}
mapping := &yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{{Kind: yaml.ScalarNode, Tag: "!!str", Value: name}, example},
}
data, err := marshalYAMLNode(mapping)
if err != nil {
return err
}
pending.WriteString(field.Tag.Get("description") + "\n")
pending.Write(data)
continue
}
key, child := node.Content[index], node.Content[index+1]
key.HeadComment = pending.String() + field.Tag.Get("description")
pending.Reset()
if err := describeYAML(child, field.Type, examples); err != nil {
return err
}
}
if pending.Len() != 0 {
if len(node.Content) == 0 {
node.FootComment = strings.TrimRight(pending.String(), "\n")
} else {
// A mapping's own foot comment escapes the indentation of its
// fields, while a key's foot comment stays in the mapping.
key := node.Content[len(node.Content)-2]
key.FootComment = strings.TrimRight(pending.String(), "\n")
}
}
case reflect.Map:
if node.Kind == yaml.MappingNode {
for i := 1; i < len(node.Content); i += 2 {
if err := describeYAML(node.Content[i], t.Elem(), examples); err != nil {
return err
}
}
}
case reflect.Slice, reflect.Array:
if node.Kind == yaml.SequenceNode {
for _, child := range node.Content {
if err := describeYAML(child, t.Elem(), examples); err != nil {
return err
}
}
}
}
return nil
}
func yamlKeyIndex(node *yaml.Node, name string) int {
for i := 0; i < len(node.Content); i += 2 {
if node.Content[i].Value == name {
return i
}
}
return -1
}
// yamlFieldExample builds the commented example a template shows for an
// omitted field. An example tag of "-" suppresses that example, so the field
// appears only once the document carries it.
func yamlFieldExample(field reflect.StructField) (*yaml.Node, error) {
if example, ok := field.Tag.Lookup("example"); ok {
if example == "-" {
return nil, nil
}
var node yaml.Node
if err := yaml.Unmarshal([]byte(example), &node); err != nil {
return nil, fmt.Errorf("yaml example for %s: %w", field.Name, err)
}
if len(node.Content) != 0 {
return node.Content[0], nil
}
}
t := field.Type
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
node := &yaml.Node{}
switch t.Kind() {
case reflect.Struct:
node.Kind = yaml.MappingNode
for i := range t.NumField() {
child := t.Field(i)
if !child.IsExported() || yamlFieldName(child) == "-" {
continue
}
example, err := yamlFieldExample(child)
if err != nil {
return nil, err
}
if example == nil {
continue
}
node.Content = append(node.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: yamlFieldName(child),
HeadComment: child.Tag.Get("description"),
}, example)
}
case reflect.Map:
node.Kind = yaml.MappingNode
case reflect.Slice, reflect.Array:
node.Kind = yaml.SequenceNode
default:
if err := node.Encode(reflect.Zero(t).Interface()); err != nil {
return nil, err
}
}
return node, nil
}
// Package testkit resolves the repository paths and prerequisites that the e2e
// suites run against.
//
// Each suite is a test binary under the e2e build tag, so this package is linked
// only there. The flags below replace the per-suite command-line flags that the
// suites needed while they were commands.
package testkit
import (
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
)
var (
lucyBinary = flag.String("lucy", "", "path to the Lucy binary (default: dist/lucy under the repository root)")
sandboxDir = flag.String("sandboxes", "", "directory holding generated sandboxes (default: .sandboxes under the repository root)")
)
var (
rootOnce sync.Once
rootPath string
rootErr error
)
// RepoRoot returns the repository root that contains the running suite.
func RepoRoot(t *testing.T) string {
t.Helper()
rootOnce.Do(func() { rootPath, rootErr = resolveRoot() })
if rootErr != nil {
t.Fatalf("resolve repository root: %v", rootErr)
}
return rootPath
}
// resolveRoot locates the repository from this source file. Tests run with the
// package directory as their working directory, so the source location is the
// only path that stays stable across suites.
func resolveRoot() (string, error) {
_, source, _, ok := runtime.Caller(0)
if !ok {
return "", fmt.Errorf("source location unavailable")
}
for dir := filepath.Dir(source); ; {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir, nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", fmt.Errorf("no go.mod above %s", source)
}
dir = parent
}
}
// Lucy returns the absolute path to the Lucy binary that the suites invoke. It
// fails the test when the binary is absent so a suite never reports success
// without running the CLI it verifies.
func Lucy(t *testing.T) string {
t.Helper()
path := *lucyBinary
if path == "" {
path = filepath.Join(RepoRoot(t), "dist", "lucy")
}
absolute, err := filepath.Abs(path)
if err != nil {
t.Fatalf("resolve Lucy binary: %v", err)
}
info, err := os.Stat(absolute)
if err != nil {
t.Fatalf("Lucy binary unavailable (%s): build it with `task build` first: %v", absolute, err)
}
if info.IsDir() {
t.Fatalf("Lucy binary is a directory: %s", absolute)
}
return absolute
}
// Sandboxes returns the absolute directory that holds generated sandboxes.
func Sandboxes(t *testing.T) string {
t.Helper()
path := *sandboxDir
if path == "" {
path = filepath.Join(RepoRoot(t), ".sandboxes")
}
absolute, err := filepath.Abs(path)
if err != nil {
t.Fatalf("resolve sandbox directory: %v", err)
}
return absolute
}
// Sandbox returns the generated sandbox directory for id. It fails the test when
// the directory is absent, so a scenario cannot pass by finding nothing to probe.
func Sandbox(t *testing.T, id string) string {
t.Helper()
dir := filepath.Join(Sandboxes(t), id)
info, err := os.Stat(dir)
if err != nil || !info.IsDir() {
t.Fatalf("sandbox %s is not generated (%s): run `task sandboxes:gen -- --only %s`", id, dir, id)
}
return dir
}
// CloneSandbox copies a generated sandbox into a temporary directory. Files
// hardlink when the filesystem allows it; a clone never modifies existing files.
func CloneSandbox(t *testing.T, id string) string {
t.Helper()
source := Sandbox(t, id)
root := t.TempDir()
err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
relative, err := filepath.Rel(source, path)
if err != nil {
return err
}
target := filepath.Join(root, relative)
if entry.IsDir() {
return os.MkdirAll(target, 0o755)
}
if err := os.Link(path, target); err == nil {
return nil
}
return copyFile(path, target)
})
if err != nil {
t.Fatalf("clone sandbox %s: %v", id, err)
}
return root
}
func copyFile(source, target string) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
out, err := os.Create(target)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
_ = out.Close()
return err
}
return out.Close()
}
// Command sandbox materializes server sandboxes from e2e/testdata/sandboxes.
package main
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json/v2"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/mclucy/lucy/internal/toolchain"
"go.yaml.in/yaml/v4"
)
const userAgent = "lucy-sandbox/1.0 (+https://github.com/mclucy/lucy)"
type manifest struct {
Version int `yaml:"version"`
Sandboxes []sandbox `yaml:"sandboxes"`
}
// docsRefs accepts either a scalar string or a sequence of strings in YAML.
type docsRefs []string
func (d *docsRefs) UnmarshalYAML(node *yaml.Node) error {
switch node.Kind {
case yaml.ScalarNode:
*d = []string{node.Value}
case yaml.SequenceNode:
var items []string
if err := node.Decode(&items); err != nil {
return err
}
*d = items
default:
return fmt.Errorf("docs must be a string or a list of strings")
}
return nil
}
type sandbox struct {
ID string `yaml:"id"`
Family string `yaml:"family"`
GameVersion string `yaml:"game_version"`
Description string `yaml:"description"`
Docs docsRefs `yaml:"docs,omitempty"`
// EntryPoint is the launch target a sandbox must contain. An
// installer-backed sandbox must produce it; a standalone sandbox pins it
// directly. It is relative to the sandbox root.
EntryPoint string `yaml:"entry_point,omitempty"`
Dirs []string `yaml:"dirs"`
Artifacts []artifact `yaml:"artifacts"`
}
type artifact struct {
Dest string `yaml:"dest"`
// SHA256 pins the expected content digest. Optional: without it, digest
// verification is skipped.
SHA256 string `yaml:"sha256"`
URL string `yaml:"url,omitempty"`
MojangVersion string `yaml:"mojang_version,omitempty"`
FabricMeta *fabricMeta `yaml:"fabric_meta,omitempty"`
Purpur *purpurSpec `yaml:"purpur,omitempty"`
Manual bool `yaml:"manual,omitempty"`
// Modpack marks a Modrinth pack archive. Generation writes the indexed
// server files and the pack overrides into the sandbox root instead of
// copying the archive.
Modpack bool `yaml:"modpack,omitempty"`
// InstallServer marks an official Forge/NeoForge installer. Generation
// runs it with --installServer in the directory that holds dest, after
// every artifact and fixture file has landed, so the sandbox carries the
// generated launch target rather than only copied libraries.
InstallServer bool `yaml:"install_server,omitempty"`
}
type fabricMeta struct {
Game string `yaml:"game"`
Loader string `yaml:"loader"`
Installer string `yaml:"installer"`
}
type purpurSpec struct {
Version string `yaml:"version"`
Build string `yaml:"build"`
}
type options struct {
manifestPath string
outRoot string
cacheDir string
manualDir string
fixturesRoot string
only string
force bool
list bool
}
func main() {
opts := options{}
flag.StringVar(
&opts.manifestPath,
"manifest",
"e2e/testdata/sandboxes/sandboxes.yaml",
"path to the sandboxes manifest",
)
flag.StringVar(&opts.outRoot, "out", ".sandboxes", "output root for generated sandboxes")
defaultCache, _ := os.UserCacheDir()
flag.StringVar(&opts.cacheDir, "cache", filepath.Join(defaultCache, "lucy-sandbox"), "download cache directory")
flag.StringVar(&opts.manualDir, "manual-dir", "", "directory holding manually supplied artifacts (default <cache>/manual)")
flag.StringVar(&opts.only, "only", "", "comma-separated sandbox ids to process")
flag.BoolVar(&opts.force, "force", false, "regenerate even if the output directory already exists")
flag.BoolVar(&opts.list, "list", false, "list sandboxes and exit")
flag.Parse()
if opts.manualDir == "" {
opts.manualDir = filepath.Join(opts.cacheDir, "manual")
}
opts.fixturesRoot = filepath.Join(filepath.Dir(opts.manifestPath), "fixtures")
data, err := os.ReadFile(opts.manifestPath)
if err != nil {
fatal("read manifest: %v", err)
}
var man manifest
if err := yaml.Unmarshal(data, &man); err != nil {
fatal("parse manifest: %v", err)
}
if err := validate(&man); err != nil {
fatal("invalid manifest: %v", err)
}
if opts.list {
listSandboxes(&man, opts.outRoot)
return
}
if err := run(&man, opts); err != nil {
fatal("%v", err)
}
}
func validate(man *manifest) error {
seen := map[string]bool{}
for _, sb := range man.Sandboxes {
if !filepath.IsLocal(sb.ID) || sb.ID == "." {
return fmt.Errorf("invalid sandbox id %q: must be a local path below the output root", sb.ID)
}
if seen[sb.ID] {
return fmt.Errorf("duplicate sandbox id %q", sb.ID)
}
seen[sb.ID] = true
installers := 0
for _, art := range sb.Artifacts {
if art.Dest == "" {
return fmt.Errorf("%s: artifact without dest", sb.ID)
}
if art.SHA256 != "" {
if len(art.SHA256) != 64 {
return fmt.Errorf("%s/%s: sha256 must be 64 hex chars", sb.ID, art.Dest)
}
if _, err := hex.DecodeString(art.SHA256); err != nil {
return fmt.Errorf("%s/%s: bad sha256: %v", sb.ID, art.Dest, err)
}
}
kinds := 0
for _, set := range []bool{art.URL != "", art.MojangVersion != "", art.FabricMeta != nil, art.Purpur != nil, art.Manual} {
if set {
kinds++
}
}
if kinds != 1 {
return fmt.Errorf(
"%s/%s: exactly one of url, mojang_version, fabric_meta, purpur, manual required",
sb.ID, art.Dest,
)
}
if art.Modpack && (art.URL == "" || art.SHA256 == "") {
return fmt.Errorf("%s/%s: modpack requires url and sha256", sb.ID, art.Dest)
}
if art.InstallServer {
installers++
if art.Modpack {
return fmt.Errorf("%s/%s: an installer cannot be a modpack", sb.ID, art.Dest)
}
if !strings.HasSuffix(strings.ToLower(art.Dest), ".jar") {
return fmt.Errorf("%s/%s: installer dest must be a jar", sb.ID, art.Dest)
}
}
}
if installers > 1 {
return fmt.Errorf("%s: at most one install_server artifact is supported", sb.ID)
}
hasEntryPoint := sb.EntryPoint != ""
if installers == 1 && !hasEntryPoint {
return fmt.Errorf("%s: install_server requires entry_point", sb.ID)
}
if hasEntryPoint {
entryPoint := filepath.FromSlash(sb.EntryPoint)
if !filepath.IsLocal(entryPoint) || entryPoint == "." {
return fmt.Errorf("%s: entry_point must be a local path below the sandbox root", sb.ID)
}
}
}
return nil
}
func listSandboxes(man *manifest, outRoot string) {
fmt.Printf("%-24s %-14s %-10s %-10s %s\n", "ID", "FAMILY", "GAME", "STATE", "DESCRIPTION")
for _, sb := range man.Sandboxes {
state := "missing"
if _, err := os.Stat(filepath.Join(outRoot, sb.ID)); err == nil {
state = "generated"
}
manual := ""
for _, art := range sb.Artifacts {
if art.Manual {
manual = " (manual)"
break
}
}
fmt.Printf("%-24s %-14s %-10s %-10s %s%s\n",
sb.ID, sb.Family, sb.GameVersion, state, sb.Description, manual)
}
}
func run(man *manifest, opts options) error {
selected := map[string]bool{}
if opts.only != "" {
for id := range strings.SplitSeq(opts.only, ",") {
selected[strings.TrimSpace(id)] = true
}
}
if err := os.MkdirAll(opts.cacheDir, 0o755); err != nil {
return err
}
var failed []string
for _, sb := range man.Sandboxes {
if len(selected) > 0 && !selected[sb.ID] {
continue
}
if err := generateSandbox(sb, opts); err != nil {
fmt.Fprintf(os.Stderr, "[FAIL] %s: %v\n", sb.ID, err)
failed = append(failed, sb.ID)
continue
}
}
if len(failed) > 0 {
return fmt.Errorf("failed sandboxes: %s", strings.Join(failed, ", "))
}
return nil
}
type resolvedArtifact struct {
artifact
cachedPath string
}
func generateSandbox(sb sandbox, opts options) error {
outDir := filepath.Join(opts.outRoot, sb.ID)
if _, err := os.Stat(outDir); err == nil && !opts.force {
fmt.Printf("[SKIP] %s (exists; use --force)\n", sb.ID)
return nil
}
resolvedArtifacts := make([]resolvedArtifact, 0, len(sb.Artifacts))
for _, art := range sb.Artifacts {
path, err := ensureCached(sb.ID, art, opts)
if err != nil {
return fmt.Errorf("artifact %s: %w", art.Dest, err)
}
resolvedArtifacts = append(resolvedArtifacts, resolvedArtifact{artifact: art, cachedPath: path})
fmt.Printf("[OK] %s: %s\n", sb.ID, art.Dest)
}
if err := os.MkdirAll(opts.outRoot, 0o755); err != nil {
return fmt.Errorf("create output root: %w", err)
}
stage, err := os.MkdirTemp(opts.outRoot, ".sandbox-*")
if err != nil {
return fmt.Errorf("create staging directory: %w", err)
}
if err := os.Chmod(stage, 0o755); err != nil {
return err
}
published := false
defer func() {
if !published {
_ = os.RemoveAll(stage)
}
}()
for _, dir := range sb.Dirs {
if err := os.MkdirAll(filepath.Join(stage, dir), 0o755); err != nil {
return err
}
}
for _, ra := range resolvedArtifacts {
if ra.Modpack {
if err := materializeModpack(ra.cachedPath, stage, opts); err != nil {
return fmt.Errorf("materialize modpack %s: %w", ra.Dest, err)
}
continue
}
dest := filepath.Join(stage, ra.Dest)
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
if err := copyFile(ra.cachedPath, dest); err != nil {
return fmt.Errorf("install %s: %w", ra.Dest, err)
}
}
fixturesDir := filepath.Join(opts.fixturesRoot, sb.ID)
if _, err := os.Stat(fixturesDir); err == nil {
if err := copyTree(fixturesDir, stage); err != nil {
return fmt.Errorf("copy fixtures: %w", err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
for _, ra := range resolvedArtifacts {
if !ra.InstallServer {
continue
}
if err := installServer(stage, ra); err != nil {
return fmt.Errorf("%s: %w", sb.ID, err)
}
fmt.Printf("[INST] %s: %s\n", sb.ID, ra.Dest)
}
if sb.EntryPoint != "" {
if err := verifyEntryPoint(stage, sb.EntryPoint); err != nil {
return fmt.Errorf("%s: %w", sb.ID, err)
}
}
// Publish only a complete, validated fixture. A failed download or
// installer run leaves no directory that a later run would skip.
if err := os.RemoveAll(outDir); err != nil {
return fmt.Errorf("replace %s: %w", outDir, err)
}
if err := os.MkdirAll(filepath.Dir(outDir), 0o755); err != nil {
return err
}
if err := os.Rename(stage, outDir); err != nil {
return fmt.Errorf("publish %s: %w", outDir, err)
}
published = true
fmt.Printf("[GEN] %s -> %s\n", sb.ID, outDir)
return nil
}
// installerJavaMinimum is the oldest runtime that the pinned Forge and
// NeoForge installers support. The generator only runs the installer; it never
// launches the server, so the game version's own Java advisory does not apply.
const installerJavaMinimum = 17
// installServer runs one pinned loader installer in the directory that holds
// it. The installer is the only source of the generated argument sidecars,
// shim, and patched server jar; a copied universal jar is a runtime library,
// not a launch target.
func installServer(outDir string, ra resolvedArtifact) error {
java, err := installerJava()
if err != nil {
return fmt.Errorf("installer %s: %w", ra.Dest, err)
}
target := filepath.Dir(filepath.Join(outDir, ra.Dest))
// Run the copied installer under its fixture name so its own log and any
// path it derives match a real `java -jar <installer> --installServer .`.
cmd := exec.Command(java, "-jar", filepath.Base(ra.Dest), "--installServer", ".")
cmd.Dir = target
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := cmd.Run(); err != nil {
return fmt.Errorf("installer %s failed: %w\n%s", ra.Dest, err, outputTail(output.String()))
}
return nil
}
// installerJava picks the oldest installed runtime that the installers
// support. Preferring the oldest qualifying major keeps legacy installers off
// newer class-file versions while still accepting the current JDK.
func installerJava() (string, error) {
inventory, err := toolchain.DiscoverJava(context.Background())
if err != nil {
return "", fmt.Errorf("discover Java runtimes: %w", err)
}
var chosen *toolchain.JavaInstallation
for index := range inventory.Java {
runtime := &inventory.Java[index]
if runtime.Major < installerJavaMinimum {
continue
}
if chosen == nil || runtime.Major < chosen.Major {
chosen = runtime
}
}
if chosen == nil {
return "", fmt.Errorf(
"no Java %d+ runtime found: install a JDK %d or newer and put java on PATH or set JAVA_HOME",
installerJavaMinimum, installerJavaMinimum,
)
}
return chosen.Java, nil
}
func outputTail(output string) string {
const limit = 8 << 10
output = strings.TrimSpace(output)
if len(output) <= limit {
return output
}
return "..." + output[len(output)-limit:]
}
// verifyEntryPoint proves that an installer produced its declared launch
// target, or that a pinned standalone launch jar is present and bootable.
func verifyEntryPoint(outDir, entryPoint string) error {
path := filepath.Join(outDir, filepath.FromSlash(entryPoint))
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("launch target %s is missing: %w", entryPoint, err)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("launch target %s is not a regular file", entryPoint)
}
if info.Size() == 0 {
return fmt.Errorf("launch target %s is empty", entryPoint)
}
if !strings.HasSuffix(strings.ToLower(entryPoint), ".jar") {
return nil
}
archive, err := zip.OpenReader(path)
if err != nil {
return fmt.Errorf("launch target %s is not a readable jar: %w", entryPoint, err)
}
defer func() { _ = archive.Close() }()
if len(archive.File) == 0 {
return fmt.Errorf("launch target %s is an empty jar", entryPoint)
}
manifest, err := readZipEntry(&archive.Reader, "META-INF/MANIFEST.MF")
if err != nil {
return fmt.Errorf("launch target %s has no manifest: %w", entryPoint, err)
}
if manifestMainClass(manifest) == "" {
return fmt.Errorf("launch target %s declares no Main-Class", entryPoint)
}
return nil
}
// manifestMainClass returns the declared Main-Class of a jar manifest, or ""
// when the attribute is absent. The manifest format is line oriented; a
// Main-Class value is short enough that Forge and NeoForge never fold it.
func manifestMainClass(manifest []byte) string {
for line := range strings.SplitSeq(string(manifest), "\n") {
key, value, ok := strings.Cut(strings.TrimSuffix(line, "\r"), ":")
if !ok || !strings.EqualFold(strings.TrimSpace(key), "Main-Class") {
continue
}
return strings.TrimSpace(value)
}
return ""
}
// modpackIndex is the subset of modrinth.index.json that server generation
// needs. Client-only entries carry env.server "unsupported".
type modpackIndex struct {
Files []struct {
Path string `json:"path"`
Hashes struct {
SHA512 string `json:"sha512"`
} `json:"hashes"`
Env struct {
Server string `json:"server"`
} `json:"env"`
Downloads []string `json:"downloads"`
} `json:"files"`
}
// materializeModpack writes the server side of a Modrinth pack into outDir:
// every indexed server file lands at its declared path, then overrides and
// server-overrides unpack at the root.
func materializeModpack(packPath, outDir string, opts options) error {
archive, err := zip.OpenReader(packPath)
if err != nil {
return err
}
defer func() { _ = archive.Close() }()
data, err := readZipEntry(&archive.Reader, "modrinth.index.json")
if err != nil {
return fmt.Errorf("read pack index: %w", err)
}
var index modpackIndex
if err := json.Unmarshal(data, &index); err != nil {
return fmt.Errorf("decode pack index: %w", err)
}
for _, file := range index.Files {
// Create+ 6.0.0 Alpha f marks one client-only jar as "unknown" for both
// sides, which the pack format does not define. Skip it until the
// upstream metadata is corrected: the jar crashes a dedicated server.
// https://github.com/Sshmoob/Create-Plus/issues/80
if file.Env.Server == "unsupported" || file.Env.Server == "unknown" {
continue
}
if len(file.Downloads) == 0 {
return fmt.Errorf("pack file %s has no download", file.Path)
}
cached, err := fetchDigest(file.Downloads[0], file.Hashes.SHA512, opts)
if err != nil {
return fmt.Errorf("pack file %s: %w", file.Path, err)
}
if err := writePackFile(outDir, file.Path, func(dest string) error {
return copyFile(cached, dest)
}); err != nil {
return fmt.Errorf("pack file %s: %w", file.Path, err)
}
}
// The pack format applies generic overrides first, then server overrides.
// Archive order carries no layer meaning, so the two prefixes get their own
// pass; a server file for a path always wins.
for _, prefix := range []string{"overrides/", "server-overrides/"} {
for _, entry := range archive.File {
name, ok := strings.CutPrefix(entry.Name, prefix)
if !ok || name == "" {
continue
}
if err := writePackFile(outDir, name, func(dest string) error {
if entry.FileInfo().IsDir() {
return os.MkdirAll(dest, 0o755)
}
return extractZipEntry(entry, dest)
}); err != nil {
return err
}
}
}
return nil
}
// writePackFile resolves a pack-relative path below outDir, creates its parent
// directory, then hands the destination to write. Pack paths use forward
// slashes and must stay inside the sandbox root, so this is the single guard
// between archive content and the filesystem.
func writePackFile(outDir, name string, write func(string) error) error {
relative := filepath.FromSlash(name)
if relative == "." || strings.Contains(name, `\`) || !filepath.IsLocal(relative) {
return fmt.Errorf("unsafe pack path %q", name)
}
dest := filepath.Join(outDir, relative)
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
return write(dest)
}
func readZipEntry(reader *zip.Reader, name string) ([]byte, error) {
file, err := reader.Open(name)
if err != nil {
return nil, err
}
defer func() { _ = file.Close() }()
return io.ReadAll(file)
}
func extractZipEntry(entry *zip.File, dest string) error {
source, err := entry.Open()
if err != nil {
return err
}
defer func() { _ = source.Close() }()
mode := entry.Mode().Perm()
if mode == 0 {
mode = 0o644
}
target, err := os.OpenFile(dest, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
if err != nil {
return err
}
if _, err := io.Copy(target, source); err != nil {
_ = target.Close()
return err
}
return target.Close()
}
// fetchDigest caches one pack file under its sha512 digest. The digest is
// mandatory: pack indexes always publish one, and it is the only integrity
// check for downloads that do not share the sandbox manifest.
func fetchDigest(url, sha512Hex string, opts options) (string, error) {
key := strings.ToLower(sha512Hex)
if len(key) != 128 {
return "", fmt.Errorf("pack file has no usable sha512")
}
if _, err := hex.DecodeString(key); err != nil {
return "", fmt.Errorf("bad sha512: %w", err)
}
cached := filepath.Join(opts.cacheDir, key[:2], key)
if _, err := os.Stat(cached); err == nil {
return cached, nil
}
if err := os.MkdirAll(filepath.Dir(cached), 0o755); err != nil {
return "", err
}
tmp, err := os.CreateTemp(opts.cacheDir, "modpack-*")
if err != nil {
return "", err
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }()
if err := downloadTo(url, tmp); err != nil {
_ = tmp.Close()
return "", err
}
if err := tmp.Close(); err != nil {
return "", err
}
digest, err := fileSHA512(tmpName)
if err != nil {
return "", err
}
if digest != key {
return "", fmt.Errorf("sha512 mismatch: got %s want %s", digest, key)
}
if err := os.Rename(tmpName, cached); err != nil {
return "", err
}
return cached, nil
}
func fileSHA512(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = file.Close() }()
h := sha512.New()
if _, err := io.Copy(h, file); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func ensureCached(sandboxID string, art artifact, opts options) (string, error) {
key := strings.ToLower(art.SHA256)
if key == "" {
sum := sha256.Sum256([]byte(sourceDescriptor(sandboxID, art)))
key = "src-" + hex.EncodeToString(sum[:])
}
cached := filepath.Join(opts.cacheDir, key[:2], key)
if _, err := os.Stat(cached); err == nil {
return cached, nil
}
if err := os.MkdirAll(filepath.Dir(cached), 0o755); err != nil {
return "", err
}
tmp, err := os.CreateTemp(opts.cacheDir, "download-*")
if err != nil {
return "", err
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }()
switch {
case art.Manual:
_ = tmp.Close()
source := filepath.Join(opts.manualDir, sandboxID, filepath.Base(art.Dest))
if _, err := os.Stat(source); err != nil {
if art.SHA256 == "" {
return "", fmt.Errorf("manual artifact missing: place the file at %s", source)
}
return "", fmt.Errorf(
"manual artifact missing: place the file at %s (expected sha256 %s)",
source, key,
)
}
if err := copyFile(source, tmpName); err != nil {
return "", err
}
case art.URL != "":
if err := downloadTo(art.URL, tmp); err != nil {
_ = tmp.Close()
return "", err
}
_ = tmp.Close()
case art.MojangVersion != "":
url, err := resolveMojangServer(art.MojangVersion)
if err != nil {
_ = tmp.Close()
return "", err
}
if err := downloadTo(url, tmp); err != nil {
_ = tmp.Close()
return "", err
}
_ = tmp.Close()
case art.FabricMeta != nil:
url := fmt.Sprintf(
"https://meta.fabricmc.net/v2/versions/loader/%s/%s/%s/server/jar",
art.FabricMeta.Game, art.FabricMeta.Loader, art.FabricMeta.Installer,
)
if err := downloadTo(url, tmp); err != nil {
_ = tmp.Close()
return "", err
}
_ = tmp.Close()
case art.Purpur != nil:
url := fmt.Sprintf(
"https://api.purpurmc.org/v2/purpur/%s/%s/download",
art.Purpur.Version, art.Purpur.Build,
)
if err := downloadTo(url, tmp); err != nil {
_ = tmp.Close()
return "", err
}
_ = tmp.Close()
}
if art.SHA256 != "" {
digest, err := fileSHA256(tmpName)
if err != nil {
return "", err
}
if digest != key {
return "", fmt.Errorf("sha256 mismatch: got %s want %s", digest, key)
}
}
if err := os.Rename(tmpName, cached); err != nil {
return "", err
}
return cached, nil
}
// sourceDescriptor names where an artifact's bytes come from. Digest-less
// artifacts key their cache entries by the hash of this descriptor, prefixed
// src- to keep them disjoint from content digests.
func sourceDescriptor(sandboxID string, art artifact) string {
switch {
case art.URL != "":
return art.URL
case art.MojangVersion != "":
return "mojang:" + art.MojangVersion
case art.FabricMeta != nil:
return fmt.Sprintf(
"fabric:%s/%s/%s",
art.FabricMeta.Game, art.FabricMeta.Loader, art.FabricMeta.Installer,
)
case art.Purpur != nil:
return fmt.Sprintf("purpur:%s/%s", art.Purpur.Version, art.Purpur.Build)
default:
return "manual:" + sandboxID + "/" + filepath.Base(art.Dest)
}
}
func resolveMojangServer(version string) (string, error) {
metaURL := "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
var manifestResp struct {
Versions []struct {
ID string `json:"id"`
URL string `json:"url"`
} `json:"versions"`
}
if err := getJSON(metaURL, &manifestResp); err != nil {
return "", fmt.Errorf("mojang manifest: %w", err)
}
var entryURL string
for _, v := range manifestResp.Versions {
if v.ID == version {
entryURL = v.URL
break
}
}
if entryURL == "" {
return "", fmt.Errorf("mojang version %q not found", version)
}
var versionJSON struct {
Downloads map[string]struct {
URL string `json:"url"`
} `json:"downloads"`
}
if err := getJSON(entryURL, &versionJSON); err != nil {
return "", fmt.Errorf("mojang version %s: %w", version, err)
}
server, ok := versionJSON.Downloads["server"]
if !ok || server.URL == "" {
return "", fmt.Errorf("mojang version %s has no server download", version)
}
return server.URL, nil
}
func getJSON(url string, target any) error {
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Get(url)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("GET %s: HTTP %d", url, resp.StatusCode)
}
return json.UnmarshalRead(resp.Body, target)
}
func downloadTo(url string, tmp *os.File) error {
client := &http.Client{Timeout: 5 * time.Minute}
var lastErr error
for range 3 {
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return err
}
if err := tmp.Truncate(0); err != nil {
return err
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err == nil {
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
lastErr = fmt.Errorf("GET %s: HTTP %d", url, resp.StatusCode)
continue
}
_, err = io.Copy(tmp, resp.Body)
_ = resp.Body.Close()
if err == nil {
return nil
}
lastErr = err
} else {
lastErr = err
}
}
return lastErr
}
func fileSHA256(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = file.Close() }()
h := sha256.New()
if _, err := io.Copy(h, file); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
tmpDst := dst + ".sandbox-tmp"
out, err := os.Create(tmpDst)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
_ = out.Close()
_ = os.Remove(tmpDst)
return err
}
if err := out.Close(); err != nil {
_ = os.Remove(tmpDst)
return err
}
return os.Rename(tmpDst, dst)
}
func copyTree(srcRoot, dstRoot string) error {
return filepath.WalkDir(srcRoot, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(srcRoot, path)
if err != nil {
return err
}
target := filepath.Join(dstRoot, rel)
if d.IsDir() {
return os.MkdirAll(target, 0o755)
}
return copyFile(path, target)
})
}
func fatal(format string, args ...any) {
fmt.Fprintf(os.Stderr, "sandbox: "+format+"\n", args...)
os.Exit(1)
}
package filetrack
import (
"bytes"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/cas"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/workspaceguard"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
)
// Service executes file tracking with an explicit HTTP client and diagnostic
// logger. The client is used only for declared recovery sources; tracking,
// storage, and transaction safety stay local.
type Service struct {
client *http.Client
logger *log.Logger
}
// NewService constructs a file tracking service. client performs recovery
// downloads; logger records reclamation and recovery diagnostics.
func NewService(client *http.Client, logger *log.Logger) *Service {
return &Service{client: client, logger: logger}
}
// Run prepares every selected file before making any accepted-state change.
func (s *Service) Run(ctx context.Context, root string, request Request) (result Result, resultErr error) {
if err := validateRequest(request); err != nil {
return result, err
}
result.Event.Operation = request.Operation
root, err := filepath.Abs(root)
if err != nil {
return result, err
}
lock, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return result, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := RecoverLocked(root, s.logger); err != nil {
return result, err
}
files, err := os.OpenRoot(root)
if err != nil {
return result, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
store, err := cas.New(filepath.Join(root, ".lucy"))
if err != nil {
return result, err
}
defer func() { resultErr = errors.Join(resultErr, store.Close()) }()
if err := store.Cleanup(); err != nil {
return result, err
}
events, historySize, err := readHistory(root, true)
if err != nil {
return result, err
}
beforeManifest, err := capture(root, files, store, documentpkg.ManifestFilename)
if err != nil {
return result, err
}
if !beforeManifest.Exists {
return result, fmt.Errorf("no %s in this workspace; run lucy init first", documentpkg.ManifestFilename)
}
beforeLock, err := capture(root, files, store, documentpkg.LockFilename)
if err != nil {
return result, err
}
reader, err := imageReader(store, beforeManifest)
if err != nil {
return result, err
}
existingManifest, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if err := errors.Join(readErr, closeErr); err != nil {
return result, err
}
document, err := documentpkg.DecodeManifest(bytes.NewReader(existingManifest))
if err != nil {
return result, err
}
own := make(map[string]struct{})
record := func(state image) {
if state.Exists && state.Hash != "" {
own[state.Hash] = struct{}{}
}
}
record(beforeManifest)
record(beforeLock)
defer func() {
reclaimed, sweepErr := reclaimObjects(root, files, store, own)
if sweepErr != nil {
s.logger.Warn(sweepErr)
}
result.Reclaimed = reclaimed
if reclaimed.Objects > 0 {
s.logger.Info(
"reclaimed unreferenced objects",
"objects", reclaimed.Objects,
"bytes", reclaimed.Bytes,
)
}
}()
if err := workspaceguard.CheckInactive(root, "changing tracked files"); err != nil {
return result, err
}
var locked *documentpkg.Lock
currentLock := false
existingLock := []byte{}
if beforeLock.Exists {
reader, err := imageReader(store, beforeLock)
if err != nil {
return result, err
}
existingLock, readErr = io.ReadAll(reader)
closeErr := reader.Close()
if err := errors.Join(readErr, closeErr); err != nil {
return result, err
}
locked, err = documentpkg.DecodeLock(bytes.NewReader(existingLock))
if err != nil {
return result, err
}
fingerprint, err := document.Fingerprint()
if err != nil {
return result, err
}
currentLock = locked.ManifestFingerprint == fingerprint
}
switch request.Operation {
case Track, Untrack:
var exact map[string]struct{}
if request.Operation == Untrack {
exact = make(map[string]struct{}, len(document.Files))
for _, file := range document.Files {
exact[file.Path] = struct{}{}
}
}
request.Paths, result.SkippedDirectories, err = expandFilePaths(
files,
request.Paths,
exact,
)
if err != nil {
return result, err
}
case Update, Recover, Lock, Unlock:
if !request.All {
var skipped []string
request.Paths, skipped, err = expandDeclaredPaths(
files,
document.Files,
request.Paths,
request.Operation,
)
if err != nil {
return result, err
}
result.Skipped = append(result.Skipped, skipped...)
}
}
selected, skipped, err := selectFiles(document.Files, request)
if err != nil {
return result, err
}
result.Skipped = append(result.Skipped, skipped...)
if len(selected) == 0 {
return result, nil
}
event := Event{Sequence: uint64(len(events) + 1), Time: time.Now().UTC(), ID: rand.Text(), Operation: request.Operation, Changes: make([]Change, 0, len(selected))}
txn := transaction{HistorySize: historySize}
nextFiles := slices.Clone(document.Files)
for _, path := range selected {
if err := ctx.Err(); err != nil {
return result, err
}
before, err := capture(root, files, store, path)
if err != nil {
return result, err
}
index := slices.IndexFunc(nextFiles, func(file documentpkg.TrackedFile) bool { return file.Path == path })
var previous *documentpkg.TrackedFile
if index >= 0 {
copy := nextFiles[index]
previous = ©
}
change, after, err := prepare(ctx, s.client, store, events, event.Sequence, request, path, previous, before)
if err != nil {
return result, err
}
event.Changes = append(event.Changes, change)
txn.Mutations = append(txn.Mutations, mutation{Path: path, Before: before, After: after})
if change.After == nil {
nextFiles = slices.Delete(nextFiles, index, index+1)
} else if index >= 0 {
nextFiles[index] = *change.After
} else {
nextFiles = append(nextFiles, *change.After)
}
}
document.Files = nextFiles
if err := document.Normalize(); err != nil {
return result, err
}
if err := ValidateOwnership(root, document.Files, locked); err != nil {
return result, err
}
raw, err := document.MergeBytes(existingManifest)
if err != nil {
return result, err
}
afterManifest, err := storeBytes(store, raw, os.FileMode(beforeManifest.Mode))
if err != nil {
return result, err
}
record(afterManifest)
txn.Mutations = append(txn.Mutations, mutation{Path: documentpkg.ManifestFilename, Before: beforeManifest, After: afterManifest})
if locked != nil {
locked.Files = slices.Clone(document.Files)
if currentLock {
locked.ManifestFingerprint, err = document.Fingerprint()
if err != nil {
return result, err
}
}
if err := locked.Validate(); err != nil {
return result, err
}
raw, err := locked.MergeBytes(existingLock)
if err != nil {
return result, err
}
afterLock, err := storeBytes(store, raw, os.FileMode(beforeLock.Mode))
if err != nil {
return result, err
}
record(afterLock)
txn.Mutations = append(txn.Mutations, mutation{Path: documentpkg.LockFilename, Before: beforeLock, After: afterLock})
}
txn.Event = event
if err := ctx.Err(); err != nil {
return result, err
}
if err := commit(root, files, store, txn); err != nil {
return result, err
}
result.Event = event
return result, nil
}
func validateRequest(request Request) error {
switch request.Operation {
case Track, Untrack, Update, Recover, Revert, Lock, Unlock:
default:
return fmt.Errorf("unknown file operation %q", request.Operation)
}
if request.All {
if len(request.Paths) > 0 || (request.Operation != Update && request.Operation != Recover) {
return fmt.Errorf("--all requires update or recover without a path")
}
} else if len(request.Paths) == 0 {
return fmt.Errorf("file operation requires a path")
}
if request.FromSource && request.Operation != Update {
return fmt.Errorf("--from-source requires update")
}
if (request.Immutable || request.NoHash || request.RecoverURL != "") && request.Operation != Track {
return fmt.Errorf("tracking choices require track")
}
if request.NoHash && (request.Immutable || request.RecoverURL != "") {
return fmt.Errorf("--no-hash conflicts with --immutable and --recover-url")
}
if (request.Hash != "" || request.Revision != 0) && request.Operation != Revert {
return fmt.Errorf("revision targets require revert")
}
if request.Hash != "" && request.Revision != 0 {
return fmt.Errorf("hash and --revision are mutually exclusive")
}
return nil
}
func selectFiles(files []documentpkg.TrackedFile, request Request) ([]string, []string, error) {
if !request.All {
declared := make(map[string]struct{}, len(files))
for _, file := range files {
declared[file.Path] = struct{}{}
}
selected := make([]string, 0, len(request.Paths))
skipped := make([]string, 0)
seen := make(map[string]struct{}, len(request.Paths))
for _, raw := range request.Paths {
path, err := input.TrackedPath(raw)
if err != nil {
return nil, nil, err
}
if _, exists := seen[path]; exists {
continue
}
seen[path] = struct{}{}
_, tracked := declared[path]
if request.Operation == Track && tracked {
return nil, nil, fmt.Errorf("file %s is already tracked; use update", path)
}
if request.Operation != Track && !tracked {
if request.Operation == Untrack {
skipped = append(skipped, path)
continue
}
return nil, nil, fmt.Errorf("file %s is not tracked", path)
}
selected = append(selected, path)
}
return selected, skipped, nil
}
selected, skipped := make([]string, 0, len(files)), make([]string, 0)
for _, file := range files {
if (request.FromSource && file.RecoverURL == "") || (request.Operation == Recover && file.Hash == "") {
skipped = append(skipped, file.Path)
continue
}
selected = append(selected, file.Path)
}
return selected, skipped, nil
}
func prepare(ctx context.Context, client *http.Client, store *cas.Store, events []Event, sequence uint64, request Request, path string, previous *documentpkg.TrackedFile, before image) (Change, image, error) {
change := Change{Path: path, Before: previous}
after := before
file := documentpkg.TrackedFile{Path: path}
if previous != nil {
file = *previous
change.Revision = currentRevision(events, path, file.Hash).sequence
}
if before.Exists {
change.BackupHash, change.BackupMode = before.Hash, before.Mode
}
switch request.Operation {
case Track:
if !before.Exists {
return change, after, fmt.Errorf("cannot track missing file %s", path)
}
file.Immutable, file.RecoverURL = request.Immutable, request.RecoverURL
if !request.NoHash {
file.Hash = before.Hash
}
case Untrack:
return change, after, nil
case Update:
if request.FromSource {
var err error
after, err = sourceImage(ctx, client, store, file, true, false)
if err != nil {
return change, after, err
}
if before.Exists {
after.Mode = before.Mode
}
} else if !before.Exists {
return change, after, fmt.Errorf("cannot accept missing file %s", path)
}
file.Hash = after.Hash
case Recover:
if file.Hash == "" {
return change, after, fmt.Errorf("file %s has no accepted hash to recover", path)
}
var err error
after, err = sourceImage(ctx, client, store, file, false, false)
if err != nil {
return change, after, err
}
if revision := currentRevision(events, path, file.Hash); revision.mode != 0 {
after.Mode = uint32(revision.mode.Perm())
} else if before.Exists {
after.Mode = before.Mode
}
case Revert:
if file.Hash == "" {
return change, after, fmt.Errorf("file %s has no accepted revision", path)
}
revision, err := revertRevision(events, path, file.Hash, request.Hash, request.Revision)
if err != nil {
return change, after, err
}
if err := verifyObject(store, revision.hash); err != nil {
return change, after, fmt.Errorf("historical backup unavailable for %s: %w", path, err)
}
file.Hash = revision.hash
after = image{Exists: true, Hash: revision.hash, Mode: uint32(revision.mode.Perm())}
if after.Mode == 0 {
after.Mode = 0o600
}
change.Revision = revision.sequence
case Lock:
if !before.Exists {
return change, after, fmt.Errorf("cannot lock missing file %s", path)
}
file.Immutable, file.Hash = true, before.Hash
case Unlock:
file.Immutable = false
}
change.After = &file
if (request.Operation == Track || request.Operation == Update || request.Operation == Lock) && file.Hash != "" {
change.Parent = change.Revision
change.Revision = sequence
change.Accepted = true
change.Mode = after.Mode
}
return change, after, nil
}
func verifyObject(store *cas.Store, hash string) (resultErr error) {
digest, err := cas.ParseDigest(hash)
if err != nil {
return err
}
reader, err := store.Open(digest)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, reader.Close()) }()
_, err = io.Copy(io.Discard, reader)
return err
}
// recoveryTimeout bounds one recovery download end to end, so a source that
// accepts the connection and stops responding cannot hold up an installation.
const recoveryTimeout = 5 * time.Minute
// maxRecoveryBytes bounds one recovery download. Tracked files are working
// files, so a longer stream is a misconfigured or hostile source.
const maxRecoveryBytes = 64 << 20
// cappedReader fails a stream that exceeds its byte budget. Truncating instead
// would store short content, which commits as an object when no accepted digest
// pins the contents.
type cappedReader struct {
reader io.Reader
left int64
}
func (c *cappedReader) Read(p []byte) (int, error) {
n, err := c.reader.Read(p)
c.left -= int64(n)
if c.left < 0 {
return n, fmt.Errorf("stream exceeds %d bytes", maxRecoveryBytes)
}
return n, err
}
func sourceImage(ctx context.Context, client *http.Client, store *cas.Store, file documentpkg.TrackedFile, update, offline bool) (result image, resultErr error) {
if !update {
if err := verifyObject(store, file.Hash); err == nil {
return image{Exists: true, Hash: file.Hash, Mode: 0o600}, nil
}
}
if offline || file.RecoverURL == "" {
return result, fmt.Errorf("no verified local backup or recovery source for %s", file.Path)
}
if client == nil {
return result, fmt.Errorf("recovery source for %s requires an HTTP client", file.Path)
}
ctx, cancel := context.WithTimeout(ctx, recoveryTimeout)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, file.RecoverURL, nil)
if err != nil {
return result, err
}
response, err := client.Do(request)
if err != nil {
return result, fmt.Errorf("fetch recovery source for %s: %w", file.Path, err)
}
defer func() { resultErr = errors.Join(resultErr, response.Body.Close()) }()
if response.StatusCode != http.StatusOK {
return result, fmt.Errorf("recovery source for %s returned HTTP %d", file.Path, response.StatusCode)
}
if response.ContentLength > maxRecoveryBytes {
return result, fmt.Errorf(
"recovery source for %s declares %d bytes, over the %d byte limit",
file.Path,
response.ContentLength,
maxRecoveryBytes,
)
}
var expected *cas.Digest
if !update {
digest, err := cas.ParseDigest(file.Hash)
if err != nil {
return result, err
}
expected = &digest
}
object, err := store.Put(
&cappedReader{reader: response.Body, left: maxRecoveryBytes},
expected,
)
if err != nil {
return result, fmt.Errorf("invalid recovery contents for %s: %w", file.Path, err)
}
return image{Exists: true, Hash: object.Digest.String(), Mode: 0o600}, nil
}
// ValidateOwnership includes generated outputs retained by the runtime receipt.
func ValidateOwnership(root string, files []documentpkg.TrackedFile, locked *documentpkg.Lock) error {
if len(files) == 0 {
return nil
}
outputs := []string{}
add := func(directory, name string) {
outputs = append(outputs, strings.ToLower(filepath.ToSlash(filepath.Join(directory, name))))
}
if err := workspacewrite.SafePath(root, receipt.Filename); err != nil {
return err
}
recorded, err := receipt.Read(root)
if err == nil {
for _, entry := range recorded.Entries {
add(".", entry.Path)
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if locked != nil {
server := locked.Server
paths, err := bootstrap.Outputs(server)
if err != nil {
return err
}
for _, name := range paths {
add(server.Directory, name)
}
if locked.MCDR != nil {
add(locked.MCDR.Directory, "run-mcdr.sh")
}
for index := range locked.Packages {
pkg := &locked.Packages[index]
if !pkg.Enabled() {
continue
}
destination, err := locked.PackageDestination(pkg)
if err != nil {
return err
}
add(".", destination)
}
}
for _, file := range files {
path := strings.ToLower(file.Path)
for _, output := range outputs {
if path == output || strings.HasPrefix(path, output+"/") || strings.HasPrefix(output, path+"/") {
return fmt.Errorf("tracked file %s collides with managed runtime output %s", file.Path, output)
}
}
}
return nil
}
package filetrack
import (
"errors"
"fmt"
"os"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileglob"
)
// expandDeclaredPaths resolves patterns against tracked declarations without
// walking the workspace, so a declared file that no longer exists still
// matches. Recover reports matched presence-only declarations as skipped.
// Lock reports matched declarations with no working file as skipped because
// there are no current bytes to accept.
func expandDeclaredPaths(
workspace *os.Root,
files []documentpkg.TrackedFile,
paths []string,
operation Operation,
) (selected, skipped []string, resultErr error) {
type argument struct {
raw string
path string
}
declared := make(map[string]documentpkg.TrackedFile, len(files))
declaredPaths := make([]string, 0, len(files))
for _, file := range files {
declared[file.Path] = file
declaredPaths = append(declaredPaths, file.Path)
}
arguments := make([]argument, 0, len(paths))
literal := make(map[string]struct{}, len(paths))
for _, raw := range paths {
path, err := input.TrackedPath(raw)
if err != nil {
return nil, nil, err
}
arguments = append(arguments, argument{raw: raw, path: path})
_, exists := declared[path]
if !fileglob.IsPattern(path) || exists {
literal[path] = struct{}{}
}
}
selected = make([]string, 0, len(files))
skipped = make([]string, 0)
selectedSeen := make(map[string]struct{}, len(files))
skippedSeen := make(map[string]struct{}, len(files))
addSelected := func(path string) {
if _, exists := selectedSeen[path]; exists {
return
}
selectedSeen[path] = struct{}{}
selected = append(selected, path)
}
addSkipped := func(path string) {
if _, exists := skippedSeen[path]; exists {
return
}
skippedSeen[path] = struct{}{}
skipped = append(skipped, path)
}
for _, argument := range arguments {
if _, exact := literal[argument.path]; exact {
addSelected(argument.path)
continue
}
matches, matchErr := fileglob.MatchPaths(argument.path, declaredPaths)
if errors.Is(matchErr, fileglob.ErrInvalidPattern) {
return nil, nil, fmt.Errorf("invalid pattern %q", argument.raw)
}
if matchErr != nil {
return nil, nil, matchErr
}
matched := false
for _, path := range matches {
matched = true
if _, explicit := literal[path]; explicit {
continue
}
file, exists := declared[path]
if !exists {
continue
}
if operation == Recover && file.Hash == "" {
addSkipped(path)
continue
}
if operation == Lock {
missing, statErr := workspaceMissing(workspace, path)
if statErr != nil {
return nil, nil, statErr
}
if missing {
addSkipped(path)
continue
}
}
addSelected(path)
}
if !matched {
return nil, nil, fmt.Errorf(
"pattern %q matches no tracked files",
argument.raw,
)
}
}
return selected, skipped, nil
}
// workspaceMissing reports whether the workspace holds no entry at path.
func workspaceMissing(workspace *os.Root, path string) (bool, error) {
if _, err := workspace.Lstat(path); !errors.Is(err, os.ErrNotExist) {
return false, err
}
return true, nil
}
package filetrack
import (
"errors"
"fmt"
"os"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fileglob"
)
// expandFilePaths resolves shell-style workspace patterns into the entries
// they select. Literal paths pass through normalization. A path in exact
// selects itself even when the workspace entry is gone, so a deleted
// declaration stays addressable by name. Directories are reported separately
// because a tracked entry is always a regular file. A pattern that matches
// neither a file nor a directory fails, so a typo cannot silently select
// nothing.
func expandFilePaths(root *os.Root, paths []string, exact map[string]struct{}) (selected, skippedDirectories []string, resultErr error) {
selected = make([]string, 0, len(paths))
skippedDirectories = make([]string, 0)
seen := make(map[string]struct{}, len(paths))
add := func(name string, directory bool) bool {
normalized, err := input.TrackedPath(name)
if err != nil {
return false
}
if _, exists := seen[normalized]; exists {
return true
}
seen[normalized] = struct{}{}
if directory {
skippedDirectories = append(skippedDirectories, normalized)
} else {
selected = append(selected, normalized)
}
return true
}
for _, raw := range paths {
normalized, err := input.TrackedPath(raw)
if err != nil {
return nil, nil, err
}
if _, ok := exact[normalized]; ok {
add(normalized, false)
continue
}
if !fileglob.IsPattern(normalized) {
info, statErr := root.Lstat(normalized)
switch {
case statErr == nil:
add(normalized, info.IsDir())
case errors.Is(statErr, os.ErrNotExist):
add(normalized, false)
default:
return nil, nil, statErr
}
continue
}
info, statErr := root.Lstat(normalized)
if statErr == nil {
add(normalized, info.IsDir())
continue
}
if !errors.Is(statErr, os.ErrNotExist) {
return nil, nil, statErr
}
entries, matchErr := fileglob.Match(root.FS(), normalized)
if errors.Is(matchErr, fileglob.ErrInvalidPattern) {
return nil, nil, fmt.Errorf("invalid pattern %q", raw)
}
if matchErr != nil {
return nil, nil, matchErr
}
matched := false
for _, entry := range entries {
if add(entry.Path, entry.Dir) {
matched = true
}
}
if !matched {
return nil, nil, fmt.Errorf(
"pattern %q matches no files or directories in this workspace",
raw,
)
}
}
return selected, skippedDirectories, nil
}
package filetrack
import (
"bufio"
"encoding/json/v2"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
)
const (
historyName = ".lucy/history/files.jsonl"
transactionName = ".lucy/file-commit.json"
)
// History is read-only and includes events for paths that are no longer tracked.
func History(root, path string) ([]Event, error) {
if err := noPending(root); err != nil {
return nil, err
}
if path != "" {
var err error
path, err = input.TrackedPath(path)
if err != nil {
return nil, err
}
}
events, _, err := readHistory(root, false)
if err != nil {
return nil, err
}
if path == "" {
return events, nil
}
selected := make([]Event, 0)
for _, event := range events {
changes := make([]Change, 0)
for _, change := range event.Changes {
if change.Path == path {
changes = append(changes, change)
}
}
if len(changes) != 0 {
event.Changes = changes
selected = append(selected, event)
}
}
return selected, nil
}
func noPending(root string) error {
for _, name := range []string{transactionName, workspacewrite.InstallJournalName} {
if err := workspacewrite.SafePath(root, name); err != nil {
return err
}
if _, err := os.Stat(filepath.Join(root, name)); err == nil {
return fmt.Errorf("unfinished workspace transaction; run a mutating Lucy command to recover it")
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
return nil
}
func readHistory(root string, repair bool) (events []Event, offset int64, resultErr error) {
if err := workspacewrite.SafePath(root, historyName); err != nil {
return nil, 0, err
}
flag := os.O_RDONLY
if repair {
flag = os.O_RDWR
}
file, err := os.OpenFile(filepath.Join(root, historyName), flag, 0)
if errors.Is(err, os.ErrNotExist) {
return []Event{}, 0, nil
}
if err != nil {
return nil, 0, err
}
defer func() { resultErr = errors.Join(resultErr, file.Close()) }()
reader := bufio.NewReader(file)
events = make([]Event, 0)
identities := map[string]bool{}
for {
line, err := reader.ReadBytes('\n')
if errors.Is(err, io.EOF) {
if len(line) != 0 {
if !repair {
return nil, offset, fmt.Errorf("incomplete file history tail; run a mutating file command to recover it")
}
if err := file.Truncate(offset); err != nil {
return nil, offset, err
}
if err := fsutil.Barrier(file); err != nil {
return nil, offset, err
}
}
return events, offset, nil
}
if err != nil {
return nil, offset, err
}
var event Event
if err := json.Unmarshal(line, &event); err != nil {
return nil, offset, fmt.Errorf("corrupt file history at byte %d: %w", offset, err)
}
if identities[event.ID] {
return nil, offset, fmt.Errorf("duplicate file history identity at byte %d", offset)
}
identities[event.ID] = true
if err := validateEvent(events, event); err != nil {
return nil, offset, fmt.Errorf("invalid file history at byte %d: %w", offset, err)
}
events = append(events, event)
offset += int64(len(line))
}
}
func validateEvent(previous []Event, event Event) error {
_, zone := event.Time.Zone()
if event.Sequence != uint64(len(previous)+1) || event.ID == "" || event.Time.IsZero() || zone != 0 || len(event.Changes) == 0 {
return fmt.Errorf("invalid event identity")
}
switch event.Operation {
case Track, Untrack, Update, Recover, Revert, Lock, Unlock:
default:
return fmt.Errorf("unknown operation")
}
paths := make(map[string]bool, len(event.Changes))
for _, change := range event.Changes {
path, err := input.TrackedPath(change.Path)
if err != nil || path != change.Path || paths[path] || change.Parent >= event.Sequence || change.Revision > event.Sequence || (change.Mode|change.BackupMode)&^uint32(0o777) != 0 {
return fmt.Errorf("invalid change for %s", change.Path)
}
paths[path] = true
for _, declaration := range []*document.TrackedFile{change.Before, change.After} {
if declaration == nil {
continue
}
copy := []document.TrackedFile{*declaration}
if err := document.NormalizeTrackedFiles(copy); err != nil || copy[0] != *declaration || declaration.Path != path {
return fmt.Errorf("invalid declaration for %s", path)
}
}
if change.BackupHash != "" {
if _, err := cas.ParseDigest(change.BackupHash); err != nil {
return fmt.Errorf("invalid working backup for %s", path)
}
}
if change.Accepted {
if (event.Operation != Track && event.Operation != Update && event.Operation != Lock) || change.After == nil || change.After.Hash == "" || change.Revision != event.Sequence {
return fmt.Errorf("invalid accepted revision for %s", path)
}
if change.Parent != 0 {
if _, ok := revisionAt(previous, path, change.Parent); !ok {
return fmt.Errorf("missing parent revision for %s", path)
}
}
} else if change.Revision != 0 {
revision, ok := revisionAt(previous, path, change.Revision)
if !ok || (change.After != nil && change.After.Hash != revision.hash) {
return fmt.Errorf("missing active revision for %s", path)
}
}
}
return nil
}
type acceptedRevision struct {
sequence uint64
parent uint64
hash string
mode os.FileMode
}
func revisionAt(events []Event, path string, sequence uint64) (acceptedRevision, bool) {
if sequence == 0 || sequence > uint64(len(events)) {
return acceptedRevision{}, false
}
for _, change := range events[sequence-1].Changes {
if change.Path == path && change.Accepted && change.After != nil {
return acceptedRevision{sequence: sequence, parent: change.Parent, hash: change.After.Hash, mode: os.FileMode(change.Mode)}, true
}
}
return acceptedRevision{}, false
}
func currentRevision(events []Event, path, hash string) acceptedRevision {
for i := len(events) - 1; i >= 0; i-- {
for _, change := range events[i].Changes {
if change.Path == path && change.Revision != 0 {
revision, ok := revisionAt(events, path, change.Revision)
if ok && revision.hash == hash {
return revision
}
return acceptedRevision{}
}
}
}
return acceptedRevision{}
}
func revertRevision(events []Event, path, acceptedHash, hash string, sequence uint64) (acceptedRevision, error) {
if hash != "" && sequence != 0 {
return acceptedRevision{}, fmt.Errorf("hash and --revision are mutually exclusive")
}
if sequence != 0 {
if revision, ok := revisionAt(events, path, sequence); ok {
return revision, nil
}
return acceptedRevision{}, fmt.Errorf("accepted revision %d is not available for %s", sequence, path)
}
if hash != "" {
for i := len(events) - 1; i >= 0; i-- {
if revision, ok := revisionAt(events, path, uint64(i+1)); ok && revision.hash == hash {
return revision, nil
}
}
return acceptedRevision{}, fmt.Errorf("accepted revision %s is not available for %s", hash, path)
}
current := currentRevision(events, path, acceptedHash)
if previous, ok := revisionAt(events, path, current.parent); ok {
return previous, nil
}
return acceptedRevision{}, fmt.Errorf("no previous accepted revision for %s", path)
}
package filetrack
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/mclucy/lucy/cas"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
)
// DeclaredFiles prefers the manifest declarations and falls back to the lock
// when only an installed workspace remains, so read-only commands also work
// without a manifest. A present but unreadable state file is an error, never an
// empty result set.
func DeclaredFiles(root string) ([]documentpkg.TrackedFile, error) {
document, manifestErr := documentpkg.ManifestFile(root).Read()
switch {
case manifestErr == nil:
return document.Files, nil
case !errors.Is(manifestErr, os.ErrNotExist):
return nil, fmt.Errorf("read manifest: %w", manifestErr)
}
locked, lockErr := documentpkg.LockFile(root).Read()
switch {
case lockErr == nil:
return locked.Files, nil
case !errors.Is(lockErr, os.ErrNotExist):
return nil, fmt.Errorf("read lockfile: %w", lockErr)
}
return nil, fmt.Errorf(
"no %s or %s in this workspace; run lucy init to create a manifest",
documentpkg.ManifestFilename,
documentpkg.LockFilename,
)
}
// Inspect makes no state directories and never contacts a recovery source.
func Inspect(root string, declarations []documentpkg.TrackedFile) (statuses []Status, resultErr error) {
if err := noPending(root); err != nil {
return nil, err
}
declarations = slices.Clone(declarations)
if err := documentpkg.NormalizeTrackedFiles(declarations); err != nil {
return nil, err
}
files, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
statuses = make([]Status, 0, len(declarations))
for _, file := range declarations {
status := Status{Path: file.Path, Immutable: file.Immutable, Hash: file.Hash, RecoverURL: file.RecoverURL}
if err := workspacewrite.SafePath(root, file.Path); err != nil {
status.State, status.Error = "error", err.Error()
statuses = append(statuses, status)
continue
}
info, err := files.Lstat(file.Path)
switch {
case errors.Is(err, os.ErrNotExist):
status.State = "missing"
case err != nil:
status.State, status.Error = "error", err.Error()
case !info.Mode().IsRegular():
status.State, status.Error = "error", "tracked path is not a regular file"
case file.Hash == "":
status.State = "presence-only"
default:
actual, err := observe(files, file.Path)
if err != nil {
status.State, status.Error = "error", err.Error()
} else {
status.ActualHash = actual.Hash
status.State = "matching"
if actual.Hash != file.Hash {
status.State = "modified"
}
}
}
statuses = append(statuses, status)
}
return statuses, nil
}
// Provision requires shared workspace ownership and preserves every existing working file.
// Availability failures are diagnostics; unsafe state and incomplete transactions are errors.
func (s *Service) Provision(ctx context.Context, root string, declarations []documentpkg.TrackedFile, offline bool) (diagnostics []Diagnostic, resultErr error) {
if err := noPending(root); err != nil {
return nil, err
}
declarations = slices.Clone(declarations)
if err := documentpkg.NormalizeTrackedFiles(declarations); err != nil {
return nil, err
}
if len(declarations) == 0 {
return []Diagnostic{}, nil
}
files, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
store, err := cas.New(filepath.Join(root, ".lucy"))
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, store.Close()) }()
diagnostics = make([]Diagnostic, 0)
for _, file := range declarations {
if err := ctx.Err(); err != nil {
return diagnostics, err
}
if err := workspacewrite.SafePath(root, file.Path); err != nil {
return diagnostics, err
}
info, err := files.Lstat(file.Path)
if err == nil {
if !info.Mode().IsRegular() {
return diagnostics, fmt.Errorf("tracked path %s is not a regular file", file.Path)
}
if file.Hash == "" {
continue
}
actual, err := observe(files, file.Path)
if err != nil {
return diagnostics, err
}
if actual.Hash != file.Hash && file.Immutable {
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: "immutable contents differ; use lucy file update to accept them or lucy file recover to restore the accepted revision"})
}
continue
}
if !errors.Is(err, os.ErrNotExist) {
return diagnostics, err
}
if file.Hash == "" {
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: "file is missing and has no accepted hash; distribute its contents or track an accepted revision"})
continue
}
accepted, err := sourceImage(ctx, s.client, store, file, false, offline)
if err != nil {
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: err.Error() + "; distribute the accepted contents or configure a source serving that digest"})
continue
}
if _, err := files.Lstat(file.Path); !errors.Is(err, os.ErrNotExist) {
if err != nil {
return diagnostics, err
}
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: "file appeared during recovery and was preserved"})
continue
}
reader, err := imageReader(store, accepted)
if err != nil {
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: "cannot open accepted contents: " + err.Error()})
continue
}
copyErr := fsutil.WriteRoot(files, file.Path, reader, fsutil.WriteOptions{
Mode: os.FileMode(accepted.Mode),
})
if err := errors.Join(copyErr, reader.Close()); err != nil {
diagnostics = append(diagnostics, Diagnostic{Path: file.Path, Message: "cannot provision accepted contents: " + err.Error()})
}
}
return diagnostics, nil
}
package filetrack
import (
"encoding/json/v2"
"errors"
"io"
"os"
"github.com/mclucy/lucy/cas"
documentpkg "github.com/mclucy/lucy/document"
)
// Reclaimed counts content store objects that a sweep removed because no
// accepted state names them.
type Reclaimed struct {
Objects int `json:"objects,omitzero"`
Bytes int64 `json:"bytes,omitzero"`
}
// reclaimObjects deletes objects outside the reference set of history, the
// manifest, the lockfile, and any pending transaction. History never forgets a
// revision, so a digest that any event named stays revertible.
//
// own holds the objects this run stored for its own transaction images. They
// are swept like any other leftover but not counted: they are the run's working
// state, not garbage it inherited.
//
// Callers hold the workspace writer lock: no command can be between storing an
// object and recording it.
func reclaimObjects(root string, files *os.Root, store *cas.Store, own map[string]struct{}) (Reclaimed, error) {
var reclaimed Reclaimed
referenced, err := references(root, files)
if err != nil {
return reclaimed, err
}
var failures []error
walkErr := store.Walk(func(object cas.Object) error {
if _, ok := referenced[object.Digest]; ok {
return nil
}
size, err := store.Remove(object.Digest)
if err != nil {
failures = append(failures, err)
return nil
}
if _, counted := own[object.Digest.String()]; counted {
return nil
}
reclaimed.Objects++
reclaimed.Bytes += size
return nil
})
return reclaimed, errors.Join(append(failures, walkErr)...)
}
// references collects every digest that a command may open later. A malformed
// hash fails the sweep: an unknowable reference set must not authorize
// deletion.
func references(root string, files *os.Root) (map[cas.Digest]struct{}, error) {
events, _, err := readHistory(root, false)
if err != nil {
return nil, err
}
referenced := make(map[cas.Digest]struct{})
for _, event := range events {
if err := addChangeReferences(referenced, event.Changes); err != nil {
return nil, err
}
}
if err := addDocumentReferences(
files,
documentpkg.ManifestFilename,
func(reader io.Reader) ([]documentpkg.TrackedFile, error) {
document, err := documentpkg.DecodeManifest(reader)
if err != nil {
return nil, err
}
return document.Files, nil
},
referenced,
); err != nil {
return nil, err
}
if err := addDocumentReferences(
files,
documentpkg.LockFilename,
func(reader io.Reader) ([]documentpkg.TrackedFile, error) {
document, err := documentpkg.DecodeLock(reader)
if err != nil {
return nil, err
}
return document.Files, nil
},
referenced,
); err != nil {
return nil, err
}
if err := addPendingReferences(files, referenced); err != nil {
return nil, err
}
return referenced, nil
}
// addPendingReferences keeps a transaction that recovery may still finish or
// roll back from losing the objects it names.
func addPendingReferences(files *os.Root, referenced map[cas.Digest]struct{}) error {
data, err := files.ReadFile(transactionName)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
var txn transaction
if err := json.Unmarshal(data, &txn); err != nil {
return err
}
for _, change := range txn.Mutations {
for _, state := range []image{change.Before, change.After} {
if err := addHash(referenced, state.Hash); err != nil {
return err
}
}
}
return addChangeReferences(referenced, txn.Event.Changes)
}
func addDocumentReferences(
files *os.Root,
name string,
decode func(io.Reader) ([]documentpkg.TrackedFile, error),
referenced map[cas.Digest]struct{},
) error {
reader, err := files.Open(name)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
declarations, decodeErr := decode(reader)
closeErr := reader.Close()
if err := errors.Join(decodeErr, closeErr); err != nil {
return err
}
for _, declaration := range declarations {
if err := addHash(referenced, declaration.Hash); err != nil {
return err
}
}
return nil
}
func addChangeReferences(referenced map[cas.Digest]struct{}, changes []Change) error {
for _, change := range changes {
for _, state := range []*documentpkg.TrackedFile{change.Before, change.After} {
if state == nil {
continue
}
if err := addHash(referenced, state.Hash); err != nil {
return err
}
}
if err := addHash(referenced, change.BackupHash); err != nil {
return err
}
}
return nil
}
func addHash(referenced map[cas.Digest]struct{}, hash string) error {
if hash == "" {
return nil
}
digest, err := cas.ParseDigest(hash)
if err != nil {
return err
}
referenced[digest] = struct{}{}
return nil
}
package filetrack
import (
"bytes"
"crypto/sha256"
"encoding/json/v2"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspaceguard"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
)
type image struct {
Exists bool `json:"exists"`
Hash string `json:"hash,omitempty"`
Mode uint32 `json:"mode,omitzero"`
}
type mutation struct {
Path string `json:"path"`
Before image `json:"before"`
After image `json:"after"`
}
type transaction struct {
Event Event `json:"event"`
HistorySize int64 `json:"history_size"`
Mutations []mutation `json:"mutations"`
}
func capture(root string, files *os.Root, store *cas.Store, name string) (result image, resultErr error) {
if err := workspacewrite.SafePath(root, name); err != nil {
return result, err
}
info, err := files.Lstat(name)
if errors.Is(err, os.ErrNotExist) {
return result, nil
}
if err != nil {
return result, err
}
if !info.Mode().IsRegular() {
return result, fmt.Errorf("file %s is not a regular file", name)
}
file, err := files.Open(name)
if err != nil {
return result, err
}
defer func() { resultErr = errors.Join(resultErr, file.Close()) }()
before, err := file.Stat()
if err != nil {
return result, err
}
object, err := store.Put(file, nil)
if err != nil {
return result, err
}
after, err := file.Stat()
if err != nil {
return result, err
}
if before.Size() != after.Size() || !before.ModTime().Equal(after.ModTime()) {
return result, fmt.Errorf("file %s changed while taking its snapshot", name)
}
return image{Exists: true, Hash: object.Digest.String(), Mode: uint32(info.Mode().Perm())}, nil
}
func observe(files *os.Root, name string) (result image, resultErr error) {
info, err := files.Lstat(name)
if errors.Is(err, os.ErrNotExist) {
return result, nil
}
if err != nil {
return result, err
}
if !info.Mode().IsRegular() {
return result, fmt.Errorf("file %s is not a regular file", name)
}
file, err := files.Open(name)
if err != nil {
return result, err
}
defer func() { resultErr = errors.Join(resultErr, file.Close()) }()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return result, err
}
var digest cas.Digest
hasher.Sum(digest[:0])
return image{Exists: true, Hash: digest.String(), Mode: uint32(info.Mode().Perm())}, nil
}
func storeBytes(store *cas.Store, data []byte, mode os.FileMode) (image, error) {
object, err := store.Put(bytes.NewReader(data), nil)
return image{Exists: err == nil, Hash: object.Digest.String(), Mode: uint32(mode.Perm())}, err
}
func applyImage(files *os.Root, store *cas.Store, name string, desired, expected image) error {
check := func() error {
current, err := observe(files, name)
if err != nil {
return err
}
if current != expected {
return fmt.Errorf("file %s changed before publication; keep pending transaction and resolve the edit", name)
}
return nil
}
if err := check(); err != nil {
return err
}
if !desired.Exists {
return workspacewrite.RemoveRoot(files, name)
}
reader, err := imageReader(store, desired)
if err != nil {
return err
}
copyErr := fsutil.WriteRoot(files, name, reader, fsutil.WriteOptions{
Mode: os.FileMode(desired.Mode),
Replace: true,
Check: check,
})
return errors.Join(copyErr, reader.Close())
}
func imageReader(store *cas.Store, state image) (io.ReadCloser, error) {
if !state.Exists {
return nil, os.ErrNotExist
}
digest, err := cas.ParseDigest(state.Hash)
if err != nil {
return nil, err
}
return store.Open(digest)
}
func ensureHistory(root string, files *os.Root) error {
if err := workspacewrite.SafePath(root, historyName); err != nil {
return err
}
if _, err := files.Lstat(historyName); errors.Is(err, os.ErrNotExist) {
return fsutil.AtomicWrite(filepath.Join(root, historyName), nil, 0o600)
} else {
return err
}
}
func appendEvent(files *os.Root, event Event) (resultErr error) {
data, err := json.Marshal(event)
if err != nil {
return err
}
data = append(data, '\n')
file, err := files.OpenFile(historyName, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, file.Close()) }()
if _, err := file.Write(data); err != nil {
return err
}
return fsutil.Barrier(file)
}
func commit(root string, files *os.Root, store *cas.Store, txn transaction) (resultErr error) {
if err := ensureHistory(root, files); err != nil {
return err
}
for _, change := range txn.Mutations {
if err := workspacewrite.SafePath(root, change.Path); err != nil {
return err
}
current, err := observe(files, change.Path)
if err != nil {
return err
}
if current != change.Before {
return fmt.Errorf("file %s changed during operation preparation", change.Path)
}
}
data, err := json.Marshal(txn)
if err != nil {
return err
}
if err := fsutil.WriteRoot(files, transactionName, bytes.NewReader(data), fsutil.WriteOptions{
Mode: 0o600,
Replace: true,
}); err != nil {
return err
}
failed := true
defer func() {
if failed {
resultErr = errors.Join(resultErr, recoverTransaction(root, files, store))
}
}()
for _, change := range txn.Mutations {
if change.Before != change.After {
if err := applyImage(files, store, change.Path, change.After, change.Before); err != nil {
return err
}
}
}
for _, change := range txn.Mutations {
current, err := observe(files, change.Path)
if err != nil {
return err
}
if current != change.After {
return fmt.Errorf("file %s changed before history commit", change.Path)
}
}
if err := appendEvent(files, txn.Event); err != nil {
return err
}
failed = false
return workspacewrite.RemoveRoot(files, transactionName)
}
// HasPendingTransaction reports whether a file transaction has not committed.
// It must run under the shared workspace writer lock.
func HasPendingTransaction(root string) (bool, error) {
if err := workspacewrite.SafePath(root, transactionName); err != nil {
return false, err
}
_, err := os.Stat(filepath.Join(root, transactionName))
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// RecoverLocked replays the installation journal and then any pending file
// transaction. The caller must hold the shared workspace writer lock: recovery
// restores the images both journals describe, so only the lock owner can prove
// no publisher is live and no later read needs the unreplayed state. History
// validation is skipped when no file transaction is pending, so recovery never
// requires writable file history from an otherwise valid workspace.
func RecoverLocked(root string, logger *log.Logger) error {
if err := workspaceguard.RecoverInstall(root, logger); err != nil {
return err
}
pending, err := HasPendingTransaction(root)
if err != nil || !pending {
return err
}
return RecoverPending(root)
}
// RecoverPending must run under the shared workspace writer lock.
func RecoverPending(root string) (resultErr error) {
if err := workspacewrite.SafePath(root, transactionName); err != nil {
return err
}
if _, err := os.Stat(filepath.Join(root, transactionName)); errors.Is(err, os.ErrNotExist) {
_, _, err := readHistory(root, true)
return err
} else if err != nil {
return err
}
if err := workspaceguard.CheckInactive(root, "recovering a pending workspace transaction"); err != nil {
return err
}
files, err := os.OpenRoot(root)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
store, err := cas.New(filepath.Join(root, ".lucy"))
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, store.Close()) }()
return recoverTransaction(root, files, store)
}
func recoverTransaction(root string, files *os.Root, store *cas.Store) error {
data, err := files.ReadFile(transactionName)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
var txn transaction
if err := json.Unmarshal(data, &txn); err != nil {
return fmt.Errorf("decode pending file transaction: %w", err)
}
if txn.Event.ID == "" || txn.Event.Sequence == 0 || len(txn.Mutations) == 0 || txn.HistorySize < 0 {
return fmt.Errorf("invalid pending file transaction")
}
events, size, err := readHistory(root, true)
if err != nil {
return err
}
sequence := txn.Event.Sequence
if sequence > uint64(len(events)+1) {
return fmt.Errorf("pending transaction has an invalid history sequence")
}
prior := events
if sequence <= uint64(len(events)) {
prior = events[:sequence-1]
}
if err := validateEvent(prior, txn.Event); err != nil {
return fmt.Errorf("invalid pending transaction event: %w", err)
}
committed := false
for _, event := range events {
if event.ID == txn.Event.ID {
expected, err := json.Marshal(txn.Event)
if err != nil {
return err
}
actual, err := json.Marshal(event)
if err != nil || !bytes.Equal(actual, expected) {
return fmt.Errorf("pending transaction conflicts with committed history")
}
committed = true
}
}
if committed && sequence != uint64(len(events)) {
return fmt.Errorf("pending transaction does not describe the latest history event")
}
if !committed && sequence != uint64(len(events)+1) {
return fmt.Errorf("pending transaction conflicts with the history sequence")
}
if !committed && size != txn.HistorySize {
return fmt.Errorf("file history changed after an interrupted transaction")
}
for _, change := range txn.Mutations {
if change.Path != document.ManifestFilename && change.Path != document.LockFilename {
if normalized, err := input.TrackedPath(change.Path); err != nil || normalized != change.Path {
return fmt.Errorf("invalid pending file transaction path")
}
}
if err := workspacewrite.SafePath(root, change.Path); err != nil {
return err
}
for _, state := range []image{change.Before, change.After} {
if state.Exists {
if _, err := cas.ParseDigest(state.Hash); err != nil || state.Mode&^uint32(0o777) != 0 {
return fmt.Errorf("invalid pending file pre-image")
}
}
}
current, err := observe(files, change.Path)
if err != nil {
return err
}
if current != change.Before && current != change.After {
return fmt.Errorf("file %s changed after interruption; keep pending transaction and resolve the edit", change.Path)
}
}
for _, change := range txn.Mutations {
desired := change.Before
if committed {
desired = change.After
}
current, err := observe(files, change.Path)
if err != nil {
return err
}
if current != change.Before && current != change.After {
return fmt.Errorf("file %s changed during interrupted transaction recovery; keep pending transaction and resolve the edit", change.Path)
}
if current != desired {
if err := applyImage(files, store, change.Path, desired, current); err != nil {
return err
}
}
}
if committed {
file, err := files.OpenFile(historyName, os.O_RDWR, 0)
if err != nil {
return err
}
syncErr := fsutil.Barrier(file)
if closeErr := file.Close(); syncErr != nil || closeErr != nil {
return errors.Join(syncErr, closeErr)
}
}
return workspacewrite.RemoveRoot(files, transactionName)
}
package input
import (
"fmt"
"path"
"path/filepath"
"strings"
)
func TrackedPath(value string) (string, error) {
if value == "" || strings.ContainsAny(value, "\\:\x00") || !filepath.IsLocal(value) {
return "", fmt.Errorf("tracked path must be workspace-relative: %q", value)
}
for component := range strings.SplitSeq(value, "/") {
if component == ".." || strings.EqualFold(component, ".lucy") || strings.EqualFold(component, ".git") {
return "", fmt.Errorf("tracked path traverses reserved state: %q", value)
}
}
value = path.Clean(value)
first, _, _ := strings.Cut(value, "/")
if value == "." ||
strings.EqualFold(first, "lucy.yaml") ||
strings.EqualFold(first, "lucy-lock.yaml") {
return "", fmt.Errorf("tracked path names Lucy state or a directory: %q", value)
}
return value, nil
}
// Package input parses package request syntax.
//
// A request has the form "provider:name@version". Provider and version are
// optional. Its target ecosystem is selected separately by the caller.
package input
import (
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
var ESyntax = errors.New("invalid syntax")
// Parse parses provider:name@version. An omitted provider lets routing choose;
// an omitted version becomes VersionAny. The ecosystem remains unspecified
// until install planning.
func Parse(s string) (catalog.VersionedRef, error) {
provider, remainder, err := parseProvider(strings.TrimSpace(s))
if err != nil {
return catalog.VersionedRef{}, err
}
name, version, err := parseNameVersion(remainder)
if err != nil {
return catalog.VersionedRef{}, err
}
return catalog.VersionedRef{
Name: name, Provider: provider,
Version: version,
}, nil
}
func ToProjectName(s string) catalog.Name {
s = strings.TrimSpace(strings.ToLower(s))
s = strings.ReplaceAll(s, "_", "-")
s = strings.ReplaceAll(s, " ", "-")
return catalog.Name(s)
}
func parseProvider(s string) (catalog.Provider, string, error) {
boundary := len(s)
if at := strings.IndexByte(s, '@'); at >= 0 {
boundary = at
}
colon := strings.IndexByte(s[:boundary], ':')
if colon < 0 {
return catalog.ProviderUnspecified, s, nil
}
provider, ok := catalog.ParseProvider(strings.ToLower(s[:colon]))
if !ok || provider == catalog.ProviderUnspecified {
return catalog.ProviderUnknown, "", fmt.Errorf("%w: unknown provider %q", ESyntax, s[:colon])
}
return provider, s[colon+1:], nil
}
func parseNameVersion(s string) (catalog.Name, versionpkg.Version, error) {
parts := strings.Split(s, "@")
switch len(parts) {
case 1:
if parts[0] == "" {
return "", "", ESyntax
}
return catalog.Name(parts[0]), versionpkg.Any, nil
case 2:
if parts[0] == "" || parts[1] == "" || versionpkg.Version(parts[1]) == versionpkg.None {
return "", "", ESyntax
}
return catalog.Name(parts[0]), versionpkg.Version(parts[1]), nil
default:
return "", "", ESyntax
}
}
package install
import (
"context"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"maps"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/github"
"github.com/mclucy/lucy/log"
)
var (
errOfflineArtifactUnavailable = errors.New("offline artifact unavailable")
errArtifactDigestMismatch = errors.New("checksum mismatch")
)
type downloadStore struct {
offline bool
storeOnly bool
trace *Trace
fetch *FetchSummary
network *cache.Client
logger *log.Logger
githubProxy string
injected artifact.Materializer
verified sync.Map // cas.Digest -> *objectVerification
progressMu sync.Mutex // concurrent staging and fetch reports
// injectedMu keeps a caller-supplied materializer one call at a time: it
// is external code that may keep state between calls.
injectedMu sync.Mutex
}
// A pinned object can be requested by several staging workers. Only one
// verifies or repairs that digest at a time.
type objectVerification struct {
mu sync.Mutex
info os.FileInfo
hashes map[string]string
}
func (s *downloadStore) verification(digest cas.Digest) *objectVerification {
if entry, ok := s.verified.Load(digest); ok {
return entry.(*objectVerification)
}
entry, _ := s.verified.LoadOrStore(digest, new(objectVerification))
return entry.(*objectVerification)
}
func (s *downloadStore) recordVerified(digest cas.Digest, path string, hashes map[string]string) {
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() {
return
}
entry := s.verification(digest)
entry.mu.Lock()
defer entry.mu.Unlock()
entry.record(info, hashes)
}
func sameObject(previous, current os.FileInfo) bool {
return previous != nil && current != nil && current.Mode().IsRegular() &&
os.SameFile(previous, current) && previous.Size() == current.Size() &&
previous.ModTime().Equal(current.ModTime())
}
func (entry *objectVerification) record(info os.FileInfo, hashes map[string]string) {
if !sameObject(entry.info, info) {
entry.info = info
entry.hashes = maps.Clone(hashes)
} else {
maps.Copy(entry.hashes, hashes)
}
}
func (entry *objectVerification) match(expected map[string]string) (map[string]string, bool) {
if entry.hashes == nil {
return nil, false
}
for algorithm, digest := range expected {
if value, ok := entry.hashes[algorithm]; !ok || digest != "" && !strings.EqualFold(digest, value) {
return nil, false
}
}
hashes := make(map[string]string, len(expected)+1)
hashes["sha256"] = entry.hashes["sha256"]
for algorithm := range expected {
hashes[algorithm] = entry.hashes[algorithm]
}
return hashes, true
}
func (s *downloadStore) cacheHit() {
s.progressMu.Lock()
defer s.progressMu.Unlock()
if s.fetch != nil {
s.fetch.Cached++
}
}
func (s *downloadStore) downloaded(bytes int64) {
s.progressMu.Lock()
defer s.progressMu.Unlock()
if s.fetch == nil {
return
}
s.fetch.Downloaded++
s.fetch.Bytes += bytes
}
// DigestFile computes the requested digests and fails when a supplied value
// does not match. sha256 is always computed because the artifact store is
// addressed by it.
func DigestFile(filename string, algorithms map[string]string) (map[string]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return digestReader(file, filename, algorithms)
}
func digestReader(file io.Reader, filename string, algorithms map[string]string) (map[string]string, error) {
hashers, writers, err := digestHashers(algorithms, true)
if err != nil {
return nil, err
}
if _, err := io.Copy(io.MultiWriter(writers...), file); err != nil {
return nil, err
}
return digestValues(hashers, algorithms, filename)
}
func digestHashers(algorithms map[string]string, includeSHA256 bool) (map[string]hash.Hash, []io.Writer, error) {
hashers := make(map[string]hash.Hash, len(algorithms)+1)
if includeSHA256 {
hashers["sha256"] = sha256.New()
}
for algorithm := range algorithms {
switch algorithm {
case "sha1":
hashers[algorithm] = sha1.New()
case "sha512":
hashers[algorithm] = sha512.New()
case "md5":
hashers[algorithm] = md5.New()
case "sha256":
default:
return nil, nil, fmt.Errorf("unsupported artifact digest %s", algorithm)
}
}
writers := make([]io.Writer, 0, len(hashers))
for _, hasher := range hashers {
writers = append(writers, hasher)
}
return hashers, writers, nil
}
func digestValues(hashers map[string]hash.Hash, algorithms map[string]string, filename string) (map[string]string, error) {
values := make(map[string]string, len(hashers))
for algorithm, hasher := range hashers {
values[algorithm] = hex.EncodeToString(hasher.Sum(nil))
if expected := algorithms[algorithm]; expected != "" && values[algorithm] != strings.ToLower(expected) {
return nil, fmt.Errorf("%s %w for %s", algorithm, errArtifactDigestMismatch, filename)
}
}
return values, nil
}
// materialize returns the verified store object and the digests computed while
// verifying it. The artifact is an input only; callers attach the returned
// hashes when the artifact becomes part of a lock. A store hit performs no
// network or cache access; a miss copies verified bytes from the network cache
// or the network into the store.
func (s *downloadStore) materialize(
ctx context.Context,
a *catalog.Artifact,
) (artifact.MaterializedFile, error) {
return s.materializeFor(ctx, a, a.Filename)
}
func (s *downloadStore) materializeFor(
ctx context.Context,
a *catalog.Artifact,
transferName string,
) (artifact.MaterializedFile, error) {
if err := ctx.Err(); err != nil {
return artifact.MaterializedFile{}, err
}
if a.Embedded != "" {
return artifact.MaterializedFile{}, fmt.Errorf("embedded artifacts are extracted from their pinned parent")
}
if a.Filename == "" || filepath.Base(a.Filename) != a.Filename || strings.ContainsAny(a.Filename, "/\\") {
return artifact.MaterializedFile{}, fmt.Errorf("invalid artifact filename %q", a.Filename)
}
if s.injected != nil {
file, err := s.injectedMaterialize(ctx, a)
if s.storeOnly && errors.Is(err, os.ErrNotExist) {
err = fmt.Errorf("%w: %s: %w", errOfflineArtifactUnavailable, a.Filename, err)
}
return file, err
}
store, err := artifactstore.Open()
if err != nil {
return artifact.MaterializedFile{}, err
}
defer store.Close()
var entry *objectVerification
if expected := strings.ToLower(strings.TrimSpace(a.Hashes["sha256"])); expected != "" {
digest, err := cas.ParseDigest("sha256:" + expected)
if err != nil {
return artifact.MaterializedFile{}, fmt.Errorf(
"artifact %s has an invalid sha256 digest %q: %w",
a.Filename, expected, err,
)
}
entry = s.verification(digest)
entry.mu.Lock()
defer entry.mu.Unlock()
if err := ctx.Err(); err != nil {
return artifact.MaterializedFile{}, err
}
destination := store.Path(digest)
var hashes map[string]string
info, err := os.Lstat(destination)
if err == nil && info.Mode().IsRegular() {
if sameObject(entry.info, info) {
if hashes, ok := entry.match(a.Hashes); ok {
s.cacheHit()
return artifact.MaterializedFile{Path: destination, Hashes: hashes}, nil
}
}
hashes, err = DigestFile(destination, a.Hashes)
if err == nil {
fresh, statErr := os.Lstat(destination)
if statErr != nil || !sameObject(info, fresh) {
err = fmt.Errorf("store object changed during verification: %s", a.Filename)
}
}
} else if err == nil {
err = fmt.Errorf("store object is not a regular file: %s", a.Filename)
}
if err == nil {
entry.record(info, hashes)
s.cacheHit()
s.logger.Debug(
"artifact verified",
"file", a.Filename,
"sha256", hashes["sha256"],
"source", "store",
)
return artifact.MaterializedFile{Path: destination, Hashes: hashes}, nil
}
if !errors.Is(err, os.ErrNotExist) {
if s.storeOnly {
return artifact.MaterializedFile{}, err
}
s.logger.Debug(
"store object is unusable; acquiring again",
"file", a.Filename,
"error", err,
)
}
}
if s.storeOnly {
return artifact.MaterializedFile{}, fmt.Errorf("%w: %s", errOfflineArtifactUnavailable, a.Filename)
}
source, cleanup, err := s.downloadArtifact(ctx, a, transferName)
if cleanup != nil {
defer cleanup()
}
if err != nil {
return artifact.MaterializedFile{}, err
}
object, hashes, err := importFile(store.Store, source, a.Filename, a.Hashes)
if err != nil {
return artifact.MaterializedFile{}, err
}
destination := store.Path(object.Digest)
if entry == nil {
s.recordVerified(object.Digest, destination, hashes)
} else if info, statErr := os.Lstat(destination); statErr == nil && info.Mode().IsRegular() {
entry.record(info, hashes)
}
s.logger.Debug(
"artifact verified",
"file", a.Filename,
"sha256", hashes["sha256"],
)
return artifact.MaterializedFile{Path: destination, Hashes: hashes}, nil
}
// injectedMaterialize verifies bytes another operation supplied. Digests are
// recomputed from the returned file, so an injected materializer cannot lower
// the hash guarantee. Verified bytes enter the artifact store because a lock
// that mentions them must remain replayable. It does not touch the fetch
// summary, which describes the configured cache's transfers.
func (s *downloadStore) injectedMaterialize(
ctx context.Context,
a *catalog.Artifact,
) (artifact.MaterializedFile, error) {
expected := maps.Clone(a.Hashes)
input := *a
input.Hashes = maps.Clone(a.Hashes)
input.Modules = slices.Clone(a.Modules)
for i := range input.Modules {
input.Modules[i].Provides = slices.Clone(a.Modules[i].Provides)
input.Modules[i].Dependencies = slices.Clone(a.Modules[i].Dependencies)
}
s.injectedMu.Lock()
materialized, err := s.injected(ctx, &input)
s.injectedMu.Unlock()
if err != nil {
return artifact.MaterializedFile{}, err
}
if materialized.Path == "" {
return artifact.MaterializedFile{}, fmt.Errorf("injected artifact %s has no path", a.Filename)
}
store, err := artifactstore.Open()
if err != nil {
return artifact.MaterializedFile{}, err
}
defer store.Close()
object, hashes, err := importFile(store.Store, materialized.Path, a.Filename, expected)
if err != nil {
return artifact.MaterializedFile{}, err
}
s.recordVerified(object.Digest, store.Path(object.Digest), hashes)
return artifact.MaterializedFile{Path: store.Path(object.Digest), Hashes: hashes}, nil
}
// importFile copies a verified local file into the store while checking every
// supplied digest. A mismatch aborts the stage, so unusable bytes are never
// published. Any previous object at the same address is replaced by these
// verified bytes.
func importFile(
store *cas.Store,
filename, display string,
expected map[string]string,
) (object cas.Object, hashes map[string]string, resultErr error) {
file, err := os.Open(filename)
if err != nil {
return cas.Object{}, nil, err
}
defer file.Close()
hashers, writers, err := digestHashers(expected, false)
if err != nil {
return cas.Object{}, nil, err
}
var pinned *cas.Digest
if value := expected["sha256"]; value != "" {
digest, err := cas.ParseDigest("sha256:" + strings.ToLower(value))
if err != nil {
return cas.Object{}, nil, err
}
pinned = &digest
}
writer, err := store.NewWriter()
if err != nil {
return cas.Object{}, nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Abort()) }()
drains := append(writers, writer)
if _, err := io.Copy(io.MultiWriter(drains...), file); err != nil {
return cas.Object{}, nil, fmt.Errorf("ingest artifact: %w", err)
}
hashes, err = digestValues(hashers, expected, display)
if err != nil {
return cas.Object{}, nil, err
}
object, err = writer.Commit(pinned)
if err != nil {
if errors.Is(err, cas.ErrCorrupt) {
err = fmt.Errorf("sha256 checksum mismatch for %s: %w", display, err)
}
return cas.Object{}, nil, err
}
hashes["sha256"] = object.Digest.Hex()
return object, hashes, nil
}
// artifactCacheIdentityHost is a reserved host (RFC 2606 .invalid) that only
// carries cache identities; no request targets it.
const artifactCacheIdentityHost = "artifact.cache.lucy.invalid"
// artifactCacheIdentity returns the network cache key for an artifact. Spiget
// download URLs are mutable and publish no upstream hash, so their key hashes
// the URL and adds provider, project, release, and file: neither a different
// release nor a different URL can alias cached bytes. Other providers keep the
// URL key.
func artifactCacheIdentity(a *catalog.Artifact) (string, error) {
if a.Provider != catalog.ProviderSpiget {
return a.URL, nil
}
project := strings.TrimSpace(a.ProjectID)
release := strings.TrimSpace(a.ReleaseID)
file := strings.TrimSpace(a.FileID)
if project == "" || release == "" || file == "" {
return "", fmt.Errorf(
"spiget artifact %s is missing its project, release, or file identity",
a.Filename,
)
}
urlDigest := sha256.Sum256([]byte(a.URL))
return "https://" + artifactCacheIdentityHost + "/" +
url.PathEscape(a.Provider.String()) + "/" +
hex.EncodeToString(urlDigest[:]) + "/" +
url.PathEscape(project) + "/" +
url.PathEscape(release) + "/" +
url.PathEscape(file), nil
}
// downloadArtifact obtains candidate bytes from the network cache or, in
// offline mode, the cache alone. The cache identity is separate from the
// request URL, so a mutable provider URL cannot alias releases; the request
// and the persisted artifact URL stay the artifact's own URL. The returned
// path is temporary; callers import it into the store before removing the
// directory.
func (s *downloadStore) downloadArtifact(
ctx context.Context,
a *catalog.Artifact,
transferName string,
) (string, func(), error) {
if s.network == nil {
return "", nil, errors.New("artifact download client is unavailable")
}
identity, err := artifactCacheIdentity(a)
if err != nil {
return "", nil, err
}
directory, err := os.MkdirTemp("", "lucy-artifact-")
if err != nil {
return "", nil, err
}
cleanup := func() { os.RemoveAll(directory) }
if s.offline {
hit, cached, _, err := s.network.Get(identity)
if err != nil {
return "", cleanup, err
}
if !hit || cached == nil {
return "", cleanup, fmt.Errorf("offline artifact unavailable: %s", a.URL)
}
destination := filepath.Join(directory, a.Filename)
out, err := os.Create(destination)
if err != nil {
return "", cleanup, errors.Join(err, cached.Close())
}
_, copyErr := io.Copy(out, cached)
closeErr := out.Close()
cachedErr := cached.Close()
if copyErr != nil {
return "", cleanup, copyErr
}
if closeErr != nil {
return "", cleanup, closeErr
}
if cachedErr != nil {
return "", cleanup, cachedErr
}
s.cacheHit()
return destination, cleanup, nil
}
var read int64
var total int64
options := cache.DownloadOptions{
Kind: cache.KindArtifact,
Filename: a.Filename,
RequestURL: github.ProxiedDownloadURL(a.URL, s.githubProxy),
FileMode: 0o600,
}
options.WrapReader = func(reader io.Reader, size int64) io.Reader {
total = size
s.progressMu.Lock()
s.trace.fetchStarted(transferName, size)
s.progressMu.Unlock()
return &fetchReader{
reader: reader,
name: transferName,
total: size,
read: &read,
store: s,
}
}
s.logger.Debug(
"artifact fetch",
"file", a.Filename,
"host", downloadHost(options.RequestURL),
)
started := time.Now()
result, err := s.network.CachedDownload(ctx, identity, directory, options)
if err != nil {
return "", cleanup, err
}
source := result.File.Name()
if err := result.File.Close(); err != nil {
return "", cleanup, err
}
origin := "network"
if result.CacheHit {
origin = "cache"
s.cacheHit()
} else {
s.downloaded(read)
s.progressMu.Lock()
s.trace.fetchProgress(transferName, read, total)
s.trace.fetchDone(transferName, false)
s.progressMu.Unlock()
}
s.logger.Debug(
"artifact fetched",
"file", a.Filename,
"source", origin,
"bytes", read,
"duration", time.Since(started).Round(time.Millisecond),
)
return source, cleanup, nil
}
// downloadHost names the host a download goes to, so a slow fetch points at
// the endpoint rather than at the resolver.
func downloadHost(raw string) string {
parsed, err := url.Parse(raw)
if err != nil {
return ""
}
return parsed.Host
}
// fetchReader reports download byte progress through the operation trace.
type fetchReader struct {
reader io.Reader
name string
total int64
read *int64
store *downloadStore
}
func (r *fetchReader) Read(buffer []byte) (int, error) {
count, err := r.reader.Read(buffer)
*r.read += int64(count)
r.store.progressMu.Lock()
r.store.trace.fetchProgress(r.name, *r.read, r.total)
r.store.progressMu.Unlock()
return count, err
}
package install
import (
"context"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/upstream"
)
// AdoptedRelease pairs a release the workspace already holds with the manifest
// reference that declares it.
type AdoptedRelease struct {
Reference string
Ecosystem catalog.Ecosystem
Candidate upstream.Candidate
Path string
SHA256 string
Analysis *artifact.Analysis
}
// adoptedCandidate answers a catalogue lookup from a release the workspace
// already holds. Adoption declares the installed version, so no catalogue
// query can select different bytes for it. The reference answers the project
// name as written; the project identity answers a demand that names it.
func adoptedCandidate(
adopted []AdoptedRelease,
registry catalog.Registry,
project string,
ecosystem catalog.Ecosystem,
) (upstream.Candidate, bool) {
for _, release := range adopted {
if release.Ecosystem != ecosystem {
continue
}
if releaseRegistry, ok := release.Candidate.Provider.Registry(); !ok ||
releaseRegistry != registry {
continue
}
provider, name, err := document.ParseReference(release.Reference)
if err != nil || provider != release.Candidate.Provider {
continue
}
if name == project || release.Candidate.ProjectID == project {
candidate := release.Candidate
candidate.PrimaryFile = true
return candidate, true
}
}
return upstream.Candidate{}, false
}
func supersededByAdoption(pkg document.Package, adopted []AdoptedRelease) bool {
for _, release := range adopted {
if release.Ecosystem != pkg.Ecosystem || release.Candidate.Provider != pkg.Provider {
continue
}
if release.Candidate.ProjectID == pkg.ProjectID {
return true
}
for _, req := range pkg.Requirements {
if req.Reference == release.Reference {
return true
}
}
}
return false
}
func adoptionMatchesLock(adopted []AdoptedRelease, lock *document.Lock) bool {
for _, release := range adopted {
candidate := release.Candidate
matches := false
for _, pkg := range lock.Packages {
if pkg.Ecosystem == release.Ecosystem && pkg.Provider == candidate.Provider &&
pkg.ProjectID == candidate.ProjectID && pkg.ReleaseID == candidate.ReleaseID &&
pkg.FileID == candidate.FileID && pkg.Filename == candidate.Filename &&
strings.EqualFold(pkg.Hashes["sha256"], release.SHA256) {
matches = true
break
}
}
if !matches {
return false
}
}
return true
}
// prepareAdoptedArtifacts imports the observed bytes of every accepted adopted
// package through one artifact store. Each import verifies the observed
// SHA-256 and every digest the candidate pinned. With a target it also records
// each package's descriptor view in a resolution cache; without one it only
// seeds the store for replay.
func prepareAdoptedArtifacts(
ctx context.Context,
root string,
adopted []AdoptedRelease,
target *resolve.Target,
) (*resolve.AnalysisCache, error) {
if len(adopted) == 0 {
return nil, nil
}
store, err := artifactstore.Open()
if err != nil {
return nil, err
}
defer store.Close()
var cache *resolve.AnalysisCache
if target != nil {
cache = resolve.NewAnalysisCache()
}
for _, release := range adopted {
if err := ctx.Err(); err != nil {
return nil, err
}
if cache != nil && release.Analysis == nil {
return nil, fmt.Errorf("missing local evidence for adopted package %s", release.Reference)
}
if name := release.Candidate.Filename; name == "" ||
filepath.Base(name) != name || strings.ContainsAny(name, "/\\") {
return nil, fmt.Errorf("invalid artifact filename %q", name)
}
observed := release.Path
if !filepath.IsAbs(observed) {
observed = filepath.Join(root, filepath.FromSlash(observed))
}
relative, ok := workspaceRelative(root, observed)
if !ok || release.SHA256 == "" {
return nil, fmt.Errorf("missing local evidence for adopted package %s", release.Reference)
}
if err := workspacewrite.SafePath(root, relative); err != nil {
return nil, err
}
info, err := os.Lstat(observed)
if err != nil || !info.Mode().IsRegular() {
return nil, fmt.Errorf("missing local evidence for adopted package %s", release.Reference)
}
candidate := release.Candidate
candidate.Hashes = maps.Clone(release.Candidate.Hashes)
if candidate.Hashes == nil {
candidate.Hashes = make(map[string]string, 1)
}
if digest := candidate.Hashes["sha256"]; digest != "" &&
!strings.EqualFold(digest, release.SHA256) {
return nil, fmt.Errorf("sha256 checksum mismatch for adopted package %s", release.Reference)
}
candidate.Hashes["sha256"] = release.SHA256
_, hashes, err := importFile(store.Store, observed, relative, candidate.Hashes)
if err != nil {
return nil, fmt.Errorf("store adopted package %s: %w", release.Reference, err)
}
if cache == nil {
continue
}
view, err := release.Analysis.Descriptor(
ctx,
target.DescriptorLoader(release.Ecosystem),
string(target.Minecraft),
)
if err != nil {
return nil, fmt.Errorf("read descriptor for adopted package %s: %w", release.Reference, err)
}
cache.RecordVerified(release.Candidate, *target, release.Ecosystem, view.Modules, hashes)
}
return cache, nil
}
// localRuntimeSource offers the runtime files initialization observed as
// artifact sources. A file satisfies an artifact only when every trusted
// digest it pins, and the observed SHA-256, match its bytes; a name or role
// never stands in for that proof, so a launcher cannot satisfy its installer.
type localRuntimeSource struct {
// mu guards the digests and store paths cached per file: acquisitions of
// one server product run in parallel and share this source.
mu sync.Mutex
root string
files []*localRuntimeFile
}
type localRuntimeFile struct {
path, rel string
digests map[string]string
// storePath is the verified artifact store object this file was imported
// as. It carries no hash map, so every request builds its own.
storePath string
}
func newLocalRuntimeSource(root string, files []AdoptedRuntimeFile) *localRuntimeSource {
source := &localRuntimeSource{root: root}
for _, observed := range files {
digest := strings.ToLower(strings.TrimSpace(observed.ExpectedSHA256))
path := observed.Path
if !filepath.IsAbs(path) {
path = filepath.Join(root, filepath.FromSlash(path))
}
if relative, ok := workspaceRelative(root, path); ok && digest != "" {
digests := map[string]string{"sha256": digest}
for algorithm, value := range observed.ExpectedHashes {
if value = strings.ToLower(strings.TrimSpace(value)); value != "" {
digests[algorithm] = value
}
}
source.files = append(source.files, &localRuntimeFile{
path: path,
rel: relative,
digests: digests,
})
}
}
return source
}
// acquire wraps next so an artifact the observed runtime proves is imported
// instead of transferred. Every other artifact keeps the normal path. It
// forwards each caller's context, so cancelling a caller abandons its work.
func (s *localRuntimeSource) acquire(next artifact.Materializer) artifact.Materializer {
return func(ctx context.Context, a *catalog.Artifact) (artifact.MaterializedFile, error) {
if materialized, matched, err := s.materialize(ctx, a); err != nil || matched {
return materialized, err
}
return next(ctx, a)
}
}
// importServer imports the core and inputs a metadata resolver pinned and
// attaches a SHA-256 the observed runtime proved when the artifact lacks one.
// It never downloads or replaces an existing pin: the existing map is cloned
// and the proven digest added, so the caller's lock is never mutated and an
// artifact that already pins SHA-256 keeps its exact values. It reports
// whether any artifact gained a SHA-256.
func (s *localRuntimeSource) importServer(
ctx context.Context,
server document.LockedServer,
) (document.LockedServer, bool, error) {
if len(s.files) == 0 {
return server, false, nil
}
server.Inputs = slices.Clone(server.Inputs)
changed := false
artifacts := make([]*catalog.Artifact, 0, len(server.Inputs)+1)
artifacts = append(artifacts, &server.Artifact)
for i := range server.Inputs {
artifacts = append(artifacts, &server.Inputs[i])
}
for _, artifact := range artifacts {
materialized, matched, err := s.materialize(ctx, artifact)
if err != nil {
return server, false, err
}
if !matched {
continue
}
proven := strings.ToLower(strings.TrimSpace(materialized.Hashes["sha256"]))
if proven == "" || strings.TrimSpace(artifact.Hashes["sha256"]) != "" {
continue
}
hashes := maps.Clone(artifact.Hashes)
if hashes == nil {
hashes = make(map[string]string, 1)
}
hashes["sha256"] = proven
artifact.Hashes = hashes
changed = true
}
return server, changed, nil
}
// withProvenServer returns old carrying the server digests the observed
// runtime proved. It keeps every pin the lock already carried and returns old
// itself when the proof added nothing, so an unchanged lock keeps its exact
// bytes and pointer identity.
func withProvenServer(
old *document.Lock,
server document.LockedServer,
changed bool,
) *document.Lock {
if !changed {
return old
}
enriched := *old
enriched.Server = server
enriched.Packages = slices.Clone(old.Packages)
enriched.Files = slices.Clone(old.Files)
return &enriched
}
func (s *localRuntimeSource) materialize(
ctx context.Context,
a *catalog.Artifact,
) (artifact.MaterializedFile, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.files) == 0 || a.Embedded != "" {
return artifact.MaterializedFile{}, false, nil
}
pins := make(map[string]string, len(a.Hashes)+1)
for algorithm, digest := range a.Hashes {
if digest = strings.ToLower(strings.TrimSpace(digest)); digest != "" {
pins[algorithm] = digest
}
}
file := s.match(pins)
if file == nil {
return artifact.MaterializedFile{}, false, nil
}
if file.storePath != "" {
return file.materialization(pins), true, nil
}
if !s.confined(file) {
return artifact.MaterializedFile{}, false, nil
}
pins["sha256"] = file.digests["sha256"]
if err := ctx.Err(); err != nil {
return artifact.MaterializedFile{}, false, err
}
if err := s.importFile(file, pins); err != nil {
return artifact.MaterializedFile{}, false, err
}
return file.materialization(pins), true, nil
}
// materialization returns a fresh digest map for one request: the store's
// SHA-256 and only the digests that request pinned. The cached digest map
// stays private, so a later request cannot change a map already returned to
// an earlier caller.
func (f *localRuntimeFile) materialization(requested map[string]string) artifact.MaterializedFile {
hashes := make(map[string]string, len(requested)+1)
hashes["sha256"] = f.digests["sha256"]
for algorithm := range requested {
hashes[algorithm] = f.digests[algorithm]
}
return artifact.MaterializedFile{Path: f.storePath, Hashes: hashes}
}
func (s *localRuntimeSource) match(pins map[string]string) *localRuntimeFile {
if len(pins) == 0 {
return nil
}
for _, file := range s.files {
if file.matches(s, pins) {
return file
}
}
return nil
}
// matches first rejects files any known digest already disproves, then
// digests only the missing pinned algorithms and the observed SHA-256 in one
// pass over the file. Computed digests are cached before comparison, so a
// non-matching file never hashes twice.
func (f *localRuntimeFile) matches(s *localRuntimeSource, pins map[string]string) bool {
needed := map[string]string{"sha256": f.digests["sha256"]}
for algorithm, digest := range pins {
if known := f.digests[algorithm]; known != "" {
if !strings.EqualFold(known, digest) {
return false
}
} else {
needed[algorithm] = ""
}
}
if len(needed) == 1 {
return true
}
if !s.confined(f) {
return false
}
computed, err := DigestFile(f.path, needed)
if err != nil {
return false
}
maps.Copy(f.digests, computed)
for algorithm, digest := range pins {
if !strings.EqualFold(f.digests[algorithm], digest) {
return false
}
}
return true
}
func (s *localRuntimeSource) confined(file *localRuntimeFile) bool {
info, err := os.Lstat(file.path)
return err == nil && info.Mode().IsRegular() &&
workspacewrite.SafePath(s.root, file.rel) == nil
}
func (s *localRuntimeSource) importFile(
file *localRuntimeFile,
expected map[string]string,
) error {
store, err := artifactstore.Open()
if err != nil {
return err
}
defer store.Close()
object, _, err := importFile(store.Store, file.path, file.rel, expected)
if err != nil {
return err
}
file.storePath = store.Path(object.Digest)
return nil
}
package install
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
"github.com/mclucy/lucy/workspace/discovery"
)
// AdoptedPackage identifies a package file discovered during initialization.
type AdoptedPackage struct {
Path string
PackageID string
ExpectedSHA256 string
ExpectedMode uint32
}
// AdoptedRuntimeFile identifies a runtime file discovered during initialization.
type AdoptedRuntimeFile struct {
Path string
Role discovery.FileRole
ExpectedSHA256 string
// ExpectedHashes carries every digest discovery computed for the file, so
// a later pin match does not read the same bytes for another algorithm.
ExpectedHashes map[string]string
ExpectedMode uint32
}
// AdoptOptions controls explicit initialization adoption.
type AdoptOptions struct {
Manifest *document.Manifest
Lock *document.Lock
RuntimeFiles []AdoptedRuntimeFile
// Image is the runtime image of Lock from Service.RuntimeImage. A nil
// image limits runtime ownership to the files the lock pins by digest.
Image []bootstrap.Output
Packages []AdoptedPackage
Logger *log.Logger
// PublishLock publishes the resolved lock with the adoption. Callers that
// reused an existing lock byte-for-byte leave it false.
PublishLock bool
// ManifestSnapshot encodes a fresh manifest. ManifestMerge merges into the
// bytes already on disk; nil replaces them, matching the configured
// document service (WithoutMerge/WithEncoder).
ManifestSnapshot func() ([]byte, error)
ManifestMerge func([]byte) ([]byte, error)
// Preconditions pins the document bytes the operation observed right after
// recovery. Publication fails instead of overwriting a document that
// changed while the operation resolved. The zero value captures the state
// at adoption start.
Preconditions WorkspaceDocuments
}
// AdoptExistingWorkspace claims runtime files that match the image, or files
// pinned by the lock if the image is unavailable. It also claims identified
// packages. It publishes the documents and receipt in one transaction and
// leaves the runtime files unchanged. The warnings name claims that the next
// install must still complete.
//
// The receipt gets a bootstrap fingerprint only when all managed image
// entries are claimed with the image's permissions and all seeds are present.
// A previously accepted receipt baseline cannot change during adoption.
func AdoptExistingWorkspace(root string, opts AdoptOptions) (warnings []error, resultErr error) {
if opts.Lock == nil {
return nil, errors.New("cannot adopt workspace without lock")
}
root, err := filepath.Abs(root)
if err != nil {
return nil, err
}
if opts.Preconditions.documents == nil {
opts.Preconditions, err = CaptureWorkspaceDocuments(root)
if err != nil {
return nil, err
}
}
files, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
tracked := trackedPaths(opts.Lock)
memo := fileidentity.NewMemo()
check := currentCheck{
memo: memo,
evidence: newCurrentEvidence(root, memo, opts.Logger),
}
current, legacy, ledger, err := loadAdoptionReceipt(
files,
root,
opts.Preconditions,
tracked,
check,
)
if err != nil {
return nil, err
}
if err := adoptRuntime(files, root, opts, tracked, ledger, check); err != nil {
return nil, err
}
if err := adoptPackages(files, root, opts, tracked, ledger, check); err != nil {
return nil, err
}
if err := adoptMCDRWrapper(root, opts, tracked, ledger); err != nil {
return nil, err
}
if err := ledger.rejectUnclaimedLegacy(); err != nil {
return nil, err
}
next, err := ledger.build(root, opts.Lock)
if err != nil {
return nil, err
}
publishReceipt := adoptionReceiptChanged(
current,
legacy,
next,
opts.Preconditions.documents[receipt.Filename].image != nil,
)
return ledger.warnings, publishAdoption(root, opts, next, publishReceipt, ledger.images, ledger.seedPaths, check)
}
// adoptionLedger accumulates ownership claims over the receipt read at
// adoption start. It keeps accepted baselines separate from the entries being
// built so a claim can never silently reset a protected file.
type adoptionLedger struct {
previous map[string]receipt.Entry
entries map[string]receipt.Entry
images map[string]*workspacewrite.InstallImage
legacyUnclaimed map[string]struct{}
bootstrapFingerprint string
// seedPaths names the seed files the fingerprint requires to exist.
seedPaths []string
warnings []error
check currentCheck
}
func newAdoptionLedger(check currentCheck) *adoptionLedger {
return &adoptionLedger{
previous: make(map[string]receipt.Entry),
entries: make(map[string]receipt.Entry),
images: make(map[string]*workspacewrite.InstallImage),
legacyUnclaimed: make(map[string]struct{}),
check: check,
}
}
// loadAdoptionReceipt decodes the receipt captured at adoption start and
// preserves its accepted baselines, without reading the document a second
// time. Legacy entries lack origin attribution, so they are held aside until
// adoption re-identifies their paths; an entry that stays unattributed fails
// closed instead of entering a receipt that cannot validate.
func loadAdoptionReceipt(
files *os.Root,
root string,
documents WorkspaceDocuments,
tracked map[string]bool,
check currentCheck,
) (*receipt.Receipt, bool, *adoptionLedger, error) {
captured, ok := documents.documents[receipt.Filename]
if !ok {
return nil, false, nil, fmt.Errorf(
"adoption preconditions do not pin %s",
receipt.Filename,
)
}
var current *receipt.Receipt
legacy := false
if captured.image != nil {
parsed, err := receipt.Decode(bytes.NewReader(captured.raw))
var legacyErr *receipt.ErrLegacyReceipt
switch {
case errors.As(err, &legacyErr):
current = legacyErr.Receipt
legacy = true
case err != nil:
return nil, false, nil, fmt.Errorf("read existing receipt: %w", err)
default:
current = parsed
}
}
ledger := newAdoptionLedger(check)
if current == nil {
return nil, false, ledger, nil
}
if current.Version != receipt.Version {
return nil, false, nil, fmt.Errorf(
"unsupported installation receipt version %d",
current.Version,
)
}
for _, entry := range current.Entries {
cleanPath := cleanWorkspacePath(entry.Path)
if !workspacePathSafe(root, cleanPath) {
return nil, false, nil, fmt.Errorf(
"unsafe existing receipt path %q",
entry.Path,
)
}
if tracked[strings.ToLower(cleanPath)] {
return nil, false, nil, fmt.Errorf(
"tracked file %s collides with previously managed output in receipt",
cleanPath,
)
}
image, err := verifyExistingBaseline(files, cleanPath, entry, check)
if err != nil {
return nil, false, nil, err
}
ledger.previous[cleanPath] = entry
ledger.images[cleanPath] = image
if !legacy || attributedOrigin(entry.Origin) {
ledger.entries[cleanPath] = entry
continue
}
ledger.legacyUnclaimed[cleanPath] = struct{}{}
}
return current, legacy, ledger, nil
}
// claim records that adoption owns path with the given origin and identity.
// An existing entry or accepted baseline must agree; a changed digest, mode,
// origin, or package identity fails closed so adoption never resets a
// protected file.
func (l *adoptionLedger) claim(
path string,
origin string,
packageID string,
observed *workspacewrite.InstallImage,
) error {
if observed.Mode == 0 {
return fmt.Errorf(
"cannot adopt %s with mode 0000: the receipt cannot record it as an observed mode",
path,
)
}
if prior, exists := l.entries[path]; exists {
if prior.Origin != origin || prior.Package != packageID {
return fmt.Errorf(
"path %s has conflicting ownership: %s/%s vs %s/%s",
path, prior.Origin, prior.Package, origin, packageID,
)
}
return nil
}
prior, exists := l.previous[path]
if !exists {
l.entries[path] = receipt.Entry{
Path: path,
SHA256: observed.SHA256,
Mode: observed.Mode,
Origin: origin,
Package: packageID,
}
l.images[path] = observed
return nil
}
if prior.SHA256 == "" {
return fmt.Errorf(
"managed output %s has no accepted baseline; remove its receipt entry before re-initializing",
path,
)
}
if observed.SHA256 != "" && !strings.EqualFold(prior.SHA256, observed.SHA256) {
return fmt.Errorf(
"locally modified managed output %s cannot be re-initialized without explicit conflict resolution",
path,
)
}
if prior.Mode != 0 && workspacewrite.EffectiveInstallMode(
os.FileMode(prior.Mode),
) != observed.Mode {
return fmt.Errorf(
"managed output %s changed mode from %#o to %#o; resolve the modification before re-initializing",
path, prior.Mode, observed.Mode,
)
}
if prior.Origin != "" && prior.Origin != origin &&
!(prior.Origin == receipt.OriginBootstrap && origin == receipt.OriginMCDR) {
return fmt.Errorf(
"path %s has conflicting ownership origins: %s and %s",
path, prior.Origin, origin,
)
}
if prior.Origin == receipt.OriginPackage &&
prior.Package != "" && packageID != "" && prior.Package != packageID {
return fmt.Errorf(
"path %s has conflicting package identity: %s and %s",
path, prior.Package, packageID,
)
}
// Preserve the accepted baseline the local edit is measured against; a
// legacy entry without a recorded mode adopts the observed one. Keep the
// image observed when the receipt was read, so a missing path stays a
// missing-path precondition and any reappearance is a conflict.
baselineMode := prior.Mode
if baselineMode == 0 {
baselineMode = observed.Mode
}
l.entries[path] = receipt.Entry{
Path: path,
SHA256: prior.SHA256,
Mode: baselineMode,
Origin: origin,
Package: packageID,
}
delete(l.legacyUnclaimed, path)
return nil
}
// rejectUnclaimedLegacy fails when a legacy entry could not be re-identified
// by this explicit adoption, because its origin and protection cannot be
// carried into a modern receipt safely.
func (l *adoptionLedger) rejectUnclaimedLegacy() error {
if len(l.legacyUnclaimed) == 0 {
return nil
}
unclaimed := make([]string, 0, len(l.legacyUnclaimed))
for path := range l.legacyUnclaimed {
unclaimed = append(unclaimed, path)
}
slices.Sort(unclaimed)
return fmt.Errorf(
"legacy installation receipt records paths initialization could not re-identify: %s; "+
"restore the files and rerun lucy init --force, or delete %s and rerun "+
"lucy init --force to rebuild the receipt from observed files",
strings.Join(unclaimed, ", "),
receipt.Filename,
)
}
// build finalizes the receipt: package fingerprint, sorted entries, alias
// rejection, and schema validation.
func (l *adoptionLedger) build(root string, lock *document.Lock) (receipt.Receipt, error) {
var packageFingerprint string
if packageSetObserved(root, lock, l.entries, l.check) {
fingerprint, err := receipt.PackageFingerprint(lock)
if err != nil {
return receipt.Receipt{}, err
}
packageFingerprint = fingerprint
}
names := make([]string, 0, len(l.entries))
for path := range l.entries {
names = append(names, path)
}
slices.Sort(names)
if err := rejectCommitPathAliases(root, "adoption", names); err != nil {
return receipt.Receipt{}, fmt.Errorf(
"conflicting path aliases in adopted files: %w",
err,
)
}
next := receipt.New()
next.BootstrapFingerprint = l.bootstrapFingerprint
next.SeedPaths = slices.Clone(l.seedPaths)
next.PackageFingerprint = packageFingerprint
next.Entries = make([]receipt.Entry, 0, len(names))
for _, name := range names {
next.Entries = append(next.Entries, l.entries[name])
}
if err := next.Validate(); err != nil {
return receipt.Receipt{}, fmt.Errorf("validate adopted receipt: %w", err)
}
return next, nil
}
func attributedOrigin(origin string) bool {
switch origin {
case receipt.OriginBootstrap, receipt.OriginPackage, receipt.OriginMCDR:
return true
default:
return false
}
}
package install
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
)
// adoptPackages claims identified package files that discovery observed. A
// file whose bytes or mode changed after discovery fails adoption instead of
// entering the receipt with a stale baseline.
func adoptPackages(
files *os.Root,
root string,
opts AdoptOptions,
tracked map[string]bool,
ledger *adoptionLedger,
check currentCheck,
) error {
for _, pkg := range opts.Packages {
if pkg.Path == "" {
continue
}
fullPath := pkg.Path
if !filepath.IsAbs(fullPath) {
fullPath = filepath.Join(root, fullPath)
}
cleanRel, ok := workspaceRelative(root, fullPath)
if !ok {
return fmt.Errorf("package file %s escapes the workspace", pkg.Path)
}
if err := workspacewrite.SafePath(root, cleanRel); err != nil {
return err
}
if tracked[strings.ToLower(cleanRel)] || installPathReserved(root, cleanRel) {
continue
}
image, err := workspacewrite.ObserveInstallImageCached(files, cleanRel, check.memo)
if err != nil || image == nil {
if pkg.ExpectedSHA256 != "" {
if err != nil {
return fmt.Errorf("inspect accepted package file %s: %w", cleanRel, err)
}
return fmt.Errorf(
"package file %s disappeared between discovery and adoption publication",
cleanRel,
)
}
if opts.Logger != nil {
opts.Logger.Debug(
"skip package file without an observed image",
"path", cleanRel,
)
}
continue
}
if pkg.ExpectedSHA256 != "" {
if !strings.EqualFold(image.SHA256, pkg.ExpectedSHA256) {
return fmt.Errorf(
"package file %s changed between discovery and adoption publication",
cleanRel,
)
}
if image.Mode != workspacewrite.EffectiveInstallMode(os.FileMode(pkg.ExpectedMode)) {
return fmt.Errorf(
"package file %s changed mode between discovery and adoption publication",
cleanRel,
)
}
}
packageID := pkg.PackageID
if packageID == "" {
packageID = lockedPackageID(opts.Lock, cleanRel)
}
if err := ledger.claim(
cleanRel,
receipt.OriginPackage,
packageID,
image,
); err != nil {
return err
}
}
return nil
}
// lockedPackageID returns the identity installation records for the package
// whose destination is path.
func lockedPackageID(lock *document.Lock, path string) string {
if lock == nil {
return ""
}
for i := range lock.Packages {
pkg := &lock.Packages[i]
dest, err := lock.PackageDestination(pkg)
if err != nil || cleanWorkspacePath(dest) != path {
continue
}
if pkg.Artifact.ProjectID != "" {
return pkg.Artifact.Provider.String() + ":" + pkg.Artifact.ProjectID
}
return pkg.Filename
}
return ""
}
// adoptMCDRWrapper claims the MCDR wrapper launcher when installation would
// generate exactly those bytes. Initialization selects no isolated
// environment, so a customized or venv-specific wrapper stays unowned.
func adoptMCDRWrapper(
root string,
opts AdoptOptions,
tracked map[string]bool,
ledger *adoptionLedger,
) error {
if opts.Lock.MCDR == nil {
return nil
}
relative := cleanWorkspacePath(
filepath.Join(opts.Lock.MCDR.Directory, "run-mcdr.sh"),
)
if !workspacePathSafe(root, relative) ||
tracked[strings.ToLower(relative)] ||
installPathReserved(root, relative) {
return nil
}
target := filepath.Join(root, filepath.FromSlash(relative))
info, err := os.Lstat(target)
switch {
case errors.Is(err, os.ErrNotExist):
return nil
case err != nil:
return err
}
if !info.Mode().IsRegular() {
return nil
}
data, err := os.ReadFile(target)
if err != nil {
return err
}
matched, err := matchesGeneratedWrapper(root, opts.Lock, data)
if err != nil {
return err
}
if !matched {
if opts.Logger != nil {
opts.Logger.Debug(
"MCDR wrapper launcher left unowned; bytes do not match a generated launcher",
"path", relative,
)
}
return nil
}
return ledger.claim(
relative,
receipt.OriginMCDR,
"",
workspacewrite.InstallBytesImage(data, info.Mode().Perm()),
)
}
// matchesGeneratedWrapper reports whether data equals one of the launcher
// scripts installation can generate for the lock. An isolated launcher is only
// valid while the interpreter it names exists in the workspace.
func matchesGeneratedWrapper(
root string,
lock *document.Lock,
data []byte,
) (bool, error) {
for _, variant := range mcdrLauncherVariants(lock) {
if !bytes.Equal(data, variant.Script) {
continue
}
if variant.Interpreter == "" {
return true, nil
}
if !workspacePathSafe(root, variant.Interpreter) {
continue
}
info, err := os.Lstat(
filepath.Join(root, filepath.FromSlash(variant.Interpreter)),
)
if err != nil || !info.Mode().IsRegular() {
continue
}
return true, nil
}
return false, nil
}
package install
import (
"os"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
)
// publishAdoption rechecks every claimed output, every seed the bootstrap
// fingerprint requires, and every reused document before the journal commit
// point, so a concurrent edit cannot enter the receipt as an accepted
// baseline.
func publishAdoption(
root string,
opts AdoptOptions,
next receipt.Receipt,
publishReceipt bool,
expected map[string]*workspacewrite.InstallImage,
seeds []string,
check currentCheck,
) error {
manifestSnapshot := opts.ManifestSnapshot
if opts.Manifest != nil && manifestSnapshot == nil {
manifestSnapshot = func() ([]byte, error) {
return document.ManifestFile(root).Snapshot(opts.Manifest)
}
}
writes, err := opts.Preconditions.documentWrites(
documentCandidate{
name: document.ManifestFilename,
mode: 0o644,
publish: opts.Manifest != nil,
snapshot: manifestSnapshot,
merge: opts.ManifestMerge,
},
documentCandidate{
name: document.LockFilename,
mode: 0o644,
publish: opts.Lock != nil && opts.PublishLock,
snapshot: opts.Lock.Snapshot,
merge: opts.Lock.MergeBytes,
},
documentCandidate{
name: receipt.Filename,
mode: 0o600,
publish: publishReceipt,
snapshot: next.Snapshot,
},
)
if err != nil {
return err
}
_, err = executeCommit(root, commitRequest{
label: "adoption",
writes: writes,
documents: opts.Preconditions,
verify: func(
files *os.Root,
_ []workspacewrite.InstallJournalEntry,
) error {
if err := verifyAdoptedOutputs(files, root, expected, check); err != nil {
return err
}
return verifyAdoptedSeeds(files, seeds)
},
}, check, opts.Logger)
if err != nil {
return err
}
check.evidence.write(root, next.Entries, opts.Logger)
return nil
}
package install
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
)
func adoptRuntime(
files *os.Root,
root string,
opts AdoptOptions,
tracked map[string]bool,
ledger *adoptionLedger,
check currentCheck,
) error {
if opts.Lock.Server.Bootstrap == "" && opts.Lock.Server.Product == "" {
return nil
}
baselines := runtimeBaselines(root, opts.RuntimeFiles)
if opts.Image == nil {
return adoptPinnedRuntime(files, root, opts, tracked, baselines, ledger)
}
entries := make([]snapshot.Entry, 0, len(opts.Image))
var skipped int
for _, out := range opts.Image {
if out.Role != bootstrap.RoleRuntime || out.Policy == bootstrap.PolicyDiscard {
continue
}
if out.Policy == bootstrap.PolicyManaged && runtimePathReserved(root, out.Path, tracked) {
skipped++
continue
}
entries = append(entries, snapshot.Entry{
Path: out.Path,
SHA256: out.SHA256,
Mode: out.Mode,
Policy: string(out.Policy),
})
}
compared, err := snapshot.CompareCached(root, entries, check.memo)
if err != nil {
return fmt.Errorf("compare existing runtime with the locked image: %w", err)
}
claim := func(entry snapshot.Entry) (bool, error) {
expected := &workspacewrite.InstallImage{
SHA256: entry.SHA256,
Mode: workspacewrite.EffectiveInstallMode(os.FileMode(entry.Mode)),
}
if !runtimeBaselineMatches(entry.Path, expected, baselines) {
return false, nil
}
return true, ledger.claim(entry.Path, receipt.OriginBootstrap, "", expected)
}
for _, entry := range compared.Matching {
if entry.Policy != string(bootstrap.PolicyManaged) {
continue
}
claimed, err := claim(entry)
if err != nil {
return err
}
if !claimed {
skipped++
}
}
// A file with the image's bytes but other permissions stays owned with
// its observed mode. The fingerprint is withheld, so the next install
// restores the image's permissions.
var otherPermissions []string
for _, entry := range compared.OtherPermissions {
claimed, err := claim(entry)
if err != nil {
return err
}
if !claimed {
skipped++
continue
}
otherPermissions = append(otherPermissions, entry.Path)
}
if len(otherPermissions) > 0 {
ledger.warnings = append(ledger.warnings, fmt.Errorf(
"runtime files have other permissions than the runtime image: %s; the next lucy install restores them",
strings.Join(otherPermissions, ", "),
))
}
runtimeDiffers := len(otherPermissions) > 0
for _, entry := range compared.Differing {
if entry.Policy == string(bootstrap.PolicyManaged) {
runtimeDiffers = true
continue
}
// An edited seed still counts as present; another kind of file at
// a seed path does not.
if !regularFileWithin(files, entry.Path) {
runtimeDiffers = true
}
}
if opts.Logger != nil {
opts.Logger.Debug(
"compared existing server with the locked runtime image",
"matching", len(compared.Matching),
"differing", len(compared.Differing),
"other-permissions", len(compared.OtherPermissions),
"missing", len(compared.Missing),
"skipped", skipped,
)
}
// Missing seeds require a stage, but existing seeds stay user-owned.
if runtimeDiffers || len(compared.Missing) > 0 || skipped > 0 {
return nil
}
fingerprint, err := receipt.BootstrapFingerprint(opts.Lock)
if err != nil {
return err
}
ledger.bootstrapFingerprint = fingerprint
ledger.seedPaths = observedSeedPaths(root, opts.Image, tracked)
return nil
}
func regularFileWithin(files *os.Root, rel string) bool {
info, err := files.Lstat(filepath.FromSlash(rel))
return err == nil && info.Mode().IsRegular()
}
func runtimeBaselines(root string, observed []AdoptedRuntimeFile) map[string]AdoptedRuntimeFile {
baselines := make(map[string]AdoptedRuntimeFile, len(observed))
for _, file := range observed {
if rel, ok := workspaceRelative(root, file.Path); ok {
baselines[rel] = file
}
}
return baselines
}
func runtimeBaselineMatches(
rel string,
current *workspacewrite.InstallImage,
baselines map[string]AdoptedRuntimeFile,
) bool {
observed, ok := baselines[rel]
return !ok || (current.Mode == observed.ExpectedMode &&
strings.EqualFold(current.SHA256, observed.ExpectedSHA256))
}
func adoptPinnedRuntime(
files *os.Root,
root string,
opts AdoptOptions,
tracked map[string]bool,
baselines map[string]AdoptedRuntimeFile,
ledger *adoptionLedger,
) error {
server := opts.Lock.Server
if err := document.SafeRelativePath(server.Directory); err != nil {
return err
}
// Only managed runtime outputs enter the receipt. A pinned input that the
// method discards after staging, such as the Forge mappings, stays with
// the user, as it does after a fresh install.
claim := func(serverRel string, pins map[string]string) error {
spec, declared, err := bootstrap.ClassifyOutput(server, serverRel)
if err != nil {
return err
}
if !declared || spec.Policy != bootstrap.PolicyManaged || spec.Role != bootstrap.RoleRuntime {
return nil
}
rel := filepath.ToSlash(filepath.Join(server.Directory, filepath.FromSlash(serverRel)))
if runtimePathReserved(root, rel, tracked) || !workspacePathSafe(root, rel) {
return nil
}
if err := requirePinnedArtifact(pins, rel); err != nil {
return nil
}
current, err := pinnedRuntimeImage(files, rel, pins)
if err != nil || current == nil {
return err
}
if !runtimeBaselineMatches(rel, current, baselines) {
return nil
}
return ledger.claim(rel, receipt.OriginBootstrap, "", current)
}
for _, input := range server.Inputs {
rel, err := bootstrap.InputPath(server.Bootstrap, input)
if err != nil {
return err
}
if err := claim(rel, input.Hashes); err != nil {
return err
}
}
corePath, err := bootstrap.CorePath(server)
if err != nil {
return err
}
if corePath != "" {
return claim(corePath, server.Artifact.Hashes)
}
return nil
}
func pinnedRuntimeImage(
files *os.Root,
rel string,
pins map[string]string,
) (*workspacewrite.InstallImage, error) {
info, err := files.Lstat(rel)
switch {
case errors.Is(err, os.ErrNotExist):
return nil, nil
case err != nil:
return nil, fmt.Errorf("inspect pinned runtime file %s: %w", rel, err)
case !info.Mode().IsRegular():
return nil, nil
}
file, err := files.Open(rel)
if err != nil {
return nil, fmt.Errorf("open pinned runtime file %s: %w", rel, err)
}
hashes, err := digestReader(file, rel, pins)
if closeErr := file.Close(); closeErr != nil {
return nil, errors.Join(err, closeErr)
}
if errors.Is(err, errArtifactDigestMismatch) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("digest pinned runtime file %s: %w", rel, err)
}
return &workspacewrite.InstallImage{
SHA256: hashes["sha256"],
Mode: workspacewrite.EffectiveInstallMode(info.Mode().Perm()),
}, nil
}
func runtimePathReserved(root, rel string, tracked map[string]bool) bool {
return tracked[strings.ToLower(rel)] || installPathReserved(root, rel)
}
// workspaceRelative converts an absolute path inside root to a clean
// workspace-relative path.
func workspaceRelative(root, path string) (string, bool) {
rel, err := filepath.Rel(root, path)
if err != nil || !filepath.IsLocal(rel) {
return "", false
}
return cleanWorkspacePath(rel), true
}
func cleanWorkspacePath(path string) string {
return filepath.ToSlash(filepath.Clean(filepath.FromSlash(path)))
}
func workspacePathSafe(root, rel string) bool {
return filepath.IsLocal(filepath.FromSlash(rel)) &&
workspacewrite.SafePath(root, rel) == nil
}
func isManagedRuntimeOutput(out bootstrap.Output) bool {
return out.Policy == bootstrap.PolicyManaged && out.Role == bootstrap.RoleRuntime
}
// observedSeedPaths lists the seed outputs a verified bootstrap produced.
// Tracked files stay user-owned and unrecorded.
func observedSeedPaths(root string, outputs []bootstrap.Output, tracked map[string]bool) []string {
paths := make([]string, 0, len(outputs))
for _, out := range outputs {
if out.Policy != bootstrap.PolicySeed {
continue
}
clean := cleanWorkspacePath(out.Path)
if tracked[strings.ToLower(clean)] || !workspacePathSafe(root, clean) {
continue
}
paths = append(paths, clean)
}
slices.Sort(paths)
return paths
}
package install
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
)
// receiptImage returns the content and normalized permission mode an accepted
// receipt entry records. A zero mode predates mode recording, so callers match
// it without permission evidence.
func receiptImage(entry receipt.Entry) *workspacewrite.InstallImage {
return &workspacewrite.InstallImage{
SHA256: strings.ToLower(entry.SHA256),
Mode: workspacewrite.EffectiveInstallMode(os.FileMode(entry.Mode)),
}
}
// matchesReceipt reports whether current still satisfies an accepted receipt
// entry. A zero mode is a legacy wildcard; every other mode is exact.
func matchesReceipt(entry receipt.Entry, current *workspacewrite.InstallImage) bool {
return workspacewrite.InstallImagesMatch(
current,
receiptImage(entry),
entry.Mode != 0,
)
}
// packageFilePinned reports whether target still holds every digest the
// artifact pins. The observation is memoized, so a package whose stat identity
// this command already hashed is not read again.
func packageFilePinned(check currentCheck, target string, pins map[string]string) bool {
algorithms := make([]string, 0, len(pins))
for algorithm, digest := range pins {
if algorithm == "sha256" || strings.TrimSpace(digest) == "" {
continue
}
algorithms = append(algorithms, algorithm)
}
observation, err := check.memo.ObservePath(target, algorithms)
if err != nil || !observation.Exists || !observation.Regular {
return false
}
for algorithm, want := range pins {
if strings.TrimSpace(want) == "" {
continue
}
got := observation.Hashes[algorithm]
if got == "" || !strings.EqualFold(got, want) {
return false
}
}
return true
}
// verifyExistingBaseline checks that a receipt entry still describes the file
// it protects and returns the observed image. Content and permission changes
// fail closed; a missing file returns a nil image and keeps its ownership
// record for later repair.
func verifyExistingBaseline(
files *os.Root,
cleanPath string,
entry receipt.Entry,
check currentCheck,
) (*workspacewrite.InstallImage, error) {
current, err := workspacewrite.ObserveInstallImageCached(files, cleanPath, check.memo)
if err != nil {
return nil, fmt.Errorf("inspect existing managed path %s: %w", cleanPath, err)
}
if current == nil {
return nil, nil
}
if entry.SHA256 == "" {
return nil, fmt.Errorf(
"existing managed path %s has no accepted baseline; remove its receipt entry before re-initializing",
cleanPath,
)
}
if matchesReceipt(entry, current) {
return current, nil
}
if !strings.EqualFold(current.SHA256, entry.SHA256) {
return nil, fmt.Errorf(
"locally modified managed output %s cannot be re-initialized without explicit conflict resolution",
cleanPath,
)
}
return nil, fmt.Errorf(
"managed output %s changed mode from %#o to %#o; resolve the modification before re-initializing",
cleanPath, entry.Mode, current.Mode,
)
}
// adoptionReceiptChanged reports whether adoption must rewrite the receipt.
// An unchanged receipt keeps its exact bytes, including hand-formatted fields;
// a legacy receipt always needs the modern origins Snapshot emits.
func adoptionReceiptChanged(
previous *receipt.Receipt,
legacy bool,
next receipt.Receipt,
exists bool,
) bool {
if !exists || previous == nil {
return len(next.Entries) > 0 ||
len(next.SeedPaths) > 0 ||
next.BootstrapFingerprint != "" ||
next.PackageFingerprint != ""
}
if legacy || previous.LockFingerprint != "" ||
previous.Version != next.Version ||
previous.BootstrapFingerprint != next.BootstrapFingerprint ||
!slices.Equal(previous.SeedPaths, next.SeedPaths) ||
previous.PackageFingerprint != next.PackageFingerprint {
return true
}
if len(previous.Entries) != len(next.Entries) {
return true
}
prior := make(map[string]receipt.Entry, len(previous.Entries))
for _, entry := range previous.Entries {
prior[entry.Path] = entry
}
for _, entry := range next.Entries {
if prior[entry.Path] != entry {
return true
}
}
return false
}
// packageSetObserved reports whether the adopted entries already describe the
// lock's enabled packages, so the receipt may record its package fingerprint.
// Package-owned paths that the lock no longer selects refuse the fingerprint
// because they still need pruning.
func packageSetObserved(
root string,
lock *document.Lock,
entries map[string]receipt.Entry,
check currentCheck,
) bool {
if len(lock.Packages) == 0 && lock.MCDR != nil {
return false
}
claimed := make(map[string]struct{}, len(lock.Packages))
for i := range lock.Packages {
pkg := &lock.Packages[i]
if !pkg.Enabled() {
continue
}
dest, err := lock.PackageDestination(pkg)
if err != nil {
return false
}
cleanDest := cleanWorkspacePath(dest)
entry, ok := entries[cleanDest]
if !ok || entry.Origin != receipt.OriginPackage {
return false
}
expectedID := pkg.Artifact.Provider.String() + ":" + pkg.Artifact.ProjectID
if pkg.Artifact.ProjectID != "" && entry.Package != "" &&
entry.Package != expectedID && entry.Package != pkg.Filename {
return false
}
if len(pkg.Artifact.Hashes) == 0 {
return false
}
target := filepath.Join(root, filepath.FromSlash(cleanDest))
if !packageFilePinned(check, target, pkg.Artifact.Hashes) {
return false
}
claimed[cleanDest] = struct{}{}
}
for path, entry := range entries {
switch entry.Origin {
case receipt.OriginPackage:
if _, ok := claimed[path]; !ok {
return false
}
case receipt.OriginMCDR:
if lock.MCDR == nil {
return false
}
}
}
return true
}
// verifyAdoptedOutputs rechecks the exact images adoption observed. A present
// file that changed, disappeared, or changed mode after planning must not
// enter the receipt with a stale baseline. A file that was already missing
// keeps its ownership record for later repair, but a path that reappears
// before the commit point is a conflict, not observed evidence.
func verifyAdoptedOutputs(
files *os.Root,
root string,
expected map[string]*workspacewrite.InstallImage,
check currentCheck,
) error {
paths := make([]string, 0, len(expected))
for path := range expected {
paths = append(paths, path)
}
slices.Sort(paths)
type verifiedOutput struct {
image *workspacewrite.InstallImage
identity fileidentity.Identity
hasIdentity bool
err error
}
results := make([]verifiedOutput, len(paths))
workers := min(len(paths), installFileWorkers)
var next atomic.Int64
var group sync.WaitGroup
for range workers {
group.Go(func() {
for {
index := int(next.Add(1)) - 1
if index >= len(paths) {
return
}
path := paths[index]
want := expected[path]
if err := workspacewrite.SafePath(root, path); err != nil {
results[index].err = err
return
}
current, identity, hasIdentity, err := workspacewrite.ObserveInstallImageEvidence(files, path, check.memo)
if err != nil {
results[index].err = fmt.Errorf(
"inspect adopted output %s before publication: %w",
path,
err,
)
return
}
switch {
case want == nil:
if current != nil {
results[index].err = fmt.Errorf(
"adopted output %s appeared before publication",
path,
)
return
}
case current == nil:
results[index].err = fmt.Errorf(
"adopted output %s disappeared before publication",
path,
)
return
case workspacewrite.InstallImagesEqual(current, want):
results[index] = verifiedOutput{
image: current,
identity: identity,
hasIdentity: hasIdentity,
}
case !strings.EqualFold(current.SHA256, want.SHA256):
results[index].err = fmt.Errorf(
"adopted output %s changed before publication",
path,
)
return
default:
results[index].err = fmt.Errorf(
"adopted output %s changed mode before publication",
path,
)
return
}
}
})
}
group.Wait()
for index, path := range paths {
result := results[index]
if result.err != nil {
return result.err
}
if result.image == nil {
continue
}
check.evidence.observe(
receipt.Entry{Path: path, SHA256: result.image.SHA256},
result.identity,
result.hasIdentity,
)
}
return nil
}
// verifyAdoptedSeeds rechecks that every seed the bootstrap fingerprint
// requires is still a regular file. A receipt with the fingerprint skips the
// runtime stage, which is the only step that restores a missing seed.
func verifyAdoptedSeeds(files *os.Root, seeds []string) error {
for _, path := range seeds {
if !regularFileWithin(files, path) {
return fmt.Errorf("runtime seed %s disappeared before publication", path)
}
}
return nil
}
package install
import (
"cmp"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
)
// restoreBootstrapSnapshot restores a stored output set into a fresh stage
// and returns the snapshot it restored. It reports false without an error
// when no snapshot exists, so the caller stages the method from scratch.
func restoreBootstrapSnapshot(
ctx context.Context,
store snapshot.Store,
key cas.Digest,
stage string,
server document.LockedServer,
link fsutil.LinkMode,
trace *Trace,
) (snapshot.Snapshot, bool, error) {
snap, ok, err := store.LookupSnapshot(ctx, key)
if err != nil {
return snapshot.Snapshot{}, false, err
}
if !ok {
return snapshot.Snapshot{}, false, nil
}
root, err := serverRootPath(stage, server)
if err != nil {
return snapshot.Snapshot{}, false, err
}
if err := requireEmptyDirectory(root); err != nil {
return snapshot.Snapshot{}, false, err
}
trace.phaseStarted("bootstrap snapshot")
if err := store.RestoreSnapshot(ctx, snap, root, link); err != nil {
return snapshot.Snapshot{}, false, err
}
return snap, true, nil
}
// publishBootstrapSnapshot stores the checked staging output for reuse by any
// workspace with the same recipe. Material a runtime does not consume (discard
// policy and bootstrap-only tools) is never stored.
//
// The link mode is a machine setting outside the recipe key, so a snapshot
// records the mode of a writable deployment. A method writes every output with
// the owner write bit; only a hardlink placement removes it. Restoring the bit
// here lets each restore apply its own link mode.
func publishBootstrapSnapshot(
ctx context.Context,
store snapshot.Store,
key cas.Digest,
stage string,
server document.LockedServer,
outputs map[string]bootstrap.Output,
) error {
root, err := serverRootPath(stage, server)
if err != nil {
return err
}
entries := make([]snapshot.Entry, 0, len(outputs))
for _, output := range outputs {
if output.Policy == bootstrap.PolicyDiscard ||
output.Role == bootstrap.RoleBootstrapOnly {
continue
}
entries = append(entries, snapshot.Entry{
Path: output.ServerPath,
SHA256: output.SHA256,
Mode: writableMode(output.Mode),
Policy: string(output.Policy),
Role: string(output.Role),
})
}
snap := snapshot.Snapshot{
Key: key,
Entries: entries,
}
return store.SaveSnapshot(ctx, snap, root)
}
// writableMode adds the owner write bit to a recorded mode. Zero stays zero,
// because it marks an unrecorded mode.
func writableMode(mode uint32) uint32 {
if mode == 0 {
return 0
}
return mode | 0o200
}
// snapshotOutputs converts a stored snapshot into the runtime image its
// entries describe, sorted by workspace path. It reads metadata only, so a
// caller that needs the image to compare workspace files does not restore the
// bytes.
func snapshotOutputs(snap snapshot.Snapshot, server document.LockedServer) []bootstrap.Output {
outputs := make([]bootstrap.Output, 0, len(snap.Entries))
for _, entry := range snap.Entries {
path := filepath.ToSlash(filepath.Join(server.Directory, filepath.FromSlash(entry.Path)))
outputs = append(outputs, bootstrap.Output{
Path: path,
ServerPath: entry.Path,
SHA256: entry.SHA256,
Mode: entry.Mode,
Policy: bootstrap.OutputPolicy(entry.Policy),
Role: bootstrap.MaterialRole(entry.Role),
})
}
slices.SortFunc(outputs, func(a, b bootstrap.Output) int {
return cmp.Compare(a.Path, b.Path)
})
return outputs
}
// openSnapshotStore opens the artifact store that owns the snapshot index.
func openSnapshotStore() (*artifactstore.Store, error) {
store, err := artifactstore.Open()
if err != nil {
return nil, fmt.Errorf("open artifact store snapshots: %w", err)
}
return store, nil
}
// serverRootPath validates the locked server directory and returns the
// directory a bootstrap method writes inside the staging root. A handcrafted
// lock may omit the directory, which means the staging root itself.
func serverRootPath(stage string, server document.LockedServer) (string, error) {
directory := cmp.Or(server.Directory, ".")
if err := document.SafeRelativePath(directory); err != nil {
return "", err
}
return filepath.Join(stage, filepath.FromSlash(directory)), nil
}
// requireEmptyDirectory refuses to restore into a directory that already holds
// content. A snapshot restore must never merge with unrelated staging state.
func requireEmptyDirectory(path string) error {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !info.IsDir() {
return fmt.Errorf("staging path %s is not a directory", path)
}
entries, err := os.ReadDir(path)
if err != nil {
return err
}
if len(entries) > 0 {
return fmt.Errorf("staging path %s is not empty; refusing to restore a snapshot over it", path)
}
return nil
}
package install
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspaceguard"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"go.yaml.in/yaml/v4"
)
// commitWrite records one path a transaction creates or replaces. Exactly one
// of data and source supplies the bytes; source names a file outside the
// workspace, such as a staged output. base is the image the planner observed,
// and after is the image the write produces. Satisfying base is the write's
// precondition, not a description of what the path currently holds.
type commitWrite struct {
path string
data []byte
source string
base *workspacewrite.InstallImage
after *workspacewrite.InstallImage
displace bool
}
// commitPrune records one path a transaction removes. A nil expected means the
// path was already absent at planning, so that absence stays a precondition
// instead of disappearing from the journal.
type commitPrune struct {
path string
expected *workspacewrite.InstallImage
}
// commitRequest describes one recoverable transaction. documents pins the
// workspace metadata a publication must not overwrite after observation;
// verify runs after every write and prune, before the commit point, and may
// refuse state the transaction would otherwise publish. Callers own their
// policy; the executor owns the journal, the rollback data, the pinned
// documents, and the recovery contract.
type commitRequest struct {
label string
writes []commitWrite
prunes []commitPrune
documents WorkspaceDocuments
verify func(files *os.Root, entries []workspacewrite.InstallJournalEntry) error
// beforeVerify releases resources the transaction no longer needs, after
// every write published and before the commit-point verification. A
// caller uses it to remove staged copies, so the metadata the
// verification observes is final.
beforeVerify func() error
}
// executeCommit applies a request and returns the entries it mutated, sorted by
// path. The caller must hold the workspace writer lock and must replay any
// interrupted journal first.
func executeCommit(
root string,
request commitRequest,
check currentCheck,
logger *log.Logger,
) (applied []workspacewrite.InstallJournalEntry, resultErr error) {
type change struct {
path string
data []byte
source string
before *workspacewrite.InstallImage
after *workspacewrite.InstallImage
prune bool
displace bool
}
changes := make([]change, 0, len(request.writes)+len(request.prunes))
for _, write := range request.writes {
changes = append(changes, change{
path: write.path,
data: write.data,
source: write.source,
before: write.base,
after: write.after,
displace: write.displace,
})
}
for _, prune := range request.prunes {
changes = append(changes, change{
path: prune.path,
before: prune.expected,
prune: true,
})
}
slices.SortFunc(changes, func(left, right change) int {
return strings.Compare(left.path, right.path)
})
if len(changes) == 0 && request.verify == nil &&
request.documents.documents == nil {
return nil, nil
}
files, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
if len(changes) == 0 {
return nil, runCommitVerify(files, request, nil, check.memo)
}
if err := request.documents.verify(files, nil, check.memo); err != nil {
return nil, err
}
names := make([]string, len(changes))
for i := range changes {
names[i] = changes[i].path
}
if err := rejectCommitPathAliases(root, request.label, names); err != nil {
return nil, err
}
for _, name := range names {
if installPathMatchesReserved(
root, name, workspacewrite.InstallJournalName,
) {
return nil, fmt.Errorf(
"%s path %s is reserved",
request.label,
name,
)
}
}
backupRelative := ".lucy/rollback-" + rand.Text()
backup := filepath.Join(root, filepath.FromSlash(backupRelative))
if err := files.Mkdir(filepath.FromSlash(backupRelative), 0o700); err != nil {
return nil, err
}
journalPublished := false
defer func() {
if journalPublished {
return
}
if err := os.RemoveAll(backup); err != nil {
logger.Warn(fmt.Errorf(
"remove unused %s backup: %w",
request.label,
err,
))
}
}()
journal := workspacewrite.InstallJournal{
Backup: backupRelative,
Entries: make([]workspacewrite.InstallJournalEntry, 0, len(changes)),
}
for _, change := range changes {
if err := workspacewrite.SafePath(root, change.path); err != nil {
return nil, err
}
before, err := workspacewrite.ObserveInstallImage(files, change.path)
if err != nil {
return nil, err
}
if change.prune {
if change.before == nil {
if before != nil {
return nil, fmt.Errorf(
"absent owned output %s reappeared before pruning",
change.path,
)
}
continue
}
if before == nil ||
!workspacewrite.InstallImagesEqual(before, change.before) {
return nil, fmt.Errorf(
"modified or unowned output cannot be pruned: %s",
change.path,
)
}
} else {
if !workspacewrite.InstallImagesEqual(before, change.before) {
return nil, fmt.Errorf(
"%s path %s changed while planning",
request.label,
change.path,
)
}
if !change.displace && before != nil &&
workspacewrite.InstallImagesEqual(before, change.after) {
continue
}
}
if before != nil {
if err := preserveInstallPreImage(
files,
backup,
backupRelative,
*before,
filepath.Join(root, change.path),
); err != nil {
return nil, err
}
}
journal.Entries = append(
journal.Entries,
workspacewrite.InstallJournalEntry{
Path: change.path,
Before: before,
After: change.after,
Displace: change.displace,
},
)
}
if len(journal.Entries) == 0 {
return nil, runCommitVerify(files, request, nil, check.memo)
}
journalBytes, err := yaml.Marshal(journal)
if err != nil {
return nil, err
}
journalPath := filepath.Join(root, workspacewrite.InstallJournalName)
if err := fsutil.AtomicWrite(journalPath, journalBytes, 0o600); err != nil {
// AtomicWrite can return a sync error after the journal replacement was
// published. Keep the backup while any journal remains, so recovery can
// still verify and remove it.
if _, statErr := os.Lstat(journalPath); statErr == nil {
journalPublished = true
}
return nil, err
}
journalPublished = true
logger.Debug(
request.label+" transaction journaled",
"journal", journalPath,
"backup", journal.Backup,
"paths", len(journal.Entries),
)
mutations := make(
map[string]workspacewrite.InstallJournalEntry,
len(journal.Entries),
)
for _, entry := range journal.Entries {
mutations[entry.Path] = entry
}
failed := true
defer func() {
if !failed {
return
}
committed, _ := workspacewrite.InstallJournalCommitted(root)
resultErr = errors.Join(
resultErr,
workspaceguard.RecoverInstall(root, logger),
)
if committed && resultErr != nil {
resultErr = &CommittedError{Err: fmt.Errorf(
"%s committed; %w",
request.label,
resultErr,
)}
}
}()
for _, change := range changes {
entry, mutated := mutations[change.path]
if !mutated {
continue
}
if change.prune {
current, err := workspacewrite.ObserveInstallImageCached(
files, change.path, check.memo,
)
if err != nil {
return nil, err
}
if !workspacewrite.InstallImagesEqual(current, entry.Before) {
return nil, fmt.Errorf(
"%s output %s changed before pruning",
request.label,
change.path,
)
}
if err := files.Remove(change.path); err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, err
}
applied = append(applied, entry)
continue
}
parent := filepath.Dir(change.path)
if parent != "." {
if err := files.MkdirAll(parent, 0o755); err != nil {
return nil, err
}
}
if change.source != "" {
// Stage files belong to this transaction alone, so a hardlink moves
// one into the workspace without a copy. A stage file that is
// itself a store link or clone keeps sharing the store content.
// A mode change falls back to a clone or copy.
if err := fsutil.WriteFileRoot(
files,
change.path,
change.source,
fsutil.LinkHardlink,
fsutil.WriteOptions{
Mode: os.FileMode(entry.After.Mode),
Replace: true,
Check: installBeforeCheck(files, entry, check.memo),
},
); err != nil {
return nil, err
}
} else if err := fsutil.WriteRoot(
files,
change.path,
bytes.NewReader(change.data),
fsutil.WriteOptions{
Mode: os.FileMode(entry.After.Mode),
Replace: true,
Check: installBeforeCheck(files, entry, check.memo),
},
); err != nil {
return nil, err
}
applied = append(applied, entry)
}
if request.beforeVerify != nil {
if err := request.beforeVerify(); err != nil {
return nil, err
}
}
if err := runCommitVerify(files, request, journal.Entries, check.memo); err != nil {
return nil, err
}
journal.Committed = true
committedBytes, err := yaml.Marshal(journal)
if err != nil {
return nil, err
}
if err := fsutil.AtomicWrite(journalPath, committedBytes, 0o600); err != nil {
return nil, err
}
failed = false
if err := workspacewrite.CleanupCommittedInstall(files, &journal); err != nil {
return nil, &CommittedError{Err: err}
}
return applied, nil
}
// runCommitVerify runs the caller's policy and then rechecks pinned documents
// at the commit point. The document check intentionally runs last: caller
// verification may hash outputs for a while, and an edit made during that work
// must still fail the transaction. It runs even when the transaction journaled
// no changes, so a publication that writes nothing still revalidates what
// callers observed.
func runCommitVerify(
files *os.Root,
request commitRequest,
entries []workspacewrite.InstallJournalEntry,
memo *fileidentity.Memo,
) error {
if request.verify != nil {
if err := request.verify(files, entries); err != nil {
return err
}
}
return request.documents.verify(files, request.writes, memo)
}
func installBeforeCheck(
files *os.Root,
entry workspacewrite.InstallJournalEntry,
memo *fileidentity.Memo,
) func() error {
return func() error {
current, err := workspacewrite.ObserveInstallImageCached(files, entry.Path, memo)
if err != nil {
return err
}
if !workspacewrite.InstallImagesEqual(current, entry.Before) {
return fmt.Errorf(
"installation output %s changed before publication",
entry.Path,
)
}
return nil
}
}
// preserveInstallPreImage stores one complete content-addressed before image
// through a synced root-confined publish and verifies the copy. A failure here
// happens before the journal publishes, so the caller removes the unused
// backup directory.
func preserveInstallPreImage(
files *os.Root,
backupPath string,
backupRelative string,
image workspacewrite.InstallImage,
source string,
) error {
relative := filepath.Join(filepath.FromSlash(backupRelative), image.SHA256)
if info, err := files.Lstat(relative); err == nil {
if !info.Mode().IsRegular() {
return fmt.Errorf(
"installation pre-image %s is not a regular file",
image.SHA256,
)
}
} else if errors.Is(err, os.ErrNotExist) {
input, err := os.Open(source)
if err != nil {
return err
}
copyErr := fsutil.WriteRoot(
files,
relative,
input,
fsutil.WriteOptions{Mode: 0o600, Replace: true},
)
closeErr := input.Close()
if copyErr != nil || closeErr != nil {
return errors.Join(copyErr, closeErr)
}
} else {
return err
}
hashes, err := DigestFile(filepath.Join(backupPath, image.SHA256), nil)
if err != nil {
return err
}
if hashes["sha256"] != image.SHA256 {
return fmt.Errorf("installation pre-image %s is incomplete", image.SHA256)
}
return nil
}
package install
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
)
// WorkspaceDocuments pins the manifest, lock, and receipt bytes an operation
// observed after journal recovery. Capture it under the workspace writer lock
// and run recovery first, so the captured state is the recovered one. A nil
// documents map is the zero value and means nothing was captured.
type WorkspaceDocuments struct {
documents map[string]workspaceDocument
}
// workspaceDocument is one document state captured before planning. A nil
// image records an absent path, which is distinct from a present empty file.
type workspaceDocument struct {
raw []byte
image *workspacewrite.InstallImage
}
// workspaceDocumentNames lists the documents a capture pins, in stable order.
var workspaceDocumentNames = [...]string{
document.ManifestFilename,
document.LockFilename,
receipt.Filename,
}
// CaptureWorkspaceDocuments records the current state of the documents an
// operation may publish. The caller must hold the workspace writer lock and
// must run journal recovery first, so the captured state is the recovered one.
func CaptureWorkspaceDocuments(root string) (captured WorkspaceDocuments, resultErr error) {
root, err := filepath.Abs(root)
if err != nil {
return WorkspaceDocuments{}, err
}
files, err := os.OpenRoot(root)
if err != nil {
return WorkspaceDocuments{}, err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
captured.documents = make(map[string]workspaceDocument, len(workspaceDocumentNames))
for _, name := range workspaceDocumentNames {
pinned, err := captureWorkspaceDocument(files, root, name)
if err != nil {
return WorkspaceDocuments{}, err
}
captured.documents[name] = pinned
}
return captured, nil
}
// captureWorkspaceDocument opens one document through the workspace root and
// reads the bytes and permission mode from that same handle, so the capture
// cannot pair bytes from one file with metadata from another. The root
// confines the open, and a replaced entry fails the identity recheck.
func captureWorkspaceDocument(
files *os.Root,
root string,
name string,
) (workspaceDocument, error) {
if err := workspacewrite.SafePath(root, name); err != nil {
return workspaceDocument{}, err
}
info, err := files.Lstat(name)
switch {
case errors.Is(err, os.ErrNotExist):
return workspaceDocument{}, nil
case err != nil:
return workspaceDocument{}, err
}
if !info.Mode().IsRegular() {
return workspaceDocument{}, fmt.Errorf(
"workspace document %s is not a regular file",
name,
)
}
file, err := files.Open(name)
if err != nil {
return workspaceDocument{}, err
}
opened, err := file.Stat()
if err != nil {
return workspaceDocument{}, errors.Join(err, file.Close())
}
if !opened.Mode().IsRegular() || !os.SameFile(info, opened) {
return workspaceDocument{}, errors.Join(
fmt.Errorf("workspace document %s changed while capturing it", name),
file.Close(),
)
}
raw, err := io.ReadAll(file)
closeErr := file.Close()
if err != nil || closeErr != nil {
return workspaceDocument{}, errors.Join(err, closeErr)
}
return workspaceDocument{
raw: raw,
image: workspacewrite.InstallBytesImage(raw, opened.Mode().Perm()),
}, nil
}
// documentWrite predicts the bytes and mode publishing a document produces
// from the captured state, without re-reading the document at publication
// time. A present document merges into its captured bytes; an absent one is
// encoded by snapshot. Publication preserves a present document's mode.
func (d WorkspaceDocuments) documentWrite(
name string,
defaultMode os.FileMode,
snapshot func() ([]byte, error),
merge func([]byte) ([]byte, error),
) (commitWrite, error) {
captured, ok := d.documents[name]
if !ok {
return commitWrite{}, fmt.Errorf(
"workspace document %s was not captured",
name,
)
}
var (
data []byte
err error
)
if captured.image != nil && merge != nil {
data, err = merge(captured.raw)
} else {
if snapshot == nil {
return commitWrite{}, fmt.Errorf(
"workspace document %s has no snapshot",
name,
)
}
data, err = snapshot()
}
if err != nil {
return commitWrite{}, err
}
mode := defaultMode
if captured.image != nil {
// The captured mode already reflects the platform's permission
// representation; reusing it preserves the document's permissions.
mode = os.FileMode(captured.image.Mode)
}
after := workspacewrite.InstallBytesImage(data, mode)
return commitWrite{
path: name,
data: data,
base: captured.image,
after: after,
}, nil
}
// documentCandidate is one metadata file a publication may rewrite. publish
// false keeps the candidate out of the transaction while still declaring its
// mode and encoders.
type documentCandidate struct {
name string
mode os.FileMode
publish bool
snapshot func() ([]byte, error)
merge func([]byte) ([]byte, error)
}
// documentWrites plans the write for every published candidate, in declaration
// order, so adoption and installation share one publication convention.
func (d WorkspaceDocuments) documentWrites(
candidates ...documentCandidate,
) ([]commitWrite, error) {
writes := make([]commitWrite, 0, len(candidates))
for _, candidate := range candidates {
if !candidate.publish {
continue
}
write, err := d.documentWrite(
candidate.name,
candidate.mode,
candidate.snapshot,
candidate.merge,
)
if err != nil {
return nil, err
}
writes = append(writes, write)
}
return writes, nil
}
// verify rechecks every pinned document against files. A document named by
// writes is compared with the image its publication produces, including a
// write skipped because the bytes already matched; every other document is
// compared with its captured image. An external edit, mode change, or
// appearance/disappearance fails closed so publication never overwrites it.
func (d WorkspaceDocuments) verify(
files *os.Root,
writes []commitWrite,
memo *fileidentity.Memo,
) error {
if d.documents == nil {
return nil
}
for _, name := range workspaceDocumentNames {
captured, ok := d.documents[name]
if !ok {
return fmt.Errorf("workspace documents do not pin %s", name)
}
expected := captured.image
for _, write := range writes {
if write.path == name {
expected = write.after
break
}
}
current, err := workspacewrite.ObserveInstallImageCached(files, name, memo)
if err != nil {
return err
}
if !workspacewrite.InstallImagesEqual(current, expected) {
return fmt.Errorf(
"workspace document %s changed since capture; refusing to publish metadata that describes a different workspace",
name,
)
}
}
return nil
}
// rejectCommitPathAliases refuses names the target filesystem resolves to the
// same entry, and names that are not canonical. Otherwise one journal entry
// could overwrite and another could prune the same file. Distinct
// case-sensitive paths stay valid.
func rejectCommitPathAliases(root, label string, names []string) error {
aliases := make(map[string][]string, len(names))
for _, name := range names {
if !filepath.IsLocal(filepath.FromSlash(name)) ||
filepath.ToSlash(filepath.Clean(filepath.FromSlash(name))) != name {
return fmt.Errorf("%s path %q is not canonical", label, name)
}
key := strings.ToLower(name)
for _, prior := range aliases[key] {
if workspacewrite.InstallPathsAlias(root, prior, name) {
return fmt.Errorf(
"%s paths %q and %q alias the same filesystem entry",
label,
prior,
name,
)
}
}
aliases[key] = append(aliases[key], name)
}
return nil
}
func installPathReserved(root, name string) bool {
for _, reserved := range []string{
workspacewrite.InstallJournalName,
document.LockFilename,
document.ManifestFilename,
} {
if installPathMatchesReserved(root, name, reserved) {
return true
}
}
return false
}
// installPathMatchesReserved rejects an exact reserved path always, and a case
// variant only when the target filesystem treats the two names as one entry.
func installPathMatchesReserved(root, name, reserved string) bool {
if name == reserved {
return true
}
if !strings.EqualFold(name, reserved) {
return false
}
return workspacewrite.InstallPathsAlias(root, reserved, name)
}
package install
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
"go.yaml.in/yaml/v4"
)
// currentStatFilename records the stat identity of every receipt file whose
// accepted digest the last command verified. It is evidence, not ownership:
// a missing or invalid record only sends the next check back to the content.
const currentStatFilename = ".lucy/current.yaml"
const currentStatVersion = 1
type currentStatDocument struct {
Version int `yaml:"version"`
Files []currentStatRecord `yaml:"files"`
}
type currentStatRecord struct {
Path string `yaml:"path"`
SHA256 string `yaml:"sha256"`
Identity fileidentity.Identity `yaml:"identity"`
}
// currentEvidence answers a currentness check from stat identities a previous
// command recorded, and collects the identities this command proved so an
// unchanged file is read once across commands.
type currentEvidence struct {
memo *fileidentity.Memo
records map[string]currentStatRecord
recordedNS int64
raw []byte
observed map[string]currentStatRecord
mu sync.Mutex
}
// newCurrentEvidence reads the stat sidecar. Any failure falls back to
// hashing, because the sidecar only saves work and never authorizes a change.
func newCurrentEvidence(
root string,
memo *fileidentity.Memo,
logger *log.Logger,
) *currentEvidence {
evidence := ¤tEvidence{
memo: memo,
records: map[string]currentStatRecord{},
observed: map[string]currentStatRecord{},
}
if err := workspacewrite.SafePath(root, currentStatFilename); err != nil {
logger.Debug("current stat record unavailable", "reason", err.Error())
return evidence
}
target := filepath.Join(root, currentStatFilename)
info, err := os.Lstat(target)
if errors.Is(err, os.ErrNotExist) {
return evidence
}
if err != nil || !info.Mode().IsRegular() {
logger.Debug("current stat record unavailable", "reason", "not a regular file")
return evidence
}
raw, err := os.ReadFile(target)
if err != nil {
logger.Debug("current stat record unreadable", "reason", err.Error())
return evidence
}
var document currentStatDocument
decoder := yaml.NewDecoder(bytes.NewReader(raw))
decoder.KnownFields(true)
if err := decoder.Decode(&document); err != nil ||
document.Version != currentStatVersion {
logger.Debug("current stat record invalid", "reason", "schema mismatch")
return evidence
}
for _, record := range document.Files {
evidence.records[record.Path] = record
}
evidence.recordedNS = info.ModTime().UnixNano()
evidence.raw = raw
return evidence
}
// trusted reports whether the recorded identity still describes entry's file.
// A record only counts when its digest matches the receipt and the file's
// change time predates the record, so a coarse timestamp cannot hide a write
// in the same granule.
func (e *currentEvidence) trusted(entry receipt.Entry, info fs.FileInfo) bool {
if e == nil {
return false
}
record, ok := e.records[entry.Path]
if !ok || !strings.EqualFold(record.SHA256, entry.SHA256) {
return false
}
identity, ok := fileidentity.Of(info)
if !ok || !identity.Same(record.Identity) {
return false
}
return identity.OlderThan(e.recordedNS)
}
func (e *currentEvidence) observe(
entry receipt.Entry,
identity fileidentity.Identity,
hasIdentity bool,
) {
if e == nil || !hasIdentity {
return
}
e.mu.Lock()
defer e.mu.Unlock()
e.observed[entry.Path] = currentStatRecord{
Path: entry.Path,
SHA256: strings.ToLower(entry.SHA256),
Identity: identity,
}
}
// write publishes the identities this command proved for entries. It keeps
// records an earlier command proved and the receipt still names, and leaves an
// unchanged record byte-identical. It never fails the command.
func (e *currentEvidence) write(
root string,
entries []receipt.Entry,
logger *log.Logger,
) {
if e == nil {
return
}
e.mu.Lock()
observed := make(map[string]currentStatRecord, len(e.observed))
for path, record := range e.observed {
observed[path] = record
}
carried := make(map[string]currentStatRecord, len(e.records))
for path, record := range e.records {
carried[path] = record
}
e.mu.Unlock()
records := make([]currentStatRecord, 0, len(entries))
for _, entry := range entries {
record, ok := observed[entry.Path]
if !ok {
record, ok = carried[entry.Path]
}
if !ok || !strings.EqualFold(record.SHA256, entry.SHA256) {
continue
}
records = append(records, record)
}
if len(records) == 0 {
return
}
slices.SortFunc(records, func(left, right currentStatRecord) int {
return strings.Compare(left.Path, right.Path)
})
raw, err := yaml.Marshal(currentStatDocument{
Version: currentStatVersion,
Files: records,
})
if err != nil {
logger.Warn(fmt.Errorf("encode current stat record: %w", err))
return
}
if bytes.Equal(raw, e.raw) {
return
}
target := filepath.Join(root, currentStatFilename)
if err := fsutil.AtomicWrite(target, raw, 0o600); err != nil {
logger.Warn(fmt.Errorf("write current stat record: %w", err))
}
}
package install
import (
"context"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/javaruntime"
)
// selectJava selects the Java runtime of the locked server. When the
// selection misses the requirement and the caller can provision a runtime,
// the caller runs first and the runtime is selected again.
func (s *Service) selectJava(ctx context.Context, root string, resolved *document.Lock, opts Options) (*javaruntime.Check, error) {
requirement := javaruntime.RequirementOf(resolved, s.logger)
check, err := javaruntime.Select(ctx, root, requirement, s.logger)
if err != nil {
return nil, err
}
if opts.ProvisionJava == nil || check.Satisfied() {
return check, nil
}
home, err := opts.ProvisionJava(ctx, requirement, check)
if err != nil {
return nil, err
}
return javaruntime.Select(ctx, root, requirement, s.logger, home)
}
package install
import (
"context"
"fmt"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/version"
)
const mcdrPyPIURL = "https://pypi.org/pypi/mcdreforged/json"
// resolveMCDRVersion picks the MCDReforged version recorded in the lock. A
// floating selector keeps the locked version; otherwise the latest stable
// release comes from PyPI metadata, without touching the local Python.
func (s *Service) resolveMCDRVersion(
ctx context.Context,
request version.Version,
previous *documentpkg.Lock,
offline bool,
) (version.Version, error) {
if !isFloating(request) {
return request, nil
}
if previous != nil && previous.MCDR != nil {
return previous.MCDR.Version, nil
}
if offline {
return "", fmt.Errorf(
"MCDReforged version %q needs network metadata; run online or pin mcdr.version",
request,
)
}
return s.latestMCDRVersion(ctx)
}
func (s *Service) latestMCDRVersion(ctx context.Context) (version.Version, error) {
var document struct {
Info struct {
Version string `json:"version"`
} `json:"info"`
}
if err := s.source.Metadata(ctx, mcdrPyPIURL, &document); err != nil {
return "", fmt.Errorf("look up MCDReforged releases: %w", err)
}
raw := strings.TrimSpace(document.Info.Version)
if raw == "" {
return "", fmt.Errorf("MCDReforged releases carry no version")
}
engine, err := version.NewEngine(version.DialectMCDR)
if err != nil {
return "", err
}
if _, err := engine.ParseVersion(version.Version(raw)); err != nil {
return "", fmt.Errorf("MCDReforged release version %q is not usable: %w", raw, err)
}
return version.Version(raw), nil
}
// mcdrPythonRequirements returns the pip requirements that the locked MCDR
// package set needs. The interpreter resolves and downloads wheels on the
// machine that runs install, so no Python version or wheel is recorded in the
// portable lock. The isolated environment is keyed by this list, so a changed
// list provisions a fresh environment.
func mcdrPythonRequirements(d *documentpkg.Lock) []string {
if d == nil || d.MCDR == nil {
return nil
}
requirements := []string{"mcdreforged==" + string(d.MCDR.Version)}
for _, p := range d.Packages {
for _, m := range p.Modules {
for _, dependency := range m.Dependencies {
if dependency.Kind != catalog.DependencyKindPython {
continue
}
id := strings.TrimSpace(dependency.ID)
if id == "" || id == "mcdreforged" {
continue
}
requirements = append(requirements, id)
}
}
}
slices.Sort(requirements)
return slices.Compact(requirements)
}
package install
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
)
type mcdrRuntime struct {
// venv reports whether the launcher uses the isolated environment.
venv bool
// key names the isolated environment. It is empty for a global runtime.
key string
}
func mcdrFlagHint() string {
return "pass --mcdr-venv to create an isolated environment"
}
func mcdrGlobalError(missing string) error {
return fmt.Errorf(
"MCDReforged is required for this workspace, but %s was not found "+
"on PATH. Install MCDReforged and Python 3.8+ globally, or %s",
missing,
mcdrFlagHint(),
)
}
// mcdrProvisionError explains how to provide a Python environment when
// provisioning fails.
func mcdrProvisionError(cause error) error {
return fmt.Errorf(
"%w\n"+
"MCDReforged needs Python 3.8+ or uv to create an isolated "+
"environment. Install Python 3 or uv, then rerun "+
"`lucy install --mcdr-venv`",
cause,
)
}
func mcdrEnvironmentKey(
goos string,
goarch string,
mcdrVersion string,
requirements []string,
) string {
hash := sha256.New()
for _, part := range append(
[]string{mcdrVersion, goos, goarch, "venv"},
requirements...,
) {
io.WriteString(hash, part)
hash.Write([]byte{0})
}
return hex.EncodeToString(hash.Sum(nil))[:32]
}
// provisionMCDR selects the runtime that will launch MCDReforged. The default
// requires a global executable; --mcdr-venv creates an isolated environment.
func provisionMCDR(
ctx context.Context,
root string,
d *document.Lock,
store *downloadStore,
python *PythonHost,
useVenv bool,
) (mcdrRuntime, error) {
m := d.MCDR
if m == nil {
return mcdrRuntime{}, nil
}
if !useVenv {
path, err := python.LookPath("mcdreforged")
if err != nil {
return mcdrRuntime{}, mcdrGlobalError(`"mcdreforged"`)
}
if _, _, err := python.Interpreter(ctx, store.trace.processOutput()); err != nil {
return mcdrRuntime{}, fmt.Errorf(
"MCDReforged requires Python 3.8+ on PATH: %w. "+
"Install Python 3, or %s",
err,
mcdrFlagHint(),
)
}
if err := python.Run(ctx, path, []string{"--version"}, store.trace.processOutput()); err != nil {
return mcdrRuntime{}, fmt.Errorf(
"global MCDReforged at %s could not run: %w. "+
"Repair it, or %s",
path,
err,
mcdrFlagHint(),
)
}
return mcdrRuntime{}, nil
}
requirements := mcdrPythonRequirements(d)
key := mcdrEnvironmentKey(
python.GOOS,
python.GOARCH,
string(m.Version),
requirements,
)
relative := filepath.Join(m.Directory, ".python", key)
if err := workspacewrite.SafePath(root, relative); err != nil {
return mcdrRuntime{}, err
}
environment := filepath.Join(root, relative)
complete := filepath.Join(environment, ".complete")
if _, err := os.Stat(complete); err == nil {
return mcdrRuntime{venv: true, key: key}, nil
} else if !os.IsNotExist(err) {
return mcdrRuntime{}, err
}
if store.offline {
return mcdrRuntime{}, fmt.Errorf(
"MCDReforged isolated environment is not provisioned; run " +
"`lucy install --mcdr-venv` once with network access",
)
}
if err := os.RemoveAll(environment); err != nil {
return mcdrRuntime{}, err
}
if err := os.MkdirAll(filepath.Dir(environment), 0o755); err != nil {
return mcdrRuntime{}, err
}
backend, err := createMCDREnvironment(ctx, environment, store, python)
if err != nil {
return mcdrRuntime{}, mcdrProvisionError(err)
}
requirementsPath := filepath.Join(environment, "requirements.txt")
if err := os.WriteFile(
requirementsPath,
[]byte(strings.Join(requirements, "\n")+"\n"),
0o600,
); err != nil {
return mcdrRuntime{}, err
}
if err := installMCDRRequirements(
ctx,
environment,
backend,
requirementsPath,
store,
python,
); err != nil {
os.RemoveAll(environment)
return mcdrRuntime{}, mcdrProvisionError(err)
}
if err := os.WriteFile(complete, nil, 0o600); err != nil {
return mcdrRuntime{}, err
}
return mcdrRuntime{venv: true, key: key}, nil
}
func createMCDREnvironment(
ctx context.Context,
environment string,
store *downloadStore,
python *PythonHost,
) (string, error) {
var uvError error
if uv, err := python.LookPath("uv"); err == nil {
err := python.Run(
ctx,
uv,
[]string{"venv", "--seed", environment},
store.trace.processOutput(),
)
if err == nil {
return "uv", nil
}
uvError = fmt.Errorf("uv venv: %w", err)
python.Logger.Warn(uvError)
}
interpreter, _, err := python.Interpreter(ctx, store.trace.processOutput())
if err != nil {
if uvError != nil {
return "", fmt.Errorf(
"no usable Python or uv: %w; %w",
err,
uvError,
)
}
return "", err
}
err = python.Run(
ctx,
interpreter,
[]string{"-m", "venv", environment},
store.trace.processOutput(),
)
if err != nil {
return "", fmt.Errorf("create Python environment with %s: %w", interpreter, err)
}
return "python", nil
}
func installMCDRRequirements(
ctx context.Context,
environment string,
backend string,
requirementsPath string,
store *downloadStore,
python *PythonHost,
) error {
environmentPython := filepath.Join(environment, "bin", "python")
if python.GOOS == "windows" {
environmentPython = filepath.Join(environment, "Scripts", "python.exe")
}
var commandName string
var arguments []string
if backend == "uv" {
uv, err := python.LookPath("uv")
if err != nil {
return err
}
commandName = uv
arguments = []string{
"pip",
"install",
"--python",
environmentPython,
"--requirement",
requirementsPath,
}
} else {
commandName = environmentPython
arguments = []string{
"-m",
"pip",
"install",
"--requirement",
requirementsPath,
}
}
if err := python.Run(
ctx,
commandName,
arguments,
store.trace.processOutput(),
); err != nil {
return fmt.Errorf("install Python requirements with %s: %w", backend, err)
}
return nil
}
package install
import (
"bytes"
"context"
"os"
"path/filepath"
"runtime"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/document"
"go.yaml.in/yaml/v4"
)
// preparePython selects the MCDReforged runtime and writes its wrapper into
// the stage. It runs while the installation is staged, before commit, so a
// failed Python provisioning leaves the workspace untouched.
func preparePython(
ctx context.Context,
root string,
stage string,
d *document.Lock,
store *downloadStore,
python *PythonHost,
useVenv bool,
) error {
runtime, err := provisionMCDR(ctx, root, d, store, python, useVenv)
if err != nil {
return err
}
if d.MCDR == nil {
return nil
}
return writeMCDRWrapper(stage, d, runtime, true, python.GOOS)
}
func writeMCDRWrapper(
base string,
d *document.Lock,
mcdr mcdrRuntime,
replaceConfig bool,
goos string,
) error {
m := d.MCDR
wrapper := filepath.Join(base, m.Directory)
if err := os.MkdirAll(wrapper, 0o755); err != nil {
return err
}
configPath := filepath.Join(wrapper, "config.yml")
_, configErr := os.Stat(configPath)
if replaceConfig || os.IsNotExist(configErr) {
launch := bootstrap.LaunchFor(d.Server.Bootstrap)
relativeServer, err := filepath.Rel(m.Directory, d.Server.Directory)
if err != nil {
return err
}
// MCDReforged parses the server log stream through a handler that
// matches the launcher, so the method selects the parser.
config := map[string]any{
"working_directory": filepath.ToSlash(relativeServer),
"start_command": launch.Command,
"handler": launch.Handler,
}
data, err := yaml.Marshal(config)
if err != nil {
return err
}
if err := os.WriteFile(configPath, data, 0o644); err != nil {
return err
}
} else if configErr != nil {
return configErr
}
launcher := "mcdreforged"
if mcdr.venv {
launcher = mcdrVenvLauncher(mcdr.key, goos)
}
return os.WriteFile(
filepath.Join(wrapper, "run-mcdr.sh"),
mcdrWrapperLauncher(launcher),
0o755,
)
}
// mcdrVenvInterpreter returns the interpreter path, relative to the MCDR
// directory, of one isolated environment key.
func mcdrVenvInterpreter(key, goos string) string {
pythonPath := filepath.Join(".python", key, "bin", "python")
if goos == "windows" {
pythonPath = filepath.Join(".python", key, "Scripts", "python.exe")
}
return filepath.ToSlash(pythonPath)
}
// mcdrVenvLauncher returns the command that runs MCDReforged from one isolated
// environment key.
func mcdrVenvLauncher(key, goos string) string {
return "'" + mcdrVenvInterpreter(key, goos) + "' -m mcdreforged"
}
// mcdrWrapperCurrent reports whether the workspace wrapper already matches
// the launcher and seed the current lock would stage. It inspects files only,
// so metadata-only operations can decide whether runtime provisioning is
// needed without executing Python.
func mcdrWrapperCurrent(root string, d *document.Lock, python *PythonHost, useVenv bool) bool {
if d == nil || d.MCDR == nil {
return true
}
directory := filepath.Join(root, filepath.FromSlash(d.MCDR.Directory))
configInfo, err := os.Stat(filepath.Join(directory, "config.yml"))
if err != nil || !configInfo.Mode().IsRegular() {
return false
}
launcher := "mcdreforged"
if useVenv {
key := mcdrEnvironmentKey(
python.GOOS,
python.GOARCH,
string(d.MCDR.Version),
mcdrPythonRequirements(d),
)
interpreter := filepath.Join(
directory, filepath.FromSlash(mcdrVenvInterpreter(key, python.GOOS)),
)
info, err := os.Stat(interpreter)
if err != nil || !info.Mode().IsRegular() {
return false
}
if _, err := os.Stat(filepath.Join(directory, ".python", key, ".complete")); err != nil {
return false
}
launcher = mcdrVenvLauncher(key, python.GOOS)
} else if _, err := python.LookPath("mcdreforged"); err != nil {
return false
}
installed, err := os.ReadFile(filepath.Join(directory, "run-mcdr.sh"))
if err != nil {
return false
}
return bytes.Equal(installed, mcdrWrapperLauncher(launcher))
}
// mcdrWrapperLauncher renders the managed launcher script for one MCDR
// launcher command. Adoption compares an existing wrapper against the same
// bytes before granting ownership.
func mcdrWrapperLauncher(launcher string) []byte {
return []byte(
"#!/bin/sh\ncd -- \"$(dirname -- \"$0\")\"\nexec " +
launcher + " \"$@\"\n",
)
}
// mcdrLauncherVariant is one launcher script Lucy can generate for a locked
// MCDR. Interpreter is set for the isolated runtime and names the venv
// interpreter relative to the workspace, so adoption can require that the
// environment it launches still exists.
type mcdrLauncherVariant struct {
Script []byte
Interpreter string
}
// mcdrLauncherVariants reports the exact wrapper scripts installation can
// produce for d on this machine: the global launcher and the isolated runtime
// whose environment key follows the provisioning algorithm.
func mcdrLauncherVariants(d *document.Lock) []mcdrLauncherVariant {
if d == nil || d.MCDR == nil {
return nil
}
m := d.MCDR
variants := []mcdrLauncherVariant{{
Script: mcdrWrapperLauncher("mcdreforged"),
}}
key := mcdrEnvironmentKey(
runtime.GOOS,
runtime.GOARCH,
string(m.Version),
mcdrPythonRequirements(d),
)
interpreter := filepath.Join(".python", key, "bin", "python")
if runtime.GOOS == "windows" {
interpreter = filepath.Join(".python", key, "Scripts", "python.exe")
}
variants = append(variants, mcdrLauncherVariant{
Script: mcdrWrapperLauncher(
"'" + filepath.ToSlash(interpreter) + "' -m mcdreforged",
),
Interpreter: filepath.ToSlash(
filepath.Join(m.Directory, interpreter),
),
})
return variants
}
package install
import (
"bytes"
"context"
"fmt"
"path/filepath"
"slices"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/workspace"
)
// Plan is the resolved outcome of one installation decision. It carries the
// documents the commit will publish and the exact workspace capture it was
// planned from, so applying it cannot silently consume a concurrent edit.
type Plan struct {
Manifest *document.Manifest
Previous *document.Lock
Resolved *document.Lock
PublishManifest bool
PublishLock bool
// base pins the manifest, lock, and receipt bytes this plan answers.
// ApplyPlan refuses a workspace whose captured documents differ.
base WorkspaceDocuments
Result *Result
}
// checkBase verifies the workspace still holds the documents the plan was
// built from, and that the documents the plan answers agree with that capture.
// The decoded manifest and lock are the preflight observation of that same
// capture, so no extra fingerprint data is stored on the plan.
func (p *Plan) checkBase(
manifest *document.Manifest,
lock *document.Lock,
documents WorkspaceDocuments,
) error {
if len(p.base.documents) == 0 {
return fmt.Errorf("plan has no captured workspace state; replan from current documents")
}
if err := p.base.matches(documents); err != nil {
return err
}
if !p.PublishManifest {
planned, err := p.Manifest.Fingerprint()
if err != nil {
return err
}
captured := ""
if manifest != nil {
if captured, err = manifest.Fingerprint(); err != nil {
return err
}
}
if planned != captured {
return fmt.Errorf("plan manifest does not answer the captured workspace; replan from current intent")
}
}
planned, captured := "", ""
var err error
if p.Previous != nil {
if planned, err = p.Previous.Fingerprint(); err != nil {
return err
}
}
if lock != nil {
if captured, err = lock.Fingerprint(); err != nil {
return err
}
}
if planned != captured {
return fmt.Errorf("plan previous lock does not answer the captured workspace; replan from current state")
}
return nil
}
// Decode reads the manifest and lock pinned by a capture. An absent document
// is nil, not an error.
func (d WorkspaceDocuments) Decode() (*document.Manifest, *document.Lock, error) {
var manifest *document.Manifest
if pin := d.documents[document.ManifestFilename]; pin.image != nil {
var err error
if manifest, err = document.DecodeManifest(bytes.NewReader(pin.raw)); err != nil {
return nil, nil, err
}
}
lock, err := d.DecodeLock()
if err != nil {
return nil, nil, err
}
return manifest, lock, nil
}
// DecodeLock reads the captured lock without decoding the manifest. A capture
// without a lock returns nil.
func (d WorkspaceDocuments) DecodeLock() (*document.Lock, error) {
pin := d.documents[document.LockFilename]
if pin.image == nil {
return nil, nil
}
return document.DecodeLock(bytes.NewReader(pin.raw))
}
// matches reports whether current holds the same document images d pinned.
func (d WorkspaceDocuments) matches(current WorkspaceDocuments) error {
for _, name := range workspaceDocumentNames {
if !workspacewrite.InstallImagesEqual(current.documents[name].image, d.documents[name].image) {
return fmt.Errorf("workspace document %s differs from the plan base; replan from current state", name)
}
}
return nil
}
// preflightLocked replays interrupted journals before anything reads the
// documents they describe, then validates the state both planning and applying
// depend on. It returns the recovered documents and the exact bytes observed
// after recovery, which are the only safe base for resolution and staging.
// Because every caller mutates the runtime tree, it also refuses to continue
// while a server still runs there.
func preflightLocked(
root string,
d *document.Manifest,
old *document.Lock,
opts Options,
logger *log.Logger,
) (*document.Manifest, *document.Lock, WorkspaceDocuments, error) {
if d == nil && old == nil {
return nil, nil, WorkspaceDocuments{}, fmt.Errorf("lucy.yaml or lucy-lock.yaml is required")
}
// A pending file transaction is rolled back unless its event reached the
// history. Reading, resolving, or publishing the manifest, lock, or tracked
// files before that replay can invalidate the pre-images recovery needs.
if err := filetrack.RecoverLocked(root, logger); err != nil {
return nil, nil, WorkspaceDocuments{}, err
}
documents, err := CaptureWorkspaceDocuments(root)
if err != nil {
return nil, nil, WorkspaceDocuments{}, err
}
baseManifest, baseLock, err := documents.Decode()
if err != nil {
return nil, nil, WorkspaceDocuments{}, err
}
// Recovery may restore a different runtime location than the caller
// requested. Both the recovered locations and a manifest being published
// must be stopped before staging rewrites their files.
directories := make([]string, 0, 3)
add := func(directory string) {
if !slices.Contains(directories, directory) {
directories = append(directories, directory)
}
}
if baseManifest != nil {
add(baseManifest.Server.Directory)
}
if baseLock != nil {
add(baseLock.Server.Directory)
}
if opts.PublishManifest && d != nil {
add(d.Server.Directory)
}
if baseManifest == nil && baseLock == nil {
switch {
case d != nil:
add(d.Server.Directory)
case old != nil:
add(old.Server.Directory)
}
}
for _, directory := range directories {
if workspace.RunningAt(filepath.Join(root, directory)) ||
(directory != "." && workspace.RunningAt(root)) {
return nil, nil, WorkspaceDocuments{}, fmt.Errorf("stop the running Minecraft server before installation")
}
}
// Callers that read the documents before the writer lock pin what they
// read, so recovery or a concurrent edit fails instead of being overwritten.
if opts.ExpectedManifest != "" {
fingerprint := ""
if baseManifest != nil {
fingerprint, err = baseManifest.Fingerprint()
if err != nil {
return nil, nil, WorkspaceDocuments{}, err
}
}
if fingerprint != opts.ExpectedManifest {
return nil, nil, WorkspaceDocuments{}, fmt.Errorf("manifest changed during package selection; retry from current intent")
}
}
if opts.ExpectedLock != "" {
fingerprint := ""
if baseLock != nil {
fingerprint, err = baseLock.Fingerprint()
if err != nil {
return nil, nil, WorkspaceDocuments{}, err
}
}
if fingerprint != opts.ExpectedLock {
return nil, nil, WorkspaceDocuments{}, fmt.Errorf("lock changed during package selection; retry from current state")
}
}
return baseManifest, baseLock, documents, nil
}
// resolveLock performs the installation mode decision and resolution. The
// caller must hold the workspace writer lock.
func (s *Service) resolveLock(
ctx context.Context,
root string,
d *document.Manifest,
old *document.Lock,
opts *Options,
store *downloadStore,
result *Result,
) (*document.Lock, error) {
resolved := old
fingerprint := ""
if d != nil {
var err error
fingerprint, err = d.Fingerprint()
if err != nil {
return nil, err
}
}
resolveNeeded := false
switch {
case opts.ForceResolve:
result.Mode = ModeResolve
result.Reason = "forced resolution"
resolveNeeded = true
case old == nil:
result.Mode = ModeResolve
result.Reason = "no lock file to replay"
resolveNeeded = true
case opts.WithOptional:
result.Mode = ModeResolve
result.Reason = "optional packages requested"
resolveNeeded = true
case d != nil && old.ManifestFingerprint != fingerprint:
result.Mode = ModeResolve
result.Reason = "manifest changed since lock"
resolveNeeded = true
default:
result.Mode = ModeReplay
result.Reason = "manifest unchanged; lock replays exactly"
}
s.logger.Debug(
"installation decision",
"mode", string(result.Mode),
"reason", result.Reason,
)
if resolveNeeded {
if opts.Locked {
if opts.ForceResolve {
return nil, fmt.Errorf("locked installation cannot force resolution")
}
if !opts.RequirementChange || old == nil || d == nil {
return nil, fmt.Errorf("locked installation requires a current lucy-lock.yaml")
}
reusable, err := s.coreReusable(ctx, d, old, opts.Offline)
if err != nil {
return nil, err
}
if !reusable {
return nil, fmt.Errorf("manifest core no longer matches lucy-lock.yaml; install without --locked")
}
s.logger.Debug(
"locked installation reuses core",
"reason", "manifest core still matches lock; requirements rebind in place",
)
resolved, err = mutateLock(d, old, fingerprint)
if err != nil {
return nil, err
}
if err := resolved.Validate(); err != nil {
return nil, err
}
result.Mode = ModeLocked
result.Reason = "manifest core matches; requirements rebind in place"
opts.publishLock = true
result.applyChanges(old, resolved, d)
return resolved, nil
}
var err error
resolved, err = s.resolveInstall(ctx, root, d, old, fingerprint, opts, store, result)
if err != nil {
return nil, err
}
}
if err := resolved.Validate(); err != nil {
return nil, err
}
opts.publishLock = resolved != old
result.applyChanges(old, resolved, d)
return resolved, nil
}
func (s *Service) newDownloadStore(opts Options, result *Result) *downloadStore {
return &downloadStore{
offline: opts.Offline,
trace: opts.Trace,
fetch: &result.Fetch,
network: s.network,
logger: s.logger,
githubProxy: s.githubProxy,
injected: opts.Materialize,
}
}
// PlanFromResolution builds a plan from a lock another resolver produced. base
// must be the workspace capture the plan answers; ApplyPlan compares it with
// the exact documents it later observes. The caller must set the final manifest
// and the lock's manifest fingerprint, so a plan can never publish a lock that
// answers a different intent.
func PlanFromResolution(
base WorkspaceDocuments,
d *document.Manifest,
previous, resolved *document.Lock,
publishManifest bool,
) (*Plan, error) {
if len(base.documents) == 0 {
return nil, fmt.Errorf("plan requires the workspace capture it answers")
}
if d == nil || resolved == nil {
return nil, fmt.Errorf("manifest and resolved lock are required")
}
fingerprint, err := d.Fingerprint()
if err != nil {
return nil, err
}
if resolved.ManifestFingerprint != fingerprint {
return nil, fmt.Errorf("resolved lock answers a different manifest")
}
if err := resolved.Validate(); err != nil {
return nil, err
}
result := newResult()
result.Kind = ResultKindUpgrade
result.Mode = ModeResolve
result.Reason = "package upgrade"
result.applyChanges(previous, resolved, d)
result.PublishedManifest = publishManifest
result.PublishedLock = previous == nil || resolved != previous
return &Plan{
Manifest: d,
Previous: previous,
Resolved: resolved,
PublishManifest: publishManifest,
PublishLock: result.PublishedLock,
base: base,
Result: result,
}, nil
}
package install
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/mclucy/lucy/log"
)
// PythonHost is the process boundary for MCDReforged's Python provisioning. A
// command boundary constructs one per invocation, so interpreter discovery,
// the environment layout, and the warnings seen by every stage agree.
// LookPath, Output, and Run are its process boundaries.
type PythonHost struct {
// LookPath resolves an executable name on PATH.
LookPath func(name string) (string, error)
// Output runs one probe command. It returns stdout for parsing and
// streams stderr to output, which already retains the diagnostics a
// failure report names.
Output func(
ctx context.Context,
name string,
args []string,
output io.Writer,
) ([]byte, error)
// Run runs one command. A non-nil output receives the combined output
// as it arrives; that output already retains the evidence a failure
// report names.
Run func(ctx context.Context, name string, args []string, output io.Writer) error
// Getenv reads an environment variable. LUCY_PYTHON names the preferred
// interpreter.
Getenv func(string) string
// GOOS and GOARCH name the platform whose environment layout the host
// creates.
GOOS string
GOARCH string
// Logger records non-fatal provisioning warnings. A nil logger records
// nothing.
Logger *log.Logger
directory string
interpreterMu sync.Mutex
interpreterPath string
interpreterVer string
interpreterOK bool
}
// NewPythonHost returns the host boundary for one invocation. It probes no
// interpreter until MCDReforged provisioning needs one.
func NewPythonHost(directory string, logger *log.Logger) *PythonHost {
if absolute, err := filepath.Abs(directory); err == nil {
directory = absolute
}
return &PythonHost{
directory: directory,
LookPath: exec.LookPath,
Output: func(
ctx context.Context,
name string,
args []string,
output io.Writer,
) ([]byte, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = directory
if output != nil {
markSection(output, cmd.String())
cmd.Stderr = output
}
return cmd.Output()
},
Run: func(ctx context.Context, name string, args []string, output io.Writer) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = directory
return runProcess(cmd, output)
},
Getenv: os.Getenv,
GOOS: runtime.GOOS,
GOARCH: runtime.GOARCH,
Logger: logger,
}
}
// Interpreter returns the Python 3.8+ executable and its version, probing at
// most once per host. stdout is parsed for the version and copied to output;
// stderr streams to output as it arrives, so the probe's evidence reaches the
// retained process log instead of an error message.
func (h *PythonHost) Interpreter(ctx context.Context, output io.Writer) (string, string, error) {
h.interpreterMu.Lock()
defer h.interpreterMu.Unlock()
if h.interpreterOK {
return h.interpreterPath, h.interpreterVer, nil
}
path, version, err := h.discoverInterpreter(ctx, output)
if err != nil {
return "", "", err
}
h.interpreterPath, h.interpreterVer = path, version
h.interpreterOK = true
return path, version, nil
}
func (h *PythonHost) discoverInterpreter(
ctx context.Context,
output io.Writer,
) (string, string, error) {
name := strings.TrimSpace(h.Getenv("LUCY_PYTHON"))
if name == "" {
name = "python3"
} else if !filepath.IsAbs(name) && (strings.ContainsRune(name, filepath.Separator) ||
(h.GOOS == "windows" && strings.ContainsRune(name, '/'))) {
name = filepath.Join(h.directory, name)
}
path, err := h.LookPath(name)
if err != nil {
return "", "", fmt.Errorf("Python interpreter %q was not found", name)
}
out, err := h.Output(
ctx,
path,
[]string{
"-c",
"import sys;print('%d.%d.%d' % sys.version_info[:3])",
},
output,
)
if output != nil && len(out) > 0 {
_, _ = output.Write(out)
}
if err != nil {
return "", "", fmt.Errorf(
"Python interpreter %s could not run: %w",
path,
err,
)
}
value := strings.TrimSpace(string(out))
parts := strings.Split(value, ".")
if len(parts) < 2 {
return "", "", fmt.Errorf(
"Python interpreter %s printed %d bytes that are not a version",
path,
len(out),
)
}
major, errMajor := strconv.Atoi(parts[0])
minor, errMinor := strconv.Atoi(parts[1])
if errMajor != nil || errMinor != nil {
return "", "", fmt.Errorf(
"Python interpreter %s printed %d bytes that are not a version",
path,
len(out),
)
}
if major < 3 || (major == 3 && minor < 8) {
return "", "", fmt.Errorf(
"Python interpreter %s is %d.%d; MCDReforged needs 3.8 or newer",
path,
major,
minor,
)
}
if major > 3 || minor > 13 {
h.Logger.Warn(fmt.Errorf(
"MCDReforged is tested through Python 3.13; %s is Python %d.%d and "+
"some dependencies may not publish wheels for it",
path,
major,
minor,
))
}
return path, value, nil
}
// runProcess streams a subprocess's combined output to output, which already
// retains the evidence the failure report needs. An output that marks sections
// also records the command line that introduced the run.
func runProcess(cmd *exec.Cmd, output io.Writer) error {
if output == nil {
output = io.Discard
}
markSection(output, cmd.String())
cmd.Stdout = output
cmd.Stderr = output
return cmd.Run()
}
// markSection records the command line in an output that keeps command
// boundaries, so a retained log can attribute the output that follows.
func markSection(output io.Writer, label string) {
if marker, ok := output.(interface{ Section(label string) }); ok {
marker.Section(label)
}
}
package install
import (
"cmp"
"fmt"
"maps"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
// requirementKey names one manifest declaration. A reference alone does not
// identify a declaration because the same project can be declared for two
// ecosystems or environments.
type requirementKey struct {
environment serverpkg.Environment
ecosystem catalog.Ecosystem
reference string
}
func compareRequirementKeys(a, b requirementKey) int {
return cmp.Or(
cmp.Compare(a.environment, b.environment),
cmp.Compare(a.ecosystem, b.ecosystem),
cmp.Compare(a.reference, b.reference),
)
}
// declaredRequirements collects every requirement the manifest declares for a
// package, keyed by the location and reference that name it.
func declaredRequirements(d *document.Manifest) map[requirementKey]document.Requirement {
declared := map[requirementKey]document.Requirement{}
var loaders []catalog.Ecosystem
for loader := range d.Server.Packages {
loaders = append(loaders, loader)
}
slices.Sort(loaders)
for _, loader := range loaders {
var refs []string
for ref := range d.Server.Packages[loader] {
refs = append(refs, ref)
}
slices.Sort(refs)
for _, ref := range refs {
key := requirementKey{serverpkg.EnvironmentServer, loader, ref}
declared[key] = d.Server.Packages[loader][ref]
}
}
if d.MCDR != nil {
refs := slices.Sorted(maps.Keys(d.MCDR.Packages))
for _, ref := range refs {
key := requirementKey{serverpkg.EnvironmentMCDR, catalog.EcosystemMCDR, ref}
declared[key] = d.MCDR.Packages[ref]
}
}
return declared
}
// lockPackageFor reports whether a reference names one locked package. The
// binding a previous resolution recorded is authoritative once the provider
// matches: providers such as Modrinth name a project by an opaque ID and a
// jar's module ID need not match the project slug (ferrite-core is provided by
// ferritecore), so identity matching alone cannot recover the declaration.
func lockPackageFor(ref string, p document.Package) bool {
provider, name, err := document.ParseReference(ref)
if err != nil {
return false
}
if p.Provider != provider {
return false
}
for _, binding := range p.Requirements {
if binding.Reference == ref {
return true
}
}
if p.ProjectID == name {
return true
}
for _, module := range p.Modules {
if module.ID == name || slices.Contains(module.Provides, name) {
return true
}
}
return false
}
// lockedSelectorSatisfied reports whether a pinned artifact answers a
// requirement selector. A locked mutation never resolves, so a selector the
// pin cannot satisfy would publish a lock that contradicts its manifest.
func lockedSelectorSatisfied(
selector version.Version,
p document.Package,
) bool {
switch selector {
case "", version.Any, version.Beta, version.Stable:
// The lock stores exact releases, so every channel selector accepts an
// existing pin.
return true
}
return p.Version == selector ||
p.ReleaseID == string(selector) ||
p.FileID == string(selector) ||
p.Filename == string(selector)
}
// bindRequirement records the manifest's current state of one requirement on
// the package that satisfies it. A requirement the lock has never seen is
// added, so a package resolved only as a dependency becomes declared.
func bindRequirement(p *document.Package, ref string, requirement document.Requirement) {
binding := document.RequirementBinding{
Reference: ref,
Selector: requirement.Selector,
FilePattern: requirement.FilePattern,
Enabled: requirement.IsEnabled(),
}
for i := range p.Requirements {
if p.Requirements[i].Reference != ref {
continue
}
p.Requirements[i] = binding
return
}
if binding.Enabled || len(p.DependencyOf) > 0 {
p.Requirements = append(p.Requirements, binding)
}
}
// rebindRequirements reapplies the manifest's requirements onto a lock that
// already resolved them. A locked mutation never reaches upstream, so it can
// only enable or disable what the lock already pins; a declared requirement the
// lock does not satisfy is reported rather than resolved. Packages left bound
// only to requirements the manifest no longer declares are dropped, so a locked
// removal uninstalls the package instead of leaving the lock pinning it.
func rebindRequirements(d *document.Manifest, resolved *document.Lock) error {
declared := declaredRequirements(d)
keys := make([]requirementKey, 0, len(declared))
for key := range declared {
keys = append(keys, key)
}
slices.SortFunc(keys, compareRequirementKeys)
for _, key := range keys {
requirement := declared[key]
pinned := false
for i := range resolved.Packages {
p := &resolved.Packages[i]
if p.Environment != key.environment || p.Ecosystem != key.ecosystem {
continue
}
if !lockPackageFor(key.reference, *p) {
continue
}
// A disabled declaration keeps its dormant pin without
// constraining resolution, so that pin need not answer the
// manifest's current selector.
if requirement.IsEnabled() && !lockedSelectorSatisfied(requirement.Selector, *p) {
return fmt.Errorf(
"lucy-lock.yaml pins %s %s, which does not satisfy selector %s; install it without --locked first",
key.reference,
p.Version,
requirement.Selector,
)
}
pinned = true
bindRequirement(p, key.reference, requirement)
}
if !pinned && requirement.IsEnabled() {
return fmt.Errorf(
"lucy-lock.yaml does not pin %s; install it without --locked first",
key.reference,
)
}
}
resolved.Packages = retainDeclared(resolved.Packages, declared)
return nil
}
// retainDeclared keeps pins reachable from remaining declarations or ambient
// packages. Disabled declarations retain pins without activating their dependencies.
func retainDeclared(
packages []document.Package,
declared map[requirementKey]document.Requirement,
) []document.Package {
type identity struct {
environment string
ecosystem catalog.Ecosystem
reference catalog.Ref
}
identityOf := func(p *document.Package) identity {
return identity{
string(p.Environment),
p.Ecosystem,
catalog.Ref{Provider: p.Provider, Name: catalog.Name(p.ProjectID)},
}
}
indices := make(map[identity]int, len(packages))
// dependents lists the packages a DependencyOf reference of p names. The
// reference carries no ecosystem, so the named dependent may be recorded
// under any ecosystem that can share p's module namespace.
dependents := func(p *document.Package, source catalog.Ref) []int {
key := identityOf(p)
key.reference = source
var parents []int
for _, ecosystem := range p.Ecosystem.LoadedAlongside() {
key.ecosystem = ecosystem
if parent, ok := indices[key]; ok {
parents = append(parents, parent)
}
}
return parents
}
retained := make([]bool, len(packages))
enabled := make([]bool, len(packages))
for i := range packages {
p := &packages[i]
indices[identityOf(p)] = i
ambient := len(p.Requirements) == 0 && len(p.DependencyOf) == 0
retained[i], enabled[i] = ambient, ambient
bindings := p.Requirements[:0]
for _, binding := range p.Requirements {
key := requirementKey{p.Environment, p.Ecosystem, binding.Reference}
if _, ok := declared[key]; ok {
bindings = append(bindings, binding)
retained[i] = true
enabled[i] = enabled[i] || binding.Enabled
}
}
p.Requirements = bindings
}
children := make([][]int, len(packages))
for i := range packages {
p := &packages[i]
for _, source := range p.DependencyOf {
for _, parent := range dependents(p, source) {
children[parent] = append(children[parent], i)
}
}
}
queue := make([]int, 0, len(packages))
propagate := func(reached []bool) {
queue = queue[:0]
for i, yes := range reached {
if yes {
queue = append(queue, i)
}
}
for next := 0; next < len(queue); next++ {
for _, child := range children[queue[next]] {
if !reached[child] {
reached[child] = true
queue = append(queue, child)
}
}
}
}
propagate(retained)
propagate(enabled)
out := packages[:0]
for i, p := range packages {
if !retained[i] {
continue
}
p.Dependency = false
sources := p.DependencyOf[:0]
for _, source := range p.DependencyOf {
kept := false
for _, parent := range dependents(&p, source) {
if retained[parent] {
kept = true
p.Dependency = p.Dependency || enabled[parent]
}
}
if kept {
sources = append(sources, source)
}
}
p.DependencyOf = sources
out = append(out, p)
}
return out
}
// mutateLock produces the lock a locked mutation commits. Only requirements,
// the Java override, and the manifest fingerprint move; every artifact pin is
// copied as recorded.
func mutateLock(d *document.Manifest, old *document.Lock, fingerprint string) (*document.Lock, error) {
resolved := *old
resolved.ManifestFingerprint = fingerprint
resolved.Files = slices.Clone(d.Files)
resolved.Server.Java = document.NewLockedJava(old.Server.Java.Advisory, d.Server.Java)
resolved.Packages = make([]document.Package, len(old.Packages))
for i, p := range old.Packages {
resolved.Packages[i] = p
resolved.Packages[i].Requirements = slices.Clone(p.Requirements)
resolved.Packages[i].DependencyOf = slices.Clone(p.DependencyOf)
}
if err := rebindRequirements(d, &resolved); err != nil {
return nil, err
}
return &resolved, nil
}
package install
import (
"context"
"fmt"
"slices"
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
)
// resolveInstall resolves d into a new lock document. The caller decides when
// a lock may be reused, so this function always resolves. The artifact store
// receives every artifact whose hash the lock records.
func (s *Service) resolveInstall(
ctx context.Context,
root string,
d *document.Manifest,
old *document.Lock,
fingerprint string,
opts *Options,
store *downloadStore,
result *Result,
) (*document.Lock, error) {
if d == nil {
return nil, fmt.Errorf("manifest required to resolve a lock")
}
if opts.Offline {
return nil, fmt.Errorf("offline resolution requires a current lock; metadata selection is unavailable")
}
s.logger.Info(
"resolving installation",
"minecraft", d.Server.Minecraft,
"product", d.Server.Core.Product,
"core", d.Server.Core.ProductVersion,
"mcdr", d.MCDR != nil,
)
coreReq := upstream.ServerProductRequest{
Minecraft: d.Server.Minecraft,
Product: d.Server.Core.Product,
ProductVersion: d.Server.Core.ProductVersion,
Repository: d.Server.Core.Repository,
FilePattern: d.Server.Core.FilePattern,
}
localRuntime := newLocalRuntimeSource(root, opts.LocalRuntime)
acquire := localRuntime.acquire(store.materialize)
var core upstream.ServerProductResolution
canReuse := false
if old != nil {
reusable, err := s.coreReusable(ctx, d, old, opts.Offline)
if err != nil {
return nil, err
}
canReuse = reusable
}
if canReuse {
s.logger.Debug(
"reusing locked core resolution",
"reason", "manifest core still matches lock",
"minecraft", old.Server.Minecraft,
"product", old.Server.Product,
"core-version", old.Server.CoreVersion,
)
core = upstream.ServerProductResolution{
Minecraft: old.Server.Minecraft,
Product: old.Server.Product,
ProductVersion: old.Server.CoreVersion,
Artifact: old.Server.Artifact,
Bootstrap: old.Server.Bootstrap,
Inputs: old.Server.Inputs,
JavaAdvisory: old.Server.Java.Advisory,
}
} else {
opts.Trace.phaseStarted("server")
start := time.Now()
var err error
core, err = s.source.ResolveServerProduct(ctx, coreReq, acquire)
if err != nil {
return nil, err
}
elapsed := time.Since(start)
result.addPhase("server", elapsed)
opts.Trace.phaseDone(PhaseInfo{
Name: "server",
Elapsed: elapsed,
Product: core.Product,
Version: core.ProductVersion,
Minecraft: core.Minecraft,
})
}
resolved := &document.Lock{
SchemaVersion: document.LockSchemaVersion,
ManifestFingerprint: fingerprint,
Server: document.LockedServer{
Minecraft: core.Minecraft,
Directory: d.Server.Directory,
Product: core.Product,
CoreVersion: core.ProductVersion,
Artifact: core.Artifact,
Bootstrap: core.Bootstrap,
Inputs: core.Inputs,
Java: document.NewLockedJava(core.JavaAdvisory, d.Server.Java),
},
Packages: []document.Package{},
Files: slices.Clone(d.Files),
}
mcdrVersion := ""
if d.MCDR != nil {
request := d.MCDR.Version
if old != nil && old.MCDR != nil && isFloating(request) {
request = old.MCDR.Version
}
resolvedVersion, err := s.resolveMCDRVersion(ctx, request, old, opts.Offline)
if err != nil {
return nil, err
}
resolved.MCDR = &document.LockedMCDR{
Directory: d.MCDR.Directory,
Version: resolvedVersion,
}
mcdrVersion = string(resolvedVersion)
}
opts.Trace.phaseStarted("packages")
start := time.Now()
coreModules, moduleErr := routing.CoreModules(
ctx,
resolved.Server.Product,
resolved.Server.Artifact,
acquire,
)
if moduleErr != nil {
s.logger.Warn(fmt.Errorf("read server core modules: %w", moduleErr))
} else {
resolved.Server.Artifact.Modules = coreModules
}
// A metadata resolver can pin the core and its inputs without acquiring
// them. Import any of those bytes the observed runtime proves anyway, so
// the lock stays replayable from the store and later staging needs no
// download. A reused core keeps every pin the old lock recorded and gains
// the SHA-256 the import proved, so an offline replay can address the
// store object.
proven, _, err := localRuntime.importServer(ctx, resolved.Server)
if err != nil {
return nil, err
}
resolved.Server = proven
var previousPackages []document.Package
if old != nil {
previousPackages = old.Packages
if len(opts.Adopted) > 0 {
previousPackages = slices.DeleteFunc(slices.Clone(previousPackages), func(pkg document.Package) bool {
return supersededByAdoption(pkg, opts.Adopted)
})
}
}
preserveLocked := old != nil &&
old.Server.Minecraft == resolved.Server.Minecraft &&
old.Server.Product == resolved.Server.Product &&
old.Server.CoreVersion == resolved.Server.CoreVersion
packageRequest := resolve.PackagesRequest{
Context: ctx,
Manifest: d,
Previous: previousPackages,
PreserveLocked: preserveLocked,
PreferLocked: !opts.ForceResolve && len(opts.Adopted) == 0,
Target: resolve.Target{
Product: resolved.Server.Product,
Minecraft: resolved.Server.Minecraft,
CoreVersion: resolved.Server.CoreVersion,
MCDRVersion: mcdrVersion,
CoreModules: resolved.Server.Artifact.Modules,
},
Materialize: store.materialize,
WithOptional: opts.WithOptional,
AcceptBroken: opts.AcceptBroken,
ExpandDependencies: !opts.declaredOnly,
Logger: s.logger,
Trace: opts.Trace.resolveTrace(),
}
if old != nil {
packageRequest.PreviousTarget = resolve.Target{
Product: old.Server.Product,
Minecraft: old.Server.Minecraft,
CoreVersion: old.Server.CoreVersion,
}
}
if len(opts.Adopted) > 0 {
cache, err := prepareAdoptedArtifacts(ctx, root, opts.Adopted, &packageRequest.Target)
if err != nil {
return nil, err
}
packageRequest.Cache = cache
}
if s.source != nil || len(opts.Adopted) > 0 {
packageRequest.Candidates = func(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
ecosystem catalog.Ecosystem,
) ([]upstream.Candidate, error) {
candidate, ok := adoptedCandidate(
opts.Adopted,
registry,
project,
ecosystem,
)
if ok {
return []upstream.Candidate{candidate}, nil
}
if s.source != nil {
return s.source.Candidates(ctx, registry, project, minecraft, ecosystem)
}
return nil, nil
}
}
packages, moduleWarnings, err := resolve.Packages(packageRequest)
if err != nil {
return nil, err
}
elapsed := time.Since(start)
result.addPhase("packages", elapsed)
opts.Trace.phaseDone(PhaseInfo{
Name: "packages",
Elapsed: elapsed,
Count: len(packages),
Total: countDeclared(d),
})
result.Warnings = append(result.Warnings, moduleWarnings...)
resolved.Packages = packages
if opts.WithOptional {
for _, p := range packages {
for _, request := range p.Requirements {
if p.Environment == server.EnvironmentMCDR {
d.MCDR.Packages[request.Reference] = document.Requirement{
Selector: request.Selector,
FilePattern: request.FilePattern,
Enabled: new(request.Enabled),
}
} else {
if d.Server.Packages[p.Ecosystem] == nil {
d.Server.Packages[p.Ecosystem] = map[string]document.Requirement{}
}
d.Server.Packages[p.Ecosystem][request.Reference] = document.Requirement{
Selector: request.Selector,
FilePattern: request.FilePattern,
Enabled: new(request.Enabled),
}
}
}
}
resolved.ManifestFingerprint, err = d.Fingerprint()
if err != nil {
return nil, err
}
opts.PublishManifest = true
}
return resolved, nil
}
package install
import (
"path/filepath"
"slices"
"sort"
"strings"
"time"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/filetrack"
versionpkg "github.com/mclucy/lucy/version"
)
// ResultSchema versions the machine-readable result.
const ResultSchema = 1
// ResultKind identifies the machine-readable install result document.
const ResultKind = "install"
// ResultKindUpgrade identifies a result produced by the upgrade command.
const ResultKindUpgrade = "upgrade"
// Mode records how the operation produced its lock.
type Mode string
const (
ModeReplay Mode = "replay"
ModeResolve Mode = "resolve"
ModeLocked Mode = "locked"
)
// Change names what happened to one package or to the server record.
type Change string
const (
ChangeAdded Change = "added"
ChangeRemoved Change = "removed"
ChangeUpgraded Change = "upgraded"
ChangeDowngraded Change = "downgraded"
ChangeRebuilt Change = "rebuilt"
ChangeChanged Change = "changed"
)
// PackageChange is one difference between the previous lock and the committed
// one, or between no lock and the first one.
type PackageChange struct {
Reference string `json:"reference,omitempty"`
Name string `json:"name"`
Provider catalog.Provider `json:"provider"`
ProjectID string `json:"project_id,omitempty"`
Version versionpkg.Version `json:"version,omitempty"`
Previous versionpkg.Version `json:"previous,omitempty"`
ReleaseID string `json:"release_id,omitempty"`
PreviousReleaseID string `json:"previous_release_id,omitempty"`
Change Change `json:"change"`
Direct bool `json:"direct"`
RequiredBy []string `json:"required_by,omitempty"`
}
// ManifestChange records a declared selector that the operation rewrites.
type ManifestChange struct {
Reference string `json:"reference"`
PreviousSelector versionpkg.Version `json:"previous_selector"`
Selector versionpkg.Version `json:"selector"`
}
// MCDRChange reports a refreshed Python environment for MCDR.
type MCDRChange struct {
Version versionpkg.Version `json:"version"`
Inputs int `json:"inputs"`
PreviousInputs int `json:"previous_inputs"`
}
// ServerChange reports a new or changed server core.
type ServerChange struct {
Change Change `json:"change,omitempty"`
Product server.Product `json:"product,omitempty"`
Minecraft versionpkg.Version `json:"minecraft,omitempty"`
Version versionpkg.Version `json:"version,omitempty"`
Previous versionpkg.Version `json:"previous,omitempty"`
}
// FileChanges counts the managed runtime outputs the commit touched.
// Displaced lists the workspace paths whose previous content the commit kept
// under the workspace's displaced directory.
type FileChanges struct {
Created int `json:"created"`
Replaced int `json:"replaced"`
Removed int `json:"removed"`
Displaced []string `json:"displaced"`
}
// FetchSummary counts artifact transfers: local reuse and network downloads.
type FetchSummary struct {
Cached int `json:"cached"`
Downloaded int `json:"downloaded"`
Bytes int64 `json:"bytes"`
}
// Phase is one timed stage of the operation.
type Phase struct {
Name string `json:"name"`
Elapsed time.Duration `json:"-"`
Seconds float64 `json:"seconds"`
}
// Result reports what one operation decided and changed. It carries facts
// only; the command layer renders them.
type Result struct {
Schema int `json:"schema"`
// Kind names the machine-readable document. Results created by this
// package default it to ResultKind; projections from other operations
// set it explicitly.
Kind string `json:"kind"`
Mode Mode `json:"mode"`
Reason string `json:"reason,omitempty"`
Policy string `json:"policy,omitempty"`
PlanHash string `json:"plan_hash,omitempty"`
Server ServerChange `json:"server"`
Packages []PackageChange `json:"packages"`
ManifestChanges []ManifestChange `json:"manifest_changes,omitempty"`
MCDR *MCDRChange `json:"mcdr,omitempty"`
Files FileChanges `json:"files"`
Fetch FetchSummary `json:"fetch"`
Phases []Phase `json:"phases"`
Diagnostics []filetrack.Diagnostic `json:"diagnostics,omitempty"`
// Java reports the Java runtime that the server runs on. It is nil when
// the operation stopped before it selected one.
Java *javaruntime.Check `json:"java,omitempty"`
Warnings []error `json:"-"`
// WarningMessages carries Warnings into machine-readable output.
WarningMessages []string `json:"warnings,omitempty"`
// TotalPackages counts every package the committed lock records.
TotalPackages int `json:"total_packages"`
// PublishedManifest and PublishedLock report which documents changed.
PublishedManifest bool `json:"published_manifest"`
PublishedLock bool `json:"published_lock"`
}
func newResult() *Result {
return &Result{
Schema: ResultSchema,
Kind: ResultKind,
Files: FileChanges{Displaced: []string{}},
}
}
// CommittedError marks a failure after the installation was committed. The
// published files and documents stay in place; nothing is rolled back.
type CommittedError struct{ Err error }
func (e *CommittedError) Error() string { return e.Err.Error() }
func (e *CommittedError) Unwrap() error { return e.Err }
func (r *Result) addPhase(name string, elapsed time.Duration) {
if r == nil {
return
}
r.Phases = append(r.Phases, Phase{
Name: name,
Elapsed: elapsed,
Seconds: elapsed.Seconds(),
})
}
// Changed reports whether the operation changed the workspace at all.
func (r *Result) Changed() bool {
if r == nil {
return false
}
return r.Server.Change != "" ||
len(r.Packages) > 0 ||
len(r.ManifestChanges) > 0 ||
r.MCDR != nil ||
r.PublishedManifest ||
r.PublishedLock ||
r.Files.Created > 0 ||
r.Files.Replaced > 0 ||
r.Files.Removed > 0
}
func (r *Result) applyChanges(
before, after *document.Lock,
d *document.Manifest,
) {
if r == nil || after == nil {
return
}
r.TotalPackages = len(after.Packages)
r.Server = serverChange(before, after)
r.Packages = packageChanges(before, after, d)
}
func serverChange(before, after *document.Lock) ServerChange {
current := ServerChange{
Product: after.Server.Product,
Minecraft: after.Server.Minecraft,
Version: after.Server.CoreVersion,
}
switch {
case before == nil:
current.Change = ChangeAdded
case before.Server.Product != after.Server.Product ||
before.Server.CoreVersion != after.Server.CoreVersion:
current.Change = ChangeUpgraded
current.Previous = before.Server.CoreVersion
}
return current
}
type packageView struct {
name string
direct bool
version versionpkg.Version
releaseID string
fileID string
dialect versionpkg.Dialect
}
func packageChanges(
before, after *document.Lock,
d *document.Manifest,
) []PackageChange {
declared := map[requirementKey]document.Requirement{}
if d != nil {
declared = declaredRequirements(d)
}
oldPackages := packageViews(before, declared)
newPackages := packageViews(after, declared)
dependents := dependencyNames(after, newPackages)
changes := make([]PackageChange, 0, len(oldPackages)+len(newPackages))
for id, current := range newPackages {
previous, existed := oldPackages[id]
change := PackageChange{
Name: current.name,
Change: ChangeAdded,
Direct: current.direct,
RequiredBy: dependents[id],
Version: current.version,
ReleaseID: current.releaseID,
}
if pkg := findPackage(after, id); pkg != nil {
change.Reference = declaredReference(pkg, declared)
change.Provider = pkg.Provider
change.ProjectID = pkg.ProjectID
}
if existed {
switch {
case previous.version == current.version:
if previous.releaseID == current.releaseID && previous.fileID == current.fileID {
continue
}
change.Change = ChangeRebuilt
change.Previous = previous.version
change.PreviousReleaseID = previous.releaseID
default:
change.Previous = previous.version
change.PreviousReleaseID = previous.releaseID
comparison, comparable := comparePackageVersions(previous, current)
switch {
case !comparable:
change.Change = ChangeChanged
case comparison < 0:
change.Change = ChangeUpgraded
case comparison > 0:
change.Change = ChangeDowngraded
default:
change.Change = ChangeChanged
}
}
}
changes = append(changes, change)
}
for id, previous := range oldPackages {
if _, still := newPackages[id]; still {
continue
}
change := PackageChange{
Name: previous.name,
Change: ChangeRemoved,
Direct: previous.direct,
Version: previous.version,
Previous: previous.version,
PreviousReleaseID: previous.releaseID,
}
if pkg := findPackage(before, id); pkg != nil {
change.Provider = pkg.Provider
change.ProjectID = pkg.ProjectID
if reference := enabledReference(pkg); reference != "" {
change.Reference = reference
change.Direct = true
}
}
changes = append(changes, change)
}
sort.SliceStable(changes, func(i, j int) bool {
a, b := &changes[i], &changes[j]
if a.Direct != b.Direct {
return a.Direct
}
return a.Name < b.Name
})
return changes
}
func packageViews(
doc *document.Lock,
declared map[requirementKey]document.Requirement,
) map[string]packageView {
views := map[string]packageView{}
if doc == nil {
return views
}
names := packageNames(doc)
for i := range doc.Packages {
p := &doc.Packages[i]
id := lockedPackageKey(p)
reference := declaredReference(p, declared)
if reference == "" {
reference = enabledReference(p)
}
name := names[id]
if reference != "" {
name = referenceName(reference)
}
direct := reference != ""
if len(declared) == 0 {
direct = len(p.Requirements) > 0
}
views[id] = packageView{
name: name,
direct: direct,
version: p.Version,
releaseID: p.ReleaseID,
fileID: p.FileID,
dialect: packageVersionDialect(p),
}
}
return views
}
// enabledReference returns the reference a package records for itself. A
// package the current manifest no longer names, such as one being removed,
// still carries the requirement that declared it.
func enabledReference(p *document.Package) string {
for _, binding := range p.Requirements {
if binding.Enabled {
return binding.Reference
}
}
if len(p.Requirements) > 0 {
return p.Requirements[0].Reference
}
return ""
}
// packageNames resolves the display name of packages that no requirement
// declares: the module that dependents refer to, else the project identity.
func packageNames(doc *document.Lock) map[string]string {
names := map[string]string{}
if doc == nil {
return names
}
for i := range doc.Packages {
p := &doc.Packages[i]
id := lockedPackageKey(p)
if p.ProjectID != "" {
names[id] = p.ProjectID
} else {
names[id] = strings.TrimSuffix(p.Filename, filepath.Ext(p.Filename))
}
}
moduleOwner := moduleOwners(doc)
for i := range doc.Packages {
p := &doc.Packages[i]
for _, module := range p.Modules {
for _, dependency := range module.Dependencies {
target := dependencyTarget(p, dependency, moduleOwner, doc)
if target == "" {
continue
}
used := dependency.ModuleID
if used == "" {
used = dependency.ID
}
if used != "" {
names[target] = used
}
}
}
}
return names
}
func dependencyNames(
doc *document.Lock,
views map[string]packageView,
) map[string][]string {
dependents := map[string][]string{}
if doc == nil {
return dependents
}
moduleOwner := moduleOwners(doc)
for i := range doc.Packages {
p := &doc.Packages[i]
source := views[lockedPackageKey(p)].name
for _, module := range p.Modules {
for _, dependency := range module.Dependencies {
target := dependencyTarget(p, dependency, moduleOwner, doc)
if target == "" {
continue
}
if slices.Contains(dependents[target], source) {
continue
}
dependents[target] = append(dependents[target], source)
}
}
}
for target := range dependents {
slices.Sort(dependents[target])
}
return dependents
}
func moduleOwners(doc *document.Lock) map[string]string {
owners := map[string]string{}
if doc == nil {
return owners
}
for i := range doc.Packages {
p := &doc.Packages[i]
id := lockedPackageKey(p)
for _, module := range p.Modules {
owners[moduleLookupKey(p, module.ID)] = id
for _, provided := range module.Provides {
owners[moduleLookupKey(p, provided)] = id
}
}
}
return owners
}
func moduleLookupKey(p *document.Package, moduleID string) string {
return string(p.Environment) + "|" + string(p.Ecosystem) + "|" + strings.ToLower(moduleID)
}
func dependencyTarget(
source *document.Package,
dependency catalog.DescriptorDependency,
moduleOwner map[string]string,
doc *document.Lock,
) string {
if dependency.Provider != "" && dependency.ProjectID != "" {
for i := range doc.Packages {
candidate := &doc.Packages[i]
if candidate.Environment == source.Environment &&
candidate.Ecosystem == source.Ecosystem &&
candidate.Provider == dependency.Provider &&
candidate.ProjectID == dependency.ProjectID {
return lockedPackageKey(candidate)
}
}
}
moduleID := dependency.ModuleID
if moduleID == "" {
moduleID = dependency.ID
}
if moduleID == "" {
return ""
}
return moduleOwner[moduleLookupKey(source, moduleID)]
}
func lockedPackageKey(p *document.Package) string {
identity := p.ProjectID
if identity == "" {
identity = p.Filename
}
return strings.Join(
[]string{
string(p.Environment),
string(p.Ecosystem),
string(p.Provider),
identity,
},
"|",
)
}
func findPackage(doc *document.Lock, id string) *document.Package {
if doc == nil {
return nil
}
for i := range doc.Packages {
if lockedPackageKey(&doc.Packages[i]) == id {
return &doc.Packages[i]
}
}
return nil
}
func declaredReference(
p *document.Package,
declared map[requirementKey]document.Requirement,
) string {
for _, binding := range p.Requirements {
key := requirementKey{p.Environment, p.Ecosystem, binding.Reference}
if _, ok := declared[key]; ok {
return binding.Reference
}
}
return ""
}
func referenceName(reference string) string {
_, project, err := document.ParseReference(reference)
if err != nil {
return reference
}
return project
}
func countDeclared(d *document.Manifest) int {
if d == nil {
return 0
}
count := 0
for _, packages := range d.Server.Packages {
for _, requirement := range packages {
if requirement.IsEnabled() {
count++
}
}
}
if d.MCDR != nil {
for _, requirement := range d.MCDR.Packages {
if requirement.IsEnabled() {
count++
}
}
}
return count
}
func packageVersionDialect(p *document.Package) versionpkg.Dialect {
for _, module := range p.Modules {
if module.VersionDialect.Valid() {
return module.VersionDialect
}
}
return p.Ecosystem.VersionDialect()
}
func comparePackageVersions(previous, current packageView) (int, bool) {
dialect := current.dialect
if !dialect.Valid() {
dialect = previous.dialect
}
if !dialect.Valid() {
return 0, false
}
before, err := versionpkg.ParseVersion(previous.version, dialect)
if err != nil {
return 0, false
}
after, err := versionpkg.ParseVersion(current.version, dialect)
if err != nil {
return 0, false
}
return versionpkg.Compare(before, after)
}
package install
import (
"cmp"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/document"
)
// ErrRuntimeImageUnavailable reports that Lucy cannot produce the runtime
// image of a lock without the network or a Java runtime. Adoption then claims
// only the files the lock pins by digest.
var ErrRuntimeImageUnavailable = errors.New("runtime image unavailable")
// storedRuntimeImage returns the runtime image the stored snapshot of the
// recipe describes, without materializing it.
func storedRuntimeImage(
ctx context.Context,
locked *document.Lock,
) ([]bootstrap.Output, bool) {
key, err := snapshot.Key(locked.Server)
if err != nil {
return nil, false
}
store, err := openSnapshotStore()
if err != nil {
return nil, false
}
defer store.Close()
snap, ok, err := store.LookupSnapshot(ctx, key)
if err != nil || !ok {
return nil, false
}
return snapshotOutputs(snap, locked.Server), true
}
// RuntimeImage returns the runtime image of a locked server: the files its
// bootstrap method produces, with their digests, modes, policies, and roles,
// sorted by path. It reads that image from the stored snapshot of the recipe,
// or builds it in a private stage under root from artifacts the store already
// holds and stores the result. It never writes the server directory and never
// uses the network; a missing artifact or Java runtime returns an error that
// wraps ErrRuntimeImageUnavailable.
//
// The caller must hold the workspace writer lock. Stage-only material is
// absent from the result.
func (s *Service) RuntimeImage(
ctx context.Context,
root string,
locked *document.Lock,
opts Options,
) (image []bootstrap.Output, resultErr error) {
if locked == nil {
return nil, errors.New("cannot build a runtime image without a lock")
}
if err := locked.Server.Bootstrap.Validate(); err != nil {
return nil, err
}
if err := document.SafeRelativePath(locked.Server.Directory); err != nil {
return nil, err
}
// A stored snapshot already names every runtime file's digest and mode.
// Adoption compares the workspace against those values, so restoring the
// bytes here would only repeat a read the comparison performs.
if image, ok := storedRuntimeImage(ctx, locked); ok {
return image, nil
}
opts.ProvisionJava = nil
check, err := s.selectJava(ctx, root, locked, opts)
if err != nil {
return nil, err
}
// A runtime that misses the lock's requirement can fail a patcher or a
// processor in ways no error type names. Without it, a method that runs
// Java reports the missing runtime, and a snapshot still restores.
java := ""
if check.Satisfied() {
java = check.Executable()
}
stage, err := os.MkdirTemp(filepath.Join(root, ".lucy"), "stage-*")
if err != nil {
return nil, err
}
defer func() {
if err := os.RemoveAll(stage); err != nil {
image = nil
// The staging cause is kept as text only: a cleanup failure is
// fatal even when that cause would permit pinned adoption.
if resultErr != nil {
resultErr = fmt.Errorf("remove runtime image stage: %w (after: %v)", err, resultErr)
} else {
resultErr = fmt.Errorf("remove runtime image stage: %w", err)
}
}
}()
store := &downloadStore{
offline: true,
storeOnly: true,
logger: s.logger,
injected: opts.Materialize,
}
// Staging attaches the verified digests without rewriting the caller's lock.
resolved := *locked
resolved.Server.Inputs = slices.Clone(locked.Server.Inputs)
outputs, err := s.stageServerTree(ctx, stage, &resolved, java, store, opts)
if errors.Is(err, errOfflineArtifactUnavailable) || errors.Is(err, bootstrap.ErrNoJava) {
return nil, fmt.Errorf("stage locked runtime: %w: %w", ErrRuntimeImageUnavailable, err)
}
if err != nil {
return nil, err
}
image = make([]bootstrap.Output, 0, len(outputs))
for _, output := range outputs {
if output.Policy != bootstrap.PolicyDiscard && output.Role != bootstrap.RoleBootstrapOnly {
image = append(image, output)
}
}
slices.SortFunc(image, func(a, b bootstrap.Output) int {
return cmp.Compare(a.Path, b.Path)
})
return image, nil
}
package install
import (
"context"
"errors"
"fmt"
"path/filepath"
"slices"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/serverregistry"
"github.com/mclucy/lucy/upstream"
)
type Source interface {
Candidates(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
ecosystem catalog.Ecosystem,
) ([]upstream.Candidate, error)
Metadata(ctx context.Context, endpoint string, target any) error
ResolveServerProduct(
ctx context.Context,
request upstream.ServerProductRequest,
acquire artifact.Materializer,
) (upstream.ServerProductResolution, error)
}
// Service owns one installation pipeline: configured routing, the artifact
// cache, tracked-file provisioning, the Python host, and the diagnostic
// logger. Every entry point receives its root and request options explicitly.
type Service struct {
source Source
network *cache.Client
tracker *filetrack.Service
python *PythonHost
registry *serverregistry.Registry
logger *log.Logger
githubProxy string
link fsutil.LinkMode
}
// NewService constructs the installation service from its explicit
// dependencies. network performs artifact transfers; tracker provisions
// tracked files; python supplies interpreter and process capabilities;
// registry records successful installations for the artifact store's
// retention sweep; githubProxy mirrors release asset downloads when
// non-empty; link selects how stored content reaches the workspace.
func NewService(
source Source,
network *cache.Client,
tracker *filetrack.Service,
python *PythonHost,
registry *serverregistry.Registry,
logger *log.Logger,
githubProxy string,
link fsutil.LinkMode,
) *Service {
return &Service{
source: source,
network: network,
tracker: tracker,
python: python,
registry: registry,
logger: logger,
githubProxy: githubProxy,
link: link,
}
}
// registerServer records the workspace before any artifact enters the store.
// A successful installation therefore always has a registry entry whose lock
// the artifact store's retention sweep can read. Registration failure fails
// the installation instead of reporting success that the sweep cannot trace.
func (s *Service) registerServer(root string, result *Result) error {
if s.registry == nil {
return errors.New("server registry is unavailable; cannot record this installation for artifact retention")
}
duplicates, err := s.registry.RegisterInstallation(root)
if err != nil {
return fmt.Errorf("register server before installation: %w", err)
}
if result != nil {
for _, duplicate := range duplicates {
result.Warnings = append(result.Warnings, fmt.Errorf(
"server name %q is also registered at %s; --server cannot select an ambiguous name",
duplicate.Name,
duplicate.Path,
))
}
}
return nil
}
// Resolve builds the lock document that answers d without staging or
// committing the server tree. It records the declared packages alone, because
// the workspace the manifest describes already holds a working set that
// catalogue dependencies must not extend. Artifact bytes still enter the
// artifact store because the lock pins their hashes. It returns the
// resolution facts alongside the lock. The caller must hold the workspace
// writer lock.
func (s *Service) Resolve(
ctx context.Context,
root string,
d *document.Manifest,
old *document.Lock,
opts Options,
) (*document.Lock, *Result, error) {
opts.Trace.reportPackageCount(old)
result := newResult()
result.Mode = ModeResolve
result.Reason = "lock resolved"
absolute, err := filepath.Abs(root)
if err != nil {
return nil, result, err
}
if d == nil {
return nil, result, fmt.Errorf("manifest required to resolve a lock")
}
opts.declaredOnly = true
if err := workspacewrite.SafePath(absolute, ".lucy"); err != nil {
return nil, result, err
}
fingerprint, err := d.Fingerprint()
if err != nil {
return nil, result, err
}
if old != nil && !opts.WithOptional && old.ManifestFingerprint == fingerprint && adoptionMatchesLock(opts.Adopted, old) {
// Reuse must still leave the accepted local bytes replayable. Only
// adopted packages and runtime files whose trusted digest proves the
// requested artifact are imported; a missing artifact is not fetched
// merely because the lock was reused.
if _, err := prepareAdoptedArtifacts(ctx, absolute, opts.Adopted, nil); err != nil {
return nil, result, err
}
localRuntime := newLocalRuntimeSource(absolute, opts.LocalRuntime)
proven, changed, err := localRuntime.importServer(ctx, old.Server)
if err != nil {
return nil, result, err
}
s.logger.Debug("lock resolution reused current lock", "reason", "manifest unchanged")
result.Mode = ModeReplay
result.Reason = "manifest unchanged; lock reused"
// The observed runtime may prove a SHA-256 the reused lock does not
// pin. Returning an enriched copy publishes that digest without
// dropping an existing pin; an unchanged lock keeps its exact bytes.
return withProvenServer(old, proven, changed), result, nil
}
store := s.newDownloadStore(opts, result)
resolved, err := s.resolveInstall(ctx, absolute, d, old, fingerprint, &opts, store, result)
if err != nil {
return nil, result, err
}
if err := resolved.Validate(); err != nil {
return nil, result, err
}
return resolved, result, nil
}
// ApplyPlan stages and commits a previously resolved plan. It rechecks the
// workspace state before staging, so a plan cannot overwrite a concurrent
// manifest or lock edit.
func (s *Service) ApplyPlan(
ctx context.Context,
root string,
plan *Plan,
opts Options,
) (result *Result, resultErr error) {
if plan == nil || plan.Resolved == nil {
return nil, fmt.Errorf("installation plan is required")
}
opts.Trace.reportPackageCount(plan.Previous)
absolute, err := filepath.Abs(root)
if err != nil {
return nil, err
}
root = absolute
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
if err := workspacewrite.SafePath(root, ".lucy"); err != nil {
return nil, err
}
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
opts.PublishManifest = plan.PublishManifest
baseManifest, baseLock, documents, err := preflightLocked(
root, plan.Manifest, plan.Previous, opts, s.logger,
)
if err != nil {
return nil, err
}
if err := plan.checkBase(baseManifest, baseLock, documents); err != nil {
return nil, err
}
if err := s.registerServer(root, plan.Result); err != nil {
return nil, err
}
// The isolated MCDReforged environment is keyed by its Python requirements,
// so staging provisions a fresh environment whenever this list changes.
if previous := plan.Previous; previous != nil && previous.MCDR != nil &&
plan.Resolved.MCDR != nil {
before := mcdrPythonRequirements(previous)
after := mcdrPythonRequirements(plan.Resolved)
if !slices.Equal(before, after) {
if plan.Result == nil {
plan.Result = newResult()
}
plan.Result.MCDR = &MCDRChange{
Version: plan.Resolved.MCDR.Version,
Inputs: len(after),
PreviousInputs: len(before),
}
}
}
result = plan.Result
if result == nil {
result = newResult()
result.applyChanges(plan.Previous, plan.Resolved, plan.Manifest)
}
store := s.newDownloadStore(opts, result)
opts.publishLock = plan.PublishLock
diagnostics, err := s.stageInstall(ctx, root, plan.Manifest, plan.Resolved, documents, store, opts, result)
result.Diagnostics = diagnostics
return result, err
}
// Sync converges the workspace to its manifest and lock. A missing manifest or
// lock is allowed only when the other document can drive the operation.
func (s *Service) Sync(
ctx context.Context,
root string,
d *document.Manifest,
old *document.Lock,
opts Options,
) (*Result, error) {
result := newResult()
diagnostics, resultErr := s.syncInstall(ctx, root, d, old, opts, result)
result.Diagnostics = diagnostics
return result, resultErr
}
// Materializer returns a verified artifact materializer and the fetch summary
// it updates. Callers must hold the workspace writer lock while resolving.
func (s *Service) Materializer(opts Options) (artifact.Materializer, *FetchSummary) {
summary := &FetchSummary{}
store := &downloadStore{
offline: opts.Offline,
trace: opts.Trace,
fetch: summary,
network: s.network,
logger: s.logger,
githubProxy: s.githubProxy,
injected: opts.Materialize,
}
return store.materialize, summary
}
// CheckJava reports whether an installed Java runtime satisfies the lock.
func (s *Service) CheckJava(
ctx context.Context,
root string,
locked *document.Lock,
) (*javaruntime.Check, error) {
return javaruntime.Select(ctx, root, javaruntime.RequirementOf(locked, s.logger), s.logger)
}
package install
import (
"context"
"path/filepath"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
)
const installFileWorkers = 4
// stagePackages validates ownership and destinations before acquiring or
// copying independent package artifacts.
func (s *Service) stagePackages(ctx context.Context, root, stage string, resolved *document.Lock, store *downloadStore, stagedOutputs map[string]bootstrap.Output, opts Options) (map[string]bool, map[string]string, error) {
if err := rejectSharedDestinations(root, resolved, stagedOutputs); err != nil {
return nil, nil, err
}
type job struct {
pkg *document.Package
destination string
}
jobs := make([]job, 0, len(resolved.Packages))
overwritePaths := map[string]bool{}
for i := range resolved.Packages {
p := &resolved.Packages[i]
if !p.Enabled() {
continue
}
destination, err := resolved.PackageDestination(p)
if err != nil {
return nil, nil, err
}
if opts.Overwrite {
overwritePaths[filepath.ToSlash(destination)] = true
}
jobs = append(jobs, job{pkg: p, destination: destination})
}
if len(jobs) == 0 {
return overwritePaths, nil, nil
}
const phase = "package staging"
started := time.Now()
opts.Trace.phaseStarted(phase)
completed := 0
hashes := make([]string, len(jobs))
err := runStagingJobs(ctx, len(jobs), store.injected != nil, func(i int) error {
j := jobs[i]
source, err := store.materializeFor(ctx, &j.pkg.Artifact, filepath.ToSlash(j.destination))
if err != nil {
return err
}
j.pkg.Artifact.Hashes = source.Hashes
hashes[i] = strings.ToLower(source.Hashes["sha256"])
if err := fsutil.Materialize(source.Path, filepath.Join(stage, j.destination), s.link.Perm(0o644), s.link); err != nil {
return err
}
store.progressMu.Lock()
completed++
opts.Trace.ReportPhaseProgress(phase, completed, len(jobs))
store.progressMu.Unlock()
return nil
})
if err != nil {
return nil, nil, err
}
opts.Trace.phaseDone(PhaseInfo{Name: phase, Elapsed: time.Since(started), Count: len(jobs), Total: len(jobs)})
s.logger.Debug("packages staged", "active", len(jobs), "recorded", len(resolved.Packages))
stagedHashes := make(map[string]string, len(jobs))
for i, j := range jobs {
if hashes[i] == "" {
continue
}
key := filepath.ToSlash(filepath.Clean(filepath.FromSlash(j.destination)))
stagedHashes[key] = hashes[i]
}
return overwritePaths, stagedHashes, nil
}
// runStagingJobs runs each job with at most installFileWorkers in flight, or
// one at a time for an injected source. A job starts as soon as a worker frees
// up, so one slow transfer does not hold up the jobs behind it. The first
// failure in input order is returned and no further job starts after it.
func runStagingJobs(ctx context.Context, count int, serial bool, run func(int) error) error {
if count == 0 {
return ctx.Err()
}
workers := min(installFileWorkers, count)
if serial {
workers = 1
}
var (
mu sync.Mutex
next int
failed bool
errs = make([]error, count)
group sync.WaitGroup
)
worker := func() {
for {
mu.Lock()
if failed || next >= count {
mu.Unlock()
return
}
index := next
next++
mu.Unlock()
if err := run(index); err != nil {
mu.Lock()
errs[index], failed = err, true
mu.Unlock()
return
}
}
}
for range workers {
group.Go(worker)
}
group.Wait()
for _, err := range errs {
if err != nil {
return err
}
}
return ctx.Err()
}
package install
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
)
// currentCheck carries the digest evidence of one command. memo avoids a
// second read of a file this command already hashed, and evidence answers a
// check from stat identities an earlier command recorded.
type currentCheck struct {
memo *fileidentity.Memo
evidence *currentEvidence
}
// installationCurrent reports whether the receipt answers the lock and both
// bootstrap and package convergence are current. It returns the evidence it
// collected so a caller can record the identities this command proved.
func installationCurrent(
ctx context.Context,
root string,
l *document.Lock,
memo *fileidentity.Memo,
logger *log.Logger,
) (bootstrapOK, packagesOK bool, evidence *currentEvidence, err error) {
evidence = newCurrentEvidence(root, memo, logger)
check := currentCheck{memo: memo, evidence: evidence}
current, err := receipt.Read(root)
if errors.Is(err, os.ErrNotExist) {
logger.Debug("installation not current", "reason", "no install receipt")
return false, false, evidence, nil
}
if err != nil {
return false, false, evidence, err
}
bCurrent, err := bootstrapCurrentWithCheck(root, l, current, check, logger)
if err != nil || !bCurrent {
return false, false, evidence, err
}
pCurrent, err := packagesCurrent(ctx, root, l, current, check, logger)
if err != nil || !pCurrent {
return true, false, evidence, err
}
logger.Debug(
"installation current",
"reason", "receipt satisfies bootstrap contract and package set",
"receipt", filepath.Join(root, receipt.Filename),
)
evidence.write(root, current.Entries, logger)
return true, true, evidence, nil
}
// bootstrapCurrent reports whether the receipt answers the resolved bootstrap
// plan: its bootstrap fingerprint matches the lock and every recorded bootstrap
// output still matches its accepted baseline.
func bootstrapCurrent(
root string,
l *document.Lock,
current *receipt.Receipt,
logger *log.Logger,
) (bool, error) {
return bootstrapCurrentWithCheck(root, l, current, currentCheck{}, logger)
}
func bootstrapCurrentWithCheck(
root string,
l *document.Lock,
current *receipt.Receipt,
check currentCheck,
logger *log.Logger,
) (bool, error) {
if current == nil {
return false, nil
}
if current.BootstrapFingerprint == "" {
logger.Debug("bootstrap not current", "reason", "bootstrap fingerprint unproven or missing")
return false, nil
}
expected, err := receipt.BootstrapFingerprint(l)
if err != nil {
return false, err
}
if current.BootstrapFingerprint != expected {
logger.Debug(
"bootstrap not current",
"reason", "bootstrap fingerprint changed",
"receipt", current.BootstrapFingerprint,
"expected", expected,
)
return false, nil
}
for _, seed := range current.SeedPaths {
if err := workspacewrite.SafePath(root, seed); err != nil {
return false, err
}
info, err := os.Lstat(filepath.Join(root, filepath.FromSlash(seed)))
switch {
case os.IsNotExist(err):
logger.Debug("bootstrap not current", "reason", "recorded seed missing", "path", seed)
return false, nil
case err != nil:
return false, err
}
if !info.Mode().IsRegular() {
logger.Debug("bootstrap not current", "reason", "recorded seed is symlink or non-regular", "path", seed)
return false, nil
}
}
tracked := trackedPaths(l)
targets := make([]receipt.Entry, 0, len(current.Entries))
hasBootstrapEntry := false
for _, entry := range current.Entries {
if entry.Origin != receipt.OriginBootstrap {
continue
}
hasBootstrapEntry = true
if tracked[strings.ToLower(entry.Path)] {
continue
}
targets = append(targets, entry)
}
if l.Server.Product != "" && !hasBootstrapEntry {
logger.Debug("bootstrap not current", "reason", "no bootstrap entries recorded in receipt")
return false, nil
}
currentFiles, err := checkFilesInOrder(
context.Background(),
len(targets),
func(i int) (bool, error) {
return receiptEntryCurrent(root, targets[i], "bootstrap", check, logger)
},
)
return currentFiles, err
}
// packagesCurrent reports whether recorded package entries match the lock's
// package pins and every package file exists with its expected digest.
func packagesCurrent(
ctx context.Context,
root string,
l *document.Lock,
current *receipt.Receipt,
check currentCheck,
logger *log.Logger,
) (bool, error) {
if current == nil {
return false, nil
}
expected, err := receipt.PackageFingerprint(l)
if err != nil {
return false, err
}
if current.PackageFingerprint != expected {
logger.Debug(
"packages not current",
"reason", "package fingerprint changed",
"receipt", current.PackageFingerprint,
"expected", expected,
)
return false, nil
}
recordedPackages := make(map[string]receipt.Entry, len(current.Entries))
for _, entry := range current.Entries {
if entry.Origin == receipt.OriginPackage {
recordedPackages[filepath.ToSlash(filepath.Clean(filepath.FromSlash(entry.Path)))] = entry
}
}
verify := func(i int) (bool, error) {
p := &l.Packages[i]
if !p.Enabled() {
return true, nil
}
dest, err := l.PackageDestination(p)
if err != nil {
return false, err
}
cleanDest := filepath.ToSlash(filepath.Clean(filepath.FromSlash(dest)))
entry, recorded := recordedPackages[cleanDest]
if !recorded {
logger.Debug("packages not current", "reason", "locked package not recorded in receipt", "path", cleanDest)
return false, nil
}
if entry.Package != p.Artifact.Provider.String()+":"+p.Artifact.ProjectID {
logger.Debug("packages not current", "reason", "package identity mismatch", "path", cleanDest)
return false, nil
}
return receiptEntryCurrent(root, entry, "packages", check, logger)
}
return checkFilesInOrder(ctx, len(l.Packages), verify)
}
// checkFilesInOrder verifies one file at a time on a bounded pool. Stop
// assigning work on a stale file but finish earlier checks: the first result
// in receipt order decides.
func checkFilesInOrder(
ctx context.Context,
count int,
check func(int) (bool, error),
) (bool, error) {
var mu sync.Mutex
var wg sync.WaitGroup
next, firstFailure := 0, count
var firstErr error
for range min(count, 4) {
wg.Go(func() {
for ctx.Err() == nil {
mu.Lock()
i := next
if i == count {
mu.Unlock()
return
}
next++
mu.Unlock()
if ok, err := check(i); !ok || err != nil {
mu.Lock()
next = count
if i < firstFailure {
firstFailure, firstErr = i, err
}
mu.Unlock()
return
}
}
})
}
wg.Wait()
if err := ctx.Err(); err != nil {
return false, err
}
return firstFailure == count, firstErr
}
// receiptEntryCurrent reports whether the file a receipt entry protects still
// exists as a regular file with its accepted digest and mode. kind names the
// entry class in diagnostics. A stat identity the sidecar recorded for the
// accepted digest answers the check without reading the file.
func receiptEntryCurrent(
root string,
entry receipt.Entry,
kind string,
check currentCheck,
logger *log.Logger,
) (bool, error) {
if err := workspacewrite.SafePath(root, entry.Path); err != nil {
return false, err
}
target := filepath.Join(root, filepath.FromSlash(entry.Path))
info, err := os.Lstat(target)
switch {
case errors.Is(err, fs.ErrNotExist):
logger.Debug(kind+" not current", "reason", "managed output missing", "path", entry.Path)
return false, nil
case err != nil:
return false, err
}
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
logger.Debug(kind+" not current", "reason", "managed output is symlink or non-regular", "path", entry.Path)
return false, nil
}
if check.evidence.trusted(entry, info) {
return true, nil
}
observation, err := check.memo.ObservePath(target, nil)
if err != nil {
return false, err
}
actual := observation.Hashes["sha256"]
if !strings.EqualFold(actual, entry.SHA256) {
logger.Debug(kind+" not current", "reason", "managed output modified", "path", entry.Path, "baseline", entry.SHA256, "actual", actual)
return false, nil
}
if entry.Mode != 0 {
actualMode := workspacewrite.EffectiveInstallMode(observation.Mode.Perm())
expectedMode := workspacewrite.EffectiveInstallMode(os.FileMode(entry.Mode))
if actualMode != expectedMode {
logger.Debug(kind+" not current", "reason", "managed output mode modified", "path", entry.Path, "expected", expectedMode, "actual", actualMode)
return false, nil
}
}
check.evidence.observe(entry, observation.Identity, observation.HasIdentity)
return true, nil
}
// trackedPaths lowercases the lock's tracked-file paths, because the
// filesystems that host a workspace may compare them case-insensitively.
func trackedPaths(l *document.Lock) map[string]bool {
paths := make(map[string]bool, len(l.Files))
for _, file := range l.Files {
paths[strings.ToLower(file.Path)] = true
}
return paths
}
package install
import (
"io"
"time"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
// PhaseInfo describes a finished stage.
type PhaseInfo struct {
Name string
Elapsed time.Duration
Count int
Total int
Product server.Product
Version version.Version
Minecraft version.Version
}
// Trace receives facts about an operation while it runs. Every field is
// optional: a nil field or a nil Trace reports nothing.
type Trace struct {
PhaseStarted func(name string)
PhaseProgress func(name string, count, total int)
PhaseDone func(phase PhaseInfo)
FetchStarted func(name string, size int64)
FetchProgress func(name string, read, total int64)
FetchDone func(name string, fromCache bool)
// PackageCount receives the current lock's package count, the bounded
// workload the operation starts from. It is reported only for an observed
// lock; an absent lock reports nothing rather than a bogus zero, while an
// observed empty lock reports a measured zero.
PackageCount func(lockedPackages int)
// ProcessOutput receives the output of subprocesses that the operation
// runs, such as installer processors, Paperclip, and pip.
ProcessOutput io.Writer
Resolve resolve.Trace
}
func (t *Trace) phaseStarted(name string) {
if t != nil && t.PhaseStarted != nil {
t.PhaseStarted(name)
}
}
func (t *Trace) phaseDone(phase PhaseInfo) {
if t != nil && t.PhaseDone != nil {
t.PhaseDone(phase)
}
}
func (t *Trace) progressPhase(name string, count, total int) {
if t != nil && t.PhaseProgress != nil {
t.PhaseProgress(name, count, total)
}
}
// ReportPhaseProgress publishes bounded progress inside a started stage.
func (t *Trace) ReportPhaseProgress(name string, count, total int) {
t.progressPhase(name, count, total)
}
// bootstrapProgress adapts the bootstrap package's callback shape to this
// operation's trace without either package importing the other.
func (t *Trace) bootstrapProgress() bootstrap.Progress {
return bootstrap.Progress{
PhaseStarted: func(name string) { t.phaseStarted(name) },
PhaseProgress: func(name string, count, total int) {
t.progressPhase(name, count, total)
},
PhaseDone: func(name string, elapsed time.Duration, count, total int) {
t.phaseDone(PhaseInfo{
Name: name,
Elapsed: elapsed,
Count: count,
Total: total,
})
},
}
}
// ReportPhase publishes a finished stage another package ran.
func (t *Trace) ReportPhase(phase PhaseInfo) {
t.phaseDone(phase)
}
func (t *Trace) fetchStarted(name string, size int64) {
if t != nil && t.FetchStarted != nil {
t.FetchStarted(name, size)
}
}
func (t *Trace) fetchProgress(name string, read, total int64) {
if t != nil && t.FetchProgress != nil {
t.FetchProgress(name, read, total)
}
}
func (t *Trace) fetchDone(name string, fromCache bool) {
if t != nil && t.FetchDone != nil {
t.FetchDone(name, fromCache)
}
}
// reportPackageCount measures the starting workload from the lock the caller
// already holds. It reports nothing when no lock was observed, so an absent
// document is not presented as a measured zero, and it never walks the
// manifest for this observation. Installation reports before it resolves or
// replays, so a failure or cancellation still carries the starting scale.
func (t *Trace) reportPackageCount(old *document.Lock) {
if t == nil || t.PackageCount == nil || old == nil {
return
}
t.PackageCount(len(old.Packages))
}
// ReportPhaseStarted publishes a stage another package began.
func (t *Trace) ReportPhaseStarted(name string) {
t.phaseStarted(name)
}
// ReportFetchStarted publishes a transfer another package began.
func (t *Trace) ReportFetchStarted(name string, size int64) {
t.fetchStarted(name, size)
}
// ReportFetchProgress updates the transfer's byte count.
func (t *Trace) ReportFetchProgress(name string, read, total int64) {
t.fetchProgress(name, read, total)
}
// ReportFetchDone publishes that the transfer ended.
func (t *Trace) ReportFetchDone(name string, fromCache bool) {
t.fetchDone(name, fromCache)
}
func (t *Trace) processOutput() io.Writer {
if t == nil || t.ProcessOutput == nil {
return io.Discard
}
return t.ProcessOutput
}
func (t *Trace) resolveTrace() resolve.Trace {
if t == nil {
return resolve.Trace{}
}
return t.Resolve
}
package install
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
)
type installCommitMode int
const (
// installCommitReconcile applies a staged tree, updates both
// fingerprints, and prunes outputs the resolution no longer needs.
installCommitReconcile installCommitMode = iota
// installCommitMetadataOnly publishes documents and carries the accepted
// ownership ledger forward without walking a stage or pruning.
installCommitMetadataOnly
// installCommitOverlay applies staged paths over the existing ledger,
// preserving entries the stage does not mention. Wrapper reconciliation
// uses it so an unchanged bootstrap and package set is never pruned.
installCommitOverlay
)
// stagedOutputPreserved reports whether a staged classification leaves any
// existing workspace file user-owned. Seeds, discard material, and
// bootstrap-only tools never grant pruning authority.
func stagedOutputPreserved(out bootstrap.Output) bool {
return out.Policy == bootstrap.PolicySeed ||
out.Policy == bootstrap.PolicyDiscard ||
out.Role == bootstrap.RoleBootstrapOnly
}
// prunable reports whether reconcile may remove an accepted entry: the file
// was not restaged, is not tracked, carries no preserved policy, and belongs
// to an origin this commit governs.
func prunable(
entry receipt.Entry,
tracked map[string]bool,
staged map[string]commitWrite,
stagedOutputs map[string]bootstrap.Output,
stagedBootstrap bool,
) (bool, error) {
if tracked[strings.ToLower(entry.Path)] {
return false, nil
}
if _, restaged := staged[entry.Path]; restaged {
return false, nil
}
if out, classified := stagedOutputs[entry.Path]; classified &&
stagedOutputPreserved(out) {
return false, nil
}
switch entry.Origin {
case receipt.OriginBootstrap:
return stagedBootstrap, nil
case receipt.OriginPackage, receipt.OriginMCDR:
return true, nil
default:
return false, fmt.Errorf(
"unrecognized entry origin %q for path %s; refusing implicit prune",
entry.Origin, entry.Path,
)
}
}
// pruneTargets plans the accepted entries a reconcile removes. An entry whose
// file is already absent maps to nil. That absence stays a precondition: the
// journal plan and the pre-commit check fail if the path reappears, so a file
// that appears after planning is never silently dropped from the ledger. A
// present entry maps to the image observed now, which later steps recheck
// before the journal captures its before image.
func pruneTargets(
root string,
previous []receipt.Entry,
tracked map[string]bool,
staged map[string]commitWrite,
stagedOutputs map[string]bootstrap.Output,
stagedBootstrap bool,
check currentCheck,
) (map[string]*workspacewrite.InstallImage, error) {
files, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer files.Close()
targets := make(map[string]*workspacewrite.InstallImage)
for _, old := range previous {
shouldPrune, err := prunable(
old,
tracked,
staged,
stagedOutputs,
stagedBootstrap,
)
if err != nil {
return nil, err
}
if !shouldPrune {
continue
}
current, err := workspacewrite.ObserveInstallImageCached(files, old.Path, check.memo)
if err != nil {
if info, statErr := files.Lstat(old.Path); statErr == nil &&
!info.Mode().IsRegular() {
return nil, fmt.Errorf("owned output is not a regular file: %s", old.Path)
}
return nil, err
}
if current == nil {
targets[old.Path] = nil
continue
}
if !matchesReceipt(old, current) {
return nil, fmt.Errorf("modified owned output cannot be pruned: %s", old.Path)
}
targets[old.Path] = current
}
return targets, nil
}
// installOutputExpectation is the image one path must hold at the commit
// point. compareMode is false for a legacy receipt entry whose zero mode is a
// wildcard rather than observed evidence.
type installOutputExpectation struct {
image *workspacewrite.InstallImage
compareMode bool
}
// verifyInstallOutputs checks the workspace at the commit point. A journaled
// write must hold its after image and a journaled prune must stay absent, so a
// path edited while the executor wrote another file is not mistaken for the
// bytes the transaction published. A path the executor skipped because it
// already matched is checked against its planned image. Entries the published
// receipt carries forward are checked against their accepted baselines,
// including legacy entries whose zero mode is a wildcard; a restaged or pruned
// path is never compared with the baseline it replaced.
func verifyInstallOutputs(
files *os.Root,
entries []workspacewrite.InstallJournalEntry,
staged map[string]commitWrite,
pruneExpected map[string]*workspacewrite.InstallImage,
retained []receipt.Entry,
check currentCheck,
) error {
mutated := make(map[string]*workspacewrite.InstallImage, len(entries))
for _, entry := range entries {
// A nil after image records a journaled prune, so the same table
// expresses "must hold these bytes" and "must stay absent".
mutated[entry.Path] = entry.After
}
expected := make(
map[string]installOutputExpectation,
len(staged)+len(pruneExpected)+len(retained),
)
for name, write := range staged {
expected[name] = installOutputExpectation{
image: write.after,
compareMode: true,
}
}
for name, image := range pruneExpected {
expected[name] = installOutputExpectation{
image: image,
compareMode: true,
}
}
for _, entry := range retained {
if _, planned := expected[entry.Path]; planned {
continue
}
expected[entry.Path] = installOutputExpectation{
image: receiptImage(entry),
compareMode: entry.Mode != 0,
}
}
names := make([]string, 0, len(expected))
for name := range expected {
names = append(names, name)
}
slices.Sort(names)
type verifiedOutput struct {
image *workspacewrite.InstallImage
identity fileidentity.Identity
hasIdentity bool
err error
}
results := make([]verifiedOutput, len(names))
workers := min(len(names), installFileWorkers)
var next atomic.Int64
var group sync.WaitGroup
for range workers {
group.Go(func() {
for {
index := int(next.Add(1)) - 1
if index >= len(names) {
return
}
name := names[index]
want := expected[name]
if after, journaled := mutated[name]; journaled {
want = installOutputExpectation{image: after, compareMode: true}
}
current, identity, hasIdentity, err := workspacewrite.ObserveInstallImageEvidence(files, name, check.memo)
if err != nil {
results[index].err = fmt.Errorf(
"inspect installation output %s before commit: %w",
name,
err,
)
return
}
if !workspacewrite.InstallImagesMatch(
current,
want.image,
want.compareMode,
) {
results[index].err = fmt.Errorf(
"installation output %s changed before commit",
name,
)
return
}
results[index] = verifiedOutput{
image: current,
identity: identity,
hasIdentity: hasIdentity,
}
}
})
}
group.Wait()
for index, name := range names {
result := results[index]
if result.err != nil {
return result.err
}
if result.image == nil {
continue
}
check.evidence.observe(
receipt.Entry{Path: name, SHA256: result.image.SHA256},
result.identity,
result.hasIdentity,
)
}
return nil
}
// applyCommit publishes the staged installation against documents the caller
// observed before the operation read or resolved anything, so an edit made
// after observation fails the transaction instead of being overwritten.
// stagedOutputs classifies every non-package file the stage is allowed to
// contain, including method bootstrap outputs validated before packages joined
// the stage and explicit wrapper outputs. mcdrOutputs identifies the subset
// produced by the MCDReforged wrapper so those entries carry their own receipt
// origin. stagedBootstrap reports whether the bootstrap contract ran for this
// operation; when false its established outputs are preserved and revalidated
// against the pinned receipt, so drift between the currency check and the
// commit aborts before anything is written. The commit never inspects the stage
// tree against the bootstrap contract, because that tree also contains package
// and wrapper files that are not bootstrap outputs.
func applyCommit(root, stage string, d *document.Manifest, l *document.Lock, publish bool, overwritePaths map[string]bool, stagedPackageHashes map[string]string, stagedOutputs, mcdrOutputs map[string]bootstrap.Output, stagedBootstrap bool, mode installCommitMode, documents WorkspaceDocuments, check currentCheck, logger *log.Logger) (FileChanges, error) {
reconcile := mode == installCommitReconcile
metadataOnly := mode == installCommitMetadataOnly
previous := receipt.New()
receiptPin, ok := documents.documents[receipt.Filename]
if !ok {
return FileChanges{}, fmt.Errorf("installation documents do not capture %s", receipt.Filename)
}
if receiptPin.image != nil {
parsed, err := receipt.Decode(bytes.NewReader(receiptPin.raw))
if err != nil {
return FileChanges{}, err
}
previous = *parsed
}
if !stagedBootstrap {
// The currency check that skipped bootstrap staging predates
// package staging and downloads, so the outputs this commit
// retains are revalidated here: a fingerprint carried forward
// over drifted files would leave the receipt reporting a server
// tree that no longer satisfies the contract.
retained, err := bootstrapCurrentWithCheck(root, l, &previous, check, logger)
if err != nil {
return FileChanges{}, err
}
if !retained {
return FileChanges{}, fmt.Errorf(
"retained bootstrap outputs no longer satisfy the locked bootstrap contract; rerun the install to restage the server tree",
)
}
}
owned := map[string]receipt.Entry{}
for _, entry := range previous.Entries {
owned[entry.Path] = entry
}
next := receipt.New()
nextIndex := make(map[string]int)
packageByDest := make(map[string]string)
if reconcile {
bf, err := receipt.BootstrapFingerprint(l)
if err != nil {
return FileChanges{}, err
}
pf, err := receipt.PackageFingerprint(l)
if err != nil {
return FileChanges{}, err
}
if stagedBootstrap {
next.BootstrapFingerprint = bf
} else {
next.BootstrapFingerprint = previous.BootstrapFingerprint
next.SeedPaths = slices.Clone(previous.SeedPaths)
}
next.PackageFingerprint = pf
if !stagedBootstrap {
for _, entry := range previous.Entries {
if entry.Origin != receipt.OriginBootstrap {
continue
}
if out, classified := stagedOutputs[entry.Path]; classified &&
stagedOutputPreserved(out) {
continue
}
next.Entries = append(next.Entries, entry)
}
}
} else {
// Metadata-only publication carries the accepted ownership ledger
// forward untouched. Overlay reconciliation updates only the staged
// paths and preserves every other accepted entry.
next.BootstrapFingerprint = previous.BootstrapFingerprint
next.SeedPaths = slices.Clone(previous.SeedPaths)
next.PackageFingerprint = previous.PackageFingerprint
next.Entries = slices.Clone(previous.Entries)
}
if !metadataOnly {
// A preserved bootstrap entry can also be restaged, for example a
// wrapper regenerated on every package change. Merge by path so the
// restaged bytes update the accepted baseline instead of producing a
// duplicate entry, and refuse when the staged file claims a different
// origin.
for i, entry := range next.Entries {
nextIndex[entry.Path] = i
}
for i := range l.Packages {
p := &l.Packages[i]
if !p.Enabled() {
continue
}
dest, err := l.PackageDestination(p)
if err != nil {
continue
}
clean := filepath.ToSlash(filepath.Clean(dest))
packageByDest[clean] = p.Artifact.Provider.String() + ":" + p.Artifact.ProjectID
}
}
tracked := trackedPaths(l)
staged := make(map[string]commitWrite)
var seedPaths []string
err := func() error {
if metadataOnly {
return nil
}
return filepath.WalkDir(stage, func(p string, e os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if e.IsDir() {
return nil
}
relative, err := filepath.Rel(stage, p)
if err != nil {
return err
}
relative = filepath.ToSlash(relative)
if err := document.SafeRelativePath(relative); err != nil {
return err
}
out, classified := stagedOutputs[relative]
if classified && (out.Policy == bootstrap.PolicyDiscard || out.Role == bootstrap.RoleBootstrapOnly) {
return nil
}
packageID, isPackage := packageByDest[relative]
if classified && isPackage {
return fmt.Errorf("staged output %s has both bootstrap and package origins", relative)
}
if !classified && !isPackage {
return fmt.Errorf("staged output %s is not classified by the bootstrap or package plan", relative)
}
target := filepath.Join(root, relative)
isSeed := classified && out.Policy == bootstrap.PolicySeed
runtimeOutput := classified && !isPackage && isManagedRuntimeOutput(out)
if tracked[strings.ToLower(relative)] {
if !isSeed {
return fmt.Errorf("tracked file %s collides with managed runtime output", relative)
}
return nil
}
seedPresent := false
if isSeed {
seedInfo, err := os.Lstat(target)
switch {
case err == nil:
if !seedInfo.Mode().IsRegular() {
return fmt.Errorf("refuse non-regular seed output %s", relative)
}
seedPresent = true
case !errors.Is(err, os.ErrNotExist):
return err
}
}
if isSeed && stagedBootstrap {
seedPaths = append(seedPaths, relative)
}
if seedPresent {
return nil
}
sha256 := out.SHA256
if sha256 == "" {
sha256 = stagedPackageHashes[relative]
}
if sha256 == "" {
hashes, err := DigestFile(p, nil)
if err != nil {
return err
}
sha256 = hashes["sha256"]
}
info, err := e.Info()
if err != nil {
return err
}
fileMode := os.FileMode(0o644)
if !isSeed {
fileMode = info.Mode().Perm()
}
var base *workspacewrite.InstallImage
displace := false
observation, err := check.memo.ObservePath(target, nil)
switch {
case err != nil:
return err
case observation.Exists:
if observation.Mode&os.ModeSymlink != 0 {
return fmt.Errorf("refuse symlink output %s", relative)
}
if !observation.Regular {
return fmt.Errorf("refuse non-regular output %s", relative)
}
current := workspacewrite.InstallImage{
SHA256: observation.Hashes["sha256"],
Mode: workspacewrite.EffectiveInstallMode(observation.Mode.Perm()),
}
base = ¤t
prior, isOwned := owned[relative]
if !isOwned {
switch {
case !runtimeOutput && overwritePaths[relative]:
logger.Debug(
"overwriting unowned output",
"path", relative,
"reason", "overwrite requested",
)
case classified && !isPackage && strings.EqualFold(current.SHA256, sha256):
// Retain the existing mode; adoption is not a replacement.
fileMode = observation.Mode.Perm()
logger.Debug(
"adopting byte-identical unowned output",
"path", relative,
"sha256", current.SHA256,
)
case runtimeOutput:
displace = true
default:
if isPackage {
return fmt.Errorf("unowned output conflict: %s (rerun with --overwrite to replace it)", relative)
}
return fmt.Errorf(
"unowned output conflict: %s (move the conflicting file before retrying bootstrap)",
relative,
)
}
} else if !matchesReceipt(prior, ¤t) {
switch {
case runtimeOutput:
displace = true
case overwritePaths[relative]:
logger.Debug(
"overwriting modified output",
"path", relative,
"reason", "overwrite requested",
)
default:
return fmt.Errorf("modified owned output conflict: %s", relative)
}
}
default:
// The write's base stays nil so the planner records an absent
// precondition instead of dropping the path.
}
if !isSeed {
origin := receipt.OriginBootstrap
if _, isMCDR := mcdrOutputs[relative]; isMCDR {
origin = receipt.OriginMCDR
}
if isPackage {
if origin != receipt.OriginBootstrap {
return fmt.Errorf(
"staged output %s has both MCDR and package origins",
relative,
)
}
origin = receipt.OriginPackage
}
entry := receipt.Entry{
Path: relative,
SHA256: sha256,
Mode: uint32(fileMode),
Origin: origin,
Package: packageID,
}
if prior, exists := owned[relative]; exists && prior.Origin != entry.Origin {
return fmt.Errorf(
"staged output %s changes receipt origin from %s to %s",
relative, prior.Origin, entry.Origin,
)
}
if index, exists := nextIndex[relative]; exists {
prior := next.Entries[index]
if prior.Origin != entry.Origin {
return fmt.Errorf(
"staged output %s changes receipt origin from %s to %s",
relative, prior.Origin, entry.Origin,
)
}
next.Entries[index] = entry
} else {
nextIndex[relative] = len(next.Entries)
next.Entries = append(next.Entries, entry)
}
}
after := workspacewrite.InstallImage{
SHA256: sha256,
Mode: workspacewrite.EffectiveInstallMode(fileMode),
}
staged[relative] = commitWrite{
path: relative,
source: p,
base: base,
after: &after,
displace: displace,
}
return nil
})
}()
if err != nil {
return FileChanges{}, err
}
if reconcile && stagedBootstrap {
slices.Sort(seedPaths)
next.SeedPaths = seedPaths
}
var pruneExpected map[string]*workspacewrite.InstallImage
if reconcile {
pruneExpected, err = pruneTargets(
root,
previous.Entries,
tracked,
staged,
stagedOutputs,
stagedBootstrap,
check,
)
if err != nil {
return FileChanges{}, err
}
}
documentWrites, err := documents.documentWrites(
documentCandidate{
name: document.LockFilename, mode: 0o644, publish: true,
snapshot: func() ([]byte, error) { return document.LockFile(root).Snapshot(l) },
merge: l.MergeBytes,
},
documentCandidate{
name: receipt.Filename, mode: 0o600, publish: true,
snapshot: next.Snapshot,
},
documentCandidate{
name: document.ManifestFilename, mode: 0o644, publish: publish,
snapshot: func() ([]byte, error) { return document.ManifestFile(root).Snapshot(d) },
merge: d.MergeBytes,
},
)
if err != nil {
return FileChanges{}, err
}
writes := make([]commitWrite, 0, len(staged)+len(documentWrites))
for name, write := range staged {
if installPathReserved(root, name) {
return FileChanges{}, fmt.Errorf("staged output %s is reserved", name)
}
writes = append(writes, write)
}
writes = append(writes, documentWrites...)
prunes := make([]commitPrune, 0, len(pruneExpected))
for name, expected := range pruneExpected {
if installPathMatchesReserved(root, name, document.ManifestFilename) {
return FileChanges{}, fmt.Errorf("installation receipt path %s is reserved", name)
}
prunes = append(prunes, commitPrune{path: name, expected: expected})
}
// Verify every path the receipt will describe at the commit point: the
// executor's journaled after images, planned paths it did not journal,
// and accepted entries carried forward without restaging.
verify := func(
files *os.Root,
entries []workspacewrite.InstallJournalEntry,
) error {
return verifyInstallOutputs(
files,
entries,
staged,
pruneExpected,
next.Entries,
check,
)
}
applied, err := executeCommit(root, commitRequest{
label: "installation",
writes: writes,
prunes: prunes,
documents: documents,
verify: verify,
// Every write hardlinks its staged source. Removing the stage before
// verification makes the link count final, so the identity the
// verification records stays valid for the next command.
beforeVerify: func() error {
if stage == "" {
return nil
}
if err := os.RemoveAll(stage); err != nil {
logger.Warn(fmt.Errorf(
"remove staged installation before verification: %w",
err,
))
}
return nil
},
}, check, logger)
if err != nil {
return FileChanges{}, err
}
check.evidence.write(root, next.Entries, logger)
counts := FileChanges{Displaced: []string{}}
for _, entry := range applied {
if entry.After == nil {
if _, pruned := pruneExpected[entry.Path]; pruned {
counts.Removed++
}
continue
}
if _, restaged := staged[entry.Path]; !restaged {
continue
}
if entry.Before == nil {
counts.Created++
} else if entry.Displace || entry.Before.SHA256 != entry.After.SHA256 {
counts.Replaced++
}
if entry.Displace {
counts.Displaced = append(counts.Displaced, entry.Path)
}
}
logger.Info(
"installation committed",
"root", root,
"files", len(staged),
"pruned", counts.Removed,
"manifest-published", publish,
)
return counts, nil
}
package install
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/receipt"
"github.com/mclucy/lucy/resolve"
)
func validateUnmanagedArtifacts(ctx context.Context, root string, d *document.Lock, overwrite bool, logger *log.Logger) error {
recorded, err := receipt.Read(root)
owned := map[string]bool{}
if err == nil {
for _, entry := range recorded.Entries {
owned[entry.Path] = true
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
runtime, hasRuntime := (resolve.Target{Product: d.Server.Product}).PackageRuntime()
seenDirectories := map[string]bool{}
for index := range d.Packages {
planned := &d.Packages[index]
if !planned.Enabled() {
continue
}
relative, err := d.PackageDirectory(planned)
if err != nil {
return err
}
key := string(planned.Environment) + "/" + string(planned.Ecosystem) + "/" + relative
if seenDirectories[key] {
continue
}
seenDirectories[key] = true
entries, err := os.ReadDir(filepath.Join(root, relative))
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
}
for _, entry := range entries {
// ReadDir reports the entry type without following links. Only regular
// files are opened, so directories, symlinks, FIFOs, sockets and devices
// are never handed to a blocking or redirecting open.
if !entry.Type().IsRegular() {
continue
}
filename := filepath.Join(relative, entry.Name())
if owned[filepath.ToSlash(filename)] {
continue
}
loader := planned.Ecosystem
if hasRuntime {
loader = runtime.ModuleNamespace(planned.Ecosystem)
}
mods, err := artifact.ReadModules(
ctx,
filepath.Join(root, filename),
loader,
)
if err != nil {
continue
}
conflict, moduleID := unmanagedConflict(d, planned, mods)
if conflict == nil {
continue
}
if overwrite {
destination, err := d.PackageDestination(conflict)
if err == nil && filepath.Clean(filename) == filepath.Clean(destination) {
logger.Debug(
"overwriting unmanaged artifact",
"path", filename,
"module", moduleID,
)
continue
}
}
return fmt.Errorf("unmanaged artifact %s conflicts with selected module %s; adopt or move it explicitly", filename, moduleID)
}
}
logger.Debug(
"ambient workspace validated",
"root", root,
"directories", len(seenDirectories),
"packages", len(d.Packages),
)
return nil
}
// unmanagedConflict reports the selected package whose module an unmanaged
// artifact duplicates. Environment and ecosystem must match, because one
// module identity may exist independently on the server and in MCDR.
// Disabled packages are not selected, so they never report a conflict.
func unmanagedConflict(
d *document.Lock,
planned *document.Package,
discovered []catalog.DescriptorModule,
) (*document.Package, string) {
for i := range d.Packages {
other := &d.Packages[i]
if !other.Enabled() {
continue
}
if other.Environment != planned.Environment || other.Ecosystem != planned.Ecosystem {
continue
}
for _, found := range discovered {
for _, selected := range other.Modules {
if artifact.ModuleProvides(found, selected.ID) || artifact.ModuleProvides(selected, found.ID) {
return other, selected.ID
}
}
}
}
return nil, ""
}
package install
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
type (
Options struct {
Locked bool
Offline bool
AcceptBroken bool
Overwrite bool
PublishManifest bool
WithOptional bool
// MCDRVenv creates an isolated MCDReforged environment instead of
// requiring a global executable.
MCDRVenv bool
// ExpectedManifest pins the manifest fingerprint the caller selected
// packages from. Preflight checks it after replaying interrupted
// journals, so a concurrent or recovered edit fails instead of being
// overwritten.
ExpectedManifest string
// ExpectedLock pins the lock fingerprint the caller planned from.
// Preflight checks it against the recovered lock for the same reason.
ExpectedLock string
// RefreshBootstrap skips the bootstrap snapshot cache, so the next
// install executes the method and publishes a fresh snapshot.
RefreshBootstrap bool
// ForceResolve resolves even when the manifest fingerprint matches the
// lock. Upgrade uses it because a lock can answer the manifest while
// still being older than the eligible versions.
ForceResolve bool
// RequirementChange records that the caller edited declared package
// requirements, so a lock whose fingerprint no longer matches is
// expected rather than stale.
RequirementChange bool
// declaredOnly records the manifest's packages without adding their
// catalogue dependencies. Adoption sets it because the workspace
// already holds a working set that resolution must not extend.
declaredOnly bool
// Adopted lists releases the workspace already holds. Resolution
// selects them for their reference without a catalogue query, so a
// locally valid artifact stays managed when upstream offers no release
// for the target server.
Adopted []AdoptedRelease
// LocalRuntime lists the regular files of a selected observed runtime
// with the digest and mode initialization recorded. Resolution may
// reuse them only when the requested artifact's trusted digest proves
// they are the same bytes. It never substitutes a file by name or role.
LocalRuntime []AdoptedRuntimeFile
publishLock bool
// SkipRegistration leaves the workspace unregistered. Staging callers
// set it because a staged tree is not yet a server; they register the
// workspace once its documents exist.
SkipRegistration bool
// Trace receives operation facts for the command layer to present.
Trace *Trace
// ProvisionJava runs before staging when the selected runtime misses
// the requirement. It returns the installed home when ordinary
// discovery cannot find it; selection then verifies the runtime again.
ProvisionJava func(ctx context.Context, requirement javaruntime.Requirement, check *javaruntime.Check) (string, error)
// Materialize, when non-nil, supplies artifact bytes for this
// operation instead of the configured cache and network. The returned
// path must exist; installation recomputes its digests and verifies
// them against the artifact's expected hashes before use. Injected
// bytes stay outside the operation's FetchSummary, which describes
// transfers the configured cache performed.
Materialize artifact.Materializer
}
)
func (s *Service) syncInstall(ctx context.Context, root string, d *document.Manifest, old *document.Lock, opts Options, result *Result) (diagnostics []filetrack.Diagnostic, resultErr error) {
// Report before recovery, resolution, or replay so a failure or
// cancellation still carries the workload this operation started from.
opts.Trace.reportPackageCount(old)
absolute, err := filepath.Abs(root)
if err != nil {
return nil, err
}
root = absolute
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
if err := workspacewrite.SafePath(root, ".lucy"); err != nil {
return nil, err
}
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
baseManifest, baseLock, documents, err := preflightLocked(root, d, old, opts, s.logger)
if err != nil {
return nil, err
}
if !opts.SkipRegistration {
if err := s.registerServer(root, result); err != nil {
return nil, err
}
}
// Resolution and staging must start from the recovered documents. A
// publishing caller still supplies the manifest it intends to write.
manifest := baseManifest
if opts.PublishManifest {
manifest = d
}
store := s.newDownloadStore(opts, result)
resolved, err := s.resolveLock(ctx, root, manifest, baseLock, &opts, store, result)
if err != nil {
return nil, err
}
return s.stageInstall(ctx, root, manifest, resolved, documents, store, opts, result)
}
// stageInstall materializes a resolved lock in the server directory and commits
// it with the manifest it was resolved from. Resolution paths differ in how they
// build the lock; every one of them lands here.
func (s *Service) stageInstall(
ctx context.Context,
root string,
d *document.Manifest,
resolved *document.Lock,
documents WorkspaceDocuments,
store *downloadStore,
opts Options,
result *Result,
) ([]filetrack.Diagnostic, error) {
if err := filetrack.ValidateOwnership(root, resolved.Files, resolved); err != nil {
return nil, err
}
check, err := s.selectJava(ctx, root, resolved, opts)
if err != nil {
return nil, err
}
result.Java = check
memo := fileidentity.NewMemo()
bootstrapOK, current, evidence, err := installationCurrent(ctx, root, resolved, memo, s.logger)
if err != nil {
return nil, err
}
commitCheck := currentCheck{memo: memo, evidence: evidence}
// A refresh request executes the bootstrap method again to publish a
// fresh snapshot.
if opts.RefreshBootstrap {
bootstrapOK, current = false, false
}
// Publishing documents alone does not require an available MCDR runtime.
// An explicit venv request still reconciles the wrapper.
metadataOnly := opts.PublishManifest || opts.publishLock
reconcileMCDR := !metadataOnly || opts.MCDRVenv
if current && (!reconcileMCDR || resolved.MCDR == nil ||
mcdrWrapperCurrent(root, resolved, s.python, opts.MCDRVenv)) {
s.logger.Info(
"installation already current",
"root", root,
"packages", len(resolved.Packages),
)
if err := validateUnmanagedArtifacts(ctx, root, resolved, opts.Overwrite, s.logger); err != nil {
return nil, err
}
if metadataOnly {
var manifest *document.Manifest
if opts.PublishManifest {
manifest = d
}
// A current installation still publishes its documents through
// the installation journal, so a concurrent edit is detected and
// a partial manifest/lock publication rolls back.
if _, err := applyCommit(
root, "", manifest, resolved, opts.PublishManifest,
nil, nil, nil, nil, false, installCommitMetadataOnly, documents,
commitCheck, s.logger,
); err != nil {
return nil, err
}
result.PublishedManifest = opts.PublishManifest
result.PublishedLock = true
return s.provisionCommitted(ctx, root, resolved, opts)
}
return s.tracker.Provision(ctx, root, resolved.Files, opts.Offline)
}
if current {
s.logger.Debug(
"reconciling MCDR wrapper through the installation transaction",
"root", root,
)
if err := validateUnmanagedArtifacts(ctx, root, resolved, opts.Overwrite, s.logger); err != nil {
return nil, err
}
stage, err := os.MkdirTemp(filepath.Join(root, ".lucy"), "stage-*")
if err != nil {
return nil, err
}
defer os.RemoveAll(stage)
if err := preparePython(ctx, root, stage, resolved, store, s.python, opts.MCDRVenv); err != nil {
return nil, err
}
var manifest *document.Manifest
if opts.PublishManifest {
manifest = d
}
mcdrOutputs := mcdrWrapperOutputs(resolved)
counts, err := applyCommit(
root, stage, manifest, resolved, opts.PublishManifest, nil, nil,
mcdrOutputs, mcdrOutputs, false, installCommitOverlay, documents,
commitCheck, s.logger,
)
if err != nil {
return nil, err
}
result.Files = counts
result.PublishedManifest = opts.PublishManifest
result.PublishedLock = opts.publishLock || opts.PublishManifest
return s.provisionCommitted(ctx, root, resolved, opts)
}
s.logger.Debug("staging installation", "root", root, "reason", "installation missing or stale")
opts.Trace.phaseStarted("install")
start := time.Now()
installed := false
defer func() {
if !installed {
return
}
elapsed := time.Since(start)
result.addPhase("install", elapsed)
opts.Trace.phaseDone(PhaseInfo{
Name: "install",
Elapsed: elapsed,
Count: result.Files.Created + result.Files.Replaced,
})
}()
stage, err := os.MkdirTemp(filepath.Join(root, ".lucy"), "stage-*")
if err != nil {
return nil, err
}
defer os.RemoveAll(stage)
var bootstrapOutputs map[string]bootstrap.Output
stagedBootstrap := !bootstrapOK
if stagedBootstrap {
// Bootstrap classification and package staging must not share a view
// of the stage. StagedImage walks the server tree and accepts only the
// method's declared outputs, so packages and wrapper files staged
// alongside it would be rejected as undeclared runtime content.
bootstrapOutputs, err = s.stageServerTree(
ctx, stage, resolved, check.Executable(), store, opts,
)
if err != nil {
return nil, err
}
} else {
s.logger.Debug("bootstrap already current; skipping server tree staging", "root", root)
}
mcdrOutputs := mcdrWrapperOutputs(resolved)
stagedOutputs := make(map[string]bootstrap.Output, len(bootstrapOutputs)+len(mcdrOutputs))
for path, output := range bootstrapOutputs {
stagedOutputs[path] = output
}
for path, output := range mcdrOutputs {
for existing := range stagedOutputs {
if !strings.EqualFold(existing, path) {
continue
}
if existing == path ||
workspacewrite.InstallPathsAlias(root, existing, path) {
return nil, fmt.Errorf(
"bootstrap output %s and MCDR wrapper output %s claim the same path",
existing, path,
)
}
}
stagedOutputs[path] = output
}
overwritePaths, stagedPackageHashes, err := s.stagePackages(
ctx, root, stage, resolved, store, stagedOutputs, opts,
)
if err != nil {
return nil, err
}
if resolved.MCDR != nil {
if err := preparePython(ctx, root, stage, resolved, store, s.python, opts.MCDRVenv); err != nil {
return nil, err
}
}
if err := validateUnmanagedArtifacts(ctx, root, resolved, opts.Overwrite, s.logger); err != nil {
return nil, err
}
counts, err := applyCommit(
root, stage, d, resolved, opts.PublishManifest,
overwritePaths, stagedPackageHashes, stagedOutputs, mcdrOutputs,
stagedBootstrap, installCommitReconcile, documents, commitCheck, s.logger,
)
if err != nil {
return nil, err
}
result.Files = counts
result.PublishedManifest = opts.PublishManifest
result.PublishedLock = opts.publishLock || opts.PublishManifest
installed = true
return s.provisionCommitted(ctx, root, resolved, opts)
}
// stageServerTree materializes the locked core and inputs, then runs the
// bootstrap that prepares the server tree in stage. It returns the validated
// bootstrap outputs by workspace path. Validation happens here, while stage
// contains bootstrap material only: later staged packages and wrapper files
// are not part of the method's output contract and must not be inspected
// against it.
func (s *Service) stageServerTree(
ctx context.Context,
stage string,
resolved *document.Lock,
java string,
store *downloadStore,
opts Options,
) (map[string]bootstrap.Output, error) {
if opts.Locked {
if err := requirePinnedArtifact(resolved.Server.Artifact.Hashes, resolved.Server.Artifact.Filename); err != nil {
return nil, err
}
for _, input := range resolved.Server.Inputs {
if input.Embedded != "" {
continue
}
if err := requirePinnedArtifact(input.Hashes, input.ProjectID); err != nil {
return nil, err
}
}
}
// A lock that pins every digest names its recipe before acquisition, so a
// stored snapshot restores without the build inputs. Otherwise the key
// exists once acquisition attaches every store digest.
key, keyErr := snapshot.Key(resolved.Server)
pinnedKey := keyErr == nil
var snapStore *artifactstore.Store
defer func() {
if snapStore != nil {
snapStore.Close()
}
}()
lookup := func() (map[string]bootstrap.Output, bool, error) {
if keyErr != nil {
s.logger.Debug("bootstrap snapshot unavailable", "reason", keyErr.Error())
return nil, false, nil
}
if snapStore == nil {
opened, err := openSnapshotStore()
if err != nil {
s.logger.Debug("bootstrap snapshot store unavailable", "reason", err.Error())
return nil, false, nil
}
snapStore = opened
}
if opts.RefreshBootstrap {
return nil, false, nil
}
return s.restoreServerSnapshot(ctx, snapStore, key, stage, resolved.Server, opts.Trace)
}
if pinnedKey {
outputs, restored, err := lookup()
if err != nil || restored {
return outputs, err
}
}
materialized := make([]artifact.MaterializedFile, 1+len(resolved.Server.Inputs))
err := runStagingJobs(ctx, len(materialized), store.injected != nil, func(i int) error {
a := &resolved.Server.Artifact
label := a.Filename
if i > 0 {
input := &resolved.Server.Inputs[i-1]
if input.Embedded != "" {
return nil
}
a, label = input, input.Filename
}
file, err := store.materializeFor(ctx, a, label)
materialized[i] = file
return err
})
if err != nil {
return nil, err
}
core := materialized[0]
resolved.Server.Artifact.Hashes = core.Hashes
inputs := make([]string, len(resolved.Server.Inputs))
for i := range resolved.Server.Inputs {
file := materialized[i+1]
if file.Path != "" {
resolved.Server.Inputs[i].Hashes = file.Hashes
inputs[i] = file.Path
}
}
// Acquisition can add a stronger digest than the lock pinned, and the key
// names the strongest one. Publication and a second lookup use the key
// that later runs with the enriched lock compute.
if enriched, enrichedErr := snapshot.Key(resolved.Server); !pinnedKey ||
(enrichedErr == nil && enriched != key) {
key, keyErr = enriched, enrichedErr
outputs, restored, err := lookup()
if err != nil || restored {
return outputs, err
}
}
if err := bootstrap.PrepareLocked(
ctx,
stage,
resolved.Server,
core.Path,
inputs,
s.link,
java,
opts.Trace.processOutput(),
opts.Trace.bootstrapProgress(),
); err != nil {
return nil, err
}
// Classify the dynamic result now, while the server tree is the only
// content in stage. This emits the output policy and role the commit
// uses, including discard and seed policy, without re-walking the tree
// after packages and wrapper files join it.
outputs, err := stagedServerOutputs(stage, resolved.Server)
if err != nil {
return nil, err
}
// Only the checked output of an executed recipe enters the snapshot store.
if snapStore != nil {
if err := publishBootstrapSnapshot(ctx, snapStore, key, stage, resolved.Server, outputs); err != nil {
s.logger.Warn(fmt.Errorf(
"cannot publish bootstrap snapshot %s: %w",
key.Hex(), err,
))
}
}
s.logger.Debug(
"server tree prepared",
"stage", stage,
"core", resolved.Server.Filename,
"inputs", len(inputs),
"outputs", len(outputs),
)
return outputs, nil
}
// restoreServerSnapshot restores the snapshot of key into stage and verifies
// it. A hit returns the restored outputs and runs no processor. A restore
// failure or a verification failure clears the server root for a cold stage,
// and a verification failure also drops the snapshot, so the next operation
// does not repeat it. Only a failure to clear the stage is returned.
func (s *Service) restoreServerSnapshot(
ctx context.Context,
snapStore *artifactstore.Store,
key cas.Digest,
stage string,
server document.LockedServer,
trace *Trace,
) (map[string]bootstrap.Output, bool, error) {
started := time.Now()
snap, restored, err := restoreBootstrapSnapshot(ctx, snapStore, key, stage, server, s.link, trace)
if err != nil {
s.logger.Warn(fmt.Errorf(
"bootstrap snapshot restore failed for %s; staging from scratch: %w",
key.Hex(), err,
))
return nil, false, clearServerRoot(stage, server)
}
if !restored {
return nil, false, nil
}
outputs, err := restoredServerOutputs(stage, server, snap)
if err == nil {
s.logger.Info("bootstrap snapshot restored", "key", key.Hex(), "files", len(outputs))
trace.phaseDone(PhaseInfo{
Name: "bootstrap snapshot",
Count: len(outputs),
Elapsed: time.Since(started),
})
return outputs, true, nil
}
s.logger.Warn(fmt.Errorf(
"restored bootstrap snapshot for %s failed verification; staging from scratch: %w",
key.Hex(), err,
))
if err := clearServerRoot(stage, server); err != nil {
return nil, false, err
}
if err := snapStore.RemoveSnapshot(key); err != nil {
s.logger.Warn(fmt.Errorf("cannot drop failed bootstrap snapshot %s: %w", key.Hex(), err))
}
return nil, false, nil
}
// restoredServerOutputs verifies a tree a snapshot restore materialized and
// indexes its entries by workspace path. The restore hashed every stored
// object before placing it, so this walk checks presence and mode instead of
// reading the same bytes again. A snapshot holds only the runtime zone and
// the seed zone, so the comparison proves those files rather than re-running
// the staging contract.
func restoredServerOutputs(
stage string,
server document.LockedServer,
snap snapshot.Snapshot,
) (map[string]bootstrap.Output, error) {
root, err := serverRootPath(stage, server)
if err != nil {
return nil, err
}
comparison, err := snapshot.VerifyRestored(root, snap.Entries)
if err != nil {
return nil, err
}
if !comparison.Complete() {
return nil, fmt.Errorf(
"restored bootstrap tree has %d differing, %d permission-differing, and %d missing files",
len(comparison.Differing), len(comparison.OtherPermissions), len(comparison.Missing),
)
}
outputs := make(map[string]bootstrap.Output, len(snap.Entries))
for _, entry := range snap.Entries {
path := filepath.ToSlash(filepath.Join(server.Directory, filepath.FromSlash(entry.Path)))
outputs[path] = bootstrap.Output{
Path: path,
ServerPath: entry.Path,
SHA256: entry.SHA256,
Mode: entry.Mode,
Policy: bootstrap.OutputPolicy(entry.Policy),
Role: bootstrap.MaterialRole(entry.Role),
}
}
return outputs, nil
}
// stagedServerOutputs classifies the current staging tree against the locked
// bootstrap contract and indexes the outputs by workspace path.
func stagedServerOutputs(stage string, server document.LockedServer) (map[string]bootstrap.Output, error) {
stagedOutputs, err := bootstrap.StagedImage(stage, server)
if err != nil {
return nil, err
}
return indexServerOutputs(stagedOutputs), nil
}
func indexServerOutputs(stagedOutputs []bootstrap.Output) map[string]bootstrap.Output {
outputs := make(map[string]bootstrap.Output, len(stagedOutputs))
for _, output := range stagedOutputs {
outputs[output.Path] = output
}
return outputs
}
// clearServerRoot empties the server directory inside a private staging root.
// A failed snapshot restore or verification leaves partial content that must
// not merge with the cold stage that follows.
func clearServerRoot(stage string, server document.LockedServer) error {
root, err := serverRootPath(stage, server)
if err != nil {
return err
}
entries, err := os.ReadDir(root)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
for _, entry := range entries {
if err := os.RemoveAll(filepath.Join(root, entry.Name())); err != nil {
return err
}
}
return nil
}
func requirePinnedArtifact(hashes map[string]string, name string) error {
hasDigest := false
for algorithm, digest := range hashes {
switch algorithm {
case "sha256", "sha512", "sha1", "md5":
default:
return fmt.Errorf("locked artifact %s has unsupported digest %s", name, algorithm)
}
hasDigest = hasDigest || strings.TrimSpace(digest) != ""
}
if hasDigest {
return nil
}
return fmt.Errorf("locked artifact %s has no pinned digest", name)
}
// mcdrWrapperOutputs declares the files writeMCDRWrapper stages for an
// installation with an MCDReforged wrapper. They are not part of the server
// bootstrap method's contract, so they are classified here by exact path: the
// generated config is seeded only when the workspace has none, and the
// launcher script is managed. Filename heuristics cannot express that
// distinction once bootstrap and wrapper outputs share a stage.
func mcdrWrapperOutputs(resolved *document.Lock) map[string]bootstrap.Output {
if resolved == nil || resolved.MCDR == nil {
return nil
}
directory := resolved.MCDR.Directory
config := filepath.ToSlash(filepath.Join(directory, "config.yml"))
launcher := filepath.ToSlash(filepath.Join(directory, "run-mcdr.sh"))
return map[string]bootstrap.Output{
config: {
Path: config,
Policy: bootstrap.PolicySeed,
Role: bootstrap.RoleRuntime,
},
launcher: {
Path: launcher,
Policy: bootstrap.PolicyManaged,
Role: bootstrap.RoleRuntime,
},
}
}
func isFloating(v version.Version) bool {
switch v {
case "", version.Stable, version.Beta, version.Any:
return true
}
return v == "latest"
}
// coreReusable reports whether a lock's server record answers the
// manifest's core request. Resolution reuses the pin when it does; a locked
// mutation treats a negative answer as a stale lock, because rebinding
// requirements must never re-target the server.
func (s *Service) coreReusable(ctx context.Context, d *document.Manifest, old *document.Lock, offline bool) (bool, error) {
request := upstream.ServerProductRequest{
Minecraft: d.Server.Minecraft,
Product: d.Server.Core.Product,
ProductVersion: d.Server.Core.ProductVersion,
Repository: d.Server.Core.Repository,
FilePattern: d.Server.Core.FilePattern,
}
if old.Server.Directory != d.Server.Directory {
s.logger.Debug(
"core pin not reusable",
"reason", "server directory changed",
"locked", old.Server.Directory,
"requested", d.Server.Directory,
)
return false, nil
}
if old.Server.Minecraft != request.Minecraft || old.Server.Product != request.Product {
s.logger.Debug(
"core pin not reusable",
"reason", "pinned minecraft or product changed",
"minecraft", old.Server.Minecraft,
"requested-minecraft", request.Minecraft,
"product", old.Server.Product,
"requested-product", request.Product,
)
return false, nil
}
if !isFloating(request.ProductVersion) && old.Server.CoreVersion != request.ProductVersion {
s.logger.Debug(
"core pin not reusable",
"reason", "core version changed",
"locked", old.Server.CoreVersion,
"requested", request.ProductVersion,
)
return false, nil
}
// Dropping the repository override retargets the server at its official
// distribution, so a locked GitHub artifact no longer satisfies the request
// even though every pinned field still matches.
if request.Repository == "" && old.Server.Provider == catalog.ProviderGitHub {
s.logger.Debug(
"core pin not reusable",
"reason", "repository override dropped while pin came from a GitHub fork",
)
return false, nil
}
if request.Repository != "" {
if offline {
s.logger.Debug(
"core pin not reusable",
"reason", "repository override needs upstream confirmation while offline",
"repository", request.Repository,
)
return false, nil
}
var repository struct {
ID int64 `json:"id"`
}
if err := s.source.Metadata(ctx, "https://api.github.com/repos/"+request.Repository, &repository); err != nil {
return false, err
}
if old.Server.Provider != catalog.ProviderGitHub || old.Server.ProjectID != strconv.FormatInt(repository.ID, 10) {
s.logger.Debug(
"core pin not reusable",
"reason", "repository identity changed",
"requested-repository", request.Repository,
"resolved-id", repository.ID,
"locked-project", old.Server.ProjectID,
)
return false, nil
}
}
if request.FilePattern != "" {
matched, err := filepath.Match(request.FilePattern, old.Server.Filename)
if err != nil {
return false, err
}
if !matched {
s.logger.Debug(
"core pin not reusable",
"reason", "artifact filename no longer matches pattern",
"locked", old.Server.Filename,
"pattern", request.FilePattern,
)
return false, nil
}
}
return true, nil
}
// rejectSharedDestinations enforces the lock's installability guarantee: a
// destination two active packages both claim, two destinations the target
// filesystem resolves to one entry, or a package destination that claims a
// bootstrap or wrapper output must fail before anything is written. Left
// unguarded the later copy silently replaces the earlier one, so the workspace
// diverges from a lock that still reports itself as current, and the commit
// would attribute the surviving bytes to the wrong origin.
func rejectSharedDestinations(
root string,
resolved *document.Lock,
stagedOutputs map[string]bootstrap.Output,
) error {
outputs := make(map[string][]bootstrap.Output, len(stagedOutputs))
for _, output := range stagedOutputs {
key := strings.ToLower(output.Path)
outputs[key] = append(outputs[key], output)
}
type claim struct {
path string
identity string
}
claimed := make(map[string][]claim)
for i := range resolved.Packages {
p := &resolved.Packages[i]
if !p.Enabled() {
continue
}
destination, err := resolved.PackageDestination(p)
if err != nil {
return err
}
destination = filepath.ToSlash(filepath.Clean(destination))
identity := p.Artifact.Provider.String() + ":" + p.Artifact.ProjectID
key := strings.ToLower(destination)
for _, output := range outputs[key] {
if output.Path == destination {
return fmt.Errorf(
"package %s installs to %s, which bootstrap already produces",
identity, destination,
)
}
if workspacewrite.InstallPathsAlias(root, output.Path, destination) {
return fmt.Errorf(
"package %s installs to %s, which aliases bootstrap output %s",
identity, destination, output.Path,
)
}
}
for _, prior := range claimed[key] {
if prior.path == destination {
return fmt.Errorf(
"packages %s and %s both install to %s",
prior.identity, identity, destination,
)
}
if workspacewrite.InstallPathsAlias(root, prior.path, destination) {
return fmt.Errorf(
"packages %s and %s install to aliasing destinations %s and %s",
prior.identity, identity, prior.path, destination,
)
}
}
claimed[key] = append(claimed[key], claim{
path: destination,
identity: identity,
})
}
return nil
}
// provisionCommitted provisions tracked files after the lock is published. A
// failure here leaves the committed installation in place, so it is marked.
func (s *Service) provisionCommitted(ctx context.Context, root string, resolved *document.Lock, opts Options) ([]filetrack.Diagnostic, error) {
diagnostics, err := s.tracker.Provision(ctx, root, resolved.Files, opts.Offline)
if err != nil {
err = &CommittedError{Err: err}
}
return diagnostics, err
}
// Package agent detects coding-agent harnesses from the process environment.
package agent
import (
"os"
"strings"
)
// Agent environment detection took reference from Cloudflare's CLI
// https://github.com/cloudflare/cf/blob/main/packages/cli/src/lib/agent-context.ts
var detectors = []func() bool{
func() bool { return exact("OPENCODE", "1") },
func() bool { return value("QWEN_CODE_SESSION_ID") != "" },
func() bool {
return exact("PI_CODING_AGENT", "true") || value("AI_AGENT") == "pi"
},
func() bool {
return exact("OMPCODE", "1") ||
value("PI_SESSION_FILE") != "" ||
value("PI_SESSION_ID") != ""
},
func() bool { return exact("DSH_SHELL", "1") },
func() bool { return exact("CURSOR_AGENT", "1") },
func() bool { return exact("CLAUDECODE", "1") },
func() bool { return value("CODEX_THREAD_ID") != "" },
func() bool { return value("AMP_CURRENT_THREAD_ID") != "" },
func() bool { return exact("GEMINI_CLI", "1") },
func() bool { return exact("AUGMENT_AGENT", "1") },
func() bool {
return exact("CRUSH", "1") || value("AI_AGENT") == "crush"
},
func() bool {
return value("AI_AGENT") == "github_copilot_vscode_agent" ||
exact("COPILOT_AGENT", "1")
},
func() bool { return value("OZ_RUN_ID") != "" },
}
// Detected reports whether any supported agent harness is present.
func Detected() bool {
for _, detect := range detectors {
if detect() {
return true
}
}
return false
}
func value(name string) string {
raw := strings.TrimSpace(os.Getenv(name))
switch strings.ToLower(raw) {
case "", "0", "false", "no", "off":
return ""
default:
return raw
}
}
func exact(name, expected string) bool {
return os.Getenv(name) == expected
}
// Package appdata locates the per-user directory Lucy owns for durable local
// state. It is the single authority for the platform's local application data
// conventions; packages that need durable state append their own subdirectory
// to the root instead of repeating the platform policy.
package appdata
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
)
// directoryName is the directory Lucy owns under the platform's local
// application data base.
const directoryName = "lucy"
// Root reports the per-user directory Lucy owns for durable machine state:
// %LOCALAPPDATA%\lucy on Windows, ~/Library/Application Support/lucy on macOS,
// and $XDG_DATA_HOME/lucy or ~/.local/share/lucy elsewhere. A relative
// XDG_DATA_HOME is ignored in favor of the home fallback, as the XDG base
// directory specification requires. Root never creates the directory.
func Root() (string, error) {
var base string
switch runtime.GOOS {
case "windows":
base = os.Getenv("LOCALAPPDATA")
if base == "" {
return "", errors.New("locate lucy data directory: LOCALAPPDATA is not set")
}
case "darwin":
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate lucy data directory: %w", err)
}
base = filepath.Join(home, "Library", "Application Support")
default:
base = os.Getenv("XDG_DATA_HOME")
if !filepath.IsAbs(base) {
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate lucy data directory: %w", err)
}
base = filepath.Join(home, ".local", "share")
}
}
return filepath.Join(base, directoryName), nil
}
// Package bisect persists and advances a binary-search session over the
// enabled requirements of a manifest. It owns the session lock, state
// serialization, manifest transitions, installation sync, and recovery.
// Command wiring and rendering stay at the command boundary.
package bisect
import (
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/depgraph"
"github.com/mclucy/lucy/server"
)
// Mod is one manifest requirement the session toggles. Reference is the
// manifest's own "provider:project" key and Ecosystem is the ecosystem it is
// declared under; together they identify the entry unambiguously.
type Mod struct {
Environment server.Environment `json:"environment"`
Ecosystem catalog.Ecosystem `json:"ecosystem"`
Reference string `json:"reference"`
Version string `json:"version,omitempty"`
}
// Label renders the requirement reference with its recorded version.
func (m Mod) Label() string {
if m.Version == "" {
return m.Reference
}
return m.Reference + "@" + m.Version
}
// Phase is the durable phase of a session. A session starts active and ends
// in exactly one terminal phase; only reset returns the workspace to having
// no session.
type Phase string
const (
PhaseActive Phase = "active"
PhaseFound Phase = "found"
PhaseExhausted Phase = "exhausted"
)
// Step names the leaf that owns a pending transition. A retry must run the
// same leaf, so the step is recorded instead of inferred from the range.
type Step string
const (
StepStart Step = "start"
StepGood Step = "good"
StepBad Step = "bad"
StepReset Step = "reset"
)
// View is the search position a command reports.
type View struct {
Total int `json:"total"`
Left int `json:"left"`
Right int `json:"right"`
Midpoint int `json:"midpoint,omitempty"`
Candidate *Mod `json:"candidate,omitempty"`
Remaining int `json:"remaining"`
}
// Result is the observable outcome of one session command. Message text and
// document rendering belong to the caller.
type Result struct {
Phase Phase
Pending Step
Complete bool
Found *Mod
// Marked is the requirement a completed good or bad transition marked.
Marked *Mod
State *View
Enabled int
Disabled int
Restored int
Warnings []string
// Findings is the live graph observation candidate selection consumed.
Findings depgraph.Findings
// NoCandidates reports a start that found no enabled requirement.
NoCandidates bool
}
package bisect
import (
"context"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/depgraph"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/workspace/identify"
)
// selectCandidates returns the manifest requirements a session may toggle,
// ordered so a package always follows the packages it depends on. doc is the
// recovered snapshot the session records as its original; dependency loading
// may take long enough that start must revalidate the file before publishing.
func selectCandidates(
ctx context.Context,
lookup identify.HashLookup,
workDir string,
doc *document.Manifest,
) ([]Mod, depgraph.Findings, error) {
loaded, err := depgraph.Load(ctx, workDir, false, lookup)
if err != nil {
return nil, loaded.Findings, err
}
var mods []Mod
seen := make(map[string]bool)
for _, root := range loaded.Graph.OrderedArtifacts() {
for _, reference := range nodeReferences(doc, root) {
if !requirementEnabled(
doc,
root.Environment,
root.Ecosystem,
reference,
) {
continue
}
mod := Mod{
Environment: root.Environment,
Ecosystem: root.Ecosystem,
Reference: reference,
Version: root.Version,
}
key := string(mod.Environment) + "|" +
string(mod.Ecosystem) + "|" + mod.Reference
if seen[key] {
continue
}
seen[key] = true
mods = append(mods, mod)
}
}
return mods, loaded.Findings, nil
}
// nodeReferences returns the manifest requirement references that select
// node. A lock graph carries the exact bindings on the node, including several
// bindings for one artifact. An observation graph has no lock bindings, so the
// manifest references are matched by provider and project identity.
func nodeReferences(doc *document.Manifest, node *depgraph.Node) []string {
if len(node.Requirements) > 0 {
references := slices.Clone(node.Requirements)
slices.Sort(references)
return slices.Compact(references)
}
var packages map[string]document.Requirement
switch node.Environment {
case server.EnvironmentServer:
packages = doc.Server.Packages[node.Ecosystem]
case server.EnvironmentMCDR:
if doc.MCDR != nil {
packages = doc.MCDR.Packages
}
}
references := make([]string, 0, len(packages))
for reference := range packages {
if referenceMatchesNode(reference, node) {
references = append(references, reference)
}
}
slices.Sort(references)
return references
}
func referenceMatchesNode(reference string, node *depgraph.Node) bool {
provider, project, err := document.ParseReference(reference)
if err != nil {
return false
}
if node.Provider != catalog.ProviderUnspecified && provider != node.Provider {
return false
}
if node.ProjectID != "" {
return project == node.ProjectID
}
if node.Provider != catalog.ProviderUnspecified {
return strings.TrimPrefix(node.ID, node.Provider.String()+":") == project
}
return node.ID == project
}
// requirementEnabled reports whether the manifest still enables the given
// requirement entry.
func requirementEnabled(
doc *document.Manifest,
environment server.Environment,
ecosystem catalog.Ecosystem,
reference string,
) bool {
var packages map[string]document.Requirement
switch environment {
case server.EnvironmentServer:
if doc.Server.Packages == nil {
return false
}
packages = doc.Server.Packages[ecosystem]
case server.EnvironmentMCDR:
if doc.MCDR == nil {
return false
}
packages = doc.MCDR.Packages
default:
return false
}
requirement, ok := packages[reference]
return ok && requirement.IsEnabled()
}
package bisect
import (
"context"
"errors"
"fmt"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/operation"
"github.com/mclucy/lucy/workspace/identify"
)
// Start begins a session, or completes an interrupted start. It captures the
// manifest, selects the requirements to search, and syncs the first range.
// Findings from candidate selection are returned even when the transition
// later fails.
func Start(
ctx context.Context,
workDir string,
logger *log.Logger,
ops *operation.Service,
lookup identify.HashLookup,
) (result Result, resultErr error) {
lock, err := lockSession(ctx, workDir, requireStartWorkspace)
if err != nil {
return Result{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return Result{}, err
}
existing, err := readState(workDir)
if err != nil {
return Result{}, err
}
if existing != nil {
if existing.Pending != nil && existing.Pending.Step == StepStart {
return completeTransition(ctx, ops, workDir, logger, existing)
}
return Result{}, startRefusal(existing)
}
var (
original *document.Manifest
originalDigest string
)
if err := withWorkspace(ctx, workDir, logger, func() error {
doc, err := document.ManifestFile(workDir).Read()
if err != nil {
return fmt.Errorf("read manifest: %w", err)
}
original = doc
originalDigest, err = manifestDigest(doc)
return err
}); err != nil {
return Result{}, err
}
mods, findings, err := selectCandidates(ctx, lookup, workDir, original)
result = Result{Findings: findings}
if err != nil {
return result, err
}
if len(mods) == 0 {
return Result{
Complete: true,
Findings: findings,
NoCandidates: true,
}, nil
}
session := &state{
Phase: PhaseActive,
Mods: mods,
Original: original,
Right: len(mods) - 1,
Pending: &pendingTransition{Step: StepStart},
}
var (
enabled int
disabled int
matched int
targetDigest string
targetResolution string
)
if err := withWorkspace(ctx, workDir, logger, func() error {
current, err := document.ManifestFile(workDir).Read()
if err != nil {
return fmt.Errorf("read manifest: %w", err)
}
currentDigest, err := manifestDigest(current)
if err != nil {
return err
}
if currentDigest != originalDigest {
return fmt.Errorf(
"manifest changed during package selection; retry `lucy bisect start`",
)
}
mid := (session.Left + session.Right) / 2
enabled, disabled, matched, targetDigest, targetResolution, err = toggleRange(current, session.Mods, mid)
if err != nil {
return err
}
session.Pending.Digest = targetDigest
session.Pending.Resolution = targetResolution
if err := ctx.Err(); err != nil {
return err
}
if err := createState(workDir, session); err != nil {
return err
}
if matched > 0 {
if err := ctx.Err(); err != nil {
return err
}
if err := document.ManifestFile(workDir).Write(current); err != nil {
return fmt.Errorf("write manifest: %w", err)
}
}
return nil
}); err != nil {
return result, err
}
output, err := commitTransition(
ctx,
ops,
workDir,
logger,
session,
*session.Pending,
targetDigest,
targetResolution,
enabled,
disabled,
0,
)
if err != nil {
return result, err
}
output.Findings = findings
return output, nil
}
// Good advances past the midpoint because the tested requirement works.
func Good(
ctx context.Context,
workDir string,
logger *log.Logger,
ops *operation.Service,
) (result Result, resultErr error) {
lock, err := lockSession(ctx, workDir, requireSession)
if err != nil {
return Result{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return Result{}, err
}
session, err := loadSession(workDir)
if err != nil {
return Result{}, err
}
if session.Pending != nil {
if session.Pending.Step != StepGood {
return Result{}, interruptedError(session.Pending)
}
return completeTransition(ctx, ops, workDir, logger, session)
}
if err := terminalError(session); err != nil {
return Result{}, err
}
mid := (session.Left + session.Right) / 2
session.Left = mid + 1
session.Pending = &pendingTransition{Step: StepGood}
if session.Left > session.Right {
session.Phase = PhaseExhausted
}
return completeTransition(ctx, ops, workDir, logger, session)
}
// Bad moves the range end onto the midpoint because the tested requirement
// fails.
func Bad(
ctx context.Context,
workDir string,
logger *log.Logger,
ops *operation.Service,
) (result Result, resultErr error) {
lock, err := lockSession(ctx, workDir, requireSession)
if err != nil {
return Result{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return Result{}, err
}
session, err := loadSession(workDir)
if err != nil {
return Result{}, err
}
if session.Pending != nil {
if session.Pending.Step != StepBad {
return Result{}, interruptedError(session.Pending)
}
return completeTransition(ctx, ops, workDir, logger, session)
}
if err := terminalError(session); err != nil {
return Result{}, err
}
mid := (session.Left + session.Right) / 2
session.Right = mid
session.Pending = &pendingTransition{Step: StepBad}
if session.Left == session.Right {
session.Phase = PhaseFound
}
return completeTransition(ctx, ops, workDir, logger, session)
}
// Status reads the session without changing it. A pending transition is
// reported as the step that must be rerun.
func Status(ctx context.Context, workDir string) (result Result, resultErr error) {
lock, err := lockSession(ctx, workDir, requireSession)
if err != nil {
return Result{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return Result{}, err
}
session, err := loadSession(workDir)
if err != nil {
return Result{}, err
}
result = Result{
Phase: session.Phase,
Complete: session.Phase != PhaseActive,
State: currentView(session),
}
if session.Phase == PhaseFound {
result.Found = &session.Mods[session.Left]
}
if session.Pending != nil {
result.Pending = session.Pending.Step
}
return result, nil
}
// Reset restores the captured manifest, syncs the installation, and removes
// the session. The session survives a failed restore or sync so the command
// can be retried.
func Reset(
ctx context.Context,
workDir string,
logger *log.Logger,
ops *operation.Service,
) (result Result, resultErr error) {
lock, err := lockSession(ctx, workDir, requireSession)
if err != nil {
return Result{}, err
}
defer func() { resultErr = errors.Join(resultErr, lock.Close()) }()
if err := ctx.Err(); err != nil {
return Result{}, err
}
session, err := loadSession(workDir)
if err != nil {
return Result{}, err
}
// Reset supersedes any pending transition: restoring the captured
// manifest and syncing it is the final state, whatever the interrupted
// leaf had intended. The session file is kept until this succeeds, so a
// failed restore remains retryable.
_, targetResolution, err := writeOriginal(
ctx,
workDir,
logger,
session,
StepReset,
)
if err != nil {
return Result{}, err
}
if err := ctx.Err(); err != nil {
return Result{}, err
}
syncResult, err := ops.Sync(
ctx,
workDir,
install.Options{ExpectedManifest: targetResolution},
)
if err != nil {
return Result{}, fmt.Errorf("sync installation: %w", err)
}
if err := ctx.Err(); err != nil {
return Result{}, err
}
if err := deleteState(workDir); err != nil {
return Result{}, err
}
return Result{
Complete: true,
Restored: countRequirements(session.Original),
Warnings: syncWarnings(syncResult),
}, nil
}
// syncWarnings collects the facts one sync produced so a bisect result can
// carry them. Diagnostics and warnings stay separate from stderr output, so a
// JSON run never emits a second document beside the result.
func syncWarnings(result *install.Result) []string {
if result == nil {
return nil
}
warnings := make([]string, 0, len(result.Diagnostics)+len(result.Warnings))
for _, diagnostic := range result.Diagnostics {
warnings = append(
warnings,
fmt.Sprintf("%s: %s", diagnostic.Path, diagnostic.Message),
)
}
for _, warning := range result.Warnings {
if warning != nil {
warnings = append(warnings, warning.Error())
}
}
return warnings
}
// countRequirements counts every declared requirement entry across the
// server and MCDR manifests, so the reported restore covers every runtime
// rather than one loader map.
func countRequirements(doc *document.Manifest) int {
total := 0
for _, packages := range doc.Server.Packages {
total += len(packages)
}
if doc.MCDR != nil {
total += len(doc.MCDR.Packages)
}
return total
}
func currentView(session *state) *View {
view := &View{
Total: len(session.Mods),
Left: session.Left,
Right: session.Right,
}
if session.Phase != PhaseActive {
return view
}
view.Remaining = session.Right - session.Left + 1
mid := (session.Left + session.Right) / 2
view.Midpoint = mid
view.Candidate = &session.Mods[mid]
return view
}
// completeTransition writes the manifest target recorded by a pending
// transition, syncs the installation, and only then clears the pending record.
// The record is durable before the first manifest write, so a failure at any
// point leaves a state that the same leaf can resume.
func completeTransition(
ctx context.Context,
ops *operation.Service,
workDir string,
logger *log.Logger,
session *state,
) (Result, error) {
if err := ctx.Err(); err != nil {
return Result{}, err
}
pending := session.Pending
if pending == nil {
return Result{}, fmt.Errorf("invalid bisect state: no pending transition")
}
var (
targetDigest string
targetResolution string
enabled int
disabled int
restored int
err error
)
switch session.Phase {
case PhaseActive:
enabled, disabled, targetDigest, targetResolution, err = prepareRange(ctx, workDir, logger, session)
case PhaseFound, PhaseExhausted:
targetDigest, targetResolution, err = writeOriginal(ctx, workDir, logger, session, pending.Step)
restored = countRequirements(session.Original)
default:
return Result{}, fmt.Errorf("invalid bisect state: unknown phase %q", session.Phase)
}
if err != nil {
return Result{}, err
}
return commitTransition(
ctx,
ops,
workDir,
logger,
session,
*pending,
targetDigest,
targetResolution,
enabled,
disabled,
restored,
)
}
// commitTransition syncs the staged manifest, then records the committed
// digest and clears the pending transition. A failure before the final write
// leaves both the staged manifest and the pending record for a retry.
func commitTransition(
ctx context.Context,
ops *operation.Service,
workDir string,
logger *log.Logger,
session *state,
pending pendingTransition,
targetDigest string,
targetResolution string,
enabled, disabled, restored int,
) (Result, error) {
if err := ctx.Err(); err != nil {
return Result{}, err
}
// Sync even when the manifest already shows the target: the manifest
// states what should be installed, not what is installed. ExpectedManifest
// also makes a concurrent edit fail instead of being overwritten by
// whichever document the sync happened to read.
syncResult, err := ops.Sync(
ctx,
workDir,
install.Options{ExpectedManifest: targetResolution},
)
if err != nil {
return Result{}, fmt.Errorf("sync installation: %w", err)
}
// The resolution fingerprint intentionally ignores name metadata, so sync
// can succeed after a concurrent rename. Validate the full digest before
// clearing pending; otherwise the session would record a stale Applied
// digest and reject every later command.
applied := targetDigest
err = withWorkspace(ctx, workDir, logger, func() error {
current, err := document.ManifestFile(workDir).Read()
if err != nil {
return fmt.Errorf("read manifest after sync: %w", err)
}
currentDigest, err := manifestDigest(current)
if err != nil {
return err
}
if currentDigest != targetDigest {
currentResolution, err := manifestResolutionFingerprint(current)
if err != nil {
return err
}
if currentResolution != targetResolution {
return errManifestChangedDuringSync
}
// Only fields resolution ignores changed, currently the server
// name. Adopt the rename into the original so reset preserves it
// instead of reverting a change the session already observed.
adoptRename(session, current)
applied = currentDigest
}
if err := ctx.Err(); err != nil {
return err
}
session.Pending = nil
session.Applied = applied
return writeState(workDir, session)
})
if err != nil {
return Result{}, err
}
output := Result{
Phase: session.Phase,
Complete: session.Phase != PhaseActive,
State: currentView(session),
Enabled: enabled,
Disabled: disabled,
Restored: restored,
Warnings: syncWarnings(syncResult),
Marked: markedMod(session, pending.Step),
}
if session.Phase == PhaseFound {
output.Found = &session.Mods[session.Left]
}
return output, nil
}
// markedMod reports the requirement a completed step marked.
func markedMod(session *state, step Step) *Mod {
switch step {
case StepGood:
if session.Left > 0 && session.Left <= len(session.Mods) {
return &session.Mods[session.Left-1]
}
case StepBad:
if session.Right >= 0 && session.Right < len(session.Mods) {
return &session.Mods[session.Right]
}
}
return nil
}
// interruptedError refuses a different leaf while a transition is pending.
// The target range already contains the recorded verdict, so letting another
// verdict advance it again would corrupt the search.
func interruptedError(pending *pendingTransition) error {
if pending.Step == StepReset {
return fmt.Errorf(
"bisect reset was interrupted; rerun `lucy bisect reset` to complete it",
)
}
return fmt.Errorf(
"bisect %s was interrupted; rerun `lucy bisect %s` to complete it or `lucy bisect reset` to abandon the session",
pending.Step,
pending.Step,
)
}
// terminalError refuses a new verdict after a session reached its terminal
// phase. Only reset may end the session, so the recorded verdict cannot
// silently change.
func terminalError(session *state) error {
switch session.Phase {
case PhaseFound:
return fmt.Errorf(
"bisect session already found %s; run `lucy bisect reset` before another verdict",
session.Mods[session.Left].Label(),
)
case PhaseExhausted:
return fmt.Errorf("bisect session already finished with no bad package; run `lucy bisect reset` before another verdict")
default:
return nil
}
}
// startRefusal explains why start cannot replace an existing session. The
// captured manifest lives only in the session file, so replacing that file
// would make the original unrecoverable.
func startRefusal(session *state) error {
if session.Pending != nil {
if session.Pending.Step == StepReset {
return fmt.Errorf(
"bisect reset was interrupted; rerun `lucy bisect reset` before starting another session",
)
}
return fmt.Errorf(
"bisect session is interrupted during %s; run `lucy bisect %s` to complete it or `lucy bisect reset` to abandon the session",
session.Pending.Step,
session.Pending.Step,
)
}
switch session.Phase {
case PhaseFound:
return fmt.Errorf(
"bisect session already found %s; run `lucy bisect reset` before starting another session",
session.Mods[session.Left].Label(),
)
case PhaseExhausted:
return fmt.Errorf("bisect session already finished with no bad package; run `lucy bisect reset` before starting another session")
default:
return fmt.Errorf("bisect session already active; run `lucy bisect reset` before starting another session")
}
}
package bisect
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/server"
)
const (
stateFilename = "bisect.json"
lockFilename = "bisect.lock"
)
// pendingTransition is the durable intent of a transition whose manifest
// write and installation sync have not both completed. The target phase and
// range live on state; this record names the command to rerun and the manifest
// digest the transition intended to publish. The midpoint it marked follows
// from the target range: good advanced Left past it, bad moved Right onto it.
type pendingTransition struct {
Step Step `json:"step"`
Digest string `json:"digest,omitempty"`
Resolution string `json:"resolution,omitempty"`
}
// state is the persisted session. Original is the manifest as it stood before
// the first toggle and is retained until reset has restored and synced it, so
// an interrupted session never loses the manifest it must return to.
type state struct {
Phase Phase `json:"phase"`
Mods []Mod `json:"mods"`
Original *document.Manifest `json:"original"`
Left int `json:"left"`
Right int `json:"right"`
// Applied is the digest of the manifest the last successful transition
// left in the workspace. Verdicts and reset refuse to overwrite a
// manifest that no longer matches it, the pending target, or the
// original.
Applied string `json:"applied,omitempty"`
Pending *pendingTransition `json:"pending,omitempty"`
}
func stateFilePath(workDir string) string {
return filepath.Join(workDir, stateFilename)
}
func lockFilePath(workDir string) string {
return filepath.Join(workDir, ".lucy", lockFilename)
}
// statePresent checks for a session without creating workspace state.
func statePresent(workDir string) (bool, error) {
_, err := os.Stat(stateFilePath(workDir))
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, fmt.Errorf("inspect bisect state: %w", err)
}
// requireSession rejects a command that cannot have a session before the lock
// creates .lucy in a directory that is not a bisect workspace.
func requireSession(workDir string) error {
present, err := statePresent(workDir)
if err != nil {
return err
}
if !present {
return fmt.Errorf("no bisect session found, run `lucy bisect start` first")
}
return nil
}
// requireStartWorkspace rejects start before locking when there is neither a
// session to resume nor a manifest to capture. A lock-only workspace cannot
// start a bisect session because Original would be missing.
func requireStartWorkspace(workDir string) error {
present, err := statePresent(workDir)
if err != nil {
return err
}
if present {
return nil
}
manifest := document.ManifestFile(workDir).Path()
if _, err := os.Stat(manifest); err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("read manifest: %w", err)
}
return fmt.Errorf("inspect manifest: %w", err)
}
return nil
}
// lockSession serializes every session transition across processes. It waits
// instead of failing so a concurrent start, verdict, status, or reset observes
// the previous command's committed state, and it stops waiting when the
// command context ends so a canceled command cannot later mutate the session.
// require runs before .lucy is created, so a command that cannot have a
// session or manifest fails without leaving a workspace marker. It is
// separate from the workspace writer lock because installation sync takes that
// lock itself.
func lockSession(
ctx context.Context,
workDir string,
require func(string) error,
) (*fsutil.FileLock, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := require(workDir); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
relative := filepath.Join(".lucy", lockFilename)
if err := workspacewrite.SafePath(workDir, relative); err != nil {
return nil, err
}
if err := fsutil.MkdirAllPrivate(filepath.Dir(lockFilePath(workDir))); err != nil {
return nil, fmt.Errorf("create workspace state directory: %w", err)
}
if err := workspacewrite.SafePath(workDir, relative); err != nil {
return nil, err
}
for {
if err := ctx.Err(); err != nil {
return nil, err
}
lock, err := fsutil.TryLockFile(lockFilePath(workDir))
if err == nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, errors.Join(ctxErr, lock.Close())
}
return lock, nil
}
if !errors.Is(err, fsutil.ErrLocked) {
return nil, fmt.Errorf("lock bisect session: %w", err)
}
timer := time.NewTimer(50 * time.Millisecond)
select {
case <-ctx.Done():
timer.Stop()
return nil, fmt.Errorf("wait for bisect session lock: %w", ctx.Err())
case <-timer.C:
}
}
}
// readState returns the session, or nil when this workspace has none. A
// corrupt state is an error rather than an empty session: replacing it would
// lose the manifest that reset must restore.
func readState(workDir string) (*state, error) {
data, err := os.ReadFile(stateFilePath(workDir))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("failed to read bisect state: %w", err)
}
var session state
if err := json.Unmarshal(data, &session); err != nil {
return nil, fmt.Errorf(
"failed to parse bisect state: %w; the captured original, if present, remains in %s; extract its original value to restore lucy.yaml manually, then delete %s",
err,
stateFilename,
stateFilename,
)
}
if err := validateState(&session); err != nil {
return nil, fmt.Errorf(
"%w; the captured original, if present, remains in %s; extract its original value to restore lucy.yaml manually, then delete %s",
err,
stateFilename,
stateFilename,
)
}
return &session, nil
}
// loadSession reads the session and reports an actionable error when the
// workspace has none.
func loadSession(workDir string) (*state, error) {
session, err := readState(workDir)
if err != nil {
return nil, err
}
if session == nil {
return nil, fmt.Errorf("no bisect session found, run `lucy bisect start` first")
}
return session, nil
}
func stateBytes(session *state) ([]byte, error) {
data, err := json.Marshal(session, jsontext.Multiline(true), jsontext.WithIndent(" "))
if err != nil {
return nil, fmt.Errorf("failed to serialize bisect state: %w", err)
}
return data, nil
}
func writeState(workDir string, session *state) error {
if err := validateState(session); err != nil {
return err
}
data, err := stateBytes(session)
if err != nil {
return err
}
if err := fsutil.AtomicWrite(stateFilePath(workDir), data, 0o600); err != nil {
return fmt.Errorf("failed to write bisect state: %w", err)
}
return nil
}
// createState publishes the first state of a session without replacing one
// that another process may have created since the caller checked.
func createState(workDir string, session *state) (resultErr error) {
if err := validateState(session); err != nil {
return err
}
data, err := stateBytes(session)
if err != nil {
return err
}
root, err := os.OpenRoot(workDir)
if err != nil {
return fmt.Errorf("open workspace: %w", err)
}
defer func() { resultErr = errors.Join(resultErr, root.Close()) }()
if err := fsutil.WriteRoot(
root,
stateFilename,
bytes.NewReader(data),
fsutil.WriteOptions{Mode: 0o600},
); err != nil {
return fmt.Errorf("failed to create bisect state: %w", err)
}
return nil
}
func deleteState(workDir string) error {
if err := os.Remove(stateFilePath(workDir)); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove bisect state: %w", err)
}
return nil
}
func validateState(session *state) error {
if session == nil {
return fmt.Errorf("invalid bisect state: empty state")
}
if len(session.Mods) == 0 {
return fmt.Errorf("invalid bisect state: no packages")
}
if session.Original == nil {
return fmt.Errorf("invalid bisect state: no captured manifest")
}
if session.Pending == nil ||
(session.Pending.Step != StepStart &&
session.Pending.Step != StepReset) {
if session.Applied == "" {
return fmt.Errorf("invalid bisect state: no committed manifest digest")
}
} else if session.Pending.Step == StepStart && session.Applied != "" {
return fmt.Errorf("invalid bisect state: interrupted start already has a committed manifest digest")
}
switch session.Phase {
case PhaseActive:
if session.Left < 0 || session.Right >= len(session.Mods) || session.Left > session.Right {
return fmt.Errorf(
"invalid bisect state: active range [%d, %d] outside %d packages",
session.Left,
session.Right,
len(session.Mods),
)
}
case PhaseFound:
if session.Left != session.Right ||
session.Left < 0 ||
session.Left >= len(session.Mods) {
return fmt.Errorf(
"invalid bisect state: found range [%d, %d] is not one package",
session.Left,
session.Right,
)
}
case PhaseExhausted:
if session.Right < 0 ||
session.Right >= len(session.Mods) ||
session.Left != session.Right+1 {
return fmt.Errorf(
"invalid bisect state: exhausted range [%d, %d] is inconsistent",
session.Left,
session.Right,
)
}
default:
return fmt.Errorf("invalid bisect state: unknown phase %q", session.Phase)
}
return validatePending(session)
}
func validatePending(session *state) error {
pending := session.Pending
if pending == nil {
return nil
}
if pending.Digest == "" || pending.Resolution == "" {
return fmt.Errorf("invalid bisect state: pending transition records no manifest digest and resolution fingerprint")
}
switch pending.Step {
case StepStart:
if session.Phase != PhaseActive ||
session.Left != 0 ||
session.Right != len(session.Mods)-1 {
return fmt.Errorf("invalid bisect state: interrupted start does not own the full range")
}
case StepGood:
if session.Left <= 0 ||
(session.Phase != PhaseActive && session.Phase != PhaseExhausted) {
return fmt.Errorf("invalid bisect state: interrupted good does not match its range or phase")
}
case StepBad:
if session.Right < 0 ||
(session.Phase != PhaseActive && session.Phase != PhaseFound) {
return fmt.Errorf("invalid bisect state: interrupted bad does not match its range or phase")
}
case StepReset:
// Reset can follow any phase; the pending digest names the manifest
// the failed reset left in place.
default:
return fmt.Errorf("invalid bisect state: unknown pending step %q", pending.Step)
}
return nil
}
// errManifestChanged refuses to proceed when the manifest no longer matches
// any state the session itself published. Restoring the original would
// otherwise discard an unrelated edit without leaving a trace.
var errManifestChanged = errors.New(
"lucy.yaml changed outside the bisect session; refusing to overwrite it. " +
"Undo that change and retry, or recover the captured original from " +
"bisect.json (mode 0600) and delete bisect.json to abandon the session",
)
var errManifestChangedDuringSync = errors.New(
"lucy.yaml changed while the installation synced; the bisect transition " +
"remains pending. Restore lucy.yaml and rerun the command, or recover " +
"the captured original from bisect.json (mode 0600)",
)
// manifestResolutionFingerprint is the fingerprint installation uses to
// decide whether a lock still answers the manifest.
func manifestResolutionFingerprint(doc *document.Manifest) (string, error) {
fingerprint, err := doc.Fingerprint()
if err != nil {
return "", fmt.Errorf("fingerprint manifest: %w", err)
}
return fingerprint, nil
}
// manifestDigest covers every persisted manifest field, including name
// metadata that resolution intentionally ignores. reset and verdicts use it to
// distinguish a manifest the session published from one edited outside it.
func manifestDigest(doc *document.Manifest) (string, error) {
if err := doc.Normalize(); err != nil {
return "", fmt.Errorf("normalize manifest: %w", err)
}
data, err := json.Marshal(doc, json.Deterministic(true))
if err != nil {
return "", fmt.Errorf("digest manifest: %w", err)
}
sum := sha256.Sum256(data)
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
// withWorkspace replays interrupted workspace journals under the shared
// writer lock and runs action while that lock is held. The caller must hold
// the bisect session lock; action must not call installation sync, which takes
// the same writer lock itself.
func withWorkspace(
ctx context.Context,
workDir string,
logger *log.Logger,
action func() error,
) (resultErr error) {
if err := ctx.Err(); err != nil {
return err
}
writer, err := workspacewrite.Lock(workDir, logger)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := ctx.Err(); err != nil {
return err
}
if err := filetrack.RecoverLocked(workDir, logger); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
return action()
}
type manifestRelation int
const (
manifestForeign manifestRelation = iota
manifestOwned
// manifestRenamed means the manifest matches the pending target in every
// field the resolution fingerprint covers, but differs in a field it
// intentionally ignores, currently the server name. The caller adopts that
// name instead of rejecting a rename that cannot affect installation.
manifestRenamed
)
// classifyManifest reports how doc relates to the states this session
// published. Without a pending transition, a changed manifest is foreign even
// when only its name differs; that edit happened after a committed step and
// reset must not discard it silently.
func classifyManifest(
session *state,
doc *document.Manifest,
) (manifestRelation, error) {
digest, err := manifestDigest(doc)
if err != nil {
return manifestForeign, err
}
if digest == session.Applied {
return manifestOwned, nil
}
if session.Pending != nil && digest == session.Pending.Digest {
return manifestOwned, nil
}
original, err := manifestDigest(session.Original)
if err != nil {
return manifestForeign, err
}
if digest == original {
return manifestOwned, nil
}
if session.Pending == nil || session.Pending.Resolution == "" {
return manifestForeign, nil
}
resolution, err := manifestResolutionFingerprint(doc)
if err != nil {
return manifestForeign, err
}
if resolution == session.Pending.Resolution {
return manifestRenamed, nil
}
return manifestForeign, nil
}
func adoptRename(session *state, doc *document.Manifest) {
session.Original.Name = doc.Name
}
// toggleRange enables requirements through mid and disables the rest after
// them without writing anything. It returns both the ownership digest and the
// resolution fingerprint machinery pins during sync.
func toggleRange(
doc *document.Manifest,
mods []Mod,
mid int,
) (
enabled, disabled, matched int,
digest, resolution string,
err error,
) {
for i, mod := range mods {
if setRequirementEnabled(doc, mod, i <= mid) {
matched++
if i <= mid {
enabled++
} else {
disabled++
}
}
}
digest, err = manifestDigest(doc)
if err != nil {
return 0, 0, 0, "", "", err
}
resolution, err = manifestResolutionFingerprint(doc)
if err != nil {
return 0, 0, 0, "", "", err
}
return enabled, disabled, matched, digest, resolution, nil
}
// prepareRangeLocked writes the target digest to the pending transition
// before changing the manifest, then writes the range. The caller holds the
// workspace writer lock after journal recovery.
func prepareRangeLocked(
ctx context.Context,
workDir string,
session *state,
) (enabled, disabled int, digest, resolution string, err error) {
if err := ctx.Err(); err != nil {
return 0, 0, "", "", err
}
if session.Pending == nil {
return 0, 0, "", "", fmt.Errorf("invalid bisect state: no pending transition")
}
doc, err := document.ManifestFile(workDir).Read()
if err != nil {
return 0, 0, "", "", fmt.Errorf("read manifest: %w", err)
}
relation, err := classifyManifest(session, doc)
if err != nil {
return 0, 0, "", "", err
}
switch relation {
case manifestForeign:
return 0, 0, "", "", errManifestChanged
case manifestRenamed:
adoptRename(session, doc)
}
mid := (session.Left + session.Right) / 2
var matched int
enabled, disabled, matched, digest, resolution, err = toggleRange(doc, session.Mods, mid)
if err != nil {
return 0, 0, "", "", err
}
session.Pending.Digest = digest
session.Pending.Resolution = resolution
if err := ctx.Err(); err != nil {
return 0, 0, "", "", err
}
if err := writeState(workDir, session); err != nil {
return 0, 0, "", "", err
}
if matched > 0 {
if err := ctx.Err(); err != nil {
return 0, 0, "", "", err
}
if err := document.ManifestFile(workDir).Write(doc); err != nil {
return 0, 0, "", "", fmt.Errorf("write manifest: %w", err)
}
}
return enabled, disabled, digest, resolution, nil
}
// prepareRange stages the pending range. The caller syncs afterwards, once
// the workspace writer lock is released, because installation takes that lock
// itself.
func prepareRange(
ctx context.Context,
workDir string,
logger *log.Logger,
session *state,
) (enabled, disabled int, digest, resolution string, err error) {
err = withWorkspace(ctx, workDir, logger, func() error {
var actionErr error
enabled, disabled, digest, resolution, actionErr = prepareRangeLocked(ctx, workDir, session)
return actionErr
})
return enabled, disabled, digest, resolution, err
}
// setRequirementEnabled flips one manifest requirement and reports whether
// the entry was present.
func setRequirementEnabled(doc *document.Manifest, mod Mod, enabled bool) bool {
var packages map[string]document.Requirement
switch mod.Environment {
case server.EnvironmentServer:
if doc.Server.Packages == nil {
return false
}
packages = doc.Server.Packages[mod.Ecosystem]
case server.EnvironmentMCDR:
if doc.MCDR == nil {
return false
}
packages = doc.MCDR.Packages
default:
return false
}
requirement, ok := packages[mod.Reference]
if !ok {
return false
}
value := enabled
requirement.Enabled = &value
packages[mod.Reference] = requirement
return true
}
// writeOriginal restores the manifest captured before the first toggle. It
// records step and the target digest on the pending transition before
// writing, then writes the original. The caller syncs afterwards; a retry
// after a failed sync must run that sync even when the manifest already
// matches.
func writeOriginal(
ctx context.Context,
workDir string,
logger *log.Logger,
session *state,
step Step,
) (digest, resolution string, err error) {
if err := ctx.Err(); err != nil {
return "", "", err
}
err = withWorkspace(ctx, workDir, logger, func() error {
current, err := document.ManifestFile(workDir).Read()
if err != nil {
return fmt.Errorf("read manifest: %w", err)
}
relation, err := classifyManifest(session, current)
if err != nil {
return err
}
switch relation {
case manifestForeign:
return errManifestChanged
case manifestRenamed:
adoptRename(session, current)
}
originalDigest, err := manifestDigest(session.Original)
if err != nil {
return err
}
originalResolution, err := manifestResolutionFingerprint(session.Original)
if err != nil {
return err
}
digest = originalDigest
resolution = originalResolution
switch {
case session.Pending == nil:
session.Pending = &pendingTransition{
Step: step,
Digest: originalDigest,
Resolution: originalResolution,
}
case step == StepReset:
// Reset supersedes an interrupted leaf. Keep that leaf's target
// digest until the original is written, so a retry can still
// recognize the manifest the failed reset left in place.
session.Pending.Step = StepReset
if session.Pending.Digest == "" {
session.Pending.Digest = originalDigest
}
if session.Pending.Resolution == "" {
session.Pending.Resolution = originalResolution
}
default:
session.Pending.Step = step
session.Pending.Digest = originalDigest
session.Pending.Resolution = originalResolution
}
if err := ctx.Err(); err != nil {
return err
}
if err := writeState(workDir, session); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
if err := document.ManifestFile(workDir).Write(session.Original); err != nil {
return fmt.Errorf("restore manifest: %w", err)
}
return nil
})
return digest, resolution, err
}
// Package buildid identifies the running Lucy binary by its content.
package buildid
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"sync"
)
// Identity returns the SHA-256 digest of the running executable. Outputs that
// any change to Lucy's code can alter, such as bootstrap results, key on it,
// so a rebuilt binary never reuses output an older algorithm produced.
var Identity = sync.OnceValues(func() (string, error) {
path, err := os.Executable()
if err != nil {
return "", fmt.Errorf("locate the running executable: %w", err)
}
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("read the running executable: %w", err)
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", fmt.Errorf("digest the running executable: %w", err)
}
return hex.EncodeToString(hasher.Sum(nil)), nil
})
// Package buildrepo statically probes the Gradle build layout of a Minecraft
// mod source repository. Gradle is never executed.
//
// Contract: filesystem paths are absolute, Gradle paths use the colon form
// (":" for the root project), and nothing outside the probed root is read.
// Whatever cannot be read from literals alone is reported as a Finding rather
// than guessed; a canceled context or an unreadable directory fails Probe
// instead.
package buildrepo
import (
"cmp"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
catalogpkg "github.com/mclucy/lucy/catalog"
)
type Layout struct {
Root string
Builds []GradleBuild
Findings []Finding
}
type GradleBuild struct {
Dir string
SettingsFile string
BuildFile string
Wrapper *Wrapper
Projects []Project
IncludedBuilds []string
Daemon *JavaConstraint
JavaHome string
}
type Project struct {
Path string
Dir string
BuildFile string
Ecosystems []catalogpkg.Ecosystem
Java JavaRequirements
}
type Wrapper struct {
Script, Jar, Properties string
DistributionURL, DistributionSHA256 string
Version string
}
type JavaConstraint struct {
Major int
Vendor string
}
// JavaRequirements separates compiler selection from bytecode compatibility.
// Nil fields denote absent or unresolved declarations, not unrestricted compilation.
type JavaRequirements struct {
Toolchain *JavaConstraint
Release, Source, Target *int
}
type Finding struct {
File string
Line int
Message string
}
// Probe reports literal declarations; evaluating Gradle is required to establish the active build graph.
func Probe(ctx context.Context, root string) (layout Layout, err error) {
if err := ctx.Err(); err != nil {
return Layout{}, err
}
abs, err := filepath.Abs(root)
if err != nil {
return Layout{}, fmt.Errorf("buildrepo: resolve %s: %w", root, err)
}
info, err := os.Stat(abs)
if err != nil {
return Layout{}, fmt.Errorf("buildrepo: stat %s: %w", abs, err)
}
if !info.IsDir() {
return Layout{}, fmt.Errorf("buildrepo: %s is not a directory", abs)
}
realpath, err := filepath.EvalSymlinks(abs)
if err != nil {
return Layout{}, fmt.Errorf("buildrepo: resolve symlinks of %s: %w", abs, err)
}
scoped, err := os.OpenRoot(realpath)
if err != nil {
return Layout{}, fmt.Errorf("open repository root: %w", err)
}
defer func() {
if closeErr := scoped.Close(); closeErr != nil {
err = errors.Join(err, fmt.Errorf("close repository root: %w", closeErr))
}
}()
p := &prober{
ctx: ctx,
root: realpath, scoped: scoped,
props: map[string]map[string]string{},
catalog: map[string]string{},
catalogs: map[string]map[string]string{},
conventions: map[string]string{},
conventionSettings: map[string]string{},
}
if err := p.discoverBuilds(); err != nil {
return Layout{}, err
}
p.indexCatalogs()
p.indexConventions()
if err := p.analyzeBuilds(); err != nil {
return Layout{}, err
}
for i := range p.builds {
sortBuild(&p.builds[i])
}
return Layout{
Root: realpath,
Builds: p.builds,
Findings: p.findings.sorted(),
}, nil
}
// skippedDirs never contain handwritten Gradle configuration.
var skippedDirs = map[string]bool{
".git": true, ".gradle": true, ".idea": true, ".kotlin": true,
"build": true, "out": true, "target": true, "node_modules": true,
}
// conventionBuildDirs hold plugin sources, never mod targets.
var conventionBuildDirs = map[string]bool{
"buildSrc": true, "build-logic": true, "buildlogic": true,
}
type prober struct {
ctx context.Context
root string
scoped *os.Root
builds []GradleBuild
findings findingList
// props caches parsed gradle.properties per directory.
props map[string]map[string]string
// catalog maps a version catalog alias to a plugin id.
catalog map[string]string
// catalogs caches parsed version catalogs per path.
catalogs map[string]map[string]string
// conventions maps a convention plugin id to its precompiled script.
conventions map[string]string
// conventionSettings holds convention plugin ids declared for settings scripts.
conventionSettings map[string]string
}
type findingList []Finding
// add records a finding once; the same observation can be reached twice, for
// example when a settings script is read during discovery and analysis.
func (f *findingList) add(file string, line int, msg string) {
for _, existing := range *f {
if existing.File == file && existing.Line == line && existing.Message == msg {
return
}
}
*f = append(*f, Finding{File: file, Line: line, Message: msg})
}
func (f findingList) sorted() []Finding {
sort.SliceStable(f, func(i, j int) bool {
a, b := &f[i], &f[j]
return cmp.Or(cmp.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line), cmp.Compare(a.Message, b.Message)) < 0
})
return f
}
// contains reports whether target stays inside the root once symlinks are
// resolved. Symlinked entries escaping the root are never followed.
func (p *prober) contains(target string) bool {
realpath, err := filepath.EvalSymlinks(target)
if err != nil {
return false
}
rel, err := filepath.Rel(p.root, realpath)
if err != nil {
return false
}
return rel == "." || filepath.IsLocal(rel)
}
func (p *prober) readFile(path string) (string, error) {
relative, err := filepath.Rel(p.root, path)
if err != nil || !filepath.IsLocal(relative) {
return "", errors.New("outside repository root")
}
info, err := p.scoped.Stat(relative)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", errors.New("not a regular file")
}
data, err := p.scoped.ReadFile(relative)
return string(data), err
}
func (p *prober) readOptional(path string) (string, bool) {
if path == "" {
return "", false
}
data, err := p.readFile(path)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
p.findings.add(path, 0, "file could not be read: "+err.Error())
}
return "", false
}
return data, true
}
func (p *prober) firstExisting(dir string, names ...string) string {
for _, name := range names {
path := filepath.Join(dir, name)
if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() {
return path
}
}
return ""
}
func lineAt(content string, offset int) int {
return strings.Count(content[:offset], "\n") + 1
}
package buildrepo
import (
"fmt"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
)
func (p *prober) analyzeBuilds() error {
for i := range p.builds {
build := &p.builds[i]
build.IncludedBuilds = p.includedBuildDirs(build.Dir, build.SettingsFile)
build.Wrapper = p.parseWrapper(build.Dir)
for dir := filepath.Dir(build.Dir); build.Wrapper == nil && p.contains(dir); dir = filepath.Dir(dir) {
build.Wrapper = p.parseWrapper(dir)
if dir == p.root {
break
}
}
p.applyDaemonSettings(build)
if err := p.analyzeProjects(build); err != nil {
return fmt.Errorf("buildrepo: probe %s: %w", build.Dir, err)
}
}
return nil
}
func (p *prober) applyDaemonSettings(build *GradleBuild) {
if home, ok := p.propertiesOf(build.Dir)["org.gradle.java.home"]; ok && home != "" {
build.JavaHome = home
if !filepath.IsAbs(home) {
build.JavaHome = filepath.Join(build.Dir, filepath.FromSlash(home))
}
}
criteria := p.firstExisting(build.Dir, filepath.Join("gradle", "gradle-daemon-jvm.properties"))
if criteria == "" {
return
}
content, ok := p.readOptional(criteria)
if !ok {
p.findings.add(criteria, 0, "daemon JVM criteria file could not be read")
return
}
properties, err := ParseProperties(content)
if err != nil {
p.findings.add(criteria, 0, "daemon JVM criteria could not be decoded: "+err.Error())
return
}
constraint := &JavaConstraint{
Major: parseMajor(properties["toolchainVersion"]), Vendor: properties["toolchainVendor"],
}
if constraint.Major > 0 || constraint.Vendor != "" {
build.Daemon = constraint
}
}
var majorPattern = regexp.MustCompile(`\d+`)
func parseMajor(text string) int {
match := majorPattern.FindString(text)
if match == "" {
return 0
}
value := 0
for _, digit := range match {
value = value*10 + int(digit-'0')
}
return value
}
func (p *prober) parseWrapper(dir string) *Wrapper {
properties := p.firstExisting(dir, filepath.Join("gradle", "wrapper", "gradle-wrapper.properties"))
scriptName := "gradlew"
if runtime.GOOS == "windows" {
scriptName = "gradlew.bat"
}
script := p.firstExisting(dir, scriptName)
jar := p.firstExisting(dir, filepath.Join("gradle", "wrapper", "gradle-wrapper.jar"))
if properties == "" && script == "" && jar == "" {
return nil
}
wrapper := &Wrapper{Script: script, Jar: jar, Properties: properties}
if properties == "" {
p.findings.add(script, 0, "gradlew is present without gradle/wrapper/gradle-wrapper.properties; no Gradle version is pinned")
return wrapper
}
content, ok := p.readOptional(properties)
if !ok {
p.findings.add(properties, 0, "wrapper properties could not be read; no Gradle version is pinned")
return wrapper
}
values, err := ParseProperties(content)
if err != nil {
p.findings.add(properties, 0, "wrapper properties could not be decoded: "+err.Error())
return wrapper
}
wrapper.DistributionURL = values["distributionUrl"]
wrapper.DistributionSHA256 = values["distributionSha256Sum"]
wrapper.Version = gradleVersionFromURL(wrapper.DistributionURL)
switch {
case wrapper.DistributionURL == "":
p.findings.add(properties, 0, "wrapper properties declare no distributionUrl; the pinned Gradle version is unknown")
case wrapper.Version == "":
p.findings.add(properties, 0, "wrapper distributionUrl "+wrapper.DistributionURL+" does not name a Gradle version")
}
if wrapper.DistributionURL != "" && wrapper.DistributionSHA256 == "" {
p.findings.add(properties, 0, "wrapper distribution is not pinned by a distributionSha256Sum checksum")
}
if jar == "" {
p.findings.add(properties, 0, "wrapper jar gradle/wrapper/gradle-wrapper.jar is missing; the checked in wrapper cannot run")
}
return wrapper
}
var gradleURLPattern = regexp.MustCompile(`gradle-([0-9][0-9A-Za-z.\-]*?)-(?:bin|all)\.zip`)
func gradleVersionFromURL(url string) string {
match := gradleURLPattern.FindStringSubmatch(url)
if match == nil {
return ""
}
return match[1]
}
func (p *prober) analyzeProjects(build *GradleBuild) error {
paths := p.declaredProjects(build.Dir, build.SettingsFile)
order := make([]string, 0, len(paths))
for path := range paths {
order = append(order, path)
}
slices.Sort(order)
var broadcast JavaRequirements
var broadcastSet bool
if build.BuildFile != "" {
if content, ok := p.readOptional(build.BuildFile); ok {
content = stripComments(content)
broadcast, broadcastSet = p.broadcastJava(build, content)
}
}
for _, path := range order {
dir := paths[path]
if dir == "" {
build.Projects = append(build.Projects, Project{Path: path})
continue
}
if !p.contains(dir) {
p.findings.add(build.SettingsFile, 0, "project "+path+" resolves outside the repository root and was not read")
continue
}
project := Project{
Path: path,
Dir: dir,
BuildFile: p.firstExisting(dir, "build.gradle", "build.gradle.kts"),
}
if project.BuildFile != "" {
if content, ok := p.readOptional(project.BuildFile); ok {
content = stripComments(content)
plugins := p.appliedPlugins(project.BuildFile, content, 0)
sources := p.appliedScriptSources(project.BuildFile, plugins)
project.Ecosystems = p.scriptEcosystems(project.BuildFile, plugins)
project.Java = p.javaConfigOf(project.BuildFile, content, build.Dir, sources)
p.noteGeneratedSources(&project)
p.noteConditional(project.BuildFile, content)
} else {
p.findings.add(project.BuildFile, 0, "project build script could not be read")
}
}
p.corroborate(&project)
p.inheritJava(&project, broadcast, broadcastSet)
build.Projects = append(build.Projects, project)
if err := p.ctx.Err(); err != nil {
return err
}
}
return nil
}
// broadcastJava returns the Java configuration a root script applies to every
// project through allprojects or subprojects blocks.
func (p *prober) broadcastJava(build *GradleBuild, content string) (JavaRequirements, bool) {
var req JavaRequirements
found := false
for _, name := range []string{"allprojects", "subprojects"} {
body, _, ok := blockNamed(content, name)
if !ok {
continue
}
block := p.javaConfig(build.BuildFile, body, build.Dir)
if block.Toolchain != nil && req.Toolchain == nil {
req.Toolchain = block.Toolchain
found = true
}
if block.Release != nil && req.Release == nil {
req.Release = block.Release
found = true
}
}
return req, found
}
func (p *prober) inheritJava(project *Project, broadcast JavaRequirements, broadcastSet bool) {
if broadcastSet {
if project.Java.Toolchain == nil {
project.Java.Toolchain = broadcast.Toolchain
}
if project.Java.Release == nil {
project.Java.Release = broadcast.Release
}
}
if project.Java.Toolchain == nil && project.Java.Release == nil &&
project.Java.Source == nil && project.Java.Target == nil {
p.findings.add(project.BuildFile, 0, "Java requirements of this project are unknown")
}
}
var modMetadata = []struct {
file string
eco catalog.Ecosystem
}{
{file: filepath.Join("src", "main", "resources", "fabric.mod.json"), eco: catalog.EcosystemFabric},
{file: filepath.Join("src", "main", "resources", "quilt.mod.json"), eco: catalog.EcosystemQuilt},
{file: filepath.Join("src", "main", "resources", "META-INF", "mods.toml"), eco: catalog.EcosystemForge},
{file: filepath.Join("src", "main", "resources", "META-INF", "neoforge.mods.toml"), eco: catalog.EcosystemNeoForge},
}
// corroborate fills ecosystems from loader metadata when no modding plugin was
// found. Metadata only ever confirms; it never overrides a plugin.
func (p *prober) corroborate(project *Project) {
if len(project.Ecosystems) > 0 {
return
}
var found []string
for _, entry := range modMetadata {
path := filepath.Join(project.Dir, entry.file)
if _, err := os.Stat(path); err == nil && p.contains(path) {
found = append(found, entry.file)
if !slices.Contains(project.Ecosystems, entry.eco) {
project.Ecosystems = append(project.Ecosystems, entry.eco)
}
}
}
if len(found) > 0 {
p.findings.add(project.BuildFile, 0,
"no modding plugin is applied; ecosystem taken from "+strings.Join(found, ", ")+" metadata")
}
slices.Sort(project.Ecosystems)
}
func (p *prober) noteGeneratedSources(project *Project) {
for _, name := range []string{"generated", "generated-src", "chiseledSrc"} {
path := filepath.Join(project.Dir, "src", name)
if _, err := os.Stat(path); err == nil && p.contains(path) {
p.findings.add(project.BuildFile, 0,
"generated sources under "+filepath.ToSlash(filepath.Join("src", name))+" are not inspected")
}
}
}
var conditionalPattern = regexp.MustCompile(`(?m)^\s*(if\s*\(|if\s+|when\s*\(|switch\s*\(|\}\s*else\b)`)
func (p *prober) noteConditional(file, content string) {
if match := conditionalPattern.FindStringIndex(content); match != nil {
p.findings.add(file, lineAt(content, match[0]),
"script contains conditional configuration; literal declarations do not establish which branches are active")
}
}
package buildrepo
import (
"path/filepath"
"slices"
"sort"
"strings"
"github.com/pelletier/go-toml/v2"
)
type catalogDocument struct {
Plugins map[string]any `toml:"plugins"`
Libraries map[string]any `toml:"libraries"`
}
type catalogEntry struct {
ID string
Module string
}
// catalogAlias rewrites the separators Gradle treats as equivalent in accessor
// keys: fabric_loom, fabric.loom, and fabric-loom all read as
// libs.plugins.fabric.loom.
var catalogAlias = strings.NewReplacer("_", "-", ".", "-")
// indexCatalogs reads every libs.versions.toml reachable from the builds,
// mapping catalog aliases to plugin ids.
func (p *prober) indexCatalogs() {
for _, build := range p.builds {
for current := build.Dir; ; current = filepath.Dir(current) {
p.readCatalog(filepath.Join(current, "gradle", "libs.versions.toml"))
if current == p.root {
break
}
}
}
}
// readCatalog parses libs.versions.toml into the alias to plugin id map.
func (p *prober) readCatalog(path string) {
if _, seen := p.catalogs[path]; seen {
return
}
p.catalogs[path] = nil
content, ok := p.readOptional(path)
if !ok {
return
}
var document catalogDocument
if err := toml.Unmarshal([]byte(content), &document); err != nil {
p.findings.add(path, 0, "version catalog could not be parsed: "+err.Error())
return
}
values := map[string]string{}
for _, section := range []struct {
plugins bool
entries map[string]any
}{
{plugins: true, entries: document.Plugins},
{entries: document.Libraries},
} {
for alias, raw := range section.entries {
if id := pluginIDOfEntry(catalogEntryOf(section.plugins, raw)); id != "" {
values[catalogAlias.Replace(alias)] = id
}
}
}
p.catalogs[path] = values
for alias, id := range values {
if existing, ok := p.catalog[alias]; ok && existing != id {
continue
}
p.catalog[alias] = id
}
}
// catalogEntryOf reduces one catalog entry to the fields Lucy reads. Gradle
// accepts every entry as a table or as a short string: a plugin string is
// "id:version" and a library string is "group:name[:version]"; anything else,
// such as a nested sub-table, carries no entry.
func catalogEntryOf(plugins bool, raw any) catalogEntry {
var entry catalogEntry
switch value := raw.(type) {
case string:
if plugins {
entry.ID, _, _ = strings.Cut(value, ":")
return entry
}
group, rest, found := strings.Cut(value, ":")
if !found {
return entry
}
name, _, _ := strings.Cut(rest, ":")
entry.Module = group + ":" + name
case map[string]any:
entry.ID, _ = value["id"].(string)
entry.Module, _ = value["module"].(string)
if entry.Module == "" {
group, _ := value["group"].(string)
name, _ := value["name"].(string)
entry.Module = group + ":" + name
}
}
return entry
}
// pluginIDOfEntry derives a plugin id from a catalog entry, covering both the
// plugins table and libraries holding plugin marker modules.
func pluginIDOfEntry(entry catalogEntry) string {
if entry.ID != "" {
return entry.ID
}
group, name, found := strings.Cut(entry.Module, ":")
if !found {
return ""
}
marker, isMarker := strings.CutSuffix(name, ".gradle.plugin")
if !isMarker || marker != group {
return ""
}
return group
}
// sortBuild orders the derived collections of a build so that repeated probes
// of the same repository produce identical output.
func sortBuild(build *GradleBuild) {
sort.Slice(build.Projects, func(i, j int) bool {
return build.Projects[i].Path < build.Projects[j].Path
})
slices.Sort(build.IncludedBuilds)
for i := range build.Projects {
slices.Sort(build.Projects[i].Ecosystems)
}
}
package buildrepo
import (
"regexp"
"strings"
)
var (
callPattern = regexp.MustCompile(`\b([A-Za-z_][A-Za-z0-9_]*)\s*\(`)
identifierWord = regexp.MustCompile(`[A-Za-z_][A-Za-z0-9_]*`)
assignmentValue = regexp.MustCompile(`=[ \t]*([^\n]*)`)
)
func calls(content, name string) []int {
mask := stringMask(content)
var out []int
for _, match := range callPattern.FindAllStringSubmatchIndex(content, -1) {
if content[match[2]:match[3]] != name || inLiteral(mask, match[0]) {
continue
}
paren := strings.IndexByte(content[match[3]:], '(')
if paren < 0 {
continue
}
out = append(out, match[3]+paren)
}
return out
}
// groovyCalls returns the offsets of the first argument of every Groovy style
// call to name, which passes string literals without parentheses.
func groovyCalls(content, name string) []int {
pattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `[ \t\r\n]+['"]`)
var out []int
for _, loc := range pattern.FindAllStringIndex(content, -1) {
out = append(out, loc[1]-1)
}
return out
}
// callArgs returns the comma separated arguments of a call starting at `at`,
// which is either an opening paren or the first argument of a Groovy style
// call, together with the line of the call.
func callArgs(content string, at int) ([]string, int) {
line := lineAt(content, at)
if at < len(content) && content[at] == '(' {
body, ok := balancedParens(content, at)
if !ok || strings.TrimSpace(body) == "" {
return nil, line
}
return splitArgs(body), line
}
var args []string
for index := at; index < len(content); {
for index < len(content) && (isSpace(content[index]) || content[index] == ',') {
index++
}
if index >= len(content) {
break
}
_, width, ok := readStringLiteral(content[index:])
if !ok {
break
}
args = append(args, content[index:index+width])
index += width
}
return args, line
}
// balancedParens returns the content between the paren at start and its match.
func balancedParens(content string, start int) (string, bool) {
depth := 0
for i := start; i < len(content); i++ {
switch content[i] {
case '\'', '"':
end := skipString(content, i)
if end < 0 {
return "", false
}
i = end
case '(':
depth++
case ')':
depth--
if depth == 0 {
return content[start+1 : i], true
}
case '{':
// A named argument block never closes with the call's paren.
if !isNamedArg(content[start:i]) {
return "", false
}
}
}
return "", false
}
// isNamedArg reports whether text before a brace looks like "name =".
func isNamedArg(text string) bool {
trimmed := strings.TrimSpace(text)
if !strings.HasSuffix(trimmed, "=") {
return false
}
trimmed = strings.TrimSuffix(trimmed, "=")
if strings.TrimSpace(trimmed) == trimmed {
return false
}
return identifierWord.MatchString(trimmed)
}
func skipString(content string, start int) int {
quote := content[start]
for i := start + 1; i < len(content); i++ {
switch content[i] {
case '\\':
i++
case quote:
return i
}
}
return -1
}
// splitArgs splits a call body on top level commas.
func splitArgs(body string) []string {
var args []string
depth, start := 0, 0
for i := 0; i < len(body); i++ {
switch body[i] {
case '\'', '"':
end := skipString(body, i)
if end < 0 {
return args
}
i = end
case '(', '[', '{':
depth++
case ')', ']', '}':
depth--
case ',':
if depth == 0 {
args = append(args, strings.TrimSpace(body[start:i]))
start = i + 1
}
}
}
if last := strings.TrimSpace(body[start:]); last != "" {
args = append(args, last)
}
return args
}
func assignmentAfter(content string, paren int, name string) (string, bool) {
_, ok := balancedParens(content, paren)
if !ok {
return "", false
}
end := closingParen(content, paren)
rest := content[end+1:]
trimmed := strings.TrimLeft(rest, " \t\r\n")
if strings.HasPrefix(trimmed, "{") {
body, _, ok := block(trimmed, 0)
if !ok {
return "", false
}
for _, entry := range splitEntries(body) {
key, value, found := strings.Cut(entry, "=")
if found && strings.TrimSpace(key) == name {
return strings.TrimSpace(value), true
}
}
return "", false
}
if !strings.HasPrefix(trimmed, "."+name) {
return "", false
}
trimmed = strings.TrimLeft(trimmed[len(name)+1:], " \t\r\n")
if !strings.HasPrefix(trimmed, "=") || strings.HasPrefix(trimmed, "==") {
return "", false
}
match := assignmentValue.FindStringSubmatch(trimmed)
if match == nil {
return "", false
}
return strings.TrimSpace(match[1]), true
}
func unwrapValue(text string) (string, bool) {
text = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(text), ";"))
if value, ok := literalString(text); ok {
return value, true
}
open := strings.IndexByte(text, '(')
if open < 0 || closingParen(text, open) != len(text)-1 {
return "", false
}
callee := strings.TrimSpace(text[:open])
body, ok := balancedParens(text, open)
if !ok {
return "", false
}
arguments := splitArgs(body)
switch callee {
case "file", "project.file", "rootProject.file", "rootDir.resolve", "settingsDir.resolve":
if len(arguments) == 1 {
return literalString(arguments[0])
}
case "File", "new File":
if len(arguments) == 1 {
return literalString(arguments[0])
}
if len(arguments) == 2 && (arguments[0] == "rootDir" || arguments[0] == "settingsDir") {
return literalString(arguments[1])
}
}
return "", false
}
func closingParen(content string, start int) int {
depth := 0
for i := start; i < len(content); i++ {
switch content[i] {
case '\'', '"':
end := skipString(content, i)
if end < 0 {
return start
}
i = end
case '(':
depth++
case ')':
depth--
if depth == 0 {
return i
}
}
}
return start
}
// literalString unwraps a literal that spans all text.
func literalString(text string) (string, bool) {
text = strings.TrimSpace(text)
value, width, ok := readStringLiteral(text)
if !ok || width != len(text) {
return "", false
}
return value, true
}
// readStringLiteral reads a quoted string at the start of text and reports how
// many bytes it consumed, including both quotes.
func readStringLiteral(text string) (string, int, bool) {
if len(text) < 2 {
return "", 0, false
}
quote := text[0]
if quote != '\'' && quote != '"' {
return "", 0, false
}
for i := 1; i < len(text); i++ {
switch text[i] {
case '\\':
i++
case '\n':
return "", 0, false
case quote:
return text[1:i], i + 1, true
}
}
return "", 0, false
}
// block returns the body of the brace block whose opening brace is at offset.
func block(content string, offset int) (string, int, bool) {
if offset >= len(content) || content[offset] != '{' {
return "", offset, false
}
depth := 0
for i := offset; i < len(content); i++ {
switch content[i] {
case '\'', '"':
end := skipString(content, i)
if end < 0 {
return "", offset, false
}
i = end
case '{':
depth++
case '}':
depth--
if depth == 0 {
return content[offset+1 : i], offset + i + 1, true
}
}
}
return "", offset, false
}
// blockNamed returns the body of the first `name {` block found in content
// together with the offset of the body's first byte.
func blockNamed(content, name string) (string, int, bool) {
from := 0
for {
index := strings.Index(content[from:], name)
if index < 0 {
return "", 0, false
}
start := from + index
rest := content[start+len(name):]
trimmed := strings.TrimLeft(rest, " \t\r\n")
brace := start + len(name) + len(rest) - len(trimmed)
if strings.HasPrefix(trimmed, "{") {
body, _, ok := block(content, brace)
return body, brace + 1, ok
}
from = start + len(name)
}
}
// stripComments blanks out comments while preserving string literals and line
// structure, so commented out declarations are never mistaken for applied
// ones and reported line numbers stay correct.
func stripComments(content string) string {
out := []byte(content)
for i := 0; i < len(content); i++ {
switch content[i] {
case '\'', '"':
end := skipString(content, i)
if end < 0 {
return string(out)
}
i = end
case '/':
if i+1 >= len(content) {
continue
}
switch content[i+1] {
case '/':
for ; i < len(content) && content[i] != '\n'; i++ {
out[i] = ' '
}
case '*':
for ; i+1 < len(content) && !(content[i] == '*' && content[i+1] == '/'); i++ {
if content[i] != '\n' {
out[i] = ' '
}
}
}
}
}
return string(out)
}
// stringMask marks every byte that lies inside a string literal, so that text
// such as "build.release.platform" is never read as a Gradle declaration.
func stringMask(content string) []bool {
mask := make([]bool, len(content))
var quote byte
for i := 0; i < len(content); i++ {
switch {
case quote == 0 && (content[i] == '\'' || content[i] == '"'):
quote = content[i]
case quote != 0 && content[i] == '\\':
i++
case quote != 0 && content[i] == quote:
quote = 0
case quote != 0:
mask[i] = true
}
}
return mask
}
// inLiteral reports whether the byte at pos lies inside a string literal.
func inLiteral(mask []bool, pos int) bool {
return pos >= 0 && pos < len(mask) && mask[pos]
}
package buildrepo
import (
"fmt"
"strconv"
"strings"
"unicode/utf16"
)
// ParseProperties decodes Java-properties escapes and continued logical lines.
func ParseProperties(content string) (map[string]string, error) {
properties := make(map[string]string)
pending := ""
parse := func(line string) error {
line = strings.TrimLeft(line, " \t\f")
if line == "" || line[0] == '#' || line[0] == '!' {
return nil
}
end := 0
for end < len(line) {
if line[end] == '\\' {
end = min(end+2, len(line))
continue
}
if propertySpace(line[end]) || line[end] == '=' || line[end] == ':' {
break
}
end++
}
valueStart := end
for valueStart < len(line) && propertySpace(line[valueStart]) {
valueStart++
}
if valueStart < len(line) && (line[valueStart] == '=' || line[valueStart] == ':') {
valueStart++
}
for valueStart < len(line) && propertySpace(line[valueStart]) {
valueStart++
}
key, err := decodeProperty(line[:end])
if err != nil {
return err
}
value, err := decodeProperty(line[valueStart:])
if err != nil {
return fmt.Errorf("property %q: %w", key, err)
}
properties[key] = value
return nil
}
for raw := range strings.SplitSeq(content, "\n") {
line := strings.TrimSuffix(raw, "\r")
if pending != "" {
line = pending + strings.TrimLeft(line, " \t\f")
} else if trimmed := strings.TrimLeft(line, " \t\f"); trimmed != "" && (trimmed[0] == '#' || trimmed[0] == '!') {
// A comment line never continues, even when it ends with a
// backslash: "# e.g. C:\Tools\" must not swallow the property
// that follows it.
continue
}
trailing := 0
for i := len(line) - 1; i >= 0 && line[i] == '\\'; i-- {
trailing++
}
if trailing%2 != 0 {
pending = line[:len(line)-1]
continue
}
pending = ""
if err := parse(line); err != nil {
return nil, err
}
}
if err := parse(pending); err != nil {
return nil, err
}
return properties, nil
}
func propertySpace(char byte) bool {
return char == ' ' || char == '\t' || char == '\f'
}
func decodeProperty(text string) (string, error) {
if !strings.ContainsRune(text, '\\') {
return text, nil
}
var decoded strings.Builder
decoded.Grow(len(text))
for i := 0; i < len(text); i++ {
if text[i] != '\\' {
decoded.WriteByte(text[i])
continue
}
i++
if i == len(text) {
return "", fmt.Errorf("incomplete property escape")
}
switch text[i] {
case 't':
decoded.WriteByte('\t')
case 'r':
decoded.WriteByte('\r')
case 'n':
decoded.WriteByte('\n')
case 'f':
decoded.WriteByte('\f')
case 'u':
value, err := propertyUnicode(text[i+1:])
if err != nil {
return "", err
}
i += 4
if utf16.IsSurrogate(value) {
if !strings.HasPrefix(text[i+1:], `\u`) {
return "", fmt.Errorf("unpaired property unicode surrogate")
}
low, err := propertyUnicode(text[i+3:])
if err != nil {
return "", err
}
value = utf16.DecodeRune(value, low)
if value == '\uFFFD' {
return "", fmt.Errorf("invalid property unicode surrogate pair")
}
i += 6
}
decoded.WriteRune(value)
default:
decoded.WriteByte(text[i])
}
}
return decoded.String(), nil
}
func propertyUnicode(text string) (rune, error) {
if len(text) < 4 {
return 0, fmt.Errorf("incomplete property unicode escape")
}
value, err := strconv.ParseUint(text[:4], 16, 16)
if err != nil {
return 0, fmt.Errorf("invalid property unicode escape: %w", err)
}
return rune(value), nil
}
package buildrepo
import (
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
catalogpkg "github.com/mclucy/lucy/catalog"
)
var pluginEcosystems = []struct {
id string
ecos []catalogpkg.Ecosystem
multi bool
}{
{id: "dev.architectury.loom", multi: true},
{id: "architectury.loom", multi: true},
{id: "architectury-plugin", multi: true},
{id: "net.fabricmc.fabric-loom", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemFabric}},
{id: "net.fabricmc.fabric-loom-remap", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemFabric}},
{id: "fabric-loom", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemFabric}},
{id: "org.quiltmc.quilt-loom", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemQuilt}},
{id: "quilt-loom", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemQuilt}},
{id: "net.minecraftforge.gradle", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemForge}},
{id: "net.neoforged.moddev.legacyforge", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemForge}},
{id: "net.neoforged.moddev", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemNeoForge}},
{id: "net.neoforged.gradle.userdev", ecos: []catalogpkg.Ecosystem{catalogpkg.EcosystemNeoForge}},
}
var (
applyFalsePattern = regexp.MustCompile(`\bapply\s*\(?\s*false\b`)
idKeywordPattern = regexp.MustCompile(`\bid\b`)
applyPluginPattern = regexp.MustCompile(`\bapply\s*\(?\s*plugin\s*[:=]\s*`)
aliasPattern = regexp.MustCompile(`\balias\s*(?:\(\s*)?([A-Za-z0-9_.]+)\.plugins\.([A-Za-z0-9_.]+)`)
)
// pluginID reads the id declaration of a single plugins block entry. It
// returns the id and the remainder of the entry, which carries the version and
// any "apply false" modifier.
func pluginID(entry string) (string, string, bool) {
from := 0
for {
loc := idKeywordPattern.FindStringIndex(entry[from:])
if loc == nil {
return "", "", false
}
index := from + loc[1]
for index < len(entry) && isSpace(entry[index]) {
index++
}
if index < len(entry) && entry[index] == '(' {
index++
for index < len(entry) && isSpace(entry[index]) {
index++
}
}
if id, width, ok := readStringLiteral(entry[index:]); ok {
return id, entry[index+width:], true
}
from = index
}
}
func isSpace(char byte) bool {
return char == ' ' || char == '\t' || char == '\r' || char == '\n'
}
type appliedPlugin struct {
id string
line int
source string
}
func (p *prober) scriptEcosystems(file string, plugins []appliedPlugin) []catalogpkg.Ecosystem {
var out []catalogpkg.Ecosystem
for _, plugin := range plugins {
entry, ok := pluginByID(plugin.id)
if !ok {
continue
}
if entry.multi {
value, _ := p.propertyValue(filepath.Dir(file), "loom.platform")
platform := catalogpkg.Ecosystem(value)
switch platform {
case catalogpkg.EcosystemFabric, catalogpkg.EcosystemForge, catalogpkg.EcosystemNeoForge:
if !slices.Contains(out, platform) {
out = append(out, platform)
}
default:
p.findings.add(file, plugin.line, "plugin "+plugin.id+" requires platform configuration that was not resolved")
}
}
for _, eco := range entry.ecos {
if !slices.Contains(out, eco) {
out = append(out, eco)
}
}
}
slices.Sort(out)
return out
}
func pluginByID(id string) (struct {
id string
ecos []catalogpkg.Ecosystem
multi bool
}, bool,
) {
for _, entry := range pluginEcosystems {
if entry.id == id {
return entry, true
}
}
return pluginEcosystems[0], false
}
// appliedPlugins returns every plugin a script applies, resolving convention
// plugins from buildSrc and composite builds.
func (p *prober) appliedPlugins(file, content string, depth int) []appliedPlugin {
var out []appliedPlugin
seen := map[string]bool{}
mask := stringMask(content)
body, bodyStart, ok := blockNamed(content, "plugins")
if ok {
cursor := bodyStart
for _, item := range splitEntries(body) {
if item == "" || applyFalsePattern.MatchString(item) {
continue
}
rel := strings.Index(content[cursor:], item)
if rel < 0 {
continue
}
line := lineAt(content, cursor+rel)
cursor += rel + len(item)
id, rest, found := pluginID(item)
if found {
if !applyFalsePattern.MatchString(rest) {
p.appendPlugin(file, line, id, depth, seen, &out)
}
}
for _, match := range aliasPattern.FindAllStringSubmatchIndex(item, -1) {
catalog := item[match[2]:match[3]]
key := strings.ReplaceAll(item[match[4]:match[5]], ".", "-")
if catalog != "libs" {
p.findings.add(file, line, "plugin alias "+catalog+".plugins."+key+" uses a catalog that was not resolved")
continue
}
id, ok := p.catalogPluginID(key)
if !ok {
p.findings.add(file, line, "plugin alias libs.plugins."+key+" could not be resolved to a plugin id")
continue
}
p.appendPlugin(file, line, id, depth, seen, &out)
}
}
}
for _, match := range applyPluginPattern.FindAllStringIndex(content, -1) {
if inLiteral(mask, match[0]) {
continue
}
line := lineAt(content, match[0])
id, _, ok := readStringLiteral(content[match[1]:])
if !ok {
p.findings.add(file, line,
"apply plugin names a plugin class or expression instead of a literal plugin id; it was not resolved")
continue
}
p.appendPlugin(file, line, id, depth, seen, &out)
}
return out
}
// scriptSource is a build script contributing configuration to a project.
type scriptSource struct {
file string
content string
}
// appliedScriptSources returns the scripts contributing configuration to a
// project: the script that applies each plugin, plus the convention script
// that introduces the plugin. A convention script configures the project even
// when it applies no plugins of its own, so it counts regardless of whether
// any nested plugin records it as a source.
func (p *prober) appliedScriptSources(file string, plugins []appliedPlugin) []scriptSource {
seen := map[string]bool{file: true}
var out []scriptSource
add := func(path string) {
if seen[path] {
return
}
seen[path] = true
script, err := p.readFile(path)
if err != nil {
return
}
out = append(out, scriptSource{file: path, content: stripComments(script)})
}
for _, plugin := range plugins {
add(plugin.source)
if path, ok := p.conventionScript(plugin.id); ok {
add(path)
}
}
return out
}
// javaConfigOf merges the Java configuration of convention scripts and the
// project script itself; the project script wins.
func (p *prober) javaConfigOf(projectFile, content, buildDir string, sources []scriptSource) JavaRequirements {
var req JavaRequirements
for _, source := range append(sources, scriptSource{file: projectFile, content: content}) {
block := p.javaConfig(source.file, source.content, buildDir)
if block.Toolchain != nil {
req.Toolchain = block.Toolchain
}
if block.Release != nil {
req.Release = block.Release
}
if block.Source != nil {
req.Source = block.Source
}
if block.Target != nil {
req.Target = block.Target
}
}
return req
}
func (p *prober) appendPlugin(file string, line int, id string, depth int, seen map[string]bool, out *[]appliedPlugin) {
if seen[id] {
return
}
seen[id] = true
*out = append(*out, appliedPlugin{id: id, line: line, source: file})
if depth >= maxConventionDepth {
return
}
convention, ok := p.conventionScript(id)
if !ok {
return
}
content, err := p.readFile(convention)
if err != nil {
return
}
for _, nested := range p.appliedPlugins(convention, stripComments(content), depth+1) {
if seen[nested.id] {
continue
}
seen[nested.id] = true
*out = append(*out, appliedPlugin{id: nested.id, line: line, source: convention})
}
}
const maxConventionDepth = 8
func splitEntries(body string) []string {
var out []string
depth, start := 0, 0
for i := 0; i < len(body); i++ {
switch body[i] {
case '\'', '"':
end := skipString(body, i)
if end < 0 {
return out
}
i = end
case '(', '[', '{':
depth++
case ')', ']', '}':
depth--
case '\n', ';':
if depth == 0 {
out = append(out, strings.TrimSpace(body[start:i]))
start = i + 1
}
}
}
return append(out, strings.TrimSpace(body[start:]))
}
func (p *prober) indexConventions() {
for _, build := range p.builds {
for _, source := range conventionSourceDirs(build.Dir) {
p.indexConventionDir(source)
}
}
}
func (p *prober) indexConventionDir(source string) {
entries, err := os.ReadDir(source)
if err != nil {
return
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
path := filepath.Join(source, entry.Name())
if !p.contains(path) {
continue
}
id := strings.TrimSuffix(strings.TrimSuffix(entry.Name(), ".gradle.kts"), ".gradle")
if id == entry.Name() || id == "" {
continue
}
if _, exists := p.conventions[id]; !exists {
p.conventions[id] = path
}
}
}
func conventionSourceDirs(dir string) []string {
var out []string
for _, base := range []string{"buildSrc", "build-logic", "buildlogic"} {
root := filepath.Join(dir, base)
for _, src := range []string{
filepath.Join(root, "src", "main", "kotlin"),
filepath.Join(root, "src", "main", "groovy"),
} {
if info, err := os.Stat(src); err == nil && info.IsDir() {
out = append(out, src)
}
}
}
return out
}
func (p *prober) conventionScript(id string) (string, bool) {
path, ok := p.conventions[id]
return path, ok
}
func (p *prober) catalogPluginID(alias string) (string, bool) {
for _, key := range []string{alias, alias + "-plugin"} {
if id, ok := p.catalog[key]; ok {
return id, true
}
}
return "", false
}
func (p *prober) propertyValue(dir, key string) (string, bool) {
for {
if value, ok := p.propertiesOf(dir)[key]; ok {
return value, true
}
if dir == p.root || slices.ContainsFunc(p.builds, func(build GradleBuild) bool { return build.Dir == dir }) {
break
}
parent := filepath.Dir(dir)
if parent == dir || !p.contains(parent) {
break
}
dir = parent
}
return "", false
}
func (p *prober) propertiesOf(dir string) map[string]string {
if cached, ok := p.props[dir]; ok {
return cached
}
path := p.firstExisting(dir, "gradle.properties")
values := map[string]string{}
if path != "" {
if content, ok := p.readOptional(path); ok {
parsed, err := ParseProperties(content)
if err != nil {
p.findings.add(path, 0, "Gradle properties could not be decoded: "+err.Error())
} else {
values = parsed
}
}
}
p.props[dir] = values
return values
}
func (p *prober) javaConfig(file, content, dir string) JavaRequirements {
var req JavaRequirements
mask := stringMask(content)
for _, match := range javaVersionPattern.FindAllStringSubmatchIndex(content, -1) {
if inLiteral(mask, match[0]) {
continue
}
line := lineAt(content, match[0])
if req.Toolchain != nil {
continue
}
major, ok := p.resolveInt(file, dir, content[match[2]:match[3]], line)
if !ok {
continue
}
req.Toolchain = &JavaConstraint{Major: major}
}
req.Release = p.releaseFlag(file, content, dir, "release")
req.Source = p.releaseFlag(file, content, dir, "sourceCompatibility")
req.Target = p.releaseFlag(file, content, dir, "targetCompatibility")
return req
}
var javaVersionPattern = regexp.MustCompile(`JavaLanguageVersion\s*\.\s*of\s*\(([^)]*)\)`)
// releaseFlag resolves a javac level flag such as options.release,
// sourceCompatibility or targetCompatibility.
func (p *prober) releaseFlag(file, content, dir, name string) *int {
pattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`)
mask := stringMask(content)
for _, loc := range pattern.FindAllStringIndex(content, -1) {
if inLiteral(mask, loc[0]) {
continue
}
expr, ok := argumentAfter(content, loc[1])
if !ok {
continue
}
if value, ok := p.resolveInt(file, dir, expr, lineAt(content, loc[0])); ok {
return &value
}
}
return nil
}
// argumentAfter reads a value written as "name = <token>", "name(...)" or a
// dotted call chain such as "name.set(...)" following the byte offset from.
func argumentAfter(content string, from int) (string, bool) {
index := from
for range 8 {
for index < len(content) && isSpace(content[index]) {
index++
}
if index >= len(content) {
return "", false
}
switch {
case content[index] == '=' && (index+1 >= len(content) || content[index+1] != '='):
return firstToken(content[index+1:]), true
case content[index] == '.':
index++
case isIdentifierByte(content[index]):
for index < len(content) && isIdentifierByte(content[index]) {
index++
}
for index < len(content) && isSpace(content[index]) {
index++
}
if index >= len(content) || content[index] != '(' {
continue
}
body, ok := balancedParens(content, index)
if !ok {
return "", false
}
return strings.TrimSpace(body), true
default:
return "", false
}
}
return "", false
}
func isIdentifierByte(char byte) bool {
return char == '_' || char == '$' ||
(char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9')
}
func firstToken(text string) string {
text = strings.TrimSpace(text)
if idx := strings.IndexAny(text, " \t\r\n,;)}"); idx >= 0 {
return text[:idx]
}
return text
}
// resolveInt resolves a Java level written as a literal, a Gradle property
// reference or a catalog-free identifier.
func (p *prober) resolveInt(file, dir, expr string, line int) (int, bool) {
expr = strings.TrimSpace(expr)
// Unwrap accessors such as JavaLanguageVersion.of(x).asInt().
for range 4 {
open := strings.Index(expr, "(")
if open < 0 || !strings.HasSuffix(expr, ")") {
break
}
body, ok := balancedParens(expr, open)
if !ok {
break
}
expr = strings.TrimSpace(body)
}
expr = strings.TrimSpace(strings.TrimPrefix(expr, "project."))
expr = strings.TrimSpace(strings.TrimPrefix(expr, "rootProject."))
if value, ok := literalString(expr); ok {
expr = value
}
if major, err := strconv.Atoi(expr); err == nil {
return major, true
}
if version, ok := strings.CutPrefix(expr, "JavaVersion.VERSION_"); ok {
if major, err := strconv.Atoi(version); err == nil {
return major, true
}
}
if value, ok := p.propertyValue(dir, expr); ok {
if major, err := strconv.Atoi(strings.TrimSpace(value)); err == nil {
return major, true
}
p.findings.add(file, line, "Gradle property "+expr+"="+value+" is not a Java version")
return 0, false
}
p.findings.add(file, line, "Java version "+expr+" could not be resolved statically")
return 0, false
}
package buildrepo
import (
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
)
func (p *prober) discoverBuilds() error {
roots := make(map[string]bool)
buildDirectories := make([]string, 0)
err := filepath.WalkDir(p.root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if err := p.ctx.Err(); err != nil {
return err
}
if entry.IsDir() {
if path != p.root && skippedDirs[entry.Name()] {
return filepath.SkipDir
}
return nil
}
switch entry.Name() {
case "settings.gradle", "settings.gradle.kts":
if p.contains(path) {
roots[filepath.Dir(path)] = true
}
case "build.gradle", "build.gradle.kts":
if p.contains(path) {
buildDirectories = append(buildDirectories, filepath.Dir(path))
}
}
return nil
})
if err != nil {
return fmt.Errorf("buildrepo: scan %s: %w", p.root, err)
}
settingsDirectories := slices.Sorted(maps.Keys(roots))
for _, dir := range buildDirectories {
covered := false
for _, settingsDir := range settingsDirectories {
relative, err := filepath.Rel(settingsDir, dir)
if err == nil && filepath.IsLocal(relative) {
covered = true
break
}
}
if !covered || filepath.Base(dir) == "buildSrc" {
roots[dir] = true
}
}
pending := slices.Collect(maps.Keys(roots))
for len(pending) > 0 {
dir := pending[0]
pending = pending[1:]
if err := p.ctx.Err(); err != nil {
return err
}
settings := p.firstExisting(dir, "settings.gradle", "settings.gradle.kts")
for _, included := range p.includedBuildDirs(dir, settings) {
if !roots[included] {
roots[included] = true
pending = append(pending, included)
}
}
}
directories := slices.Sorted(maps.Keys(roots))
for _, dir := range directories {
p.builds = append(p.builds, GradleBuild{
Dir: dir, SettingsFile: p.firstExisting(dir, "settings.gradle", "settings.gradle.kts"),
BuildFile: p.firstExisting(dir, "build.gradle", "build.gradle.kts"),
})
}
return nil
}
func (p *prober) includedBuildDirs(dir, settings string) []string {
if settings == "" {
return nil
}
content, _ := p.readOptional(settings)
content = stripComments(content)
p.noteConditional(settings, content)
included := make([]string, 0)
for _, call := range slices.Concat(calls(content, "includeBuild"), groovyCalls(content, "includeBuild")) {
arguments, line := callArgs(content, call)
if len(arguments) == 0 {
continue
}
path, ok := literalString(arguments[0])
if !ok {
p.findings.add(settings, line, "includeBuild target is not a literal path; composite build not resolved")
continue
}
target := filepath.Join(dir, filepath.FromSlash(path))
if !p.contains(target) {
if _, err := os.Lstat(target); errors.Is(err, os.ErrNotExist) {
p.findings.add(settings, line, fmt.Sprintf("includeBuild %q is not present in the checkout", path))
} else {
p.findings.add(settings, line, fmt.Sprintf("includeBuild %q resolves outside the repository root", path))
}
continue
}
if !slices.Contains(included, target) {
included = append(included, target)
}
}
return included
}
func (p *prober) declaredProjects(dir, settings string) map[string]string {
projects := map[string]string{":": dir}
if settings == "" {
return projects
}
content, _ := p.readOptional(settings)
content = stripComments(content)
mappings := make(map[string]string)
renames := make(map[string]string)
unresolved := make(map[string]bool)
for _, call := range slices.Concat(calls(content, "include"), groovyCalls(content, "include")) {
arguments, line := callArgs(content, call)
for _, argument := range arguments {
name, ok := literalString(argument)
if !ok {
p.findings.add(settings, line, "include argument is not a literal project name; project set is incomplete")
continue
}
path := gradlePathOf(name)
for path != "" && path != ":" {
if _, exists := projects[path]; !exists {
projects[path] = ""
}
path, _, _ = strings.CutLast(path, ":")
}
}
}
for _, call := range slices.Concat(calls(content, "project"), groovyCalls(content, "project")) {
arguments, line := callArgs(content, call)
if len(arguments) == 0 {
continue
}
path, ok := literalString(arguments[0])
if !ok || !strings.HasPrefix(path, ":") {
continue
}
if assignment, ok := assignmentAfter(content, call, "projectDir"); ok {
value, resolved := unwrapValue(assignment)
if !resolved {
p.findings.add(settings, line, "project "+path+" projectDir is not a literal path")
unresolved[path] = true
continue
}
mappings[path] = value
}
if assignment, ok := assignmentAfter(content, call, "name"); ok {
name, resolved := literalString(assignment)
if resolved && name != "" && !strings.Contains(name, ":") {
parent, _, _ := strings.CutLast(path, ":")
renames[path] = parent + ":" + name
} else {
p.findings.add(settings, line, "project "+path+" name is not a literal; final project path is unknown")
}
}
}
for path := range projects {
if path == ":" {
continue
}
if unresolved[path] {
projects[path] = ""
continue
}
physical := strings.ReplaceAll(strings.TrimPrefix(path, ":"), ":", "/")
if mapped, ok := mappings[path]; ok {
physical = mapped
}
if filepath.IsAbs(physical) {
projects[path] = filepath.Clean(physical)
} else {
projects[path] = filepath.Join(dir, filepath.FromSlash(physical))
}
}
for _, original := range slices.SortedFunc(maps.Keys(renames), func(a, b string) int {
return len(b) - len(a)
}) {
renamed := renames[original]
if original == renamed {
continue
}
for path, physical := range projects {
if path == original || strings.HasPrefix(path, original+":") {
target := renamed + strings.TrimPrefix(path, original)
if _, exists := projects[target]; exists {
p.findings.add(settings, 0, "project rename collides with "+target)
continue
}
delete(projects, path)
projects[target] = physical
}
}
}
return projects
}
func gradlePathOf(name string) string {
name = ":" + strings.Trim(strings.TrimSpace(name), ":")
if name == ":" || strings.Contains(name, "::") {
return ""
}
return name
}
// Package cipher provides runtime decryption for embedded secrets.
// Designed to deter casual extraction, not provide complete security.
//
// Build-time material is split into four linker fragments and optionally bound
// to a release identity (version + commit) via AEAD associated data.
package cipher
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"golang.org/x/crypto/chacha20poly1305"
)
// Linker-injected material. Set only via -X at build time; never set in source.
var (
keyA string
keyB string
ciphertextA string
ciphertextB string
// Public release identity used as AEAD associated data.
// Both empty = local unbound material; both set = tagged release.
releaseVersion string
releaseCommit string
)
// Fixed domain separator for associated data. Bump if the AD format changes.
const adDomain = "lucy-cipher-v1"
// Decode decrypts the embedded ciphertext and returns the plaintext API key.
//
// Empty embedding (all four fragments empty) returns ("", nil).
// Partial material, bad hex, wrong key length, incomplete identity, or
// ciphertext that is too short returns an error (never panics).
func Decode() (string, error) {
if keyA == "" && keyB == "" && ciphertextA == "" && ciphertextB == "" {
return "", nil
}
if keyA == "" || keyB == "" || ciphertextA == "" || ciphertextB == "" {
return "", errors.New("cipher: partial embedded material")
}
keyBytes, err := hex.DecodeString(keyA + keyB)
if err != nil {
return "", fmt.Errorf("cipher: malformed key hex: %w", err)
}
if len(keyBytes) != chacha20poly1305.KeySize {
return "", errors.New("cipher: incorrect key length")
}
data, err := hex.DecodeString(ciphertextA + ciphertextB)
if err != nil {
return "", fmt.Errorf("cipher: malformed ciphertext hex: %w", err)
}
ad, err := associatedData(releaseVersion, releaseCommit)
if err != nil {
return "", err
}
aead, err := chacha20poly1305.NewX(keyBytes)
if err != nil {
return "", err
}
if len(data) < aead.NonceSize() {
return "", errors.New("cipher: ciphertext too short")
}
nonce := data[:aead.NonceSize()]
ct := data[aead.NonceSize():]
plaintext, err := aead.Open(nil, nonce, ct, ad)
if err != nil {
return "", err
}
return string(plaintext), nil
}
// GenerateKey returns a fresh 32-byte key from crypto/rand.
func GenerateKey() ([]byte, error) {
key := make([]byte, chacha20poly1305.KeySize)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return nil, fmt.Errorf("cipher: generate key: %w", err)
}
return key, nil
}
// Encrypt encrypts plaintext with key, binding associated data for version and
// commit. Both identity fields must be empty (local unbound) or both nonempty
// (tagged release). Returns hex(nonce || ciphertext).
func Encrypt(key []byte, plaintext, version, commit string) (string, error) {
if len(key) != chacha20poly1305.KeySize {
return "", errors.New("cipher: incorrect key length")
}
ad, err := associatedData(version, commit)
if err != nil {
return "", err
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return "", err
}
nonce := make([]byte, aead.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("cipher: read nonce: %w", err)
}
ct := aead.Seal(nil, nonce, []byte(plaintext), ad)
out := make([]byte, 0, len(nonce)+len(ct))
out = append(out, nonce...)
out = append(out, ct...)
return hex.EncodeToString(out), nil
}
// associatedData builds the canonical AD sequence:
//
// lucy-cipher-v1 \0 <version> \0 <commit>
func associatedData(version, commit string) ([]byte, error) {
vEmpty := version == ""
cEmpty := commit == ""
if vEmpty != cEmpty {
return nil, errors.New("cipher: incomplete release identity")
}
n := len(adDomain) + 1 + len(version) + 1 + len(commit)
ad := make([]byte, 0, n)
ad = append(ad, adDomain...)
ad = append(ad, 0)
ad = append(ad, version...)
ad = append(ad, 0)
ad = append(ad, commit...)
return ad, nil
}
package cli
import (
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/operation"
"github.com/spf13/cobra"
)
const (
flagWithOptionalName = "with-optional"
flagLockedName = "locked"
flagOfflineName = "offline"
flagDowngradeName = "downgrade"
flagForceName = "force"
)
func NewAddCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: help.AddShort,
Args: cobra.MinimumNArgs(1),
Aliases: []string{"a"},
PreRunE: func(cmd *cobra.Command, args []string) error {
ecosystem, _ := cmd.Flags().GetString(FlagEcosystem)
if ecosystem != "" && !catalog.Ecosystem(ecosystem).Valid() {
return fmt.Errorf("invalid ecosystem %q", ecosystem)
}
return validateAddDowngradeFlags(cmd, args)
},
RunE: func(cmd *cobra.Command, args []string) error {
return actionAdd(cmd, inv, deps, args)
},
}
installJSON.Bind(contracts, cmd)
cmd.Flags().Bool(
flagWithOptionalName,
false,
"Also install optional upstream dependencies",
)
cmd.Flags().Bool(
flagLockedName,
false,
"Do not resolve new versions; fail when the lock cannot satisfy",
)
cmd.Flags().Bool(
flagOfflineName,
false,
"Disallow network access; fail if a needed file is not already available locally",
)
cmd.Flags().Int(
flagDowngradeName,
0,
"Step back N versions from the locked version; --downgrade=N, default 1",
)
cmd.Flags().Lookup(flagDowngradeName).NoOptDefVal = "1"
cmd.Flags().Bool(
flagForceName,
false,
"Commit the downgrade despite package conflicts (requires --downgrade)",
)
AddEcosystemFlag(cmd)
return cmd
}
func validateAddDowngradeFlags(cmd *cobra.Command, args []string) error {
force, _ := cmd.Flags().GetBool(flagForceName)
if !cmd.Flags().Changed(flagDowngradeName) {
if force {
return fmt.Errorf("--%s requires --%s", flagForceName, flagDowngradeName)
}
return nil
}
steps, _ := cmd.Flags().GetInt(flagDowngradeName)
if steps < 1 {
return fmt.Errorf("--%s needs a positive step count", flagDowngradeName)
}
if locked, _ := cmd.Flags().GetBool(flagLockedName); locked {
return fmt.Errorf(
"--%s cannot be combined with --%s",
flagDowngradeName,
flagLockedName,
)
}
if offline, _ := cmd.Flags().GetBool(flagOfflineName); offline {
return fmt.Errorf(
"--%s cannot be combined with --%s",
flagDowngradeName,
flagOfflineName,
)
}
for _, raw := range args {
if strings.ContainsRune(raw, '@') {
return fmt.Errorf(
"--%s does not accept a version selector: %q",
flagDowngradeName,
raw,
)
}
}
return nil
}
func actionAdd(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
withOptional, _ := cmd.Flags().GetBool(flagWithOptionalName)
locked, _ := cmd.Flags().GetBool(flagLockedName)
offline, _ := cmd.Flags().GetBool(flagOfflineName)
force, _ := cmd.Flags().GetBool(flagForceName)
downgrade := cmd.Flags().Changed(flagDowngradeName)
steps, _ := cmd.Flags().GetInt(flagDowngradeName)
ecosystem, _ := cmd.Flags().GetString(FlagEcosystem)
opts := install.Options{
Locked: locked,
Offline: offline,
WithOptional: withOptional,
PublishManifest: false,
}
output := newInstallOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
ctx, stop := CommandContext(cmd)
defer stop()
var (
result *install.Result
err error
)
if downgrade {
result, err = deps.Operations.Downgrade(
ctx,
inv.Directory,
args,
catalog.Ecosystem(ecosystem),
operation.DowngradeOptions{
Steps: steps,
AcceptPackageConflicts: force,
Install: opts,
},
)
} else {
result, err = deps.Operations.Add(
ctx,
inv.Directory,
args,
catalog.Ecosystem(ecosystem),
opts,
)
}
if err != nil {
return output.Failure(err)
}
return output.Render(result)
}
package cli
import (
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/internal/bisect"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/depgraph"
"github.com/spf13/cobra"
)
// bisectJSON is the shared machine-readable result of every bisect leaf: they
// all report progress through bisectOutput.
var bisectJSON JSONResult[bisectOutput]
func NewBisectCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
bisectStartCmd := &cobra.Command{
Use: "start",
Short: help.BisectStartShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionBisectStart(cmd, inv, deps, args)
},
}
bisectGoodCmd := &cobra.Command{
Use: "good",
Short: help.BisectGoodShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionBisectGood(cmd, inv, deps, args)
},
}
bisectBadCmd := &cobra.Command{
Use: "bad",
Short: help.BisectBadShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionBisectBad(cmd, inv, deps, args)
},
}
bisectStatusCmd := &cobra.Command{
Use: "status",
Short: help.BisectStatusShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionBisectStatus(cmd, inv, deps, args)
},
}
bisectResetCmd := &cobra.Command{
Use: "reset",
Short: help.BisectResetShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionBisectReset(cmd, inv, deps, args)
},
}
bisectCmd := &cobra.Command{
Use: "bisect",
Short: help.BisectShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
MarkHelpOnly(bisectCmd)
bisectJSON.Bind(contracts, bisectStartCmd)
bisectJSON.Bind(contracts, bisectGoodCmd)
bisectJSON.Bind(contracts, bisectBadCmd)
bisectJSON.Bind(contracts, bisectStatusCmd)
bisectJSON.Bind(contracts, bisectResetCmd)
bisectCmd.AddCommand(
bisectStartCmd,
bisectGoodCmd,
bisectBadCmd,
bisectStatusCmd,
bisectResetCmd,
)
return bisectCmd
}
type bisectOutput struct {
Message string `json:"message"`
Phase bisect.Phase `json:"phase,omitempty"`
Pending bisect.Step `json:"pending,omitempty"`
Complete bool `json:"complete"`
Found *bisect.Mod `json:"found,omitempty"`
State *bisect.View `json:"state,omitempty"`
Enabled int `json:"enabled"`
Disabled int `json:"disabled"`
Restored int `json:"restored"`
Warnings []string `json:"warnings,omitempty"`
}
// reportBisectFindings renders the live observation candidate selection
// consumed and returns its warnings for the result document.
func reportBisectFindings(
cmd *cobra.Command,
inv *Invocation,
findings depgraph.Findings,
) []string {
if findings.Observation == nil {
return nil
}
output := NewOperationOutput(cmd, inv)
reportObservationFindings(findings.Observation, output)
return output.Warnings()
}
func bisectOutputFrom(result bisect.Result) bisectOutput {
return bisectOutput{
Phase: result.Phase,
Pending: result.Pending,
Complete: result.Complete,
Found: result.Found,
State: result.State,
Enabled: result.Enabled,
Disabled: result.Disabled,
Restored: result.Restored,
Warnings: result.Warnings,
}
}
func outputBisect(
cmd *cobra.Command,
inv *Invocation,
view bisectOutput,
) error {
output := NewOperationOutput(cmd, inv)
if cmd.Name() == "status" && cmd.Parent() != nil && cmd.Parent().Name() == "bisect" {
output = NewQueryOutput(cmd, inv)
}
if output.JSON() {
return bisectJSON.Write(output, view)
}
if _, err := fmt.Fprintln(output.Human(), formatBisectOutput(view)); err != nil {
return err
}
for _, warning := range view.Warnings {
output.Warn(errors.New(warning))
}
return nil
}
func formatBisectOutput(output bisectOutput) string {
var builder strings.Builder
builder.WriteString("Bisect: ")
builder.WriteString(output.Message)
builder.WriteByte('\n')
if output.State != nil {
builder.WriteString(
fmt.Sprintf(
"Range: [%d, %d]\n",
output.State.Left,
output.State.Right,
),
)
builder.WriteString(
fmt.Sprintf(
"Remaining: %d of %d\n",
output.State.Remaining,
output.State.Total,
),
)
if output.State.Candidate != nil {
builder.WriteString(
fmt.Sprintf(
"Candidate: %s (midpoint %d)\n",
output.State.Candidate.Label(),
output.State.Midpoint,
),
)
}
}
if output.Found != nil {
builder.WriteString("Bad package: ")
builder.WriteString(output.Found.Label())
builder.WriteByte('\n')
}
if output.Enabled > 0 || output.Disabled > 0 || output.Restored > 0 {
builder.WriteString(
fmt.Sprintf(
"Changed: enabled %d, disabled %d, restored %d\n",
output.Enabled,
output.Disabled,
output.Restored,
),
)
}
if output.Pending == bisect.StepReset {
builder.WriteString("Pending: rerun `lucy bisect reset` to complete the interrupted reset.\n")
} else if output.Pending != "" {
builder.WriteString(
fmt.Sprintf(
"Pending: rerun `lucy bisect %s` to complete the interrupted transition or `lucy bisect reset` to abandon the session.\n",
output.Pending,
),
)
}
if !output.Complete && output.Pending == "" && output.State != nil && output.State.Candidate != nil {
builder.WriteString("Start the server, test it, then run `lucy bisect good` or `lucy bisect bad`.")
}
return strings.TrimRight(builder.String(), "\n")
}
// bisectTransitionMessage names the outcome of the transition a leaf
// completed.
func bisectTransitionMessage(step bisect.Step, result bisect.Result) string {
switch step {
case bisect.StepStart:
return "session started"
case bisect.StepGood:
if result.Phase == bisect.PhaseExhausted {
return "all remaining packages are good; no bad package found"
}
if result.Marked != nil {
return fmt.Sprintf("marked %s good", result.Marked.Label())
}
case bisect.StepBad:
if result.Phase == bisect.PhaseFound {
return "found bad package"
}
if result.Marked != nil {
return fmt.Sprintf("marked %s bad", result.Marked.Label())
}
case bisect.StepReset:
return "session reset"
}
return "unknown transition"
}
// bisectStatusMessage names the observed session state.
func bisectStatusMessage(result bisect.Result) string {
if result.Pending != "" {
return fmt.Sprintf("session interrupted during %s", result.Pending)
}
switch result.Phase {
case bisect.PhaseFound:
return "session complete: bad package identified"
case bisect.PhaseExhausted:
return "session complete: no bad package found"
default:
return "session active"
}
}
func actionBisectStart(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
result, err := bisect.Start(
ctx,
inv.Directory,
inv.Logger,
deps.Operations,
deps.Router.ResolveArtifactsByHash,
)
warnings := reportBisectFindings(cmd, inv, result.Findings)
if err != nil {
return err
}
if result.NoCandidates {
return outputBisect(
cmd,
inv,
bisectOutput{
Message: "no enabled package requirements found in this manifest",
Complete: true,
Warnings: warnings,
},
)
}
result.Warnings = append(warnings, result.Warnings...)
output := bisectOutputFrom(result)
output.Message = bisectTransitionMessage(bisect.StepStart, result)
return outputBisect(cmd, inv, output)
}
func actionBisectGood(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
result, err := bisect.Good(
ctx,
inv.Directory,
inv.Logger,
deps.Operations,
)
if err != nil {
return err
}
output := bisectOutputFrom(result)
output.Message = bisectTransitionMessage(bisect.StepGood, result)
return outputBisect(cmd, inv, output)
}
func actionBisectBad(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
result, err := bisect.Bad(
ctx,
inv.Directory,
inv.Logger,
deps.Operations,
)
if err != nil {
return err
}
output := bisectOutputFrom(result)
output.Message = bisectTransitionMessage(bisect.StepBad, result)
return outputBisect(cmd, inv, output)
}
func actionBisectStatus(
cmd *cobra.Command,
inv *Invocation,
_ *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
result, err := bisect.Status(ctx, inv.Directory)
if err != nil {
return err
}
output := bisectOutputFrom(result)
output.Message = bisectStatusMessage(result)
return outputBisect(cmd, inv, output)
}
func actionBisectReset(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
result, err := bisect.Reset(
ctx,
inv.Directory,
inv.Logger,
deps.Operations,
)
if err != nil {
return err
}
output := bisectOutputFrom(result)
output.Message = "session reset"
return outputBisect(cmd, inv, output)
}
package cli
import (
"fmt"
"io"
"slices"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
// cacheLsJSON is the machine-readable `cache ls` result: every cached entry.
var cacheLsJSON JSONResult[[]*cache.Entry]
// cacheClearJSON is the machine-readable `cache clear` result.
var cacheClearJSON JSONResult[cache.ResetReport]
func NewCacheCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cacheLsCmd := &cobra.Command{
Use: "ls",
Aliases: []string{"list"},
Short: help.CacheLsShort,
RunE: func(cmd *cobra.Command, args []string) error {
return actionCacheLs(cmd, inv, deps, args)
},
}
cacheClearCmd := &cobra.Command{
Use: "clear",
Aliases: []string{"rm"},
Short: help.CacheClearShort,
RunE: func(cmd *cobra.Command, args []string) error {
return actionCacheClear(cmd, inv, deps, args)
},
}
cacheCmd := &cobra.Command{
Use: "cache",
Short: help.CacheShort,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
MarkHelpOnly(cacheCmd)
cacheLsJSON.Bind(contracts, cacheLsCmd)
cacheClearJSON.Bind(contracts, cacheClearCmd)
cacheCmd.AddCommand(cacheLsCmd, cacheClearCmd)
return cacheCmd
}
func actionCacheLs(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
output := NewQueryOutput(cmd, inv)
entries := deps.Network.All()
if output.JSON() {
return cacheLsJSON.Write(output, entries)
}
if len(entries) == 0 {
_, err := fmt.Fprintln(output.Human(), "Cache is empty")
return err
}
slices.SortFunc(entries, func(a, b *cache.Entry) int {
return b.CreatedAt.Compare(a.CreatedAt)
})
facts := make([]terminal.Fact, 0, len(entries)+1)
facts = append(facts, terminal.Fact{
Key: "Cache",
Value: fmt.Sprintf("%d entries", len(entries)),
})
for _, entry := range entries {
facts = append(facts, terminal.Fact{
Key: entry.Key,
Value: fmt.Sprintf(
"%s %s %s",
entry.Kind,
style.FormatBytesBinary(entry.Size),
inv.Theme.Muted(style.FormatTTL(entry.Expiration)),
),
})
}
return output.Document(func(out io.Writer, screen style.Terminal) error {
_, err := fmt.Fprintln(
out,
terminal.RenderFacts(facts, screen.Width, inv.Theme),
)
return err
})
}
func actionCacheClear(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
output := NewOperationOutput(cmd, inv)
cleared, err := deps.Network.ClearAll()
if err != nil {
return fmt.Errorf("failed to clear cache: %w", err)
}
if output.JSON() {
return cacheClearJSON.Write(output, cleared)
}
// The cache backend only collects the successful removals; the command
// presents them, in the order the reset walked the cache directory.
out := output.Human()
for _, removed := range cleared.Removed {
if _, err := fmt.Fprintf(out, "removed %s\n", removed); err != nil {
return err
}
}
_, err = fmt.Fprintf(
out,
"all cache items cleared\nremoved %d files, freed up %s of space\n",
cleared.FileCount,
style.FormatBytesBinary(cleared.TotalFreedSize),
)
return err
}
package cli
import (
"context"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/spf13/cobra"
)
type CompletionCandidate struct {
Value string
Description string
}
// FilterByPrefix keeps candidates whose Value starts with prefix,
// matching case-insensitively.
func FilterByPrefix(
candidates []CompletionCandidate,
prefix string,
) []CompletionCandidate {
if prefix == "" {
return candidates
}
lower := strings.ToLower(prefix)
var out []CompletionCandidate
for _, c := range candidates {
if strings.HasPrefix(strings.ToLower(c.Value), lower) {
out = append(out, c)
}
}
return out
}
// ToCobraCompletions formats candidates as cobra's "value\tDescription" lines.
func ToCobraCompletions(candidates []CompletionCandidate) []string {
out := make([]string, 0, len(candidates))
for _, c := range candidates {
if c.Description != "" {
out = append(out, c.Value+"\t"+c.Description)
} else {
out = append(out, c.Value)
}
}
return out
}
func StaticStatusLogoCandidates() []CompletionCandidate {
return []CompletionCandidate{
{Value: "small", Description: "Compact logo (default)"},
{Value: "none", Description: "Hide the logo"},
{Value: "large", Description: "Full-size logo"},
}
}
// StaticSearchEcosystemCandidates lists the ecosystems offered in the search rollout.
func StaticSearchEcosystemCandidates() []CompletionCandidate {
return []CompletionCandidate{
{Value: catalog.EcosystemFabric.String(), Description: "Fabric mods"},
{Value: catalog.EcosystemQuilt.String(), Description: "Quilt mods"},
{Value: catalog.EcosystemForge.String(), Description: "Forge mods"},
{Value: catalog.EcosystemNeoForge.String(), Description: "NeoForge mods"},
{Value: catalog.EcosystemBukkit.String(), Description: "Bukkit/Spigot plugins"},
{Value: catalog.EcosystemPaper.String(), Description: "Paper plugins"},
}
}
func StaticSearchRegistryCandidates() []CompletionCandidate {
return []CompletionCandidate{
{Value: catalog.RegistryModrinth.String(), Description: "Modrinth"},
{Value: catalog.RegistryCurseForge.String(), Description: "CurseForge"},
{Value: catalog.RegistryHangar.String(), Description: "Hangar"},
{Value: catalog.RegistrySpiget.String(), Description: "Spiget"},
{Value: catalog.RegistryMCDR.String(), Description: "MCDR Plugin Catalogue"},
}
}
func StaticVersionCandidates() []CompletionCandidate {
return []CompletionCandidate{
{Value: "any", Description: "Latest version, any stability (default)"},
{Value: "stable", Description: "Latest stable release, no betas"},
{Value: "beta", Description: "Latest version, allow pre-releases"},
}
}
// LockCandidates lists the package references the current lock resolves, with
// their versions.
func LockCandidates(root string) []CompletionCandidate {
lock, err := document.LockFile(root).Read()
if err != nil {
return nil
}
out := make([]CompletionCandidate, 0, len(lock.Packages))
for _, pkg := range lock.Packages {
reference := pkg.Provider.String() + ":" + pkg.ProjectID
description := string(pkg.Environment) + "/" + pkg.Ecosystem.String() + " " + pkg.Version.String()
out = append(out, CompletionCandidate{
Value: reference,
Description: description,
})
}
return out
}
// ResolveLockReference resolves a native module name to the single manifest
// reference the current lock binds it to. An empty result means the lock
// resolves no such package; an error means the name is ambiguous and the
// caller must supply an explicit "provider:project".
func ResolveLockReference(root, name string) (string, error) {
lock, err := document.LockFile(root).Read()
if err != nil {
return "", nil
}
return lock.LookupReference(name)
}
// CompletePackageIDSuggestions completes a "provider:project@version" token
// for the invocation workspace.
func CompletePackageIDSuggestions(
_ context.Context,
root string,
token string,
) ([]string, cobra.ShellCompDirective) {
_, name, version, segment := ParseCompletionToken(token)
switch segment {
case "version":
candidates := FilterByPrefix(StaticVersionCandidates(), version)
return ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
case "name":
candidates := FilterByPrefix(LockCandidates(root), name)
return ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
default:
return nil, cobra.ShellCompDirectiveNoFileComp
}
}
// ParseCompletionToken parses a partial "provider:project@version" completion
// token. Target ecosystem is selected by --ecosystem, not package syntax.
func ParseCompletionToken(token string) (provider, name, version, segment string) {
provider = "auto"
beforeVersion := token
if before, after, ok := strings.Cut(token, "@"); ok {
beforeVersion = before
version = after
segment = "version"
}
if before, after, ok := strings.Cut(beforeVersion, ":"); ok {
provider = before
name = after
if segment == "" {
segment = "name"
}
return
}
name = beforeVersion
if segment == "" {
segment = "name"
}
return
}
package cli
import (
"fmt"
"io"
"github.com/mclucy/lucy/config"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
"go.yaml.in/yaml/v4"
)
const (
flagConfigGlobalName = "global"
flagConfigForceName = "force"
flagConfigNoCommentsName = "no-comments"
)
// configValuesJSON, configJavaJSON, configGitHubJSON, configCurseForgeJSON,
// and configStringJSON are the shapes `lucy config get` prints: a whole layer,
// a section, or a scalar leaf.
var (
configValuesJSON JSONResult[*config.Values]
configJavaJSON JSONResult[config.Java]
configGitHubJSON JSONResult[config.GitHub]
configCurseForgeJSON JSONResult[config.CurseForge]
configStringJSON JSONResult[string]
)
// configWriteJSON is the machine-readable result of `lucy config set` and
// `lucy config create`.
var configWriteJSON JSONResult[*config.WriteResult]
func NewConfigCommand(
contracts *JSONContracts,
inv *Invocation,
_ *Dependencies,
) *cobra.Command {
configGetCmd := &cobra.Command{
Use: "get [key]",
Short: help.ConfigGetShort,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionConfigGet(cmd, inv, args)
},
}
configSetCmd := &cobra.Command{
Use: "set <key> <value>",
Short: help.ConfigSetShort,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return actionConfigSet(cmd, inv, args)
},
}
configCreateCmd := &cobra.Command{
Use: "create",
Short: help.ConfigCreateShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return actionConfigCreate(cmd, inv)
},
}
configCmd := &cobra.Command{
Use: "config",
Short: help.ConfigShort,
}
configValuesJSON.Bind(contracts, configGetCmd)
configJavaJSON.Bind(contracts, configGetCmd)
configGitHubJSON.Bind(contracts, configGetCmd)
configCurseForgeJSON.Bind(contracts, configGetCmd)
configStringJSON.Bind(contracts, configGetCmd)
configWriteJSON.Bind(contracts, configSetCmd)
configWriteJSON.Bind(contracts, configCreateCmd)
configCmd.PersistentFlags().Bool(
flagConfigGlobalName,
false,
"Use the global configuration instead of the workspace configuration",
)
configCreateCmd.Flags().BoolP(
flagConfigForceName,
"f",
false,
"Overwrite an existing configuration file",
)
configCreateCmd.Flags().Bool(
flagConfigNoCommentsName,
false,
"Write the configuration without explanatory comments",
)
configCmd.AddCommand(configGetCmd, configSetCmd, configCreateCmd)
return configCmd
}
func actionConfigGet(
cmd *cobra.Command,
inv *Invocation,
args []string,
) error {
service, err := newConfigService(inv)
if err != nil {
return err
}
key := ""
if len(args) == 1 {
key = args[0]
}
value, err := service.Get(key, configScope(cmd))
if err != nil {
return err
}
if !config.Secret(key) {
value = config.Redacted(value)
}
output := NewQueryOutput(cmd, inv)
if output.JSON() {
return writeConfigJSON(output, value)
}
return output.Document(func(out io.Writer, _ style.Terminal) error {
return writeConfigValue(out, key, value)
})
}
// writeConfigJSON writes the shape the selected key produced.
func writeConfigJSON(output *Output, value any) error {
switch value := value.(type) {
case *config.Values:
return configValuesJSON.Write(output, value)
case config.Java:
return configJavaJSON.Write(output, value)
case config.GitHub:
return configGitHubJSON.Write(output, value)
case config.CurseForge:
return configCurseForgeJSON.Write(output, value)
case string:
return configStringJSON.Write(output, value)
default:
return fmt.Errorf("unsupported config value type %T", value)
}
}
func actionConfigSet(
cmd *cobra.Command,
inv *Invocation,
args []string,
) error {
service, err := newConfigService(inv)
if err != nil {
return err
}
key, value := args[0], args[1]
result, err := service.Set(key, value, configScope(cmd))
if err != nil {
return err
}
inv.Logger.Info(
"configuration updated",
"path", result.Path,
"key", key,
"scope", configScopeLabel(cmd),
"created", result.Created,
)
output := NewOperationOutput(cmd, inv)
if output.JSON() {
return configWriteJSON.Write(output, result)
}
out := output.Human()
if result.Created {
if _, err := fmt.Fprintf(out, "Created %s\n", result.Path); err != nil {
return err
}
}
shown := value
if config.Secret(key) && shown != "" {
shown = config.RedactedValue
}
_, err = fmt.Fprintf(out, "Set %s to %s\n", key, shown)
return err
}
func actionConfigCreate(cmd *cobra.Command, inv *Invocation) error {
service, err := newConfigService(inv)
if err != nil {
return err
}
force, err := cmd.Flags().GetBool(flagConfigForceName)
if err != nil {
return err
}
noComments, err := cmd.Flags().GetBool(flagConfigNoCommentsName)
if err != nil {
return err
}
result, err := service.Create(
configScope(cmd),
config.CreateOptions{Force: force, NoComments: noComments},
)
if err != nil {
return err
}
inv.Logger.Info(
"configuration written",
"path", result.Path,
"scope", configScopeLabel(cmd),
"created", result.Created,
)
output := NewOperationOutput(cmd, inv)
if output.JSON() {
return configWriteJSON.Write(output, result)
}
verb := "Wrote"
if result.Created {
verb = "Created"
}
_, err = fmt.Fprintf(output.Human(), "%s %s\n", verb, result.Path)
return err
}
func newConfigService(inv *Invocation) (*config.Service, error) {
return config.New(inv.Directory, inv.Logger)
}
func configScopeLabel(cmd *cobra.Command) string {
if configScope(cmd) == config.GlobalScope {
return "global"
}
return "workspace"
}
func configScope(cmd *cobra.Command) config.Scope {
global, _ := cmd.Flags().GetBool(flagConfigGlobalName)
if global {
return config.GlobalScope
}
return config.WorkspaceScope
}
// writeConfigValue renders the value of a key for people: scalar values print
// verbatim, while a section prints as YAML. The whole effective configuration
// also prints as YAML.
func writeConfigValue(out io.Writer, key string, value any) error {
if key != "" {
switch value := value.(type) {
case nil:
_, err := fmt.Fprintln(out)
return err
case string:
_, err := fmt.Fprintln(out, value)
return err
}
}
data, err := yaml.Marshal(value)
if err != nil {
return fmt.Errorf("encode configuration: %w", err)
}
_, err = out.Write(data)
return err
}
package cli
import (
"context"
"github.com/spf13/cobra"
)
// CommandContext derives the command's context. Signal handling belongs to
// the process boundary, which cancels the context the root was executed
// with.
func CommandContext(cmd *cobra.Command) (context.Context, context.CancelFunc) {
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
return context.WithCancel(ctx)
}
package cli
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/javainstall"
"github.com/mclucy/lucy/operation"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/upstream/routing"
"github.com/mclucy/lucy/version"
"github.com/spf13/cobra"
)
const (
flagCreateForceName = "force"
flagCreateCoreName = "core"
flagCreateCoreVersionName = "core-version"
flagCreateMcName = "minecraft"
flagCreateMCDRVersionName = "mcdr-version"
flagCreateDirectoryName = "directory"
flagCreateNameName = "name"
flagCreateInstallName = "install"
flagCreateNoInstallName = "no-install"
flagCreateJavaName = "java"
flagCreateJavaRepoName = "add-java-repository"
createProductMinecraft = "minecraft"
)
// Keywords accepted for the Minecraft version of a new server. Release and
// snapshot name Mojang's channels; latest asks the chosen product which
// version it serves.
const (
createMinecraftLatest = "latest"
createMinecraftRelease = "release"
createMinecraftSnapshot = "snapshot"
)
func NewCreateCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "create",
Short: help.CreateShort,
Long: help.CreateLong,
Example: " lucy create\n" +
" lucy create --minecraft 1.21.4 --core paper\n" +
" lucy create --directory server --minecraft 1.21.4 --core paper --no-install",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionCreate(cmd, inv, deps, args)
},
}
createJSON.Bind(contracts, cmd)
cmd.Flags().BoolP(
flagCreateForceName,
"f",
false,
"Replace an existing manifest in the target directory",
)
cmd.Flags().StringP(
flagCreateCoreName,
"c",
"",
"Server software, optionally with a version (e.g. paper@232, fabric@0.16.9)",
)
cmd.Flags().String(
flagCreateCoreVersionName,
"",
"Server software version or version rule",
)
cmd.Flags().StringP(
flagCreateMcName,
"m",
"",
"Target Minecraft version (e.g. 1.21.4), release, snapshot, or latest",
)
cmd.Flags().String(
flagCreateMCDRVersionName,
"",
"Record this MCDReforged version",
)
cmd.Flags().StringP(
flagCreateDirectoryName,
"d",
".",
"Directory to create the server in",
)
cmd.Flags().String(
flagCreateNameName,
"",
"Server name to record (default: the target directory name)",
)
cmd.Flags().Bool(
flagCreateInstallName,
false,
"Install the server after writing the manifest and lock (default)",
)
cmd.Flags().Bool(
flagCreateNoInstallName,
false,
"Only write lucy.yaml and lucy-lock.yaml; install later",
)
cmd.Flags().Bool(
flagCreateJavaName,
false,
"Also install the Java runtime the server asks for when no installed runtime meets it",
)
cmd.Flags().Bool(
flagCreateJavaRepoName,
false,
"Let --java add the Java vendor's package repository to the system package manager",
)
MarkTelemetryFlagArgument(cmd, flagCreateCoreName, TelemetryArgumentSelector)
MarkTelemetryFlagArgument(cmd, flagCreateCoreVersionName, TelemetryArgumentVersion)
MarkTelemetryFlagArgument(cmd, flagCreateMcName, TelemetryArgumentVersion)
MarkTelemetryFlagArgument(cmd, flagCreateMCDRVersionName, TelemetryArgumentVersion)
return cmd
}
// createChoices carries the values the command has settled before the form or
// the operation. Product is the selector value.
type createChoices struct {
Directory string
Name string
Product string
Minecraft string
CoreVersion string
MCDRVersion string
Force bool
Install bool
InstallChosen bool
Java bool
AddJavaRepository bool
}
func actionCreate(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
choices, err := choicesFromCreateFlags(cmd)
if err != nil {
return err
}
interactive := NewPromptGate(cmd, inv).Available()
if interactive {
choices, err = promptCreate(ctx, cmd, deps.Router, inv.Directory, choices)
if err != nil {
if errors.Is(err, context.Canceled) {
return &report.Detail{
Title: "creation cancelled",
Lines: []string{"Nothing was written."},
Cause: err,
}
}
return err
}
if err := validateCreateChoices(choices); err != nil {
return err
}
} else if err := validateCreateChoices(choices); err != nil {
return err
}
if !interactive {
if err := warnCreateTarget(cmd, inv, choices); err != nil {
return err
}
}
choices.Minecraft, err = resolveCreateMinecraft(
ctx,
deps.Router,
createProduct(choices.Product),
choices.Minecraft,
)
if err != nil {
return err
}
opts := createOperationOptions(choices, inv.Directory)
output := newCreateOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
if choices.Java && choices.Install {
opts.InstallOptions.ProvisionJava = output.provisionJava(
deps.JavaHost,
javainstall.Policy{
Interactive: NewPromptGate(cmd, inv).Available(),
AllowRepository: choices.AddJavaRepository,
},
false,
)
}
result, err := deps.Operations.Create(ctx, opts)
if err != nil {
return output.Failure(err)
}
return output.Render(result)
}
func choicesFromCreateFlags(cmd *cobra.Command) (createChoices, error) {
installFlag, _ := cmd.Flags().GetBool(flagCreateInstallName)
noInstallFlag, _ := cmd.Flags().GetBool(flagCreateNoInstallName)
installSet := cmd.Flags().Changed(flagCreateInstallName)
noInstallSet := cmd.Flags().Changed(flagCreateNoInstallName)
installChosen := installSet || noInstallSet
if installSet && noInstallSet && installFlag == noInstallFlag {
return createChoices{}, errors.New("--install and --no-install contradict each other")
}
install := true
if cmd.Flags().Changed(flagCreateInstallName) {
install = installFlag
}
if cmd.Flags().Changed(flagCreateNoInstallName) {
install = !noInstallFlag
}
javaFlag, _ := cmd.Flags().GetBool(flagCreateJavaName)
javaRepository, _ := cmd.Flags().GetBool(flagCreateJavaRepoName)
if javaRepository && !javaFlag {
return createChoices{}, fmt.Errorf("--%s needs --%s", flagCreateJavaRepoName, flagCreateJavaName)
}
name := strings.TrimSpace(flagStringCreate(cmd, flagCreateNameName))
if cmd.Flags().Changed(flagCreateNameName) {
if _, err := document.NormalizeName(name); err != nil {
return createChoices{}, fmt.Errorf("--%s: %w", flagCreateNameName, err)
}
}
coreRaw := flagStringCreate(cmd, flagCreateCoreName)
productName, inlineVersion := parseCoreDistributionCreate(coreRaw)
if explicitVersion := flagStringCreate(cmd, flagCreateCoreVersionName); explicitVersion != "" {
if inlineVersion != "" && inlineVersion != explicitVersion {
return createChoices{}, fmt.Errorf(
"--core includes @%s but --core-version is %s; use one version",
inlineVersion,
explicitVersion,
)
}
inlineVersion = explicitVersion
}
choices := createChoices{
Directory: flagStringCreate(cmd, flagCreateDirectoryName),
Name: name,
Minecraft: strings.TrimSpace(flagStringCreate(cmd, flagCreateMcName)),
CoreVersion: strings.TrimSpace(inlineVersion),
MCDRVersion: strings.TrimSpace(flagStringCreate(cmd, flagCreateMCDRVersionName)),
Force: flagBoolCreate(cmd, flagCreateForceName),
Install: install,
InstallChosen: installChosen,
Java: javaFlag,
AddJavaRepository: javaRepository,
}
productName = strings.TrimSpace(productName)
if productName == "" {
if choices.CoreVersion != "" {
return createChoices{}, fmt.Errorf("--%s needs --%s", flagCreateCoreVersionName, flagCreateCoreName)
}
choices.Product = createProductMinecraft
return choices, nil
}
product, known := serverpkg.ParseProduct(productName)
if !known || !createProductSupported(product) {
return createChoices{}, fmt.Errorf(
"server software %q is not supported by create; choose minecraft, paper, purpur, fabric, forge, or neoforge",
productName,
)
}
if product == serverpkg.ProductMinecraft {
if choices.CoreVersion != "" && choices.CoreVersion != choices.Minecraft {
return createChoices{}, fmt.Errorf(
"--%s does not apply to the Minecraft core; the Minecraft version is the server version",
flagCreateCoreVersionName,
)
}
choices.CoreVersion = ""
}
choices.Product = string(product)
return choices, nil
}
func validateCreateChoices(choices createChoices) error {
if strings.TrimSpace(choices.Directory) == "" {
return errors.New("choose a directory with --directory")
}
if choices.Name != "" {
if _, err := document.NormalizeName(choices.Name); err != nil {
return fmt.Errorf("--%s: %w", flagCreateNameName, err)
}
}
if err := validateCreateMinecraft(
choices.Minecraft,
createProduct(choices.Product),
); err != nil {
return fmt.Errorf("--%s: %w", flagCreateMcName, err)
}
if choices.Java && !choices.Install {
return errors.New("--java needs installation; omit --no-install or choose Install")
}
return nil
}
func createOperationOptions(
choices createChoices,
base string,
) operation.CreateOptions {
product := choices.Product
if product == "" {
product = createProductMinecraft
}
return operation.CreateOptions{
Directory: resolveInvocationPath(base, choices.Directory),
Name: choices.Name,
Minecraft: choices.Minecraft,
Product: product,
ProductVersion: choices.CoreVersion,
MCDRVersion: choices.MCDRVersion,
Force: choices.Force,
Install: choices.Install,
}
}
func warnCreateTarget(
cmd *cobra.Command,
inv *Invocation,
choices createChoices,
) error {
target, err := operation.InspectCreateTarget(
resolveInvocationPath(inv.Directory, choices.Directory),
)
if err != nil {
return err
}
if target.ManifestExists && !choices.Force {
return fmt.Errorf(
"lucy.yaml exists in %s; pass --force to replace declared intent",
target.Path,
)
}
if !target.NonEmpty {
return nil
}
location := displayCreatePath(target.Path, inv.Directory)
message := "the current directory is not empty"
if location != "." {
message = "directory " + location + " is not empty"
}
if len(target.Entries) > 0 {
message += " (" + strings.Join(target.Entries, ", ") + ")"
}
message += "; existing files are left in place"
if target.ManifestExists {
message += ", and lucy.yaml will be replaced"
if target.DeclaredPackages > 0 {
message += " (" + createPackageCountLabel(target.DeclaredPackages) +
" declared; installation may remove their files)"
}
}
if JSONMode(cmd) == JSONNone {
report.New(cmd.ErrOrStderr(), inv.Theme).Warn(errors.New(message))
}
return nil
}
func parseCoreDistributionCreate(raw string) (distribution, coreVersion string) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", ""
}
if dist, ver, found := strings.Cut(raw, "@"); found {
return dist, ver
}
return raw, ""
}
func flagStringCreate(cmd *cobra.Command, name string) string {
value, _ := cmd.Flags().GetString(name)
return value
}
func flagBoolCreate(cmd *cobra.Command, name string) bool {
value, _ := cmd.Flags().GetBool(name)
return value
}
func createProductSupported(product serverpkg.Product) bool {
switch product {
case serverpkg.ProductMinecraft,
serverpkg.ProductPaper,
serverpkg.ProductPurpur,
serverpkg.ProductFabric,
serverpkg.ProductQuilt,
serverpkg.ProductForge,
serverpkg.ProductNeoForge:
return true
default:
return false
}
}
// createProduct names the server product a choice selects, defaulting to
// vanilla.
func createProduct(name string) serverpkg.Product {
trimmed := strings.TrimSpace(name)
if trimmed == "" {
return serverpkg.ProductMinecraft
}
if parsed, known := serverpkg.ParseProduct(trimmed); known {
return parsed
}
return serverpkg.Product(strings.ToLower(trimmed))
}
// createMinecraftKeyword maps a floating game version request, including the
// loader channel spellings, to its canonical keyword.
func createMinecraftKeyword(value string) (string, bool) {
switch strings.ToLower(strings.TrimSpace(value)) {
case createMinecraftLatest:
return createMinecraftLatest, true
case createMinecraftRelease, string(version.Stable):
return createMinecraftRelease, true
case createMinecraftSnapshot, string(version.Beta):
return createMinecraftSnapshot, true
default:
return "", false
}
}
func validateCreateMinecraft(value string, product serverpkg.Product) error {
value = strings.TrimSpace(value)
if value == "" {
return errors.New("enter a Minecraft version")
}
if keyword, ok := createMinecraftKeyword(value); ok {
if keyword != createMinecraftLatest && !productFollowsMinecraftReleases(product) {
return fmt.Errorf(
"%s builds for Minecraft releases only and lags behind them; "+
"name an exact version or use latest",
product,
)
}
return nil
}
parsed := version.Version(value)
if parsed.CanInfer() || parsed.IsInvalid() {
return errors.New(
"enter a Minecraft version, e.g. 1.21.4, release, snapshot, or latest",
)
}
return nil
}
// productFollowsMinecraftReleases reports whether the product publishes builds
// as Minecraft versions ship. Vanilla always does, and Fabric and Quilt track
// both releases and snapshots. Forge, NeoForge, Paper, and Purpur build
// releases only and lag behind them, so a channel keyword would name a version
// they do not serve yet.
func productFollowsMinecraftReleases(product serverpkg.Product) bool {
switch product {
case serverpkg.ProductMinecraft, serverpkg.ProductFabric, serverpkg.ProductQuilt:
return true
default:
return false
}
}
// resolveCreateMinecraft turns a floating keyword into the version the
// manifest records. The interactive form and the flags share this step.
func resolveCreateMinecraft(
ctx context.Context,
router *routing.Router,
product serverpkg.Product,
value string,
) (string, error) {
keyword, ok := createMinecraftKeyword(value)
if !ok {
return strings.TrimSpace(value), nil
}
var (
resolved version.Version
err error
)
switch keyword {
case createMinecraftLatest:
resolved, err = router.LatestMinecraftVersion(ctx, product)
case createMinecraftRelease:
resolved, err = router.LatestMojangMinecraft(ctx, false)
case createMinecraftSnapshot:
resolved, err = router.LatestMojangMinecraft(ctx, true)
}
if err != nil {
return "", fmt.Errorf("--%s: %w", flagCreateMcName, err)
}
return resolved.String(), nil
}
// displayCreatePath keeps the form and the final summary short when the
// target is below the current directory.
func displayCreatePath(path, base string) string {
absolute := resolveInvocationPath(base, path)
relative, err := filepath.Rel(base, absolute)
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return absolute
}
return relative
}
// displayCreateLocation names the current directory in prose instead of
// leaving a bare dot in a sentence.
// resolveInvocationPath anchors a user-supplied path at the invocation
// directory. Handlers never rely on the process working directory.
func resolveInvocationPath(base, path string) string {
path = strings.TrimSpace(path)
if path == "" {
return filepath.Clean(base)
}
if filepath.IsAbs(path) {
return filepath.Clean(path)
}
return filepath.Join(base, path)
}
func displayCreateLocation(path, base string) string {
display := displayCreatePath(path, base)
if display == "." {
return "the current directory"
}
return display
}
package cli
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"sync/atomic"
"unicode"
"charm.land/huh/v2"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/operation"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream/routing"
"github.com/spf13/cobra"
)
// promptCreate collects the choices for a new workspace. Flags prefill the
// form; the form remains the authority for an interactive invocation.
func promptCreate(
ctx context.Context,
cmd *cobra.Command,
router *routing.Router,
base string,
defaults createChoices,
) (createChoices, error) {
values := defaults
forceFromFlag := values.Force
if values.Directory == "" {
values.Directory = "."
}
// The name follows the directory until the operator supplies one, so the
// prefilled default never outlives the directory it was derived from.
derivedName := defaultCreateName(values.Directory, base)
nameFromFlag := values.Name != ""
if !nameFromFlag {
values.Name = derivedName
}
if values.Product == "" {
values.Product = createProductMinecraft
}
nameAccessor := huh.NewPointerAccessor(&values.Name)
name := huh.NewInput().
Key("name").
Title("Name").
Description("Select this server by name with --server. Defaults to the target directory name.").
Placeholder("survival").
Accessor(nameAccessor).
Validate(validateCreateName)
directory := huh.NewInput().
Key("directory").
Title("Directory").
DescriptionFunc(func() string {
return describeCreateDirectory(values.Directory, values.Force, base)
}, &values.Directory).
Placeholder(".").
Value(&values.Directory).
Validate(func(path string) error {
if err := validateCreateDirectory(path, base); err != nil {
return err
}
if nameFromFlag || values.Name != derivedName {
return nil
}
derivedName = defaultCreateName(path, base)
values.Name = derivedName
// huh reads the text field, not the accessor, while editing, so
// reattaching the accessor is what shows the new default.
name.Accessor(nameAccessor)
return nil
})
product := huh.NewSelect[string]().
Key("product").
Title("Server software").
Description("Choose the server implementation to create.").
Options(createProductOptions(values.Product)...).
Value(&values.Product)
var minecraftVersions atomic.Value
go func() {
releases, err := router.MinecraftReleases(ctx)
if err != nil {
return
}
versions := make([]string, 0, min(len(releases), 100))
for _, release := range releases {
versions = append(versions, release.String())
if len(versions) == 100 {
break
}
}
minecraftVersions.Store(versions)
}()
minecraft := huh.NewInput().
Key("minecraft").
Title("Minecraft version").
Placeholder("1.21.4").
Description("A release or snapshot ID such as 1.21.4, or release, snapshot, or latest. Start typing for known versions.").
Value(&values.Minecraft).
SuggestionsFunc(func() []string {
versions, _ := minecraftVersions.Load().([]string)
return versions
}, &values.Minecraft).
Validate(func(value string) error {
return validateCreateMinecraft(value, createProduct(values.Product))
})
coreVersion := huh.NewInput().
Key("core-version").
Title("Server software version").
PlaceholderFunc(func() string {
return createCoreVersionPlaceholder(values.Product)
}, &values.Product).
DescriptionFunc(func() string {
return createCoreVersionDescription(values.Product)
}, &values.Product).
Value(&values.CoreVersion)
groups := []*huh.Group{
huh.NewGroup(directory, name, product, minecraft).
Title("New server").
Description("Choose where the server lives, what it is called, and what it runs."),
huh.NewGroup(coreVersion).
Title("Server version").
Description("Pick an exact build or let Lucy choose the latest.").
WithHideFunc(func() bool {
return values.Product == createProductMinecraft
}),
}
summary := huh.NewNote().
Title("Review").
DescriptionFunc(func() string {
return createFormSummary(values, base)
}, &values)
if values.InstallChosen {
summary = summary.Next(true).NextLabel("Create")
groups = append(groups, huh.NewGroup(summary).
Title("Finish").
Description("Review the choices, then create the server."))
} else {
install := huh.NewConfirm().
Key("install").
Title("Install the server now?").
Description("Not yet writes only lucy.yaml and lucy-lock.yaml; run lucy install later.").
Affirmative("Install").
Negative("Not yet").
Value(&values.Install)
if values.Java {
install = install.Validate(func(install bool) error {
if !install {
return errors.New("--java needs installation; choose Install")
}
return nil
})
}
groups = append(groups, huh.NewGroup(summary, install).
Title("Finish").
Description("Confirm the installation choice to create the server."))
}
replaceGroup := huh.NewGroup(
huh.NewConfirm().
Key("replace").
Title("Replace existing manifest?").
DescriptionFunc(func() string {
target, err := operation.InspectCreateTarget(
resolveInvocationPath(base, values.Directory),
)
if err != nil || !target.ManifestExists {
return ""
}
if target.DeclaredPackages == 0 {
return "The existing lucy.yaml will be replaced."
}
return "The existing lucy.yaml declares " +
createPackageCountLabel(target.DeclaredPackages) +
". Installation may remove files those packages own."
}, &values.Directory).
Affirmative("Replace").
Negative("Choose another directory").
Value(&values.Force).
Validate(func(replace bool) error {
if !replace {
return errors.New("choose another directory or confirm replacement")
}
return nil
}),
).
Title("Existing manifest").
Description("Confirm before replacing the existing lucy.yaml.").
WithHideFunc(func() bool {
if forceFromFlag {
return true
}
target, err := operation.InspectCreateTarget(
resolveInvocationPath(base, values.Directory),
)
return err != nil || !target.ManifestExists
})
groups = append([]*huh.Group{groups[0], replaceGroup}, groups[1:]...)
form := huh.NewForm(groups...).
WithInput(cmd.InOrStdin()).
WithOutput(cmd.ErrOrStderr())
if err := RunPrompt(ctx, form); err != nil {
return createChoices{}, err
}
values.Directory = strings.TrimSpace(values.Directory)
if values.Directory == "" {
values.Directory = "."
}
values.Name = strings.TrimSpace(values.Name)
if values.Name == "" {
values.Name = defaultCreateName(values.Directory, base)
}
values.Minecraft = strings.TrimSpace(values.Minecraft)
values.CoreVersion = strings.TrimSpace(values.CoreVersion)
if values.Product == createProductMinecraft {
values.CoreVersion = ""
}
return values, nil
}
// createProductOptions lists what the wizard offers. A product that flags
// settled outside that list stays offered so the flag survives the form.
func createProductOptions(selected string) []huh.Option[string] {
options := []huh.Option[string]{
huh.NewOption("Minecraft (vanilla)", createProductMinecraft),
huh.NewOption("Fabric", string(serverpkg.ProductFabric)),
huh.NewOption("Quilt", string(serverpkg.ProductQuilt)),
huh.NewOption("Forge", string(serverpkg.ProductForge)),
huh.NewOption("NeoForge", string(serverpkg.ProductNeoForge)),
}
for _, option := range options {
if option.Value == selected {
return options
}
}
if selected == "" || selected == createProductMinecraft {
return options
}
return append(options, huh.NewOption(createProductTitle(selected), selected))
}
func createProductTitle(product string) string {
if parsed, known := serverpkg.ParseProduct(product); known {
return parsed.Title()
}
if product == "" {
return "Minecraft"
}
runes := []rune(product)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}
func createCoreVersionDescription(product string) string {
switch product {
case string(serverpkg.ProductPaper):
return "Paper build number such as 232, or stable / any."
case string(serverpkg.ProductPurpur):
return "Purpur build number, latest, or any."
case string(serverpkg.ProductFabric):
return "Fabric loader version such as 0.16.9, or any for the latest."
case string(serverpkg.ProductQuilt):
return "Quilt loader version such as 0.27.1, or any for the latest."
case string(serverpkg.ProductForge):
return "Forge version such as 47.3.0, or any for the latest."
case string(serverpkg.ProductNeoForge):
return "NeoForge version such as 21.1.233, or any for the latest."
default:
return "Leave empty to let Lucy choose the latest version."
}
}
func createCoreVersionPlaceholder(product string) string {
switch product {
case string(serverpkg.ProductPaper):
return "232"
case string(serverpkg.ProductPurpur):
return "latest"
case string(serverpkg.ProductFabric):
return "0.16.9"
case string(serverpkg.ProductQuilt):
return "0.27.1"
case string(serverpkg.ProductForge):
return "47.3.0"
case string(serverpkg.ProductNeoForge):
return "21.1.233"
default:
return "any"
}
}
func createFormSummary(values createChoices, base string) string {
serverVersion := strings.TrimSpace(values.CoreVersion)
if values.Product == createProductMinecraft {
serverVersion = "the Minecraft version"
} else if serverVersion == "" {
serverVersion = "any (latest)"
}
server := createProductTitle(values.Product)
lines := []string{
"Name: " + values.Name,
"Directory: " + displayCreateLocation(values.Directory, base),
"Server: " + server + " for Minecraft " + values.Minecraft,
"Server version: " + serverVersion,
}
install := "not yet"
if values.Install {
install = "yes"
}
lines = append(lines, "Install after creation: "+install)
if target, err := operation.InspectCreateTarget(
resolveInvocationPath(base, values.Directory),
); err == nil {
if target.NonEmpty {
lines = append(lines, "Warning: the directory is not empty.")
}
if target.ManifestExists && values.Force {
replacement := "Existing lucy.yaml will be replaced."
if target.DeclaredPackages > 0 {
replacement = "Existing lucy.yaml will be replaced; it declares " +
createPackageCountLabel(target.DeclaredPackages) + "."
}
lines = append(lines, replacement)
}
}
return strings.Join(lines, "\n")
}
func describeCreateDirectory(path string, force bool, base string) string {
usingCurrent := strings.TrimSpace(path) == ""
if usingCurrent {
path = "."
}
target, err := operation.InspectCreateTarget(resolveInvocationPath(base, path))
if err != nil {
return err.Error()
}
prefix := ""
if usingCurrent {
prefix = "Using the current directory. "
}
if !target.Exists {
return prefix + "This directory will be created."
}
if !target.NonEmpty {
return prefix + "This directory is empty."
}
description := prefix + "Warning: this directory is not empty"
if len(target.Entries) > 0 {
description += " (" + strings.Join(target.Entries, ", ")
if len(target.Entries) == 5 {
description += ", …"
}
description += ")"
}
description += ". Existing files stay in place; installation may conflict."
if target.ManifestExists {
if force {
description += " An existing lucy.yaml will be replaced."
if target.DeclaredPackages > 0 {
description += " It declares " + createPackageCountLabel(target.DeclaredPackages) +
"; installation may remove files those packages own."
}
} else {
description += " lucy.yaml already exists; confirm replacement on the next step."
}
}
return description
}
func createPackageCountLabel(count int) string {
if count == 1 {
return "1 package"
}
return fmt.Sprintf("%d packages", count)
}
func validateCreateDirectory(path, base string) error {
if strings.TrimSpace(path) == "" {
path = "."
}
_, err := operation.InspectCreateTarget(resolveInvocationPath(base, path))
return err
}
// defaultCreateName names a new server after the directory it occupies. The
// name is not slugged: an unusable directory name leaves the input empty so
// the form asks for an explicit name.
func defaultCreateName(directory, base string) string {
target, err := operation.InspectCreateTarget(
resolveInvocationPath(base, directory),
)
if err != nil {
return ""
}
name, err := document.NormalizeName(filepath.Base(target.Path))
if err != nil {
return ""
}
return name
}
func validateCreateName(value string) error {
_, err := document.NormalizeName(value)
return err
}
package cli
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/shell"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/operation"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
"github.com/mclucy/lucy/version"
"github.com/spf13/cobra"
)
// createOutput reuses install progress and warning plumbing, but owns the
// create summary and failure wording.
type createOutput struct {
*installOutput
}
// createJSON is the machine-readable result of one creation.
var createJSON JSONResult[*operation.CreateResult]
func newCreateOutput(cmd *cobra.Command, inv *Invocation) *createOutput {
return &createOutput{installOutput: newInstallOutput(cmd, inv)}
}
// Render prints one creation outcome. JSON goes to stdout; human output goes
// to stderr, like every other mutating command.
func (o *createOutput) Render(result *operation.CreateResult) error {
if result == nil {
return nil
}
result.WarningMessages = append(result.WarningMessages, o.Warnings()...)
if o.JSON() {
return createJSON.Write(o.Output, result)
}
lines := createSummaryLines(result, o.inv.Theme, o.inv.Directory)
o.renderer.Println(append([]string{""}, lines...)...)
o.Close()
for _, warning := range result.Warnings {
o.Warn(warning)
}
for _, diagnostic := range result.Diagnostics {
o.Warn(fmt.Errorf("%s: %s", diagnostic.Path, diagnostic.Message))
}
return nil
}
// Failure adds the state that a create failure leaves behind. The shared
// install presenter explains the operation error itself.
func (o *createOutput) Failure(err error) error {
if err == nil {
return nil
}
if resolveErr, ok := errors.AsType[*operation.CreateResolveError](err); ok {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return &report.Detail{
Title: "creation cancelled",
Lines: []string{"No manifest was written."},
Cause: err,
}
}
detail := &report.Detail{
Title: "could not create the " + createProductTitle(string(resolveErr.Product)) + " server",
Lines: []string{
"Directory: " + displayCreateLocation(resolveErr.Workspace, o.inv.Directory),
"Minecraft: " + versionLabel(resolveErr.Minecraft),
"Server version: " + versionLabel(resolveErr.Selector),
},
Cause: err,
}
if inner := createErrorDetail(o, resolveErr.Err); inner != nil {
detail.Lines = append(detail.Lines, inner.Lines...)
detail.Hint = inner.Hint
} else {
detail.Lines = append(detail.Lines, resolveErr.Err.Error())
}
if detail.Hint == "" {
switch {
case resolveErr.Product == serverpkg.ProductPaper:
detail.Hint = "Paper versions are build numbers; try 232, stable, or any."
case resolveErr.Product == serverpkg.ProductPurpur:
detail.Hint = "Purpur versions are build numbers or latest."
default:
detail.Hint = "Check the server software version and the Minecraft version, then retry."
}
}
return detail
}
if publishErr, ok := errors.AsType[*operation.CreatePublishError](err); ok {
detail := &report.Detail{
Title: "could not write the server directory",
Lines: []string{"Directory: " + displayCreatePath(publishErr.Workspace, o.inv.Directory)},
Cause: err,
}
if publishErr.ManifestWritten {
detail.Lines = append(detail.Lines, "lucy.yaml was written, but lucy-lock.yaml was not.")
detail.Hint = "Run " + createInstallCommand(publishErr.Workspace, o.inv.Directory) + " to finish resolving the lock."
} else {
detail.Lines = append(detail.Lines, "No manifest or lock was written.")
detail.Hint = "Check that the directory is writable and try again."
}
detail.Lines = append(detail.Lines, publishErr.Err.Error())
return detail
}
if registrationErr, ok := errors.AsType[*operation.CreateRegistrationError](err); ok {
return &report.Detail{
Title: "the server directory was created but it was not registered",
Lines: []string{
"Directory: " + displayCreateLocation(registrationErr.Workspace, o.inv.Directory),
"lucy.yaml and lucy-lock.yaml were written.",
registrationErr.Err.Error(),
},
Hint: "Fix the server registry or the workspace name, then run lucy install again.",
Cause: err,
}
}
if installErr, ok := errors.AsType[*operation.CreateInstallError](err); ok {
detail := &report.Detail{
Title: "the server directory was created but installation failed",
Lines: []string{
"Directory: " + displayCreateLocation(installErr.Workspace, o.inv.Directory),
"lucy.yaml and lucy-lock.yaml were written.",
},
Cause: err,
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
detail.Title = "installation interrupted"
detail.Lines = append(detail.Lines, "The server directory was created; installation did not finish.")
}
if _, committed := errors.AsType[*install.CommittedError](installErr.Err); committed {
detail.Title = "the server directory was created but provisioning was interrupted"
detail.Lines = append(detail.Lines, "The installation was committed; file provisioning did not finish.")
}
if inner := createErrorDetail(o, installErr.Err); inner != nil {
detail.Lines = append(detail.Lines, inner.Lines...)
detail.Hint = inner.Hint
} else {
detail.Lines = append(detail.Lines, installErr.Err.Error())
detail.Lines = detailLines(
o.installOutput.processLogNote(),
detail.Lines...,
)
}
if detail.Hint == "" {
detail.Hint = "Run " + createInstallCommand(installErr.Workspace, o.inv.Directory) + " to finish."
}
message := installErr.Err.Error()
switch {
case errors.Is(installErr.Err, bootstrap.ErrNoJava):
detail.Hint = "Run " + createInstallCommand(installErr.Workspace, o.inv.Directory) +
" --java to install the Java runtime the server asks for."
case strings.Contains(message, "unowned or modified output conflict"):
detail.Hint = "Move the existing file out of the way, or run lucy init to adopt the existing server."
case strings.Contains(message, "stop the running Minecraft server"):
detail.Hint = "Stop the server, then run " + createInstallCommand(installErr.Workspace, o.inv.Directory) + "."
}
return detail
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return &report.Detail{
Title: "creation cancelled",
Lines: []string{"No manifest was written."},
Cause: err,
}
}
return o.installOutput.Failure(err)
}
func createSummaryLines(
result *operation.CreateResult,
theme style.Theme,
base string,
) []string {
path := displayCreateLocation(result.Workspace, base)
title := createProductTitle(string(result.Server.Product))
minecraft := string(result.Server.Minecraft)
coreVersion := string(result.Server.Version)
if coreVersion == "" {
coreVersion = minecraft
}
var headline string
custom := result.Manifest != nil && result.Manifest.Server.Core.Repository != ""
switch {
case result.Server.Product == serverpkg.ProductMinecraft:
headline = theme.Success("✓") + " Created a Minecraft " + minecraft + " server"
case custom:
headline = theme.Success("✓") + " Created " + title + " " +
coreVersion + " for Minecraft " + minecraft
default:
headline = theme.Success("✓") + " Created " + title + " " + coreVersion +
" for Minecraft " + minecraft
}
if path != "" {
headline += " in " + path
}
written := "Wrote lucy.yaml"
if result.ReplacedManifest {
written = "Replaced lucy.yaml"
}
if result.PublishedLock {
written += " and lucy-lock.yaml"
} else {
written += " (lucy-lock.yaml unchanged)"
}
lines := []string{
headline,
theme.Muted(" " + written),
}
if result.Installed {
files := result.Files.Created + result.Files.Replaced
switch {
case files > 0:
lines = append(lines, theme.Muted(" Installed "+fileCountLabel(files)))
default:
lines = append(lines, theme.Muted(" Server files are current"))
}
if result.Files.Removed > 0 {
lines = append(lines, theme.Muted(" Removed "+fileCountLabel(result.Files.Removed)))
}
if line := displacedFilesLine(len(result.Files.Displaced)); line != "" {
lines = append(lines, theme.Muted(line))
}
} else {
lines = append(
lines,
" "+theme.Note("Next:")+" "+createInstallCommand(result.Workspace, base),
)
}
return lines
}
func createInstallCommand(workspace, base string) string {
path := displayCreatePath(workspace, base)
if path == "." || path == "" {
return "lucy install"
}
if !filepath.IsAbs(path) {
path = "./" + path
}
return "cd " + shell.Quote(path) + " && lucy install"
}
func fileCountLabel(count int) string {
if count == 1 {
return "1 file"
}
return fmt.Sprintf("%d files", count)
}
func displacedFilesLine(count int) string {
if count == 0 {
return ""
}
noun := "files"
if count == 1 {
noun = "file"
}
return fmt.Sprintf(" Kept %d replaced %s in %s/", count, noun, workspacewrite.DisplacedRoot)
}
func versionLabel(value version.Version) string {
text := strings.TrimSpace(value.String())
if text == "" {
return "any"
}
return text
}
// createErrorDetail uses the install presenter's richer failure mapping, then
// falls back to the generic resolution detail.
func createErrorDetail(o *createOutput, err error) *report.Detail {
if inner := o.installOutput.Failure(err); inner != nil {
if detail, ok := errors.AsType[*report.Detail](inner); ok {
return detail
}
}
return errorDetail(err)
}
package cli
import (
"fmt"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/spf13/cobra"
)
// deinitDocument is the machine-readable outcome of one deinitialization.
type deinitDocument struct {
Removed []string `json:"removed"`
Displaced string `json:"displaced,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
var deinitJSON JSONResult[deinitDocument]
func NewDeinitCommand(contracts *JSONContracts, inv *Invocation, deps *Dependencies) *cobra.Command {
deinitCmd := &cobra.Command{
Use: "deinit",
Short: help.DeinitShort,
Long: help.DeinitLong,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return actionDeinit(cmd, inv, deps)
},
}
deinitJSON.Bind(contracts, deinitCmd)
return deinitCmd
}
func actionDeinit(cmd *cobra.Command, inv *Invocation, deps *Dependencies) error {
output := NewOperationOutput(cmd, inv)
result, err := deps.Operations.Deinitialize(inv.Directory)
if err != nil {
return err
}
for _, warning := range result.Warnings {
output.Warn(warning)
}
document := deinitDocument{
Removed: result.Removed,
Displaced: result.Displaced,
Warnings: output.Warnings(),
}
if output.JSON() {
return deinitJSON.Write(output, document)
}
out := output.Human()
for _, name := range result.Removed {
if _, err := fmt.Fprintf(out, "removed %s\n", name); err != nil {
return err
}
}
if result.Displaced != "" {
if _, err := fmt.Fprintf(out, "kept displaced files in %s/\n", result.Displaced); err != nil {
return err
}
}
_, err = fmt.Fprintln(out, "Lucy no longer manages this server")
return err
}
package cli
import (
"fmt"
"strings"
"unicode/utf8"
"github.com/mclucy/lucy/resolve"
versionpkg "github.com/mclucy/lucy/version"
)
const (
maxFactChainTypes = 12
maxFactFailures = 5
maxFactRejections = 8
maxFactTextBytes = 256
maxFactDepth = 32
)
// genericErrorTypes name wrapping errors that carry no fact of their own.
// They stay out of the chain so a failure document does not grow a key for
// every layer the command boundary happens to add.
var genericErrorTypes = map[string]bool{
"report.Detail": true,
"errors.errorString": true,
"errors.joinError": true,
"fmt.wrapError": true,
}
// FailureFacts returns the machine-readable evidence behind a failure: the
// typed errors on the way to the root cause, and the facts they carry. It
// walks the whole error tree, including joined children, because errors.As
// only reaches the first match.
//
// The result holds identifiers, enum names, and counts. It never holds free
// text other than the rejection details the resolver already formats from
// module identifiers, and it returns nil when the tree holds no typed error,
// so ordinary failures keep an unchanged error document.
func FailureFacts(err error) map[string]any {
if err == nil {
return nil
}
collector := factCollector{seenTypes: map[string]bool{}}
collector.walk(err, 0)
return collector.facts()
}
type factCollector struct {
types []string
seenTypes map[string]bool
failures []failureFacts
attempts int
}
type failureFacts struct {
key string
project string
provider string
projectID string
minecraft string
ecosystem string
candidates int
aborted bool
occurrences int
rejections []rejectionFacts
}
type rejectionFacts struct {
kind string
detail string
count int
firstVersion string
lastVersion string
requiredBy string
dependency string
constraint string
selected string
}
func (c *factCollector) walk(err error, depth int) {
if err == nil || depth > maxFactDepth {
return
}
c.addType(fmt.Sprintf("%T", err))
switch node := err.(type) {
case *resolve.Failure:
c.addFailure(node)
case *resolve.SearchLimitError:
if node.Attempts > c.attempts {
c.attempts = node.Attempts
}
}
switch node := err.(type) {
case interface{ Unwrap() []error }:
for _, child := range node.Unwrap() {
c.walk(child, depth+1)
}
case interface{ Unwrap() error }:
c.walk(node.Unwrap(), depth+1)
}
}
func (c *factCollector) addType(name string) {
name = strings.TrimPrefix(name, "*")
if name == "" || genericErrorTypes[name] || c.seenTypes[name] || len(c.types) >= maxFactChainTypes {
return
}
c.seenTypes[name] = true
c.types = append(c.types, name)
}
func (c *factCollector) addFailure(failure *resolve.Failure) {
if failure == nil {
return
}
key := failureKey(failure)
for index := range c.failures {
if c.failures[index].key == key {
c.failures[index].occurrences++
return
}
}
if len(c.failures) >= maxFactFailures {
return
}
entry := failureFacts{
key: key,
project: factText(failure.Project),
provider: string(failure.Provider),
projectID: factText(failure.ProjectID),
minecraft: factVersion(failure.Minecraft),
ecosystem: string(failure.Ecosystem),
candidates: failure.Candidates,
aborted: failure.Aborted,
occurrences: 1,
}
for _, group := range failure.Groups {
if len(entry.rejections) >= maxFactRejections {
break
}
entry.rejections = append(entry.rejections, rejectionFacts{
kind: string(group.Kind),
detail: factText(group.Detail),
count: group.Count,
firstVersion: factText(group.FirstVersion),
lastVersion: factText(group.LastVersion),
requiredBy: factText(group.RequiredBy),
dependency: factText(group.Dependency),
constraint: factText(group.Constraint),
selected: factText(group.Selected),
})
}
c.failures = append(c.failures, entry)
}
func failureKey(failure *resolve.Failure) string {
parts := []string{
failure.Project,
failure.ProjectID,
fmt.Sprint(failure.Aborted),
}
for _, group := range failure.Groups {
parts = append(parts, string(group.Kind), group.Detail)
}
return strings.Join(parts, "\x00")
}
func (c *factCollector) facts() map[string]any {
facts := map[string]any{}
if len(c.types) > 0 {
facts["chain"] = c.types
}
if c.attempts > 0 {
facts["search_limit"] = map[string]any{"attempts": c.attempts}
}
if len(c.failures) > 0 {
entries := make([]map[string]any, 0, len(c.failures))
for _, failure := range c.failures {
entries = append(entries, failure.entry())
}
facts["failures"] = entries
}
if len(facts) == 0 {
return nil
}
return facts
}
func (f failureFacts) entry() map[string]any {
entry := map[string]any{}
if f.project != "" {
entry["project"] = f.project
}
if f.projectID != "" {
entry["project_id"] = f.projectID
}
if f.provider != "" {
entry["provider"] = f.provider
}
if f.ecosystem != "" {
entry["ecosystem"] = f.ecosystem
}
if f.minecraft != "" {
entry["minecraft"] = f.minecraft
}
if f.candidates > 0 {
entry["candidates"] = f.candidates
}
if f.aborted {
entry["aborted"] = true
}
if f.occurrences > 1 {
entry["occurrences"] = f.occurrences
}
if len(f.rejections) > 0 {
rejections := make([]map[string]any, 0, len(f.rejections))
for _, rejection := range f.rejections {
rejections = append(rejections, rejection.entry())
}
entry["rejections"] = rejections
}
return entry
}
func (r rejectionFacts) entry() map[string]any {
entry := map[string]any{"kind": r.kind}
if r.detail != "" {
entry["detail"] = r.detail
}
if r.count > 0 {
entry["count"] = r.count
}
if r.firstVersion != "" {
entry["first_version"] = r.firstVersion
}
if r.lastVersion != "" {
entry["last_version"] = r.lastVersion
}
if r.requiredBy != "" {
entry["required_by"] = r.requiredBy
}
if r.dependency != "" {
entry["dependency"] = r.dependency
}
if r.constraint != "" {
entry["constraint"] = r.constraint
}
if r.selected != "" {
entry["selected"] = r.selected
}
return entry
}
// factVersion renders a version fact, and drops the values that describe no
// target: the zero version and the wildcard both mean the failure was not
// bound to one Minecraft version.
func factVersion(value versionpkg.Version) string {
if value == "" || value == versionpkg.Any {
return ""
}
return factText(value.String())
}
// factText bounds one fact string. Identifiers and versions are far shorter
// than the bound; it only exists so a rejection detail cannot grow the report.
func factText(value string) string {
return truncateFactText(value, maxFactTextBytes)
}
func truncateFactText(value string, limit int) string {
value = strings.TrimSpace(value)
if limit <= 0 || len(value) <= limit {
return value
}
cut := limit
for cut > 0 && !utf8.RuneStart(value[cut]) {
cut--
}
return value[:cut] + "…"
}
package cli
import "strconv"
// ExitError carries an explicit process exit status through the command
// boundary. Silent suppresses error rendering for successful statuses, such as
// a search with no matches.
type ExitError struct {
Code int
Err error
Silent bool
}
// ExitWith reports a failure with a specific process exit status.
func ExitWith(code int, err error) error {
return &ExitError{
Code: code,
Err: err,
}
}
// SilentExit reports a status without an error message.
func SilentExit(code int) error {
return &ExitError{
Code: code,
Silent: true,
}
}
func (e *ExitError) Error() string {
if e.Err != nil {
return e.Err.Error()
}
return "exit status " + strconv.Itoa(e.Code)
}
func (e *ExitError) Unwrap() error {
return e.Err
}
func (e *ExitError) ExitStatus() int {
return e.Code
}
func (e *ExitError) SilentExit() bool {
return e.Silent
}
package cli
import "github.com/spf13/cobra"
// HelpOnlyAnnotation marks a command that displays its own help when invoked
// bare.
const HelpOnlyAnnotation = "lucy.io/help-only"
func MarkHelpOnly(command *cobra.Command) {
if command.Annotations == nil {
command.Annotations = map[string]string{}
}
command.Annotations[HelpOnlyAnnotation] = "true"
}
// IsHelpOnly reports whether command was marked by MarkHelpOnly.
func IsHelpOnly(command *cobra.Command) bool {
return command != nil && command.Annotations[HelpOnlyAnnotation] != ""
}
package cli
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/operation"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/spf13/cobra"
)
const (
flagImportDirectoryName = "directory"
flagImportSHA256Name = "sha256"
)
// importArchiveSuffixes are removed from a source basename before it becomes
// a directory name.
var importArchiveSuffixes = []string{".mrpack", ".tar.gz", ".zip"}
// importJSON is the machine-readable result of `lucy import`.
var importJSON JSONResult[*operation.ImportResult]
func NewImportCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "import <source>",
Short: help.ImportShort,
Args: cobra.ExactArgs(1),
Long: "Create a workspace from a server archive, a direct archive URL, or a " +
"modpack on Modrinth or CurseForge. Modpacks are named by identifier " +
"(modrinth:<slug>[@<version>], curseforge:<slug-or-id>[@<file-id>]) or by " +
"project page URL. CurseForge sources need a CurseForge API key in the " +
"curseforge.api_key setting.",
Example: " lucy import ./server-pack.zip\n" +
" lucy import https://example.com/packs/server.mrpack\n" +
" lucy import modrinth:all-the-mods\n" +
" lucy import modrinth:all-the-mods@1.2.0\n" +
" lucy import https://modrinth.com/modpack/all-the-mods/version/1.2.0\n" +
" lucy import curseforge:all-the-mods@4567890\n" +
" lucy import https://www.curseforge.com/minecraft/modpacks/all-the-mods/files/4567890\n",
RunE: func(cmd *cobra.Command, args []string) error {
return actionImport(cmd, inv, deps, args[0])
},
}
importJSON.Bind(contracts, cmd)
cmd.Flags().StringP(
flagImportDirectoryName,
"d",
"",
"Directory to create the workspace in (default: the current directory when empty, otherwise a directory named after the source)",
)
cmd.Flags().String(
flagInitNameName,
"",
"Server name to record (default: the target directory name)",
)
cmd.Flags().String(
flagInitMCDRVersionName,
"",
"MCDReforged version to record",
)
cmd.Flags().Bool(
flagInitNoCommentsName,
false,
"Write generated manifests and configuration without explanatory comments",
)
cmd.Flags().String(
flagImportSHA256Name,
"",
"Expected SHA-256 of the source archive, as 64 hexadecimal characters",
)
cmd.Flags().String(
flagInitCoreName,
"",
"Expect this server product; no match fails and lists the observed runtimes",
)
cmd.Flags().String(
flagInitCoreVersionName,
"",
"Expect this exact server product version",
)
cmd.Flags().String(
flagInitMinecraftName,
"",
"Expect this exact Minecraft version",
)
return cmd
}
func actionImport(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
source string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
opts, err := importOptions(cmd, inv, source)
if err != nil {
return err
}
return importWorkspace(ctx, cmd, inv, deps, opts)
}
// importOptions turns the command line into operation options. Local sources
// resolve against the invocation directory; URLs and remote modpack references
// (modrinth:, curseforge:, or project page URLs) pass through unchanged.
func importOptions(
cmd *cobra.Command,
inv *Invocation,
source string,
) (operation.ImportOptions, error) {
source = strings.TrimSpace(source)
if source == "" {
return operation.ImportOptions{}, errors.New("source must not be empty")
}
_, isRemote, err := operation.ParseRemoteImportSource(source)
if err != nil {
return operation.ImportOptions{}, err
}
if !isRemote {
if err := rejectImportScheme(source); err != nil {
return operation.ImportOptions{}, err
}
}
if _, ok := importURL(source); !ok && !isRemote {
source = resolveInvocationPath(inv.Directory, source)
}
target, err := importTarget(
inv,
flagStringInit(cmd, flagImportDirectoryName),
source,
)
if err != nil {
return operation.ImportOptions{}, err
}
name := flagStringInit(cmd, flagInitNameName)
if cmd.Flags().Changed(flagInitNameName) {
if _, err := document.NormalizeName(name); err != nil {
return operation.ImportOptions{}, fmt.Errorf(
"--%s: %w",
flagInitNameName,
err,
)
}
} else {
name, err = document.NormalizeName(filepath.Base(target))
if err != nil {
return operation.ImportOptions{}, fmt.Errorf(
"invalid default workspace name: %w; use --%s",
err,
flagInitNameName,
)
}
}
sha := strings.ToLower(
strings.TrimSpace(flagStringInit(cmd, flagImportSHA256Name)),
)
if cmd.Flags().Changed(flagImportSHA256Name) && !validImportSHA256(sha) {
return operation.ImportOptions{}, fmt.Errorf(
"--%s expects %d hexadecimal characters",
flagImportSHA256Name,
hex.EncodedLen(sha256.Size),
)
}
expectation, err := initExpectation(cmd)
if err != nil {
return operation.ImportOptions{}, err
}
return operation.ImportOptions{
Source: source,
Directory: target,
Name: name,
MCDRVersion: flagStringInit(cmd, flagInitMCDRVersionName),
NoComments: flagBoolInit(cmd, flagInitNoCommentsName),
SHA256: sha,
Expectation: expectation,
}, nil
}
// importTarget chooses the workspace directory. An explicit directory wins.
// Without one, an empty or absent invocation directory is used in place; a
// non-empty one receives a new directory named after the source.
func importTarget(inv *Invocation, explicit, source string) (string, error) {
if strings.TrimSpace(explicit) != "" {
return resolveInvocationPath(inv.Directory, explicit), nil
}
empty, err := directoryIsEmpty(inv.Directory)
if err != nil {
return "", err
}
if empty {
return filepath.Clean(inv.Directory), nil
}
slug, err := importSlug(source)
if err != nil {
return "", err
}
return filepath.Join(inv.Directory, slug), nil
}
func directoryIsEmpty(dir string) (bool, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, fs.ErrNotExist) {
return true, nil
}
if err != nil {
return false, fmt.Errorf("read %s: %w", dir, err)
}
return len(entries) == 0, nil
}
// importSlug derives a directory name from a source basename.
func importSlug(source string) (string, error) {
base := importSourceBase(source)
for _, suffix := range importArchiveSuffixes {
if len(base) > len(suffix) &&
strings.EqualFold(base[len(base)-len(suffix):], suffix) {
base = base[:len(base)-len(suffix)]
break
}
}
slug := sanitizeImportSlug(base)
if slug == "" {
return "", fmt.Errorf(
"cannot derive a directory name from %s; pass --%s",
source,
flagImportDirectoryName,
)
}
return slug, nil
}
func importSourceBase(source string) string {
if remote, ok, err := operation.ParseRemoteImportSource(source); ok && err == nil {
return remote.Project
}
if parsed, ok := importURL(source); ok {
base := path.Base(parsed.Path)
if base == "/" || base == "." {
return ""
}
return base
}
return filepath.Base(source)
}
// sanitizeImportSlug lowercases name and joins its ASCII letter and digit runs
// with hyphens, so the result is always a single safe path segment.
func sanitizeImportSlug(name string) string {
var builder strings.Builder
separator := false
for _, r := range strings.ToLower(name) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
if separator && builder.Len() > 0 {
builder.WriteByte('-')
}
builder.WriteRune(r)
separator = false
continue
}
separator = true
}
return builder.String()
}
// rejectImportScheme reports a source that names a URL scheme other than http
// or https. Such a source is neither downloadable nor a local path, so treating
// it as a path would report a misleading missing file.
func rejectImportScheme(source string) error {
scheme, rest, found := strings.Cut(source, "://")
if !found || rest == "" {
return nil
}
if strings.EqualFold(scheme, "http") || strings.EqualFold(scheme, "https") {
return nil
}
return fmt.Errorf(
"source %q uses unsupported URL scheme %q: use an http or https URL, a local path, or a modrinth: or curseforge: reference",
source,
scheme,
)
}
// importURL reports whether source is an http or https URL.
func importURL(source string) (*url.URL, bool) {
parsed, err := url.Parse(source)
if err != nil || parsed.Host == "" {
return nil, false
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, false
}
return parsed, true
}
func validImportSHA256(value string) bool {
if len(value) != hex.EncodedLen(sha256.Size) {
return false
}
_, err := hex.DecodeString(value)
return err == nil
}
func importWorkspace(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
opts operation.ImportOptions,
) error {
output := newInstallOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
opts.PromptRuntime = func(observed discovery.Result) (*discovery.Installation, error) {
output.EndProgress()
// The prompt owns the terminal while it runs; adoption and install
// phases still need a renderer after it returns.
defer output.RestartProgress()
return promptRuntime(ctx, cmd, inv, observed)
}
result, err := deps.Operations.Import(ctx, opts, deps.Network)
if err != nil {
return output.Failure(err)
}
output.EndProgress()
for _, warning := range result.Warnings {
output.Warn(warning)
}
reportDiscoveryFindings(&result.Discovery, output.Output)
if output.JSON() {
return importJSON.Write(output.Output, result)
}
writeImportReport(output.Human(), inv, result)
return nil
}
func writeImportReport(
w io.Writer,
inv *Invocation,
result *operation.ImportResult,
) {
if !result.Initialized {
fmt.Fprintf(
w,
"Extracted %s into %s\n",
result.Name,
displayCreatePath(result.Workspace, inv.Directory),
)
fmt.Fprintln(w, " Server: not detected")
fmt.Fprintf(w, " Files: %s\n", importFileCount(result.ServerFiles))
writeImportFindings(w, result)
return
}
fmt.Fprintf(
w,
"Imported %s into %s\n",
result.Name,
displayCreatePath(result.Workspace, inv.Directory),
)
fmt.Fprintf(w, " Server: %s\n", importServerLabel(result))
fmt.Fprintf(
w,
" Files: %d server, %d client files skipped\n",
result.ServerFiles,
result.SkippedClient,
)
fmt.Fprintf(w, " Managed: %s\n", packageCountLabel(result.ManagedPackages))
writeImportFindings(w, result)
}
// writeImportFindings reports the files lucy does not manage and the lines
// that need attention. Both import outcomes share them.
func writeImportFindings(w io.Writer, result *operation.ImportResult) {
if len(result.Unmanaged) > 0 {
fmt.Fprintf(w, " Unmanaged: %d files\n", len(result.Unmanaged))
for _, file := range result.Unmanaged {
fmt.Fprintf(w, " %s\n", file)
}
}
if len(result.Review) > 0 {
fmt.Fprintln(w, " Review:")
for _, line := range result.Review {
fmt.Fprintf(w, " %s\n", line)
}
}
}
func importFileCount(count int) string {
if count == 1 {
return "1 file"
}
return fmt.Sprintf("%d files", count)
}
func importServerLabel(result *operation.ImportResult) string {
label := result.Product
if result.CoreVersion != "" {
label += " " + result.CoreVersion
}
return label + " for Minecraft " + result.Minecraft
}
package cli
import (
"context"
"errors"
"fmt"
"strings"
"charm.land/huh/v2"
"github.com/mclucy/lucy/config"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/operation"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/terminal/report"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/spf13/cobra"
)
const (
flagInitForceName = "force"
flagInitNameName = "name"
flagInitMCDRVersionName = "mcdr-version"
flagInitCoreName = "core"
flagInitCoreVersionName = "core-version"
flagInitMinecraftName = "minecraft"
flagInitNoCommentsName = "no-comments"
)
func NewInitCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "init",
Short: help.InitShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionInit(cmd, inv, deps, args)
},
}
initJSON.Bind(contracts, cmd)
cmd.Flags().BoolP(
flagInitForceName,
"f",
false,
"Overwrite an existing manifest without asking",
)
cmd.Flags().String(
flagInitNameName,
"",
"Server name to record (default: the directory name, or the existing name with --force)",
)
cmd.Flags().String(
flagInitMCDRVersionName,
"",
"MCDReforged version to record",
)
cmd.Flags().String(
flagInitCoreName,
"",
"Expect this server product; no match fails and lists the observed runtimes",
)
cmd.Flags().String(
flagInitCoreVersionName,
"",
"Expect this exact server product version",
)
cmd.Flags().String(
flagInitMinecraftName,
"",
"Expect this exact Minecraft version",
)
cmd.Flags().Bool(
flagInitNoCommentsName,
false,
"Write generated manifests and configuration without explanatory comments",
)
return cmd
}
// initJSON is the machine-readable result of `lucy init`.
var initJSON JSONResult[*initResult]
// initResult adds workspace configuration publication to the install result
// that other operations share.
type initResult struct {
*install.Result
PublishedConfig bool `json:"published_config"`
}
func actionInit(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
name := flagStringInit(cmd, flagInitNameName)
if cmd.Flags().Changed(flagInitNameName) {
if _, err := document.NormalizeName(name); err != nil {
return fmt.Errorf("--%s: %w", flagInitNameName, err)
}
}
expectation, err := initExpectation(cmd)
if err != nil {
return err
}
opts := operation.InitOptions{
Name: name,
MCDRVersion: flagStringInit(cmd, flagInitMCDRVersionName),
Expectation: expectation,
Force: flagBoolInit(cmd, flagInitForceName),
NoComments: flagBoolInit(cmd, flagInitNoCommentsName),
}
return initializeWorkspace(ctx, cmd, inv, deps, opts)
}
// initializeWorkspace initializes one workspace and owns its presentation.
// Warnings observed during initialization surface on stderr once, failures
// return to the command framework, and success reports the files written from
// the returned document instead of rereading them.
func initializeWorkspace(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
opts operation.InitOptions,
) error {
output := newInstallOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
opts.PromptRuntime = func(observed discovery.Result) (*discovery.Installation, error) {
output.EndProgress()
// The prompt owns the terminal while it runs; later phases still need
// a renderer after it returns.
defer output.RestartProgress()
return promptRuntime(ctx, cmd, inv, observed)
}
result, err := deps.Operations.Initialize(ctx, inv.Directory, opts)
recordInitWorkspaceTelemetry(inv, result)
if err != nil {
return output.Failure(initializationFailure(err, result))
}
output.Close()
for _, warning := range result.Warnings {
output.Warn(warning)
}
reportDiscoveryFindings(&result.Discovery, output.Output)
if output.JSON() {
return initJSON.Write(output.Output, &initResult{
Result: &install.Result{
Schema: install.ResultSchema,
Kind: "install",
Mode: install.ModeResolve,
Server: install.ServerChange{
Product: result.Lock.Server.Product,
Minecraft: result.Lock.Server.Minecraft,
Version: result.Lock.Server.CoreVersion,
},
Packages: []install.PackageChange{},
Phases: []install.Phase{},
TotalPackages: len(result.Lock.Packages),
PublishedManifest: true,
PublishedLock: result.PublishedLock,
WarningMessages: output.Warnings(),
},
PublishedConfig: result.PublishedConfig,
})
}
written := []string{document.ManifestFilename}
if result.PublishedLock {
written = append(written, document.LockFilename)
}
if result.PublishedConfig {
written = append(written, config.WorkspaceFilename)
}
fmt.Fprintf(
output.Human(),
"Wrote %s for Minecraft %s (%s)\n Recorded %s\n",
writtenFilesLabel(written),
result.Document.Server.Minecraft,
result.Document.Server.Core.Product,
packageCountLabel(len(result.Lock.Packages)),
)
return nil
}
// writtenFilesLabel names the files a command wrote in running prose.
func writtenFilesLabel(paths []string) string {
if len(paths) < 2 {
return strings.Join(paths, "")
}
return strings.Join(paths[:len(paths)-1], ", ") + " and " + paths[len(paths)-1]
}
// initializationFailure turns a typed selection failure into an actionable
// report. The commands name observed installations by identity.
func initializationFailure(err error, result *operation.InitResult) error {
var unreadable []string
if result != nil {
unreadable = unreadableFindingLines(&result.Discovery)
}
var selectionErr *discovery.SelectionError
if !errors.As(err, &selectionErr) {
if len(unreadable) == 0 {
return err
}
return &report.Detail{
Title: err.Error(),
Lines: unreadable,
Cause: err,
}
}
detail := &report.Detail{Cause: err}
var commands []string
switch selectionErr.State {
case discovery.SelectionAmbiguous:
detail.Title = "several server runtimes share this directory"
commands = installationCommands(selectionErr.Installations)
case discovery.SelectionUnmatched:
detail.Title = "no installed server matches the requested filters"
detail.Lines = observedInstallationLines(selectionErr.Installations)
case discovery.SelectionMissingDeclared:
detail.Title = "the declared server installation is missing"
case discovery.SelectionInvalid:
detail.Title = "no launchable server installation was found"
default:
return err
}
detail.Lines = append(detail.Lines, commands...)
detail.Lines = append(detail.Lines, unreadable...)
if len(commands) > 0 {
detail.Hint = "Run one of these commands to select the server to initialize."
} else if selectionErr.State == discovery.SelectionUnmatched {
detail.Hint = "Omit --core, --core-version, and --minecraft to choose interactively, or pass values that match an installed server."
}
return detail
}
func installationCommands(installations []discovery.Installation) []string {
var commands []string
seen := map[string]bool{}
for i := range installations {
identity := installations[i].Identity
if !identity.IsValid() {
continue
}
command := identitySelectionCommand(identity)
if command == "" || seen[command] {
continue
}
seen[command] = true
commands = append(commands, command)
}
return commands
}
func observedInstallationLines(installations []discovery.Installation) []string {
lines := make([]string, 0, len(installations))
seen := map[string]bool{}
for i := range installations {
identity := installations[i].Identity
if !identity.IsValid() {
continue
}
label := installationIdentityLabel(identity)
if seen[label] {
continue
}
seen[label] = true
lines = append(lines, label)
}
return lines
}
// initExpectation builds the invocation filter from the selection flags. It
// never supplies facts; discovery still has to observe a matching runtime.
func initExpectation(cmd *cobra.Command) (*discovery.Expectation, error) {
core := strings.TrimSpace(flagStringInit(cmd, flagInitCoreName))
coreVersion, err := concreteInitVersion(cmd, flagInitCoreVersionName)
if err != nil {
return nil, err
}
minecraft, err := concreteInitVersion(cmd, flagInitMinecraftName)
if err != nil {
return nil, err
}
if core == "" && coreVersion == "" && minecraft == "" {
return nil, nil
}
if coreVersion != "" && core == "" {
return nil, fmt.Errorf("--%s needs --%s", flagInitCoreVersionName, flagInitCoreName)
}
product, known := serverpkg.ParseProduct(core)
if !known {
product = serverpkg.Product(strings.ToLower(core))
}
return &discovery.Expectation{
Product: product,
Minecraft: minecraft,
CoreVersion: coreVersion,
}, nil
}
func concreteInitVersion(
cmd *cobra.Command,
name string,
) (versionpkg.Version, error) {
raw := strings.TrimSpace(flagStringInit(cmd, name))
if raw == "" {
return "", nil
}
value := versionpkg.Version(raw)
if value.IsInvalid() || value.CanInfer() {
return "", fmt.Errorf("--%s expects an exact version, got %q", name, raw)
}
return value, nil
}
func promptRuntime(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
observed discovery.Result,
) (*discovery.Installation, error) {
// A closed gate returns no selection, so Initialize reports the typed
// ambiguous-selection error whose commands name identities exactly.
if !NewPromptGate(cmd, inv).Available() {
return nil, nil
}
options := make([]huh.Option[int], 0, len(observed.Installations))
for i := range observed.Installations {
installation := &observed.Installations[i]
if !installation.Identity.IsValid() {
continue
}
options = append(options, huh.NewOption(
installationIdentityLabel(installation.Identity),
i,
))
}
if len(options) == 0 {
return nil, nil
}
selected := -1
form := huh.NewForm(huh.NewGroup(huh.NewSelect[int]().
Title("Select the server to initialize").
Description("Use --core, --core-version, and --minecraft to make this selection without a prompt.").
Options(options...).Value(&selected))).
WithInput(cmd.InOrStdin()).WithOutput(cmd.ErrOrStderr())
if err := RunPrompt(ctx, form); err != nil {
return nil, fmt.Errorf("server selection cancelled: %w", err)
}
if selected < 0 || selected >= len(observed.Installations) {
return nil, nil
}
return &observed.Installations[selected], nil
}
func flagStringInit(cmd *cobra.Command, name string) string {
value, _ := cmd.Flags().GetString(name)
return value
}
func flagBoolInit(cmd *cobra.Command, name string) bool {
value, _ := cmd.Flags().GetBool(name)
return value
}
package cli
import (
"fmt"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/javainstall"
"github.com/spf13/cobra"
)
const (
flagInstallLockedName = "locked"
flagInstallOfflineName = "offline"
flagInstallWithOptionalName = "with-optional"
flagInstallAcceptBrokenName = "accept-broken"
flagInstallOverwriteName = "overwrite"
flagInstallForceName = "force"
flagInstallJavaName = "java"
flagInstallJavaRepoName = "add-java-repository"
flagInstallMCDRVenvName = "mcdr-venv"
flagInstallRefreshBootstrapName = "refresh-bootstrap"
)
func NewInstallCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "install",
Short: help.InstallShort,
Args: cobra.NoArgs,
Aliases: []string{"i"},
RunE: func(cmd *cobra.Command, args []string) error {
return actionInstall(cmd, inv, deps, args)
},
}
installJSON.Bind(contracts, cmd)
cmd.Flags().Bool(
flagInstallLockedName,
false,
"Do not resolve new versions; fail when the lock cannot satisfy",
)
cmd.Flags().Bool(
flagInstallOfflineName,
false,
"Disallow network acquisition; fail if any file is missing or mismatched",
)
cmd.Flags().Bool(
flagInstallWithOptionalName,
false,
"Also install optional dependencies and record them as explicit packages",
)
cmd.Flags().Bool(
flagInstallAcceptBrokenName,
false,
"Complete the installation even when required modules are missing or versions do not satisfy their constraints",
)
cmd.Flags().Bool(
flagInstallOverwriteName,
false,
"Replace files already present at package destinations",
)
cmd.Flags().BoolP(
flagInstallForceName,
"f",
false,
"Combine --accept-broken and --overwrite",
)
cmd.Flags().Bool(
flagInstallJavaName,
false,
"Also install the Java runtime the server asks for when no installed runtime meets it",
)
cmd.Flags().Bool(
flagInstallJavaRepoName,
false,
"Let --java add the Java vendor's package repository to the system package manager",
)
cmd.Flags().Bool(
flagInstallMCDRVenvName,
false,
"Create an isolated MCDReforged Python environment instead of using the global MCDReforged executable",
)
cmd.Flags().Bool(
flagInstallRefreshBootstrapName,
false,
"Run bootstrap again instead of reusing the current runtime or a snapshot",
)
return cmd
}
func actionInstall(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
locked, _ := cmd.Flags().GetBool(flagInstallLockedName)
offline, _ := cmd.Flags().GetBool(flagInstallOfflineName)
withOptional, _ := cmd.Flags().GetBool(flagInstallWithOptionalName)
acceptBroken, _ := cmd.Flags().GetBool(flagInstallAcceptBrokenName)
overwrite, _ := cmd.Flags().GetBool(flagInstallOverwriteName)
force, _ := cmd.Flags().GetBool(flagInstallForceName)
installJava, _ := cmd.Flags().GetBool(flagInstallJavaName)
addJavaRepository, _ := cmd.Flags().GetBool(flagInstallJavaRepoName)
mcdrVenv, _ := cmd.Flags().GetBool(flagInstallMCDRVenvName)
refreshBootstrap, _ := cmd.Flags().GetBool(flagInstallRefreshBootstrapName)
if addJavaRepository && !installJava {
return fmt.Errorf("--%s needs --%s", flagInstallJavaRepoName, flagInstallJavaName)
}
opts := install.Options{
Locked: locked,
Offline: offline,
AcceptBroken: acceptBroken || force,
Overwrite: overwrite || force,
WithOptional: withOptional,
MCDRVenv: mcdrVenv,
PublishManifest: false,
RefreshBootstrap: refreshBootstrap,
}
output := newInstallOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
if installJava {
opts.ProvisionJava = output.provisionJava(
deps.JavaHost,
javainstall.Policy{
Interactive: NewPromptGate(cmd, inv).Available(),
AllowRepository: addJavaRepository,
},
offline,
)
}
ctx, stop := CommandContext(cmd)
defer stop()
result, err := deps.Operations.Sync(ctx, inv.Directory, opts)
if err != nil {
return output.Failure(err)
}
return output.Render(result)
}
package cli
import (
"context"
"fmt"
"io"
"github.com/mclucy/lucy/internal/javainstall"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/terminal/report"
)
// provisionJava installs the first usable plan, most native first. A configured
// runtime is the user's choice, so the hook leaves it unchanged. Installation
// needs network access.
func (o *installOutput) provisionJava(
host *javainstall.Host,
policy javainstall.Policy,
offline bool,
) func(context.Context, javaruntime.Requirement, *javaruntime.Check) (string, error) {
return func(ctx context.Context, _ javaruntime.Requirement, check *javaruntime.Check) (string, error) {
if check.Source == javaruntime.SourceConfigured {
o.inv.Logger.Info(
"java installation skipped",
"reason", check.ConfigPath+" selects the Java runtime",
"home", check.ConfiguredHome,
)
return "", nil
}
if offline {
return "", &report.Detail{
Title: "cannot install Java while offline",
Lines: []string{fmt.Sprintf(
"no installed runtime meets the requirement for Java %d, and every installation method needs network access",
check.Target,
)},
Hint: "Run lucy install --java without --offline, or select a runtime with lucy config set java.home <home>.",
}
}
request := javainstall.Request{Major: check.Target, Distribution: check.Distribution}
plans, skipped, err := host.Plans(ctx, request, policy)
if err != nil {
return "", err
}
if len(plans) == 0 {
return "", noJavaPlanDetail(request, skipped)
}
plan := plans[0]
o.inv.Logger.Info(
"java install plan selected",
"method", plan.Method,
"package", plan.Package,
"alternatives", len(plans)-1,
"skipped", len(skipped),
)
var home string
err = o.suspend(func(w io.Writer) error {
fmt.Fprintf(
w,
"%s Java %d (%s) with %s\n",
o.inv.Theme.Accent("Installing"),
request.Major,
javaDistributionLabel(plan.Distribution),
plan.Method,
)
for _, line := range plan.Commands() {
fmt.Fprintln(w, " "+o.inv.Theme.Muted(line))
}
if plan.Method == javainstall.MethodDownload {
for _, s := range skipped {
fmt.Fprintln(w, " "+o.inv.Theme.Muted(skipText(s)))
}
}
var executeErr error
home, executeErr = host.Execute(ctx, plan, policy, o.input, w)
return executeErr
})
return home, err
}
}
// suspend stops the progress area while run owns the terminal, so a package
// manager can prompt for a password, then starts a new progress area.
func (o *installOutput) suspend(run func(io.Writer) error) error {
o.renderer.Close()
defer o.RestartProgress()
return run(o.Human())
}
func noJavaPlanDetail(request javainstall.Request, skipped []javainstall.Skipped) error {
detail := &report.Detail{
Title: fmt.Sprintf(
"no way to install Java %d (%s) is available here",
request.Major,
javaDistributionLabel(request.Distribution),
),
}
for _, s := range skipped {
detail.Lines = append(detail.Lines, skipText(s))
}
if len(skipped) == 0 {
detail.Hint = "Install the Java runtime manually, then run lucy config set java.home <home>."
}
return detail
}
func skipText(s javainstall.Skipped) string {
offer := fmt.Sprintf("%s offers %s", s.Plan.Method, s.Plan.Package)
switch s.Reason {
case javainstall.SkipNeedsRepositoryConsent:
return fmt.Sprintf(
"%s from %s (%s); rerun with --%s to add the repository",
offer,
s.Plan.Repository.Name,
s.Plan.Repository.URL,
flagInstallJavaRepoName,
)
case javainstall.SkipNeedsTerminal:
return offer + ", but it asks for confirmation; rerun in an interactive terminal"
case javainstall.SkipNeedsRoot:
return offer + ", but it needs root; rerun as root or with sudo access"
default:
return offer
}
}
package cli
import (
"github.com/mclucy/lucy/internal/telemetry"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/terminal/pager"
"github.com/mclucy/lucy/terminal/style"
)
// Invocation is the state of one `lucy` run that every command shares:
// where the run operates, which diagnostics it may write, and how it may
// present results. It carries no services and no ambient lookups; commands
// receive the services they use as explicit constructor parameters.
//
// Directory is resolved before actions run. Theme, Stdout, Stderr, and
// Interactive depend on parsed persistent flags, so the root wiring fills
// them before the action executes.
type Invocation struct {
// Directory is the absolute directory the command operates on. Server
// selection resolves it; handlers never read or change the process
// working directory.
Directory string
// Logger receives diagnostics for this run. A nil Logger deliberately
// records nothing.
Logger *log.Logger
Theme style.Theme
Stdout style.Terminal
Stderr style.Terminal
// Interactive reports whether prompts and animated output are allowed.
Interactive bool
// ASCII selects plain-glyph output when styling is disabled.
ASCII bool
// Pager selects when long human documents go through the pager.
Pager pager.Mode
// TelemetryEnabled permits projections of facts already observed by a command.
TelemetryEnabled bool
// TelemetryObservation accumulates bounded execution and observed workload
// facts for this run when telemetry is enabled. A nil observation records
// nothing.
TelemetryObservation *TelemetryObservation
// TelemetryContexts holds only explicitly projected, bounded observations.
TelemetryContexts []telemetry.Context
}
// NewInvocation prepares the per-run state for directory. Presentation
// fields stay at their no-color, pipe defaults until the root wiring
// configures them.
func NewInvocation(directory string, logger *log.Logger) *Invocation {
return &Invocation{
Directory: directory,
Logger: logger,
Theme: style.New(false),
Stdout: style.Terminal{Width: 80, Height: 24},
Stderr: style.Terminal{Width: 80, Height: 24},
Interactive: false,
Pager: pager.Auto,
}
}
package cli
import (
"context"
"errors"
"fmt"
"io"
"os"
"slices"
"strconv"
"strings"
"charm.land/huh/v2"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/java"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/operation"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
const flagJavaDistributionName = "distribution"
// javaChoices lists the long-term support releases that the interactive form
// offers next to the installed major versions.
var javaChoices = []int{8, 11, 17, 21, 25}
var javaListJSON JSONResult[javaListView]
var javaUseJSON JSONResult[*operation.JavaChangeResult]
func NewJavaCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
javaCmd := &cobra.Command{
Use: "java <subcommand>",
Short: help.JavaShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Help()
},
}
MarkHelpOnly(javaCmd)
javaListCmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: help.JavaListShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionJavaList(cmd, inv, deps, args)
},
}
javaUseCmd := &cobra.Command{
Use: "use [version|auto]",
Short: help.JavaUseShort,
Long: help.JavaUseLong,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionJavaUse(cmd, inv, deps, args)
},
}
javaListJSON.Bind(contracts, javaListCmd)
javaUseJSON.Bind(contracts, javaUseCmd)
javaUseCmd.Flags().String(
flagJavaDistributionName,
"",
"Pin a Java distribution in lucy.yaml, or auto to accept any",
)
MarkTelemetryPositionArgument(javaUseCmd, 1, TelemetryArgumentVersion)
javaCmd.AddCommand(javaListCmd, javaUseCmd)
return javaCmd
}
// javaListView is the machine-readable `java list` result.
type javaListView struct {
Requirement *javaruntime.Requirement `json:"requirement,omitempty"`
Selection *javaruntime.Check `json:"selection,omitempty"`
Runtimes []javaRuntimeView `json:"runtimes"`
}
type javaRuntimeView struct {
javaruntime.Runtime
Selected bool `json:"selected"`
Problems []string `json:"problems,omitempty"`
}
func actionJavaList(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
root := inv.Directory
ctx, stop := CommandContext(cmd)
defer stop()
requirement, err := lockedJavaRequirement(root, inv)
if err != nil {
return err
}
runtimes, err := javaruntime.Installed(ctx, inv.Logger)
if err != nil {
recordJavaTelemetryFailure(inv)
return err
}
view := javaListView{Requirement: requirement, Runtimes: []javaRuntimeView{}}
if requirement != nil {
if view.Selection, err = javaruntime.Select(
ctx,
root,
*requirement,
inv.Logger,
); err != nil {
recordJavaTelemetryFailure(inv)
return err
}
}
for _, runtime := range runtimes {
entry := javaRuntimeView{Runtime: runtime}
if requirement != nil {
entry.Problems = requirement.Misses(&runtime)
}
entry.Selected = view.Selection != nil && view.Selection.Runtime != nil &&
view.Selection.Runtime.Home == runtime.Home
view.Runtimes = append(view.Runtimes, entry)
}
recordJavaTelemetry(inv, view.Selection)
output := NewQueryOutput(cmd, inv)
if output.JSON() {
return javaListJSON.Write(output, view)
}
if err := output.Document(func(out io.Writer, _ style.Terminal) error {
if requirement == nil {
fmt.Fprintf(
out,
"No %s; run lucy install to resolve the Java the server asks for.\n",
document.LockFilename,
)
} else {
writeJavaRequirement(out, requirement, inv.Theme)
}
if view.Selection != nil && view.Selection.Source == javaruntime.SourceConfigured {
fmt.Fprintf(out, "%s selects %s\n", view.Selection.ConfigPath, view.Selection.ConfiguredHome)
}
fmt.Fprintln(out)
if len(view.Runtimes) == 0 {
fmt.Fprintln(out, "No Java runtime found.")
}
for _, entry := range view.Runtimes {
writeJavaRuntime(out, entry, requirement != nil, inv.Theme)
}
return nil
}); err != nil {
return err
}
if view.Selection != nil {
reporter := report.New(cmd.ErrOrStderr(), inv.Theme)
for _, warning := range javaWarnings(view.Selection) {
reporter.Warn(warning)
}
}
return nil
}
func writeJavaRequirement(
out io.Writer,
requirement *javaruntime.Requirement,
theme style.Theme,
) {
target := strconv.Itoa(requirement.Target())
fmt.Fprintf(
out,
"%s %s\n",
theme.Accent("Requires"),
javaSpecLabel(target, requirement.Distribution),
)
width := 0
for _, c := range requirement.Constraints {
width = max(width, len(c.Source))
}
for _, c := range requirement.Constraints {
fmt.Fprintf(
out,
" %-*s %s\n",
width,
c.Source,
theme.Muted(c.Expression),
)
}
}
func writeJavaRuntime(
out io.Writer,
entry javaRuntimeView,
checked bool,
theme style.Theme,
) {
marker := " "
switch {
case !checked:
case len(entry.Problems) == 0:
marker = theme.Success("✓")
default:
marker = theme.Failure("✗")
}
line := fmt.Sprintf(
"%s %-3d %-12s %-22s %s",
marker,
entry.Major,
entry.Version,
entry.Build(),
theme.Muted(entry.Home),
)
if entry.Selected {
line += " " + theme.Accent("(selected)")
}
fmt.Fprintln(out, line)
}
func actionJavaUse(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
root := inv.Directory
ctx, stop := CommandContext(cmd)
defer stop()
change, err := javaChangeFromFlags(cmd, args)
if err != nil {
return err
}
if change == (operation.JavaChange{}) {
if !NewPromptGate(cmd, inv).Available() {
return fmt.Errorf(
"specify a Java version, auto, or --%s; interactive selection is unavailable "+
"with --no-interactive or without a terminal",
flagJavaDistributionName,
)
}
if change, err = promptJavaChange(ctx, root, NewPromptGate(cmd, inv), inv.Logger); err != nil {
return err
}
}
result, err := deps.Operations.SetJava(ctx, root, change)
if err != nil {
return err
}
output := NewOperationOutput(cmd, inv)
if output.JSON() {
return javaUseJSON.Write(output, result)
}
out := output.Human()
fmt.Fprintf(out, "%s: %s\n", document.ManifestFilename, javaOverrideLabel(result.Java))
if result.PublishedManifest {
fmt.Fprintf(out, "Run lucy install to update %s.\n", document.LockFilename)
}
return nil
}
func javaChangeFromFlags(cmd *cobra.Command, args []string) (operation.JavaChange, error) {
var change operation.JavaChange
if len(args) == 1 {
version, err := parseJavaMajor(args[0])
if err != nil {
return change, err
}
change.Version = &version
}
if cmd.Flags().Changed(flagJavaDistributionName) {
raw, _ := cmd.Flags().GetString(flagJavaDistributionName)
distribution, err := document.ParseJavaDistribution(raw)
if err != nil {
return change, err
}
change.Distribution = &distribution
}
return change, nil
}
func parseJavaMajor(raw string) (int, error) {
raw = strings.TrimSpace(raw)
if strings.EqualFold(raw, document.JavaAuto) {
return 0, nil
}
version, err := strconv.Atoi(raw)
if err != nil || version < document.MinimumJava {
return 0, fmt.Errorf(
"%q is not a Java major version of %d or later, or auto",
raw,
document.MinimumJava,
)
}
return version, nil
}
// promptJavaChange asks for the Java version and distribution that lucy.yaml
// pins. Each answer starts at the current value.
func promptJavaChange(
ctx context.Context,
root string,
gate PromptGate,
logger *log.Logger,
) (operation.JavaChange, error) {
d, err := document.ManifestFile(root).Read()
if err != nil {
return operation.JavaChange{}, err
}
runtimes, err := javaruntime.Installed(ctx, logger)
if err != nil {
return operation.JavaChange{}, err
}
current := document.ManifestJava{}
if d.Server.Java != nil {
current = *d.Server.Java
}
version, distribution := current.Version, current.Distribution
majors := slices.Clone(javaChoices)
for _, runtime := range runtimes {
majors = append(majors, runtime.Major)
}
if version != 0 {
majors = append(majors, version)
}
slices.Sort(majors)
majors = slices.Compact(majors)
slices.Reverse(majors)
versionOptions := []huh.Option[int]{
huh.NewOption("auto (the version Mojang recommends)", 0),
}
for _, major := range majors {
versionOptions = append(versionOptions, huh.NewOption("Java "+strconv.Itoa(major), major))
}
distributionOptions := []huh.Option[java.Distribution]{
huh.NewOption("auto (any distribution)", java.DistributionAny),
}
for _, known := range java.Distributions {
distributionOptions = append(
distributionOptions,
huh.NewOption(known.Title()+" ("+string(known)+")", known),
)
}
form := huh.NewForm(
huh.NewGroup(
huh.NewSelect[int]().
Title("Java version in "+document.ManifestFilename).
Options(versionOptions...).
Value(&version),
huh.NewSelect[java.Distribution]().
Title("Java distribution in "+document.ManifestFilename).
Options(distributionOptions...).
Value(&distribution),
),
).
WithInput(gate.Input()).
WithOutput(gate.Output())
if err := RunPrompt(ctx, form); err != nil {
return operation.JavaChange{}, err
}
return operation.JavaChange{
Version: &version,
Distribution: &distribution,
}, nil
}
// lockedJavaRequirement returns the Java requirement of the lock in root, or
// nil when the workspace has no lock.
func lockedJavaRequirement(root string, inv *Invocation) (*javaruntime.Requirement, error) {
lock, err := document.LockFile(root).Read()
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
requirement := javaruntime.RequirementOf(lock, inv.Logger)
return &requirement, nil
}
// javaWarnings turns the problems of a Java check into warnings, with a hint
// that names the command that fixes them.
func javaWarnings(check *javaruntime.Check) []error {
if check == nil || check.Satisfied() {
return nil
}
warnings := make([]error, 0, len(check.Problems)+1)
for _, problem := range check.Problems {
warnings = append(warnings, errors.New(problem))
}
if check.Source == javaruntime.SourceConfigured {
warnings = append(warnings, errors.New(
"run lucy config set java.home <home> to select another Java runtime, "+
"or lucy config set java.home '' to let Lucy choose",
))
return warnings
}
warnings = append(warnings, fmt.Errorf(
"run lucy install --java to install Java %d (%s)",
check.Target,
javaDistributionLabel(check.Distribution),
))
return warnings
}
func javaDistributionLabel(distribution java.Distribution) string {
if distribution == java.DistributionAny {
return "any distribution"
}
return distribution.Title()
}
func javaSpecLabel(version string, distribution java.Distribution) string {
return "Java " + version + " from " + javaDistributionLabel(distribution)
}
func javaOverrideLabel(override *document.ManifestJava) string {
if override.IsAuto() {
return javaSpecLabel(document.JavaAuto, java.DistributionAny)
}
version := document.JavaAuto
if override.Version != 0 {
version = strconv.Itoa(override.Version)
}
return javaSpecLabel(version, override.Distribution)
}
package cli
import (
"fmt"
"reflect"
"slices"
"strconv"
"strings"
"github.com/invopop/jsonschema"
"github.com/spf13/cobra"
)
// JSONResult binds the type written by a command to its discoverable contract.
type JSONResult[T any] struct{}
func (JSONResult[T]) Bind(contracts *JSONContracts, cmd *cobra.Command) {
t := reflect.TypeFor[T]()
if !slices.Contains(contracts.results[cmd], t) {
contracts.results[cmd] = append(contracts.results[cmd], t)
}
}
func (JSONResult[T]) Write(output *Output, value T) error {
return output.writeJSON(output.cmd.OutOrStdout(), value)
}
// JSONContracts belongs to one command tree. Schemas are generated only on lookup.
type JSONContracts struct {
results map[*cobra.Command][]reflect.Type
ignored map[*cobra.Command]bool
native map[*cobra.Command]bool
}
func NewJSONContracts() *JSONContracts {
return &JSONContracts{
results: make(map[*cobra.Command][]reflect.Type),
ignored: make(map[*cobra.Command]bool),
native: make(map[*cobra.Command]bool),
}
}
func (c *JSONContracts) Ignore(cmd *cobra.Command) { c.ignored[cmd] = true }
func (c *JSONContracts) Native(cmd *cobra.Command) { c.native[cmd] = true }
func (c *JSONContracts) Ignores(cmd *cobra.Command) bool {
for current := cmd; current != nil; current = current.Parent() {
if c.ignored[current] {
return true
}
}
return false
}
func (c *JSONContracts) IsNative(cmd *cobra.Command) bool { return c.native[cmd] }
func (c *JSONContracts) Supports(cmd *cobra.Command) bool {
return len(c.results[cmd]) > 0 || c.IsNative(cmd)
}
func (c *JSONContracts) Paths(root *cobra.Command) []string {
paths := make([]string, 0)
prefix := root.Root().Name() + " "
for cmd := range c.results {
for ancestor := cmd; ancestor != nil; ancestor = ancestor.Parent() {
if ancestor == root {
paths = append(paths, strings.TrimPrefix(cmd.CommandPath(), prefix))
break
}
}
}
slices.Sort(paths)
return paths
}
func (c *JSONContracts) Schema(cmd *cobra.Command) (*jsonschema.Schema, error) {
types := c.results[cmd]
if len(types) == 0 {
return nil, fmt.Errorf("%s does not provide a JSON result schema", cmd.CommandPath())
}
schema := reflectJSONSchema(types)
schema.Title = cmd.CommandPath() + " JSON result"
return schema, nil
}
func reflectJSONSchema(types []reflect.Type) *jsonschema.Schema {
reflector := &jsonschema.Reflector{
Anonymous: true,
AdditionalFields: jsonOutputFields,
Namer: func(t reflect.Type) string {
if t.Name() == "" {
return ""
}
return strings.ReplaceAll(t.PkgPath(), "/", ".") + "." + t.Name()
},
}
if len(types) == 1 {
return reflector.ReflectFromType(types[0])
}
result := &jsonschema.Schema{
Version: jsonschema.Version,
Definitions: make(jsonschema.Definitions),
AnyOf: make([]*jsonschema.Schema, 0, len(types)),
}
for _, t := range types {
variant := reflector.ReflectFromType(t)
for name, definition := range variant.Definitions {
result.Definitions[name] = definition
}
variant.Version = ""
variant.ID = ""
variant.Definitions = nil
result.AnyOf = append(result.AnyOf, variant)
}
return result
}
// The reflector's defaults do not account for nullable pointers or JSON-v2's
// presence rules for numeric and boolean fields tagged with omitempty.
func jsonOutputFields(t reflect.Type) []reflect.StructField {
fields := make([]reflect.StructField, 0)
for i := range t.NumField() {
field := t.Field(i)
if !field.IsExported() {
continue
}
tags := strings.Split(field.Tag.Get("json"), ",")
if tags[0] == "-" || field.Anonymous && tags[0] == "" {
continue
}
omitEmpty := slices.Contains(tags[1:], "omitempty")
omitZero := slices.Contains(tags[1:], "omitzero")
keyword := ""
switch field.Type.Kind() {
case reflect.Pointer:
if !omitEmpty && !omitZero {
keyword = "nullable"
}
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
if omitEmpty && !omitZero {
keyword = "required"
}
}
if keyword == "" {
continue
}
old, exists := field.Tag.Lookup("jsonschema")
updated := keyword
if old != "" {
updated = old + "," + keyword
}
tag := string(field.Tag)
if exists {
tag = strings.Replace(tag, "jsonschema:"+strconv.Quote(old), "jsonschema:"+strconv.Quote(updated), 1)
} else {
tag += " jsonschema:" + strconv.Quote(updated)
}
field.Tag = reflect.StructTag(tag)
fields = append(fields, field)
}
return fields
}
package cli
import (
"fmt"
"io"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/depgraph"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
var leavesJSON JSONResult[leavesOutput]
func NewLeavesCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
leavesCmd := &cobra.Command{
Use: "leaves",
Short: help.LeavesShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionLeaves(cmd, inv, deps, args)
},
}
leavesJSON.Bind(contracts, leavesCmd)
leavesCmd.Flags().Bool(
"live",
false,
"Observe the live workspace instead of reading the lock",
)
return leavesCmd
}
func actionLeaves(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
forceLive, _ := cmd.Flags().GetBool("live")
output := NewQueryOutput(cmd, inv)
loaded, err := depgraph.Load(
ctx,
inv.Directory,
forceLive,
deps.Router.ResolveArtifactsByHash,
)
reportObservationFindings(loaded.Findings.Observation, output)
if err != nil {
return err
}
graph, origin := loaded.Graph, loaded.Origin
if output.JSON() {
return leavesJSON.Write(output, leavesDocument(graph, origin, output.Warnings()))
}
return output.Document(func(out io.Writer, _ style.Terminal) error {
fmt.Fprintf(out, "Using data from: %s\n\n", origin.String())
leaves := graph.Leaves()
if len(leaves) == 0 {
fmt.Fprintln(out, "No leaf packages found")
} else {
for _, leaf := range leaves {
fmt.Fprintln(out, nodeLabel(leaf))
}
}
fmt.Fprintf(out, "\n(from %s)\n", origin.String())
return nil
})
}
type leafNode struct {
ID string `json:"id"`
Version string `json:"version"`
Provider string `json:"provider,omitempty"`
Project string `json:"project,omitempty"`
Filename string `json:"filename,omitempty"`
Environment string `json:"environment"`
Ecosystem string `json:"ecosystem"`
}
// leavesOutput is the complete machine-readable `leaves` result.
type leavesOutput struct {
Leaves []leafNode `json:"leaves"`
Origin string `json:"origin"`
Warnings []string `json:"warnings,omitempty"`
}
func leavesDocument(
graph *depgraph.Graph,
origin depgraph.Origin,
warnings []string,
) leavesOutput {
leaves := graph.Leaves()
jsonLeaves := make([]leafNode, 0, len(leaves))
for _, leaf := range leaves {
jsonLeaves = append(
jsonLeaves, leafNode{
ID: leaf.ID,
Version: leaf.Version,
Provider: leaf.Provider.String(),
Project: leaf.ProjectID,
Filename: leaf.Filename,
Environment: string(leaf.Environment),
Ecosystem: leaf.Ecosystem.String(),
},
)
}
return leavesOutput{
Leaves: jsonLeaves,
Origin: origin.String(),
Warnings: warnings,
}
}
package cli
import (
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/internal/shell"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
// reportObservationFindings renders each consumed observation once.
func reportObservationFindings(observed *workspace.Workspace, output *Output) {
if observed == nil {
return
}
for _, warning := range observed.Warnings {
output.Warn(warning)
}
reportDiscoveryFindings(&observed.Discovery, output)
}
// reportDiscoveryFindings presents one discovery result. A resolved layout
// never reports a failure: automatic choices are warnings, and unmanaged or
// alternative entry points stay informational.
func reportDiscoveryFindings(observed *discovery.Result, output *Output) {
if observed == nil {
return
}
selection := observed.Selection
resolved := selection.IsValid()
automatic := selection.Source == discovery.SourcePreferred ||
selection.Source == discovery.SourceCoverage
unresolvedReported := false
unreadableReported := map[string]bool{}
for finding := range observed.Findings() {
switch finding.Kind {
case discovery.FindingAutomaticSelection:
output.Warn(automaticSelectionMessage(finding))
case discovery.FindingUnreadableFile:
key := unreadableFindingKey(finding)
if unreadableReported[key] {
continue
}
unreadableReported[key] = true
output.Warn(unreadableFindingError(finding))
case discovery.FindingUnmanagedInstallation:
message := installationFindingMessage(finding)
if output.JSON() {
output.Warn(errors.New(message))
} else {
output.Info(message)
}
case discovery.FindingMissingDeclaredInstallation:
output.Warn(errors.New(
"declared server installation is missing; run lucy install --locked",
))
case discovery.FindingOwnershipError:
output.Warn(fmt.Errorf(
"cannot verify ownership of %s: %w",
finding.Path,
finding.Cause,
))
case discovery.FindingModifiedFile:
output.Warn(fmt.Errorf(
"managed file %s was modified",
finding.Path,
))
case discovery.FindingReceiptError:
if finding.Cause != nil {
output.Warn(fmt.Errorf(
"cannot verify installation ownership: %w",
finding.Cause,
))
} else {
output.Warn(errors.New("cannot verify installation ownership"))
}
case discovery.FindingInvalidIdentity:
output.Warn(fmt.Errorf(
"cannot identify the server in %s: %v",
finding.Path,
finding.Cause,
))
case discovery.FindingConflictingIdentities,
discovery.FindingAmbiguousInstallations:
if resolved || automatic || unresolvedReported {
continue
}
message := unresolvedRuntimeMessage(finding)
if output.JSON() {
output.Warn(message)
} else {
output.Error(message)
}
unresolvedReported = true
}
}
}
// unreadableFindingKey identifies one underlying read failure. Recognizers
// can inspect the same artifact, so identical path and cause pairs collapse.
func unreadableFindingKey(finding discovery.Finding) string {
cause := ""
if finding.Cause != nil {
cause = finding.Cause.Error()
}
return finding.Path + "\x00" + cause
}
func unreadableFindingError(finding discovery.Finding) error {
if finding.Cause != nil {
return fmt.Errorf("cannot read %s: %w", finding.Path, finding.Cause)
}
return fmt.Errorf("cannot read %s", finding.Path)
}
// unreadableFindingLines presents each underlying read failure once for a
// command failure detail.
func unreadableFindingLines(result *discovery.Result) []string {
if result == nil {
return nil
}
var lines []string
seen := map[string]bool{}
for _, finding := range result.Diagnostics {
if finding.Kind != discovery.FindingUnreadableFile {
continue
}
key := unreadableFindingKey(finding)
if seen[key] {
continue
}
seen[key] = true
if finding.Cause != nil {
lines = append(
lines,
fmt.Sprintf("%s: %v", finding.Path, finding.Cause),
)
} else {
lines = append(lines, finding.Path)
}
}
return lines
}
func installationFindingMessage(finding discovery.Finding) string {
label := "unmanaged server"
switch finding.Ownership {
case discovery.OwnershipModified:
label = "modified server"
case discovery.OwnershipUnreadable, discovery.OwnershipUnknown:
label = "unreadable server"
}
return fmt.Sprintf(
"%s %s; left unchanged",
label,
installationIdentityLabel(finding.Identity),
)
}
// automaticSelectionMessage names the chosen installation and every competing
// installation. The choice is read-only; the message suggests an explicit
// selection command.
func automaticSelectionMessage(finding discovery.Finding) error {
selected := installationIdentityLabel(finding.Identity)
message := fmt.Sprintf(
"multiple server runtimes found; using %s automatically",
selected,
)
if len(finding.Identities) > 0 {
competitors := make([]string, 0, len(finding.Identities))
for _, identity := range finding.Identities {
competitors = append(competitors, installationIdentityLabel(identity))
}
message += "; also present: " + strings.Join(competitors, ", ")
}
if command := identitySelectionCommand(finding.Identity); command != "" {
message += "; run " + command + " to select one"
}
return errors.New(message)
}
func unresolvedRuntimeMessage(finding discovery.Finding) error {
identities := finding.Identities
if len(identities) == 0 && finding.Identity.IsValid() {
identities = []discovery.Identity{finding.Identity}
}
if len(identities) == 0 {
return errors.New("no unambiguous server runtime was found")
}
commands := make([]string, 0, len(identities))
seen := map[string]bool{}
for _, identity := range identities {
command := identitySelectionCommand(identity)
if command == "" || seen[command] {
continue
}
seen[command] = true
commands = append(commands, command)
}
if len(commands) == 0 {
return errors.New("no unambiguous server runtime was found")
}
return fmt.Errorf(
"cannot choose between server runtimes; select one with %s",
strings.Join(commands, " or "),
)
}
// installationIdentityLabel renders one installation identity for prompts and
// diagnostics.
func installationIdentityLabel(identity discovery.Identity) string {
name := identity.Primary.Name.String()
if product := identity.Product(); product != serverpkg.ProductUnknown {
name = product.Title()
}
parts := make([]string, 0, 2)
if name = strings.TrimSpace(name); name != "" {
parts = append(parts, name)
}
if version := identity.Primary.Version.String(); strings.TrimSpace(version) != "" {
parts = append(parts, version)
}
label := strings.Join(parts, " ")
if minecraft := identity.MinecraftVersion(); concreteIdentityVersion(minecraft) &&
identity.Product() != serverpkg.ProductMinecraft {
label += " / Minecraft " + minecraft.String()
}
if label == "" {
return "unknown server"
}
return label
}
// identitySelectionCommand renders a non-interactive selection for one
// installation identity.
func identitySelectionCommand(identity discovery.Identity) string {
parts := []string{"lucy", "init"}
switch product := identity.Product(); {
case product != serverpkg.ProductUnknown:
parts = append(parts, "--core", shell.Quote(product.String()))
case identity.Primary.Name.String() != "":
parts = append(parts, "--core", shell.Quote(identity.Primary.Name.String()))
default:
return ""
}
if version := identity.Primary.Version; concreteIdentityVersion(version) {
parts = append(parts, "--core-version", shell.Quote(version.String()))
}
if minecraft := identity.MinecraftVersion(); concreteIdentityVersion(minecraft) {
parts = append(parts, "--minecraft", shell.Quote(minecraft.String()))
}
return strings.Join(parts, " ")
}
func concreteIdentityVersion(value versionpkg.Version) bool {
return value != "" && !value.IsInvalid() && !value.CanInfer()
}
package cli
import (
"context"
"errors"
"fmt"
"io"
"strings"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
// installJSON is the machine-readable result shared by every operation that
// resolves, publishes, and installs: add, remove, install, init, and upgrade.
var installJSON JSONResult[*install.Result]
// installOutput adapts operation traces and results to the command presenter.
type installOutput struct {
*Output
input io.Reader
spool *log.ProcessSpool
note string
noted bool
phase string
phaseCount int
phaseTotal int
resolved int
pending int
rejected int
rejectedProject string
fetchedBytes int64
// activeFetches keeps received bytes per transfer name. Archive workers
// may start and finish several transfers interleaved, so one current
// transfer cannot attribute the bytes that end. Transfers that share a
// name use a FIFO slot each; a producer that passes the logical artifact
// path gives every slot a distinct key and exact accounting.
activeFetches map[string][]int64
fetchedFiles int
}
func newInstallOutput(cmd *cobra.Command, inv *Invocation) *installOutput {
output := NewOperationOutput(cmd, inv)
output.Progress()
return &installOutput{
Output: output,
input: cmd.InOrStdin(),
spool: log.NewProcessSpool(cmd.Name(), inv.Logger),
}
}
// Trace returns the hooks the operation reports through.
func (o *installOutput) Trace() *install.Trace {
trace := &install.Trace{
PhaseStarted: o.phaseStarted,
PhaseProgress: o.phaseProgress,
PhaseDone: o.phaseDone,
FetchStarted: o.fetchStarted,
FetchProgress: o.fetchProgress,
FetchDone: o.fetchDone,
ProcessOutput: processTee{area: processLog{o}, spool: o.spool},
Resolve: resolve.Trace{
State: o.resolveState,
Rejected: o.resolveRejected,
},
}
if observation := o.inv.TelemetryObservation; observation != nil {
trace.PackageCount = observation.ObservePackages
}
return trace
}
func (o *installOutput) phaseStarted(name string) {
o.inv.TelemetryObservation.PhaseStart(name)
o.phase = name
o.phaseCount = 0
o.phaseTotal = 0
o.resolved = 0
o.pending = 0
o.rejected = 0
o.rejectedProject = ""
o.fetchedFiles = 0
o.renderer.PhaseStarted(phaseLabel(name))
}
// phaseProgress reports bounded work inside the active phase. A late update
// from a phase that already ended is dropped, so a status line can never
// outlive the completion that replaced it.
func (o *installOutput) phaseProgress(name string, count, total int) {
if name != o.phase {
return
}
o.phaseCount = count
o.phaseTotal = total
o.updateStatus()
}
func (o *installOutput) phaseDone(phase install.PhaseInfo) {
o.inv.TelemetryObservation.PhaseDone(phase.Name, phase.Elapsed)
switch phase.Name {
case "packages":
o.inv.TelemetryObservation.ObservePackages(phase.Count)
case "install", "files":
// Import reports the server files it materialized, and a committed
// installation reports the files it created and replaced.
o.inv.TelemetryObservation.ObserveFiles(phase.Count)
}
o.phase = ""
o.phaseCount = 0
o.phaseTotal = 0
// An empty text ends the phase without printing: a phase whose outcome
// has no prose must still clear the live area.
o.renderer.PhaseDone(phaseText(phase), phase.Elapsed)
}
func (o *installOutput) fetchStarted(name string, size int64) {
if o.activeFetches == nil {
o.activeFetches = map[string][]int64{}
}
o.activeFetches[name] = append(o.activeFetches[name], 0)
o.renderer.Download(name, 0, size)
o.updateStatus()
}
func (o *installOutput) fetchProgress(name string, read, total int64) {
if o.activeFetches == nil {
o.activeFetches = map[string][]int64{}
}
slots := o.activeFetches[name]
if len(slots) == 0 {
slots = []int64{read}
} else {
slots[len(slots)-1] = read
}
o.activeFetches[name] = slots
o.renderer.Download(name, read, total)
o.updateStatus()
}
func (o *installOutput) fetchDone(name string, _ bool) {
if slots := o.activeFetches[name]; len(slots) > 0 {
o.fetchedBytes += slots[0]
slots = slots[1:]
if len(slots) == 0 {
delete(o.activeFetches, name)
} else {
o.activeFetches[name] = slots
}
}
o.fetchedFiles++
o.renderer.DownloadDone()
o.updateStatus()
}
func (o *installOutput) resolveState(resolved, pending int) {
o.resolved = resolved
o.pending = pending
o.updateStatus()
}
func (o *installOutput) resolveRejected(project, _, _ string) {
o.rejected++
o.rejectedProject = project
o.updateStatus()
}
func (o *installOutput) updateStatus() {
if o.phase == "" {
return
}
o.renderer.Status(o.statusText())
}
// activeBytes sums the transfers still running. Completed transfers move into
// fetchedBytes, so interleaved archive workers never double count.
func (o *installOutput) activeBytes() int64 {
var bytes int64
for _, slots := range o.activeFetches {
for _, read := range slots {
bytes += read
}
}
return bytes
}
func (o *installOutput) statusText() string {
var parts []string
if o.phase == "packages" {
parts = append(
parts,
fmt.Sprintf("%d resolved", o.resolved),
fmt.Sprintf("%d pending", o.pending),
)
}
if o.phase == "files" && o.fetchedFiles > 0 {
label := fmt.Sprintf("%d files", o.fetchedFiles)
if o.fetchedFiles == 1 {
label = "1 file"
}
parts = append(parts, label)
}
if o.phaseTotal > 0 {
switch o.phase {
case "classification":
parts = append(parts, fmt.Sprintf("%d of %d mod files", o.phaseCount, o.phaseTotal))
case "package staging":
parts = append(parts, fmt.Sprintf("%d of %d packages", o.phaseCount, o.phaseTotal))
case "processors":
parts = append(parts, fmt.Sprintf("%d of %d processors", o.phaseCount, o.phaseTotal))
}
}
if fetched := o.fetchedBytes + o.activeBytes(); fetched > 0 {
parts = append(parts, style.FormatBytesDecimal(fetched)+" fetched")
}
if o.rejectedProject != "" {
parts = append(parts, fmt.Sprintf("%d builds of %s rejected", o.rejected, o.rejectedProject))
}
return strings.Join(parts, ", ")
}
// Render prints the result. Human output goes to stderr; JSON goes to stdout.
func (o *installOutput) Render(result *install.Result) error {
if result == nil {
return nil
}
result.Warnings = append(result.Warnings, javaWarnings(result.Java)...)
warnings := warningMessages(result.Warnings)
result.WarningMessages = append(warnings, o.Warnings()...)
if o.JSON() {
return installJSON.Write(o.Output, result)
}
if !result.Changed() {
if !result.PublishedManifest && !result.PublishedLock {
line := o.inv.Theme.Success("✓") + " Already up to date"
if result.TotalPackages > 0 {
line = o.inv.Theme.Success("✓") + " " +
packageCountLabel(result.TotalPackages) + " already up to date"
}
o.renderer.Println(line)
}
} else {
var changes []string
if result.Server.Change == install.ChangeUpgraded {
changes = append(changes, serverChangeLine(result.Server, o.inv.Theme))
}
changes = append(changes, packageChangeLines(result.Packages, o.inv.Theme)...)
if len(changes) > 0 {
o.renderer.Println(append([]string{""}, changes...)...)
}
}
if line := displacedFilesLine(len(result.Files.Displaced)); line != "" {
o.renderer.Println(o.inv.Theme.Muted(line))
}
if trailer := publicationLine(result, o.inv.Theme); trailer != "" {
o.renderer.Println("", trailer)
}
// Flush the summary before warnings so the two surfaces cannot interleave.
o.renderer.Close()
for _, warning := range result.Warnings {
o.warn(warning)
}
for _, diagnostic := range result.Diagnostics {
o.warn(fmt.Errorf("%s: %s", diagnostic.Path, diagnostic.Message))
}
return nil
}
// Failure converts an operation error into the detail the command framework
// renders. When a subprocess ran, the retained process log is named once, in
// the returned error and in every detail built from it.
func (o *installOutput) Failure(err error) error {
if err == nil {
return nil
}
note := o.processLogNote()
var failure *resolve.Failure
if errors.As(err, &failure) {
detail := resolutionDetail(failure)
detail.Lines = append(detail.Lines, "Resolution did not change the manifest or lock.")
return detail
}
var committed *install.CommittedError
if errors.As(err, &committed) &&
(errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)) {
return &report.Detail{
Title: "interrupted",
Lines: detailLines(
note,
"The installation was committed, but file provisioning was interrupted.",
"Run lucy install again to finish.",
),
Cause: err,
}
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return &report.Detail{
Title: "interrupted",
Lines: detailLines(
note,
"The installation stopped before it committed; staged files were rolled back.",
),
Cause: err,
}
}
if errors.Is(err, bootstrap.ErrNoJava) {
return &report.Detail{
Title: "no Java runtime",
Lines: detailLines(note, err.Error()),
Hint: "Run lucy install --java to install the Java runtime the server asks for.",
Cause: err,
}
}
if note != "" {
return fmt.Errorf("%w\n%s", err, note)
}
return err
}
// processLogNote retains the process log and returns the sentence that names
// it. It returns an empty string when no subprocess ran, so unrelated
// failures stay unchanged. The first call fixes the sentence, so a presenter
// that adapts the failure again names the same file. A log that dropped output
// says so instead of claiming it saved everything observed.
func (o *installOutput) processLogNote() string {
if o.noted {
return o.note
}
o.noted = true
retained, ok := o.spool.Retain()
if !ok {
return ""
}
observed := style.FormatBytesDecimal(retained.Observed)
if retained.Truncated {
o.note = fmt.Sprintf(
"Subprocess output (%s observed) is incomplete: %s holds %s",
observed,
retained.Path,
style.FormatBytesDecimal(retained.Stored),
)
return o.note
}
o.note = fmt.Sprintf(
"Subprocess output (%s) saved to %s",
observed,
retained.Path,
)
return o.note
}
// Close ends the command's output lifetime. The progress area stops and an
// unretained process log is discarded, so a surviving file is always evidence
// of a failure.
func (o *installOutput) Close() {
o.Output.Close()
o.spool.Discard()
}
// EndProgress closes the progress area only. A prompt or plain report owns the
// terminal while the command keeps running, and the process log is kept for
// the steps that follow.
func (o *installOutput) EndProgress() {
o.Output.Close()
}
// detailLines appends the process log note to the fixed lines of a failure
// detail, so a human rendering and a machine document name the same evidence.
func detailLines(note string, lines ...string) []string {
if note == "" {
return lines
}
return append(lines, note)
}
// processLog forwards subprocess output to the current progress area, which
// changes when a Java installation suspends it.
type processLog struct{ o *installOutput }
func (l processLog) Write(data []byte) (int, error) {
return l.o.renderer.LogWriter().Write(data)
}
// processTee streams subprocess output to the progress area and to the
// retained process log. Section markers reach only the log, because the
// command line they name already narrates on the terminal.
type processTee struct {
area io.Writer
spool *log.ProcessSpool
}
func (t processTee) Write(data []byte) (int, error) {
written, err := t.area.Write(data)
if err != nil {
return written, err
}
return t.spool.Write(data)
}
func (t processTee) Section(label string) {
t.spool.Section(label)
}
func warningMessages(warnings []error) []string {
messages := make([]string, 0, len(warnings))
for _, warning := range warnings {
if warning != nil {
messages = append(messages, warning.Error())
}
}
return messages
}
func phaseLabel(name string) string {
switch name {
case "server":
return "Resolving server"
case "packages":
return "Resolving packages"
case "identification":
return "Identifying the installed server"
case "adoption":
return "Adopting installed packages"
case "python environment":
return "Preparing Python environment"
case "package staging":
return "Staging packages"
case "bootstrap snapshot":
return "Restoring the bootstrap snapshot"
case "install":
return "Installing"
case "download pack":
return "Downloading the modpack"
case "download archive":
return "Downloading the archive"
case "files":
return "Writing server files"
case "classification":
return "Classifying installed mods"
case "loader preparation":
return "Preparing the loader"
case "processors":
return "Running installer processors"
case "loader installer":
return "Running the loader installer"
default:
return style.Capitalize(name)
}
}
func phaseText(phase install.PhaseInfo) string {
switch phase.Name {
case "server":
if phase.Version == "" {
return fmt.Sprintf("Resolved %s", phase.Product)
}
return fmt.Sprintf(
"Resolved %s %s for Minecraft %s",
phase.Product,
phase.Version,
phase.Minecraft,
)
case "packages":
if phase.Count == 0 && phase.Total == 0 {
return ""
}
if phase.Total > 0 && phase.Count > phase.Total {
return fmt.Sprintf(
"Resolved %d packages (%d requested, %d dependencies)",
phase.Count,
phase.Total,
phase.Count-phase.Total,
)
}
return fmt.Sprintf("Resolved %d packages", phase.Count)
case "identification":
return "Identified the installed server"
case "classification":
if phase.Total == 0 {
return ""
}
if phase.Count == phase.Total {
if phase.Count == 1 {
return "Kept 1 mod file"
}
return fmt.Sprintf("Kept all %d mod files", phase.Count)
}
return fmt.Sprintf(
"Kept %d of %d mod files",
phase.Count,
phase.Total,
)
case "loader preparation":
return "Prepared the loader"
case "bootstrap snapshot":
return fmt.Sprintf("Restored %d bootstrap files without running the installer", phase.Count)
case "processors":
if phase.Count == 0 {
return ""
}
if phase.Total > 0 && phase.Count < phase.Total {
return fmt.Sprintf(
"Ran %d of %d installer processors",
phase.Count,
phase.Total,
)
}
if phase.Count == 1 {
return "Ran 1 installer processor"
}
return fmt.Sprintf("Ran %d installer processors", phase.Count)
case "python environment":
return "Prepared Python environment"
case "package staging":
if phase.Count == 0 {
return ""
}
if phase.Total > 0 && phase.Count < phase.Total {
return fmt.Sprintf(
"Staged %d of %d packages",
phase.Count,
phase.Total,
)
}
if phase.Count == 1 {
return "Staged 1 package"
}
return fmt.Sprintf("Staged %d packages", phase.Count)
case "download pack":
return "Downloaded the modpack"
case "download archive":
return "Downloaded the archive"
case "files":
if phase.Count == 0 {
return ""
}
if phase.Count == 1 {
return "Wrote 1 server file"
}
return fmt.Sprintf("Wrote %d server files", phase.Count)
case "loader installer":
return "Ran the loader installer"
case "adoption":
if phase.Total == 0 {
return ""
}
if phase.Count == phase.Total {
if phase.Count == 1 {
return "Adopted 1 installed file"
}
return fmt.Sprintf("Adopted %d installed files", phase.Count)
}
return fmt.Sprintf(
"Adopted %d of %d installed files",
phase.Count,
phase.Total,
)
case "install":
if phase.Count == 0 {
return ""
}
if phase.Count == 1 {
return "Installed 1 file"
}
return fmt.Sprintf("Installed %d files", phase.Count)
default:
return style.Capitalize(phase.Name)
}
}
func serverChangeLine(change install.ServerChange, theme style.Theme) string {
version := string(change.Version)
if change.Change == install.ChangeUpgraded {
version = fmt.Sprintf("%s → %s", change.Previous, change.Version)
}
return fmt.Sprintf(
" %s %s %s",
changeGlyph(change.Change, theme),
change.Product,
version,
)
}
func packageChangeLines(changes []install.PackageChange, theme style.Theme) []string {
width := 0
for _, change := range changes {
width = max(width, len(change.Name))
}
lines := make([]string, 0, len(changes))
for _, change := range changes {
version := string(change.Version)
switch change.Change {
case install.ChangeUpgraded, install.ChangeDowngraded, install.ChangeChanged:
version = fmt.Sprintf("%s → %s", change.Previous, change.Version)
case install.ChangeRebuilt:
if change.PreviousReleaseID != "" && change.ReleaseID != "" && change.PreviousReleaseID != change.ReleaseID {
version = fmt.Sprintf("%s (build %s → %s)", change.Version, change.PreviousReleaseID, change.ReleaseID)
} else {
version = fmt.Sprintf("%s (build changed)", change.Version)
}
}
line := fmt.Sprintf(
" %s %-*s %s",
changeGlyph(change.Change, theme),
width,
change.Name,
version,
)
if change.Change == install.ChangeAdded && !change.Direct && len(change.RequiredBy) > 0 {
line += " " + theme.Muted("dependency of "+joinLimited(change.RequiredBy, 2))
}
lines = append(lines, line)
}
return lines
}
func changeGlyph(change install.Change, theme style.Theme) string {
switch change {
case install.ChangeAdded:
return theme.Success("+")
case install.ChangeRemoved:
return theme.Failure("-")
case install.ChangeUpgraded:
return theme.Warning("~")
case install.ChangeDowngraded:
return theme.Failure("v")
case install.ChangeRebuilt:
return theme.Warning("r")
case install.ChangeChanged:
return theme.Warning("!")
default:
return " "
}
}
func joinLimited(values []string, limit int) string {
if len(values) <= limit {
return strings.Join(values, ", ")
}
return fmt.Sprintf("%s and %d more", strings.Join(values[:limit], ", "), len(values)-limit)
}
func pluralBuilds(count int) string {
if count == 1 {
return "1 build"
}
return fmt.Sprintf("%d builds", count)
}
func packageCountLabel(count int) string {
if count == 1 {
return "1 package"
}
return fmt.Sprintf("%d packages", count)
}
func publicationLine(result *install.Result, theme style.Theme) string {
switch {
case result.PublishedManifest && result.PublishedLock:
return theme.Muted("Updated lucy.yaml and lucy-lock.yaml")
case result.PublishedManifest:
return theme.Muted("Updated lucy.yaml")
case result.PublishedLock:
return theme.Muted("Updated lucy-lock.yaml")
default:
return ""
}
}
func resolutionDetail(failure *resolve.Failure) *report.Detail {
detail := &report.Detail{Cause: failure}
if failure.Aborted {
detail.Title = failure.Error()
if failure.Project != "" {
detail.Lines = append(detail.Lines, fmt.Sprintf(
"%s rejected %d builds for Minecraft %s on %s before the search stopped",
failure.Project,
failure.Candidates,
failure.Minecraft,
failure.Ecosystem,
))
appendRejectionGroups(detail, failure)
}
return detail
}
versionOnly := len(failure.Groups) == 1 &&
failure.Groups[0].Kind == resolve.RejectionVersionMismatch
if versionOnly {
group := failure.Groups[0]
detail.Title = fmt.Sprintf("%s has no build matching %q", failure.Project, group.Detail)
if failure.Candidates > 0 {
detail.Lines = append(detail.Lines, fmt.Sprintf(
"%d builds exist for Minecraft %s on %s",
failure.Candidates,
failure.Minecraft,
failure.Ecosystem,
))
}
if group.FirstVersion != "" && group.LastVersion != "" && group.FirstVersion != group.LastVersion {
detail.Lines = append(detail.Lines, group.FirstVersion+" … "+group.LastVersion)
}
if group.FirstVersion != "" {
detail.Hint = fmt.Sprintf("lucy add %s@%s", failure.Project, group.FirstVersion)
}
return detail
}
if constraint, ok := serverConstraint(failure.Groups); ok {
detail.Title = fmt.Sprintf(
"%s requires %s %s, but this server runs %s",
constraint.RequiredBy,
constraint.Dependency,
constraint.Constraint,
constraint.Selected,
)
detail.Lines = append(detail.Lines, fmt.Sprintf(
"no build of %s for Minecraft %s on %s can change it",
failure.Project,
failure.Minecraft,
failure.Ecosystem,
))
appendRejectionGroups(detail, failure)
return detail
}
detail.Title = fmt.Sprintf("no build of %s works on this server", failure.Project)
if failure.Candidates > 0 {
detail.Lines = append(detail.Lines, fmt.Sprintf(
"checked %d builds for Minecraft %s on %s",
failure.Candidates,
failure.Minecraft,
failure.Ecosystem,
))
}
appendRejectionGroups(detail, failure)
return detail
}
// serverConstraint returns the requirement the server itself fails to satisfy.
// No candidate can change it, so it is the cause of the failure.
func serverConstraint(groups []resolve.RejectionGroup) (resolve.RejectionGroup, bool) {
for _, group := range groups {
if group.Kind == resolve.RejectionServer {
return group, true
}
}
return resolve.RejectionGroup{}, false
}
// appendRejectionGroups reports each aggregated rejection on its own line.
func appendRejectionGroups(detail *report.Detail, failure *resolve.Failure) {
for _, group := range failure.Groups {
switch group.Kind {
case resolve.RejectionEmpty:
detail.Lines = append(detail.Lines, group.Detail)
case resolve.RejectionModules, resolve.RejectionServer:
prefix := pluralBuilds(group.Count)
if group.Count == failure.Candidates {
prefix = fmt.Sprintf("all %d", group.Count)
}
detail.Lines = append(detail.Lines, prefix+": "+group.Detail)
default:
detail.Lines = append(detail.Lines, pluralBuilds(group.Count)+": "+group.Detail)
}
}
}
package cli
import (
"context"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/terminal/report"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
// ErrorSchema versions the machine-readable failure document.
ErrorSchema = 1
// ErrorKind identifies a machine-readable failure document.
ErrorKind = "error"
// CodeCommandFailed marks an action that failed for an unclassified
// reason.
CodeCommandFailed = "command.failed"
// CodeInvalidInvocation marks a command line that could not be parsed or
// validated before the action ran.
CodeInvalidInvocation = "usage.invalid_invocation"
// CodeOperationCancelled marks an action interrupted through its context.
CodeOperationCancelled = "operation.cancelled"
// CodeResolveNoMatchingBuild marks a version request with no matching
// builds.
CodeResolveNoMatchingBuild = "resolve.no_matching_build"
// CodeResolveNoCompatibleBuild marks a project whose builds do not fit
// this server.
CodeResolveNoCompatibleBuild = "resolve.no_compatible_build"
)
// ErrorDocument is the single document a failure writes to stderr in machine
// mode.
type ErrorDocument struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
Code string `json:"code"`
Title string `json:"title"`
Details []string `json:"details"`
Hint string `json:"hint,omitempty"`
// Facts carries the machine-readable evidence of the error tree. Human
// rendering ignores it; the JSON document and the telemetry report body
// read it, so both describe a failure with the same data.
Facts map[string]any `json:"facts,omitempty"`
Log string `json:"log"`
}
// SetJSONRendering overrides the rendering selected when the output was
// created. The command boundary uses it when flags fail before parsing.
func (o *Output) SetJSONRendering(mode JSONRendering) {
o.json = mode
}
// JSONModeFromArgs finds output flags without mistaking another flag's value
// for an output option. It also works when Cobra stops parsing on an error.
func JSONModeFromArgs(cmd *cobra.Command, args []string) JSONRendering {
pretty, compact := false, false
flagSets := [3]*pflag.FlagSet{cmd.Flags(), cmd.InheritedFlags(), cmd.PersistentFlags()}
findFlag := func(name string, shorthand bool) *pflag.Flag {
for _, flags := range flagSets {
if shorthand {
if flag := flags.ShorthandLookup(name); flag != nil {
return flag
}
} else if flag := flags.Lookup(name); flag != nil {
return flag
}
}
return nil
}
for index := 0; index < len(args); index++ {
arg := args[index]
if arg == "--" {
break
}
if name, long := strings.CutPrefix(arg, "--"); long {
name, value, assigned := strings.Cut(name, "=")
flag := findFlag(name, false)
if flag != nil && flag.NoOptDefVal == "" && !assigned {
index++
continue
}
if !assigned {
value = "true"
}
switch name {
case FlagJSON:
pretty = boolValue(value)
case FlagJSONCompact:
compact = boolValue(value)
}
continue
}
if shorthand, short := strings.CutPrefix(arg, "-"); short {
for len(shorthand) > 0 {
flag := findFlag(shorthand[:1], true)
if flag == nil {
break
}
shorthand = shorthand[1:]
if flag.NoOptDefVal == "" {
if shorthand == "" {
index++
}
break
}
if strings.HasPrefix(shorthand, "=") {
break
}
}
}
}
if compact {
return JSONCompact
}
if pretty {
return JSONPretty
}
return JSONNone
}
func boolValue(value string) bool {
parsed, err := strconv.ParseBool(value)
return err == nil && parsed
}
// IsUsageError reports failures that happen before a command's own action:
// unknown commands or flags, missing flag values, and rejected arguments.
func IsUsageError(err error) bool {
if err == nil {
return false
}
if isUsageMessage(err.Error()) {
return true
}
switch unwrapped := err.(type) {
case interface{ Unwrap() []error }:
for _, child := range unwrapped.Unwrap() {
if IsUsageError(child) {
return true
}
}
case interface{ Unwrap() error }:
return IsUsageError(unwrapped.Unwrap())
}
return false
}
func isUsageMessage(message string) bool {
for _, prefix := range []string{
"flag needs an argument:",
"unknown flag:",
"unknown shorthand flag:",
"unknown command",
"invalid argument",
"accepts ",
"requires at least ",
"required flag(s)",
} {
if strings.HasPrefix(message, prefix) {
return true
}
}
return false
}
// IsFrameworkUsageError reports the subset of invalid invocations that the
// command framework renders with its own usage hint.
func IsFrameworkUsageError(err error) bool {
if err == nil {
return false
}
message := err.Error()
for _, prefix := range []string{
"flag needs an argument:",
"unknown flag:",
"unknown shorthand flag:",
"unknown command",
"invalid argument",
} {
if strings.HasPrefix(message, prefix) {
return true
}
}
return false
}
// UsageHint names the flags this command accepts when the framework rejected
// an unknown flag or shorthand before the command ran. Mistaking a sibling
// command's flag for this one is the common failure, and the flag list answers
// it without a second round trip to --help. It returns an empty string for
// every other failure.
func UsageHint(cmd *cobra.Command, err error) string {
if _, ok := unknownFlagName(err); !ok {
return ""
}
names := localFlagNames(cmd)
if len(names) == 0 {
return ""
}
return cmd.CommandPath() + " accepts " + strings.Join(names, ", ") + "."
}
// unknownFlagName reports the rejected flag, spelled as the caller wrote it.
func unknownFlagName(err error) (string, bool) {
if err == nil {
return "", false
}
message := err.Error()
if name, ok := strings.CutPrefix(message, "unknown flag: "); ok {
return name, true
}
rest, ok := strings.CutPrefix(message, "unknown shorthand flag: ")
if !ok || len(rest) < 3 || rest[0] != '\'' {
return "", false
}
end := strings.Index(rest[1:], "'")
if end <= 0 {
return "", false
}
return "-" + rest[1:1+end], true
}
// localFlagNames lists the flags this command answers to, sorted for a stable
// message: everything it declares itself, plus the persistent flags of the
// command groups above it, such as `lucy config --global`. The root's
// persistent set stays out because it is identical for every command and does
// not explain this rejection, and so do the framework's --help and --version.
func localFlagNames(cmd *cobra.Command) []string {
if cmd == nil {
return nil
}
collected := map[string]bool{}
collect := func(flags *pflag.FlagSet) {
flags.VisitAll(func(flag *pflag.Flag) {
switch flag.Name {
case "help", "version":
return
}
if flag.Hidden {
return
}
collected["--"+flag.Name] = true
})
}
collect(cmd.LocalNonPersistentFlags())
if root := cmd.Root(); cmd != root {
collect(cmd.PersistentFlags())
for parent := cmd.Parent(); parent != nil && parent != root; parent = parent.Parent() {
collect(parent.PersistentFlags())
}
}
names := make([]string, 0, len(collected))
for name := range collected {
names = append(names, name)
}
sort.Strings(names)
return names
}
// WriteError renders one failure. Machine mode writes a single document to
// stderr; human mode keeps the structured detail formatting and names the log
// file. The command boundary calls it exactly once per failure.
func (o *Output) WriteError(err error, logPath string) {
if err == nil || o == nil || o.cmd == nil {
return
}
if o.JSON() {
_ = o.writeJSON(o.cmd.ErrOrStderr(), newErrorDocument(o.cmd, err, logPath))
return
}
o.writeHumanError(err, logPath)
}
func (o *Output) writeHumanError(err error, logPath string) {
writer := o.cmd.ErrOrStderr()
var detail *report.Detail
if errors.As(err, &detail) && detail != nil {
report.RenderDetail(writer, detail, o.inv.Theme)
} else if IsUsageError(err) {
fmt.Fprintln(writer, o.inv.Theme.Failure("error:")+" "+err.Error())
hint := UsageHint(o.cmd, err)
if hint == "" {
hint = "Run --help for usage."
}
fmt.Fprintln(writer, " "+o.inv.Theme.Note("hint:")+" "+hint)
} else {
report.New(writer, o.inv.Theme).Error(err)
}
if logPath != "" {
fmt.Fprintf(writer, " %s %s\n", o.inv.Theme.Muted("log:"), logPath)
}
}
func newErrorDocument(cmd *cobra.Command, err error, logPath string) ErrorDocument {
document := ErrorDocument{
Schema: ErrorSchema,
Kind: ErrorKind,
Details: []string{},
Log: logPath,
}
detail := errorDetail(err)
if detail != nil {
document.Title = plain(detail.Title)
for _, line := range detail.Lines {
document.Details = append(document.Details, plain(line))
}
document.Hint = plain(detail.Hint)
document.Code = detail.Code
if document.Title == "" && detail.Cause != nil {
document.Title = plain(detail.Cause.Error())
}
document.Details = append(document.Details, joinedDetails(err, detail)...)
} else {
lines := errorLines(err)
if len(lines) > 0 {
document.Title = lines[0]
document.Details = append(document.Details, lines[1:]...)
}
}
if document.Title == "" {
document.Title = "command failed"
}
if document.Code == "" {
document.Code = errorCode(err)
}
if document.Hint == "" && document.Code == CodeInvalidInvocation {
document.Hint = UsageHint(cmd, err)
if document.Hint == "" {
document.Hint = "Run --help for usage."
}
}
document.Facts = FailureFacts(err)
return document
}
func errorDetail(err error) *report.Detail {
var detail *report.Detail
if errors.As(err, &detail) && detail != nil {
return detail
}
var failure *resolve.Failure
if errors.As(err, &failure) && failure != nil {
return resolutionDetail(failure)
}
return nil
}
// joinedDetails keeps secondary failures, such as a log file that fails to
// close, inside the primary failure's document instead of dropping them or
// writing a second document.
func joinedDetails(err error, primary *report.Detail) []string {
joined, ok := err.(interface{ Unwrap() []error })
if !ok {
return nil
}
var lines []string
for _, child := range joined.Unwrap() {
var detail *report.Detail
if errors.As(child, &detail) && detail == primary {
continue
}
if primary.Cause != nil && errors.Is(child, primary.Cause) {
continue
}
lines = append(lines, errorLines(child)...)
}
return lines
}
func errorLines(err error) []string {
raw := strings.Split(plain(err.Error()), "\n")
lines := make([]string, 0, len(raw))
for _, line := range raw {
line = strings.TrimSuffix(line, "\r")
if line == "" {
continue
}
lines = append(lines, line)
}
return lines
}
func errorCode(err error) string {
switch {
case IsUsageError(err):
return CodeInvalidInvocation
case errors.Is(err, context.Canceled),
errors.Is(err, context.DeadlineExceeded):
return CodeOperationCancelled
}
var failure *resolve.Failure
if errors.As(err, &failure) && failure != nil {
if failure.Aborted {
return CodeCommandFailed
}
if len(failure.Groups) == 1 &&
failure.Groups[0].Kind == resolve.RejectionVersionMismatch {
return CodeResolveNoMatchingBuild
}
return CodeResolveNoCompatibleBuild
}
return CodeCommandFailed
}
func plain(value string) string {
return ansi.Strip(value)
}
package cli
import (
"bytes"
"io"
"github.com/mclucy/lucy/terminal/pager"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
// FlagPager selects when long human output goes through the pager.
const FlagPager = "pager"
// AddPagerFlag registers the pager mode on the root command. A bare --pager
// requests paging regardless of document length.
func AddPagerFlag(root *cobra.Command, inv *Invocation) {
root.PersistentFlags().Var(
pagerModeValue{mode: &inv.Pager},
FlagPager,
"Page long human output: auto, always, or never; --pager alone means always",
)
root.PersistentFlags().Lookup(FlagPager).NoOptDefVal = pager.Always.String()
_ = root.RegisterFlagCompletionFunc(
FlagPager,
func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return []string{"auto", "always", "never"}, cobra.ShellCompDirectiveNoFileComp
},
)
}
type pagerModeValue struct {
mode *pager.Mode
}
func (v pagerModeValue) String() string {
if v.mode == nil {
return pager.Auto.String()
}
return v.mode.String()
}
func (v pagerModeValue) Set(raw string) error {
mode, err := pager.ParseMode(raw)
if err != nil {
return err
}
*v.mode = mode
return nil
}
func (v pagerModeValue) Type() string { return "mode" }
// PageDocument renders one human document, paging it when the invocation and
// terminal allow it. Rendering completes before the pager starts, so a pipe,
// redirect, or test sees the same bytes it would without a pager. While the
// pager is open, a resize re-renders the document at the new geometry.
func PageDocument(
cmd *cobra.Command,
inv *Invocation,
writer io.Writer,
render func(io.Writer, style.Terminal) error,
) error {
if !inv.Interactive || inv.Pager == pager.Never {
return render(writer, inv.Stdout)
}
renderAt := func(width, height int) (string, error) {
var document bytes.Buffer
screen := inv.Stdout
screen.Width = width
screen.Height = height
if err := render(&document, screen); err != nil {
return "", err
}
return document.String(), nil
}
initial, err := renderAt(inv.Stdout.Width, inv.Stdout.Height)
if err != nil {
return err
}
handled, pagerErr := pager.Show(pager.Options{
Title: cmd.CommandPath(),
Text: initial,
Render: renderAt,
Input: cmd.InOrStdin(),
Output: writer,
Terminal: inv.Stdout,
Theme: inv.Theme,
Mode: inv.Pager,
})
if handled && pagerErr == nil {
return nil
}
if _, err := io.WriteString(writer, initial); err != nil {
return err
}
return pagerErr
}
// Document renders a command's human result through the invocation's pager.
func (o *Output) Document(render func(io.Writer, style.Terminal) error) error {
if o.JSON() {
return nil
}
return PageDocument(o.cmd, o.inv, o.human, render)
}
package cli
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"io"
"github.com/mclucy/lucy/terminal/progress"
"github.com/mclucy/lucy/terminal/report"
"github.com/spf13/cobra"
)
// Output owns a command's streams and optional progress area.
// Documents and their human renderers stay with the command.
type Output struct {
cmd *cobra.Command
inv *Invocation
json JSONRendering
human io.Writer
renderer progress.Renderer
warnings []string
}
// NewQueryOutput sends human results to stdout.
func NewQueryOutput(cmd *cobra.Command, inv *Invocation) *Output {
return &Output{cmd: cmd, inv: inv, json: JSONMode(cmd), human: cmd.OutOrStdout()}
}
// NewOperationOutput sends human results to stderr.
func NewOperationOutput(cmd *cobra.Command, inv *Invocation) *Output {
return &Output{cmd: cmd, inv: inv, json: JSONMode(cmd), human: cmd.ErrOrStderr()}
}
func (o *Output) JSON() bool { return o.json != JSONNone }
// Human is silent in machine mode, even when a command reports a notice.
func (o *Output) Human() io.Writer {
if o.JSON() {
return io.Discard
}
return o.human
}
func (o *Output) writeJSON(w io.Writer, value any) error {
var options []json.Options
if o.json != JSONCompact {
options = []json.Options{jsontext.Multiline(true), jsontext.WithIndent(" ")}
}
data, err := json.Marshal(value, options...)
if err != nil {
return fmt.Errorf("encode output: %w", err)
}
if _, err := w.Write(append(data, '\n')); err != nil {
return fmt.Errorf("write output: %w", err)
}
return nil
}
// Warn records warnings for the result document and reports them in human mode.
func (o *Output) Warn(err error) {
o.warn(err)
}
// warn records one warning for the result document and, in human mode,
// renders it.
func (o *Output) warn(err error) {
if err == nil {
return
}
o.warnings = append(o.warnings, err.Error())
if !o.JSON() {
o.Close()
report.New(o.cmd.ErrOrStderr(), o.inv.Theme).Warn(err)
}
}
func (o *Output) Warnings() []string { return o.warnings }
// Info reports an informational human notice. Machine output carries the
// same fact in its document instead.
func (o *Output) Info(message string) {
if o.JSON() {
return
}
report.New(o.cmd.ErrOrStderr(), o.inv.Theme).Info(message)
}
// Error reports an error-level human notice that does not fail the command.
func (o *Output) Error(err error) {
if err == nil || o.JSON() {
return
}
o.Close()
report.New(o.cmd.ErrOrStderr(), o.inv.Theme).Error(err)
}
// Progress starts a renderer only when a command has work to narrate.
func (o *Output) Progress() progress.Renderer {
if o.renderer == nil {
o.renderer = o.newProgress()
}
return o.renderer
}
// RestartProgress rebuilds the renderer after a command suspended it, for
// example while a package manager owned the terminal. Closing the previous
// renderer is idempotent, so a caller that already ended it pays nothing and a
// caller that did not cannot leak its animation goroutine.
func (o *Output) RestartProgress() {
if o.renderer != nil {
o.renderer.Close()
}
o.renderer = o.newProgress()
}
func (o *Output) newProgress() progress.Renderer {
if o.JSON() {
return progress.Discard()
}
return progress.New(progress.Options{
Writer: o.cmd.ErrOrStderr(),
Theme: o.inv.Theme,
Terminal: o.inv.Stderr,
Interactive: o.inv.Interactive,
})
}
func (o *Output) Close() {
if o.renderer != nil {
o.renderer.Close()
}
}
package cli
import (
"context"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"charm.land/huh/v2"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
)
// PromptGate decides whether one command may open an interactive selection.
// Machine-readable output and --no-interactive (which --no-style implies) turn
// prompts off: neither can be steered by terminal input.
type PromptGate struct {
cmd *cobra.Command
inv *Invocation
}
func NewPromptGate(cmd *cobra.Command, inv *Invocation) PromptGate {
return PromptGate{cmd: cmd, inv: inv}
}
// Input is the stream a prompt may read from.
func (g PromptGate) Input() io.Reader { return g.cmd.InOrStdin() }
// Output is the stream a prompt renders on. Prompts never own stdout.
func (g PromptGate) Output() io.Writer { return g.cmd.ErrOrStderr() }
// Available reports whether a prompt may read the terminal. A caller that
// still needs the selection fails with the flag that carries the same choice.
func (g PromptGate) Available() bool {
if !g.flagsAllow() || !g.inv.Interactive {
return false
}
stdin, ok := g.cmd.InOrStdin().(*os.File)
return ok && term.IsTerminal(stdin.Fd())
}
// flagsAllow reports whether the command's switches leave prompting enabled.
// Keeping it apart from the terminal test makes the switch behavior verifiable
// without a terminal.
func (g PromptGate) flagsAllow() bool {
if g.cmd == nil || JSONMode(g.cmd) != JSONNone {
return false
}
if noInteractive, _ := g.cmd.Flags().GetBool(FlagNoInteractive); noInteractive {
return false
}
if noStyle, _ := g.cmd.Flags().GetBool(FlagNoStyle); noStyle {
return false
}
return true
}
type promptTimerKey struct{}
// PromptTimer accumulates the observed wait of the forms one invocation ran.
// Elapsed is unmeasured until a form executes, so an unopened prompt differs
// from a form that closed immediately.
type PromptTimer struct {
mu sync.Mutex
elapsed time.Duration
measured bool
}
// WithPromptTimer attaches the invocation's input timer to its form context.
func WithPromptTimer(ctx context.Context, timer *PromptTimer) context.Context {
return context.WithValue(ctx, promptTimerKey{}, timer)
}
func (t *PromptTimer) measure(elapsed time.Duration) {
if t == nil {
return
}
t.mu.Lock()
t.elapsed += elapsed
t.measured = true
t.mu.Unlock()
}
func (t *PromptTimer) wait() (time.Duration, bool) {
if t == nil {
return 0, false
}
t.mu.Lock()
defer t.mu.Unlock()
return t.elapsed, t.measured
}
// RunPrompt runs one form and measures its wait when the invocation requests
// it. The measurement covers each form exactly once, even when it fails.
func RunPrompt(ctx context.Context, form *huh.Form) error {
timer, _ := ctx.Value(promptTimerKey{}).(*PromptTimer)
if timer == nil {
return NormalizePromptError(ctx, form.RunWithContext(ctx))
}
started := time.Now()
raw := form.RunWithContext(ctx)
timer.measure(time.Since(started))
return NormalizePromptError(ctx, raw)
}
// ErrPromptAborted reports an explicit form abort. It wraps context.Canceled
// so every caller that treats a canceled invocation as an interruption keeps
// matching the abort.
var ErrPromptAborted = fmt.Errorf("prompt aborted: %w", context.Canceled)
// Huh can report a cancelled context as a timeout instead of its cause.
func NormalizePromptError(ctx context.Context, err error) error {
if err == nil {
return nil
}
if cause := ctx.Err(); cause != nil {
return cause
}
if errors.Is(err, huh.ErrUserAborted) {
return ErrPromptAborted
}
return err
}
package cli
import (
"fmt"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/spf13/cobra"
)
const (
flagRemoveLockedName = "locked"
flagRemoveOfflineName = "offline"
)
func NewRemoveCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
Short: help.RemoveShort,
Args: cobra.MinimumNArgs(1),
Aliases: []string{"rm"},
PreRunE: func(cmd *cobra.Command, args []string) error {
ecosystem, _ := cmd.Flags().GetString(FlagEcosystem)
if ecosystem != "" && !catalog.Ecosystem(ecosystem).Valid() {
return fmt.Errorf("invalid ecosystem %q", ecosystem)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return actionRemove(cmd, inv, deps, args)
},
}
installJSON.Bind(contracts, cmd)
cmd.Flags().Bool(
flagRemoveLockedName,
false,
"Do not resolve new versions; fail when the lock cannot satisfy",
)
cmd.Flags().Bool(
flagRemoveOfflineName,
false,
"Disallow network acquisition for any re-resolution this triggers",
)
AddEcosystemFlag(cmd)
return cmd
}
func actionRemove(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
locked, _ := cmd.Flags().GetBool(flagRemoveLockedName)
offline, _ := cmd.Flags().GetBool(flagRemoveOfflineName)
ecosystemArg, _ := cmd.Flags().GetString(FlagEcosystem)
ecosystem := catalog.Ecosystem(ecosystemArg)
opts := install.Options{
Locked: locked,
Offline: offline,
WithOptional: false,
PublishManifest: false,
}
output := newInstallOutput(cmd, inv)
defer output.Close()
opts.Trace = output.Trace()
ctx, stop := CommandContext(cmd)
defer stop()
result, err := deps.Operations.Remove(ctx, inv.Directory, args, ecosystem, opts)
if err != nil {
return output.Failure(err)
}
return output.Render(result)
}
package cli
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"strings"
)
const (
maxReportMessageBytes = 512
maxReportStages = 32
maxReportStack = 32
maxReportCommandBytes = 256
)
// StageCount is one captured diagnostic stage and how often it repeated.
// Stages repeat because a command retries work, such as one resolution per
// candidate combination, so the count carries the retry width that the plain
// message loses.
type StageCount struct {
Code string `json:"code"`
Count int `json:"count"`
}
// ReportBody is the machine-readable body of a submitted failure report. It
// carries the failure code and the projected facts of the error tree, the same
// evidence the error document shows in machine mode, without the human title,
// detail lines, hint, or log path.
type ReportBody struct {
Command string `json:"command"`
Code string `json:"code"`
Message string `json:"message,omitempty"`
Stages []StageCount `json:"stages,omitempty"`
Facts map[string]any `json:"facts,omitempty"`
Stack []string `json:"stack,omitempty"`
}
// Encode renders the body as one line of JSON bounded for transport. The
// telemetry client sanitizes it afterwards, so this method only enforces the
// size limits that keep a report small.
func (b ReportBody) Encode() string {
b.Command = truncateFactText(b.Command, maxReportCommandBytes)
b.Code = truncateFactText(b.Code, 64)
b.Message = truncateFactText(collapseRepeatedLines(b.Message), maxReportMessageBytes)
if len(b.Stages) > maxReportStages {
b.Stages = b.Stages[:maxReportStages]
}
if len(b.Stack) > maxReportStack {
b.Stack = b.Stack[:maxReportStack]
}
// Subprocess diagnostics are arbitrary bytes, not necessarily UTF-8.
payload, err := json.Marshal(b, jsontext.AllowInvalidUTF8(true))
if err != nil {
return fmt.Sprintf("command=%s code=%s", b.Command, b.Code)
}
return string(payload)
}
// collapseRepeatedLines drops consecutive duplicate lines so a joined error
// that repeated the same cause five times reads as one cause.
func collapseRepeatedLines(text string) string {
if text == "" {
return ""
}
lines := strings.Split(text, "\n")
collapsed := lines[:0]
for _, line := range lines {
if len(collapsed) > 0 && collapsed[len(collapsed)-1] == line {
continue
}
collapsed = append(collapsed, line)
}
return strings.Join(collapsed, "\n")
}
// StageCounts groups captured stage messages by identity, keeping the order in
// which each first appeared.
func StageCounts(stages []string) []StageCount {
if len(stages) == 0 {
return nil
}
counts := make([]StageCount, 0, len(stages))
indexes := make(map[string]int, len(stages))
for _, stage := range stages {
if position, found := indexes[stage]; found {
counts[position].Count++
continue
}
indexes[stage] = len(counts)
counts = append(counts, StageCount{Code: stage, Count: 1})
}
return counts
}
package cli
import (
"fmt"
"reflect"
"strings"
"github.com/invopop/jsonschema"
"github.com/mclucy/lucy/terminal/report"
"github.com/spf13/cobra"
)
func NewSchemaCommand(
contracts *JSONContracts,
inv *Invocation,
) *cobra.Command {
cmd := &cobra.Command{
Use: "schema [COMMAND...]",
Short: "Describe a command's JSON result",
Hidden: true,
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
output := NewQueryOutput(cmd, inv)
if !output.JSON() {
output.SetJSONRendering(JSONPretty)
}
failure, _ := cmd.Flags().GetBool("error")
if failure {
if len(args) != 0 {
return &report.Detail{
Title: "--error describes shared failures and does not accept a command path",
Code: CodeInvalidInvocation,
Hint: "Run lucy schema --error without a command path.",
}
}
schema := reflectJSONSchema([]reflect.Type{reflect.TypeFor[ErrorDocument]()})
schema.Title = "Lucy JSON failure"
return (JSONResult[*jsonschema.Schema]{}).Write(output, schema)
}
target := cmd.Root()
if len(args) != 0 {
found, remaining, err := cmd.Root().Find(args)
if err != nil || len(remaining) != 0 {
return &report.Detail{
Title: fmt.Sprintf("unknown command path %q", strings.Join(args, " ")),
Code: CodeInvalidInvocation,
Hint: "Run lucy schema to list supported command paths.",
}
}
target = found
}
if len(contracts.results[target]) == 0 {
paths := contracts.Paths(target)
if target == cmd.Root() || len(paths) != 0 {
return (JSONResult[[]string]{}).Write(output, paths)
}
return &report.Detail{
Title: fmt.Sprintf("%s does not provide a JSON result schema", target.CommandPath()),
Code: "usage.unsupported_output",
Hint: "Run lucy schema to list supported command paths.",
}
}
schema, err := contracts.Schema(target)
if err != nil {
return err
}
return (JSONResult[*jsonschema.Schema]{}).Write(output, schema)
},
}
cmd.Flags().Bool("error", false, "Describe the shared JSON failure document on stderr")
JSONResult[*jsonschema.Schema]{}.Bind(contracts, cmd)
JSONResult[[]string]{}.Bind(contracts, cmd)
contracts.Native(cmd)
return cmd
}
package cli
import (
"fmt"
"runtime"
"github.com/mclucy/lucy/internal/selfupdate"
"github.com/spf13/cobra"
)
const (
flagSelfUpdateCheck = "check"
flagSelfUpdateForce = "force"
)
// BuildInfo identifies the running binary for commands that reason about
// releases. The root wiring supplies it from linker flags.
type BuildInfo struct {
Version string
Commit string
Official bool
}
var selfUpdateJSON JSONResult[selfUpdateDocument]
type selfUpdateDocument struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
CurrentVersion string `json:"current_version"`
CurrentCommit string `json:"current_commit,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
LatestChannel string `json:"latest_channel,omitempty"`
LatestCommit string `json:"latest_commit,omitempty"`
UpdateAvailable bool `json:"update_available"`
Action string `json:"action"`
Asset string `json:"asset,omitempty"`
Checksum string `json:"checksum,omitempty"`
Executable string `json:"executable,omitempty"`
ReleaseURL string `json:"release_url,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// NewSelfUpdateCommand replaces the running binary from the published release
// manifest.
func NewSelfUpdateCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
build BuildInfo,
) *cobra.Command {
command := &cobra.Command{
Use: "self-update",
Short: "Update the lucy binary",
Long: "Update the lucy binary in place from the published release manifest. " +
"Installations managed by Homebrew, Go, Docker, or Nix update through their manager.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionSelfUpdate(cmd, inv, deps, build)
},
}
selfUpdateJSON.Bind(contracts, command)
command.Flags().Bool(
flagSelfUpdateCheck,
false,
"Report the available release without changing the binary",
)
command.Flags().Bool(
flagSelfUpdateForce,
false,
"Reinstall the selected release over a non-release build or the same version",
)
return command
}
func actionSelfUpdate(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
build BuildInfo,
) error {
check, _ := cmd.Flags().GetBool(flagSelfUpdateCheck)
force, _ := cmd.Flags().GetBool(flagSelfUpdateForce)
if check && force {
return fmt.Errorf("--%s cannot be combined with --%s", flagSelfUpdateCheck, flagSelfUpdateForce)
}
ctx, stop := CommandContext(cmd)
defer stop()
output := NewOperationOutput(cmd, inv)
defer output.Close()
service := selfupdate.New(deps.Network, inv.Logger)
options := selfupdate.Options{
Version: build.Version,
Commit: build.Commit,
Official: build.Official,
Force: force,
}
if check {
result, err := service.Check(ctx, options)
if err != nil {
return err
}
return writeSelfUpdate(output, result, true)
}
progress := output.Progress()
options.OnResolved = func(result *selfupdate.Result) {
if output.JSON() {
return
}
fmt.Fprintf(
output.Human(),
"Updating lucy %s → %s (%s/%s)\n",
selfUpdateVersionLabel(result.CurrentVersion),
result.LatestVersion,
runtime.GOOS,
runtime.GOARCH,
)
}
options.Progress = progress.Download
result, err := service.Apply(ctx, options)
progress.DownloadDone()
if err != nil {
return err
}
return writeSelfUpdate(output, result, false)
}
func writeSelfUpdate(output *Output, result *selfupdate.Result, check bool) error {
action := result.Action
switch {
case check:
action = "checked"
case action != "updated":
action = "up-to-date"
}
if output.JSON() {
return selfUpdateJSON.Write(output, selfUpdateDocument{
Schema: 1,
Kind: "self-update",
CurrentVersion: result.CurrentVersion,
CurrentCommit: result.CurrentCommit,
LatestVersion: result.LatestVersion,
LatestChannel: result.LatestChannel,
LatestCommit: result.LatestCommit,
UpdateAvailable: result.UpdateAvailable,
Action: action,
Asset: result.Asset,
Checksum: result.Checksum,
Executable: result.Executable,
ReleaseURL: result.ReleaseURL,
Warnings: result.Notes,
})
}
switch {
case result.Action == "updated":
fmt.Fprintf(
output.Human(),
"%s Updated lucy %s → %s\n",
output.inv.Theme.Success("✓"),
selfUpdateVersionLabel(result.CurrentVersion),
result.LatestVersion,
)
fmt.Fprintln(output.Human(), " "+output.inv.Theme.Muted(result.Executable))
case result.UpdateAvailable:
fmt.Fprintf(
output.Human(),
"lucy %s is available (current: %s).\n",
result.LatestVersion,
selfUpdateVersionLabel(result.CurrentVersion),
)
default:
fmt.Fprintf(
output.Human(),
"lucy %s is up to date.\n",
selfUpdateVersionLabel(result.CurrentVersion),
)
}
for _, note := range result.Notes {
output.Info(note)
}
return nil
}
func selfUpdateVersionLabel(version string) string {
if version == "" {
return "unknown"
}
return version
}
package cli
import (
"fmt"
"io"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/serverregistry"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
// serverListJSON is the machine-readable `server list` result: every
// registered entry, including entries whose target cannot serve as a server.
var serverListJSON JSONResult[[]serverregistry.Entry]
// serverForgetJSON is the machine-readable result of forgetting one entry.
var serverForgetJSON JSONResult[serverForgetDocument]
// serverRenameJSON is the machine-readable result of one rename.
var serverRenameJSON JSONResult[serverRenameDocument]
type serverForgetDocument struct {
Path string `json:"path"`
}
type serverRenameDocument struct {
Previous string `json:"previous_name"`
Name string `json:"name"`
Path string `json:"path"`
Warnings []string `json:"warnings,omitempty"`
}
func NewServerCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
serverListCmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: help.ServerListShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionServerList(cmd, inv, deps, args)
},
}
serverForgetCmd := &cobra.Command{
Use: "forget <path>",
Short: help.ServerForgetShort,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionServerForget(cmd, inv, deps, args)
},
}
serverRenameCmd := &cobra.Command{
Use: "rename <server> <name>",
Short: help.ServerRenameShort,
Args: cobra.ExactArgs(2),
ValidArgsFunction: completeServerRenameArguments,
RunE: func(cmd *cobra.Command, args []string) error {
return actionServerRename(cmd, inv, deps, args)
},
}
serverCmd := &cobra.Command{
Use: "server",
Short: help.ServerShort,
Args: cobra.NoArgs,
}
serverListJSON.Bind(contracts, serverListCmd)
serverForgetJSON.Bind(contracts, serverForgetCmd)
serverRenameJSON.Bind(contracts, serverRenameCmd)
serverCmd.AddCommand(serverListCmd, serverForgetCmd, serverRenameCmd)
return serverCmd
}
func completeServerRenameArguments(
cmd *cobra.Command,
args []string,
toComplete string,
) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return completeServerNames(cmd, args, toComplete)
}
// actionServerList reports the registry as it is. Unavailable targets stay in
// the listing with their state and problem instead of being pruned or hidden.
func actionServerList(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
output := NewQueryOutput(cmd, inv)
registry, err := deps.ServerRegistry()
if err != nil {
return err
}
entries, err := registry.List()
if err != nil {
return err
}
if output.JSON() {
if entries == nil {
entries = []serverregistry.Entry{}
}
return serverListJSON.Write(output, entries)
}
return output.Document(func(out io.Writer, screen style.Terminal) error {
return writeServerList(out, entries, inv.Theme, screen.Width)
})
}
// writeServerList renders one aligned row per entry. A name column that is
// empty in the registry stays visible as "-", and a problem wraps below the
// entry instead of hiding the path.
func writeServerList(
out io.Writer,
entries []serverregistry.Entry,
theme style.Theme,
width int,
) error {
if len(entries) == 0 {
_, err := fmt.Fprintln(out, "No servers registered")
return err
}
facts := make([]terminal.Fact, 0, len(entries))
for _, entry := range entries {
name := entry.Name
if name == "" {
name = "-"
}
value := entry.State + " " + entry.Path
if entry.Problem != "" {
value += "\n" + theme.Muted(entry.Problem)
}
facts = append(facts, terminal.Fact{Key: name, Value: value})
}
_, err := fmt.Fprintln(out, terminal.RenderFacts(facts, width, theme))
return err
}
// actionServerForget removes a registry entry whose recorded server directory
// is gone. The registry decides whether the target is confirmed missing; the
// command reports the forgotten path and never deletes server data.
func actionServerForget(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
output := NewOperationOutput(cmd, inv)
registry, err := deps.ServerRegistry()
if err != nil {
return err
}
entry, err := registry.Forget(args[0])
if err != nil {
return err
}
if output.JSON() {
return serverForgetJSON.Write(output, serverForgetDocument{Path: entry.Path})
}
_, err = fmt.Fprintf(output.Human(), "forgot server %s\n", entry.Path)
return err
}
// actionServerRename changes the manifest name of one registered server. The
// new name may already be in use; registration reports that ambiguity as a
// warning instead of rejecting the rename.
func actionServerRename(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
output := NewOperationOutput(cmd, inv)
registry, err := deps.ServerRegistry()
if err != nil {
return err
}
entry, err := registry.Resolve(args[0])
if err != nil {
return err
}
name, err := document.NormalizeName(args[1])
if err != nil {
return err
}
previous, err := deps.Operations.RenameServer(entry.Path, name)
if err != nil {
return err
}
registerWorkspace(entry.Path, output, inv, deps)
result := serverRenameDocument{
Previous: previous,
Name: name,
Path: entry.Path,
Warnings: output.Warnings(),
}
if output.JSON() {
return serverRenameJSON.Write(output, result)
}
out := output.Human()
switch {
case previous == "":
_, err = fmt.Fprintf(out, "named server %s\n", name)
case previous == name:
_, err = fmt.Fprintf(out, "server is already named %s\n", name)
default:
_, err = fmt.Fprintf(out, "renamed %s to %s\n", previous, name)
}
return err
}
package cli
import (
"fmt"
"path/filepath"
"strings"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/serverregistry"
"github.com/spf13/cobra"
)
const FlagServer = "server"
func RegisterServerSelection(root *cobra.Command) {
root.PersistentFlags().String(FlagServer, "", "Run the command in the registered server's directory")
_ = root.RegisterFlagCompletionFunc(FlagServer, completeServerNames)
}
// ResolveServer applies the parsed --server selection to inv. It resolves the
// registered name to its absolute directory; the process working directory is
// never changed. Completion commands are not server selections.
func ResolveServer(
cmd *cobra.Command,
registry *serverregistry.Registry,
inv *Invocation,
) error {
if cmd.Name() == "__complete" || cmd.Name() == "__completeNoDesc" {
return nil
}
flags := cmd.Root().PersistentFlags()
if !flags.Changed(FlagServer) {
return nil
}
name, err := flags.GetString(FlagServer)
if err != nil {
return err
}
if registry == nil {
return fmt.Errorf("select server %q: server registry is unavailable", name)
}
entry, err := registry.Resolve(name)
if err != nil {
return err
}
inv.Directory = entry.Path
inv.Logger.Debug(
"server selected",
"name", name,
"directory", entry.Path,
)
return nil
}
func completeServerNames(_ *cobra.Command, _ []string, prefix string) ([]string, cobra.ShellCompDirective) {
registry, err := serverregistry.New()
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
entries, err := registry.List()
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
seen := make(map[string]bool)
var names []string
for _, entry := range entries {
if entry.State != serverregistry.StateAvailable || entry.Name == "" || !strings.HasPrefix(entry.Name, prefix) || seen[entry.Name] {
continue
}
seen[entry.Name] = true
names = append(names, entry.Name+"\t"+entry.Path)
}
return names, cobra.ShellCompDirectiveNoFileComp
}
func registerWorkspace(
root string,
output *Output,
inv *Invocation,
deps *Dependencies,
) {
if err := workspacewrite.SafePath(root, ".lucy/"+workspacewrite.LockFileName); err != nil {
output.Warn(fmt.Errorf("server registration failed: %w", err))
return
}
// Do not recreate .lucy if deinit removed it after the operation returned.
writer, err := fsutil.TryLockFile(filepath.Join(root, ".lucy", workspacewrite.LockFileName))
if err != nil {
output.Warn(fmt.Errorf("server registration failed: %w", err))
return
}
defer func() {
if err := writer.Close(); err != nil {
output.Warn(fmt.Errorf("release server registration lock: %w", err))
}
}()
registry, err := deps.ServerRegistry()
if err != nil {
output.Warn(fmt.Errorf("server registration skipped: %w", err))
return
}
duplicates, err := registry.Register(root)
if err != nil {
output.Warn(fmt.Errorf("server registration failed: %w", err))
return
}
inv.Logger.Debug("server registration checked", "directory", root)
for _, duplicate := range duplicates {
output.Warn(fmt.Errorf(
"server name %q is also registered at %s; --server cannot select an ambiguous name",
duplicate.Name,
duplicate.Path,
))
}
}
package cli
import (
"errors"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/javainstall"
"github.com/mclucy/lucy/operation"
"github.com/mclucy/lucy/serverregistry"
"github.com/mclucy/lucy/upstream/routing"
)
// Dependencies is the concrete service assembly one invocation uses. The root
// wiring fills it after server selection, so services observe the selected
// workspace rather than the process working directory. Every field is an
// explicitly typed service; commands read only the fields they declared in
// their constructor.
type Dependencies struct {
// Operations runs workspace operations through the configured installer.
Operations *operation.Service
// Files tracks and restores files in the selected workspace.
Files *filetrack.Service
// Router answers upstream metadata requests.
Router *routing.Router
// Network fetches and caches upstream responses.
Network *cache.Client
// Registry resolves registered server names and paths. RegistryError
// reports why the registry could not be constructed; commands that need
// the registry return it instead of dereferencing a nil Registry.
Registry *serverregistry.Registry
RegistryError error
// JavaHost plans and executes Java installations for this invocation.
JavaHost *javainstall.Host
}
// ServerRegistry returns the invocation's registry or the reason it is
// unavailable. Commands that need the registry call this instead of
// dereferencing Registry directly.
func (d *Dependencies) ServerRegistry() (*serverregistry.Registry, error) {
if d.Registry != nil {
return d.Registry, nil
}
if d.RegistryError != nil {
return nil, d.RegistryError
}
return nil, errors.New("server registry is unavailable")
}
package cli
import (
"context"
"errors"
"fmt"
"os"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/report"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/mclucy/lucy/workspace/identify"
"github.com/spf13/cobra"
)
const flagStatusFromLockName = "from-lock"
var statusJSON JSONResult[statusDocument]
func NewStatusCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
statusCmd := &cobra.Command{
Use: "status",
Short: help.StatusShort,
Args: cobra.NoArgs,
Aliases: []string{"s"},
PreRunE: func(cmd *cobra.Command, args []string) error {
logo, _ := cmd.Flags().GetString(FlagLogo)
if _, ok := terminal.ParseStatusLogoMode(logo); !ok {
return fmt.Errorf("--logo must be one of none, small, large")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return actionStatus(cmd, inv, deps, args)
},
}
statusJSON.Bind(contracts, statusCmd)
AddLongFlag(statusCmd)
AddLogoFlag(statusCmd)
statusCmd.Flags().Bool(
flagStatusFromLockName,
false,
"Render the server identity and packages from lucy-lock.yaml instead of the live directory",
)
_ = statusCmd.RegisterFlagCompletionFunc(
FlagLogo,
func(cmd *cobra.Command, args []string, toComplete string) (
[]string,
cobra.ShellCompDirective,
) {
candidates := FilterByPrefix(StaticStatusLogoCandidates(), toComplete)
return ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
},
)
return statusCmd
}
func actionStatus(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
long, _ := cmd.Flags().GetBool(FlagLong)
logo, _ := cmd.Flags().GetString(FlagLogo)
logoMode, _ := terminal.ParseStatusLogoMode(logo)
output := NewQueryOutput(cmd, inv)
fromLock, _ := cmd.Flags().GetBool(flagStatusFromLockName)
if fromLock {
return actionStatusFromLock(cmd.Context(), output, inv, long, logoMode)
}
return actionStatusLive(cmd, output, inv, deps, long, logoMode)
}
// actionStatusLive observes the working directory and reports the runtime and
// packages found there. Selection uncertainty is part of the document, not a
// command failure: an empty, ambiguous, or declared-missing workspace still
// prints a useful status.
func actionStatusLive(
cmd *cobra.Command,
output *Output,
inv *Invocation,
deps *Dependencies,
long bool,
logoMode terminal.StatusLogoMode,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
root := inv.Directory
observed := workspace.Observe(root, discovery.Request{Policy: discovery.PolicyPreferModified})
identifyWarnings := identify.Packages(ctx, observed, deps.Router.ResolveArtifactsByHash, nil)
if err := ctx.Err(); err != nil {
return err
}
reportObservationFindings(observed, output)
for _, warning := range identifyWarnings {
output.Warn(warning)
}
if failure := statusSelectionFailure(observed); failure != nil {
recordWorkspaceTelemetryFailure(inv)
return failure
}
document := newLiveStatusDocument(observed, root)
if document.Server != nil &&
(document.Server.Product.Version == "" ||
document.Server.Product.Version == versionpkg.Unknown.String()) {
// Paperclip carries no build number in its metadata, and an installed
// core may be renamed. The lock records the adopted build.
if lock, err := documentpkg.LockFile(root).Read(); err == nil && lock.Server.CoreVersion != "" {
document.Server.Product.Version = lock.Server.CoreVersion.String()
}
}
if document.MCDR == nil ||
document.MCDR.Version == "" ||
document.MCDR.Version == versionpkg.Unknown.String() {
// MCDReforged is provisioned locally, so a missing global executable
// leaves the observation unknown. The lock carries the managed version.
if lock, err := documentpkg.LockFile(root).Read(); err == nil && lock.MCDR != nil {
document.MCDR = &statusMCDR{
Directory: statusRelativePath(root, lock.MCDR.Directory),
Version: lock.MCDR.Version.String(),
}
}
}
document.Name = statusNameFromManifest(root)
recordWorkspaceTelemetry(inv, observed, document)
document.Warnings = append(document.Warnings, output.Warnings()...)
return writeStatusDocument(ctx, output, inv, document, long, logoMode)
}
// actionStatusFromLock reports only the facts persisted in lucy-lock.yaml.
// The lock cannot prove whether the server is running or which entry point an
// installation would use, so the document leaves both unobserved.
func actionStatusFromLock(
ctx context.Context,
output *Output,
inv *Invocation,
long bool,
logoMode terminal.StatusLogoMode,
) error {
root := inv.Directory
lock, err := documentpkg.LockFile(root).Read()
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return &report.Detail{
Title: fmt.Sprintf("no %s to render", documentpkg.LockFilename),
Lines: []string{
"The workspace has no lock file yet.",
},
Hint: "Run lucy install first.",
Code: statusErrorLockMissing,
Cause: err,
}
}
return &report.Detail{
Title: "cannot read " + documentpkg.LockFilename,
Lines: []string{err.Error()},
Code: statusErrorReadFailed,
Cause: err,
}
}
document := newLockStatusDocument(root, lock)
document.Name = statusNameFromManifest(root)
return writeStatusDocument(
ctx,
output,
inv,
document,
long,
logoMode,
)
}
// statusSelectionFailure reports only selection outcomes that make the
// observation unusable. An empty workspace, an unresolved declaration, and
// competing candidates remain successful reports; discovery already turns
// them into document warnings.
func statusSelectionFailure(observed *workspace.Workspace) error {
if observed == nil {
return nil
}
failure := observed.SelectionError()
if failure == nil {
return nil
}
var typed *discovery.SelectionError
if errors.As(failure, &typed) {
switch typed.State {
case discovery.SelectionNone,
discovery.SelectionAmbiguous,
discovery.SelectionMissingDeclared:
return nil
}
}
return &report.Detail{
Title: "cannot select a server runtime",
Lines: []string{failure.Error()},
Code: statusErrorSelectionFailed,
Cause: failure,
}
}
func writeStatusDocument(
ctx context.Context,
output *Output,
inv *Invocation,
document statusDocument,
long bool,
logoMode terminal.StatusLogoMode,
) error {
if err := ctx.Err(); err != nil {
return err
}
if output.JSON() {
return statusJSON.Write(output, document)
}
_, err := fmt.Fprintln(
output.Human(),
renderStatus(document, long, logoMode, inv.ASCII, inv.Stdout, inv.Theme),
)
if err != nil {
return fmt.Errorf("write status: %w", err)
}
return nil
}
package cli
import (
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/depgraph"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
const (
statusDocumentSchema = 1
statusDocumentKind = "status"
statusSourceLive = "live"
statusSourceLock = "lock"
statusActivityRunning = "running"
statusActivityStopped = "stopped"
statusActivityUnknown = "unknown"
statusErrorLockMissing = "status.lock_missing"
statusErrorReadFailed = "status.read_failed"
statusErrorSelectionFailed = "status.selection_failed"
)
// statusDocument is the one wire format both live observation and lock
// rendering produce. Entries are never folded here; the human renderer bounds
// its own view.
type statusDocument struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
Source string `json:"source"`
Root string `json:"root"`
Name string `json:"name"`
Server *statusServer `json:"server"`
Packages []statusPackage `json:"packages"`
MCDR *statusMCDR `json:"mcdr,omitempty"`
Warnings []string `json:"warnings"`
}
type statusServer struct {
Product statusProduct `json:"product"`
Minecraft string `json:"minecraft"`
Activity string `json:"activity"`
Components []statusComponent `json:"components"`
CompatibleEcosystems []statusEcosystem `json:"compatible_ecosystems"`
PackageDirectories []string `json:"package_directories"`
}
type statusProduct struct {
Name string `json:"name"`
Version string `json:"version"`
Ecosystem string `json:"ecosystem"`
}
type statusComponent struct {
Name string `json:"name"`
Version string `json:"version"`
Provider string `json:"provider"`
Ecosystem string `json:"ecosystem"`
}
type statusEcosystem struct {
Ecosystem string `json:"ecosystem"`
Compatibility string `json:"compatibility"`
}
type statusPackage struct {
Name string `json:"name"`
Version string `json:"version"`
Provider string `json:"provider"`
Ecosystem string `json:"ecosystem"`
Environment string `json:"environment"`
Path string `json:"path"`
}
type statusMCDR struct {
Directory string `json:"directory"`
Version string `json:"version"`
}
func newStatusDocument(source, root string) statusDocument {
return statusDocument{
Schema: statusDocumentSchema,
Kind: statusDocumentKind,
Source: source,
Root: root,
Packages: []statusPackage{},
Warnings: []string{},
}
}
// A missing or unreadable manifest leaves the name absent; status still
// reports the rest of the workspace.
func statusNameFromManifest(root string) string {
manifest, err := documentpkg.ManifestFile(root).Read()
if err != nil {
return ""
}
return manifest.Name
}
func newLiveStatusDocument(
observed *workspace.Workspace,
root string,
) statusDocument {
document := newStatusDocument(statusSourceLive, root)
if observed == nil {
return document
}
selection := observed.Runtime()
if selection != nil {
document.Server = statusServerFromObservation(observed, selection, root)
}
document.Packages = statusPackagesFromObservation(
observed.Packages,
selection,
root,
)
document.MCDR = statusMCDRFromObservation(observed, root)
return document
}
func statusServerFromObservation(
observed *workspace.Workspace,
selection *discovery.Selection,
root string,
) *statusServer {
activity := statusActivityStopped
if observed.Running() {
activity = statusActivityRunning
}
return &statusServer{
Product: statusProductFromSelection(selection),
Minecraft: selection.MinecraftVersion().String(),
Activity: activity,
Components: statusComponents(depgraph.RuntimeComponents(selection)),
CompatibleEcosystems: statusCompatibleEcosystems(observed.ServedEcosystems()),
PackageDirectories: statusRelativePaths(root, observed.PackageDirs()),
}
}
// statusProductFromSelection reports the catalogued product identity rather
// than the observed artifact identity. A launcher that records its full
// filename as its version still reports the short product name.
func statusProductFromSelection(
selection *discovery.Selection,
) statusProduct {
if selection == nil || selection.Installation == nil {
return statusProduct{}
}
identity := selection.Installation.Identity
primary := identity.Primary
name := primary.Name.String()
ecosystem := primary.Ecosystem
if match, ok := serverpkg.NormalizeProduct(primary); ok {
name = match.Product.String()
if ecosystem == catalog.EcosystemUnspecified {
ecosystem = match.Ecosystem
}
}
if ecosystem == catalog.EcosystemUnspecified {
ecosystem = identity.Ecosystem()
}
return statusProduct{
Name: name,
Version: primary.Version.String(),
Ecosystem: ecosystem.String(),
}
}
func statusComponents(
components []catalog.VersionedRef,
) []statusComponent {
result := make([]statusComponent, 0, len(components))
for _, component := range components {
result = append(result, statusComponent{
Name: component.Name.String(),
Version: component.Version.String(),
Provider: component.Provider.String(),
Ecosystem: component.Ecosystem.String(),
})
}
return result
}
func statusCompatibleEcosystems(
offers []workspace.ServedEcosystem,
) []statusEcosystem {
result := make([]statusEcosystem, 0, len(offers))
for _, offer := range offers {
result = append(result, statusEcosystem{
Ecosystem: offer.Ecosystem.String(),
Compatibility: string(offer.Compatibility),
})
}
return result
}
// statusPackagesFromObservation projects installed content packages. Runtime
// components belong in the server document, and server products are not
// content packages, so both are excluded from the package list.
func statusPackagesFromObservation(
packages []workspace.DiscoveredPackage,
selection *discovery.Selection,
root string,
) []statusPackage {
result := make([]statusPackage, 0, len(packages))
runtimeComponents := map[string]struct{}{}
if selection != nil {
for _, component := range depgraph.RuntimeComponents(selection) {
runtimeComponents[component.StringBase()] = struct{}{}
}
}
for _, pkg := range packages {
if _, isComponent := runtimeComponents[pkg.ID.StringBase()]; isComponent {
continue
}
if serverpkg.IsProduct(pkg.ID) {
continue
}
environment := serverpkg.EnvironmentServer
if pkg.ID.Ecosystem == catalog.EcosystemMCDR {
environment = serverpkg.EnvironmentMCDR
}
result = append(result, statusPackage{
Name: pkg.ID.Name.String(),
Version: pkg.ID.Version.String(),
Provider: pkg.ID.Provider.String(),
Ecosystem: pkg.ID.Ecosystem.String(),
Environment: string(environment),
Path: statusRelativePath(root, pkg.Path),
})
}
return result
}
func statusMCDRFromObservation(
observed *workspace.Workspace,
root string,
) *statusMCDR {
if observed == nil || observed.Wrappers.MCDR == nil {
return nil
}
return &statusMCDR{
Directory: statusRelativePath(root, root),
Version: observed.Wrappers.MCDR.Version.String(),
}
}
func newLockStatusDocument(
root string,
lock *documentpkg.Lock,
) statusDocument {
document := newStatusDocument(statusSourceLock, root)
if lock == nil {
return document
}
document.Server = &statusServer{
Product: statusProduct{
Name: lock.Server.Product.String(),
Version: lock.Server.CoreVersion.String(),
Ecosystem: statusLockProductEcosystem(lock).String(),
},
Minecraft: lock.Server.Minecraft.String(),
Activity: statusActivityUnknown,
Components: statusLockComponents(lock),
CompatibleEcosystems: statusLockCompatibleEcosystems(lock),
PackageDirectories: statusLockPackageDirectories(root, lock),
}
if lock.MCDR != nil {
document.MCDR = &statusMCDR{
Directory: statusRelativePath(root, lock.MCDR.Directory),
Version: lock.MCDR.Version.String(),
}
}
document.Packages = make([]statusPackage, 0, len(lock.Packages))
for i := range lock.Packages {
pkg := &lock.Packages[i]
document.Packages = append(document.Packages, statusPackage{
Name: statusLockPackageName(pkg),
Version: pkg.Version.String(),
Provider: pkg.Provider.String(),
Ecosystem: pkg.Ecosystem.String(),
Environment: string(pkg.Environment),
Path: statusRelativePath(root, statusLockPackageDestination(lock, pkg)),
})
}
return document
}
// statusLockComponents reports the runtime components the lock proves. The
// lock records the core version and the Minecraft version, so loader cores
// contribute their loader component exactly as live selection does.
func statusLockComponents(lock *documentpkg.Lock) []statusComponent {
components := make([]statusComponent, 0, 2)
components = append(components, statusComponent{
Name: "minecraft",
Version: lock.Server.Minecraft.String(),
Ecosystem: catalog.EcosystemMinecraft.String(),
})
component := lock.Server.Product.LoaderComponent()
if component == "" || !statusConcreteVersion(lock.Server.CoreVersion) {
return components
}
return append(components, statusComponent{
Name: component.String(),
Version: lock.Server.CoreVersion.String(),
Ecosystem: lock.Server.Product.Ecosystem().String(),
})
}
func statusLockCompatibleEcosystems(
lock *documentpkg.Lock,
) []statusEcosystem {
result := make([]statusEcosystem, 0, 3)
seen := make(map[catalog.Ecosystem]bool, 3)
add := func(ecosystem catalog.Ecosystem, compatibility workspace.Compatibility) {
if !ecosystem.Valid() ||
ecosystem == catalog.EcosystemUnspecified ||
ecosystem == catalog.EcosystemMinecraft ||
seen[ecosystem] {
return
}
seen[ecosystem] = true
result = append(result, statusEcosystem{
Ecosystem: ecosystem.String(),
Compatibility: string(compatibility),
})
}
native := statusLockNativeEcosystems(lock)
for _, offer := range native {
add(offer.Ecosystem, offer.Compatibility)
}
productEcosystem := statusLockProductEcosystem(lock)
connectorBridge := statusLockHasConnectorBridge(lock)
for i := range lock.Packages {
pkg := &lock.Packages[i]
if !pkg.Enabled() || pkg.Environment != serverpkg.EnvironmentServer {
continue
}
compatibility := workspace.CompatFull
if connectorBridge &&
pkg.Ecosystem == catalog.EcosystemFabric &&
(productEcosystem == catalog.EcosystemForge ||
productEcosystem == catalog.EcosystemNeoForge) {
compatibility = workspace.CompatDegraded
}
add(pkg.Ecosystem, compatibility)
}
if connectorBridge &&
(productEcosystem == catalog.EcosystemForge ||
productEcosystem == catalog.EcosystemNeoForge) {
add(catalog.EcosystemFabric, workspace.CompatDegraded)
}
if seen[catalog.EcosystemPaper] {
add(catalog.EcosystemBukkit, workspace.CompatFull)
}
return result
}
// statusLockHasConnectorBridge reports the same package roster the live
// workspace uses to offer degraded Fabric compatibility. Locked packages may
// name the project through a binding or only expose the module identity.
func statusLockHasConnectorBridge(lock *documentpkg.Lock) bool {
for i := range lock.Packages {
pkg := &lock.Packages[i]
if !pkg.Enabled() || pkg.Environment != serverpkg.EnvironmentServer {
continue
}
if pkg.Ecosystem != catalog.EcosystemForge &&
pkg.Ecosystem != catalog.EcosystemNeoForge {
continue
}
if statusIsConnectorName(statusLockPackageName(pkg)) {
return true
}
for _, module := range pkg.Modules {
if statusIsConnectorName(module.ID) {
return true
}
}
}
return false
}
func statusIsConnectorName(name string) bool {
switch strings.ToLower(strings.TrimSpace(name)) {
case "sinytra-connector", "connector", "connectormod":
return true
default:
return false
}
}
// statusLockPackageDirectories lists the directories locked packages land in.
// A runtime whose ecosystem has a conventional content directory contributes
// that directory even when the lock selects no packages.
func statusLockPackageDirectories(
root string,
lock *documentpkg.Lock,
) []string {
result := make([]string, 0, 4)
seen := make(map[string]bool, 4)
add := func(directory string) {
if directory == "" {
return
}
relative := statusRelativePath(root, directory)
if relative == "" || seen[relative] {
return
}
seen[relative] = true
result = append(result, relative)
}
ecosystem := statusLockProductEcosystem(lock)
switch ecosystem.Family() {
case catalog.FamilyMod, catalog.FamilyPlugin:
directory, err := lock.PackageDirectory(&documentpkg.Package{
Environment: serverpkg.EnvironmentServer,
Ecosystem: ecosystem,
})
if err == nil {
add(directory)
}
}
for i := range lock.Packages {
if destination := statusLockPackageDestination(lock, &lock.Packages[i]); destination != "" {
add(filepath.Dir(destination))
}
}
return result
}
func statusLockPackageDestination(
lock *documentpkg.Lock,
pkg *documentpkg.Package,
) string {
if pkg.Environment != serverpkg.EnvironmentServer &&
pkg.Environment != serverpkg.EnvironmentMCDR {
return ""
}
destination, err := lock.PackageDestination(pkg)
if err != nil {
return ""
}
return destination
}
// statusLockPackageName prefers the project a lock binding names. The lock's
// ProjectID is the opaque provider identity and stays the fallback when no
// binding reference is readable.
func statusLockPackageName(pkg *documentpkg.Package) string {
var fallback string
for _, binding := range pkg.Requirements {
_, project, err := documentpkg.ParseReference(binding.Reference)
if err != nil || project == "" {
continue
}
if binding.Enabled {
return project
}
if fallback == "" {
fallback = project
}
}
if fallback != "" {
return fallback
}
if pkg.ProjectID != "" {
return pkg.ProjectID
}
return strings.TrimSuffix(pkg.Filename, filepath.Ext(pkg.Filename))
}
func statusConcreteVersion(version versionpkg.Version) bool {
return version != "" && !version.CanInfer() && !version.IsInvalid()
}
// Native product support must not narrow to the packages currently declared.
func statusLockNativeEcosystems(lock *documentpkg.Lock) []workspace.ServedEcosystem {
components := make([]catalog.VersionedRef, 0)
for _, input := range lock.Server.Inputs {
for _, module := range input.Modules {
components = append(components, catalog.VersionedRef{
Name: catalog.Name(module.ID),
Version: module.Version,
Ecosystem: module.Ecosystem,
})
}
}
product := catalog.VersionedRef{
Name: catalog.Name(lock.Server.Product.String()),
Version: lock.Server.CoreVersion,
}
if match, ok := serverpkg.NormalizeProduct(product); ok {
product.Ecosystem = match.Ecosystem
}
return workspace.ProductServedEcosystems(product, components)
}
func statusLockProductEcosystem(lock *documentpkg.Lock) catalog.Ecosystem {
match, ok := serverpkg.NormalizeProduct(catalog.VersionedRef{
Name: catalog.Name(lock.Server.Product.String()),
})
if ok && match.Ecosystem != catalog.EcosystemUnspecified {
return match.Ecosystem
}
return depgraph.EcosystemFromLock(lock)
}
// statusRelativePath reports a path relative to the document root. Absolute
// paths outside the root stay relative so the document never mixes roots.
func statusRelativePath(root, path string) string {
if path == "" {
return ""
}
if !filepath.IsAbs(path) {
return filepath.ToSlash(filepath.Clean(path))
}
relative, err := filepath.Rel(root, path)
if err != nil {
return filepath.ToSlash(path)
}
return filepath.ToSlash(relative)
}
func statusRelativePaths(root string, paths []string) []string {
result := make([]string, 0, len(paths))
for _, path := range paths {
relative := statusRelativePath(root, path)
if relative == "" {
continue
}
result = append(result, relative)
}
return result
}
package cli
import (
"cmp"
"fmt"
"slices"
"strings"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/catalog"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/style"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
)
const (
// statusViewPackageGridLines bounds the default package grid. The total
// package count stays visible, and the dim tail marker reports the rest.
statusViewPackageGridLines = 6
statusViewColumnGap = 2
)
// renderStatus renders the human status view from the same document that
// produces JSON. The caller supplies the width; process globals only decide
// whether the logo may appear at all.
func renderStatus(
document statusDocument,
long bool,
logoMode terminal.StatusLogoMode,
ascii bool,
term style.Terminal,
theme style.Theme,
) string {
width := term.Width
if width <= 0 {
width = 80
}
logo := resolveStatusViewLogo(document, theme)
layout := terminal.NegotiateStatusLayout(
width,
logo.largeWidth(),
logo.smallWidth(),
term.IsTTY,
logoMode,
)
if logo.empty() {
layout = terminal.StatusLayoutParams{
Mode: terminal.LayoutInfoOnly,
InfoWidth: width,
}
}
if layout.InfoWidth <= 0 {
layout.InfoWidth = width
}
infoWidth := max(1, layout.InfoWidth-2)
packages := statusViewPackageGroups(document.Packages)
facts := statusViewFacts(document, packages, long, infoWidth, theme)
info := terminal.RenderFactGroups(facts, infoWidth, theme)
if long {
for index, group := range packages {
separator := "\n\n"
if index == 0 && len(facts) > 1 && len(facts[1]) > 0 {
separator = "\n"
}
info += separator + group.title + " " +
theme.Muted(fmt.Sprintf("(%d)", len(group.packages)))
info += "\n" + statusViewPackageTable(
document.Root,
group.packages,
infoWidth,
theme,
)
}
}
if document.Name != "" {
info = statusViewName(document.Name, infoWidth, ascii) + "\n\n" + info
}
info = " " + strings.ReplaceAll(info, "\n", "\n ")
return statusViewCompose(info, logo, layout, logoMode)
}
type statusViewPackageGroup struct {
title string
packages []statusPackage
}
type statusViewLogo struct {
product serverpkg.Product
ecosystem catalog.Ecosystem
version versionpkg.Version
large []string
small []string
}
func (l statusViewLogo) empty() bool {
return len(l.large) == 0 && len(l.small) == 0
}
func (l statusViewLogo) largeWidth() int {
return statusViewBlockWidth(l.large)
}
func (l statusViewLogo) smallWidth() int {
return statusViewBlockWidth(l.small)
}
func statusViewBlockWidth(lines []string) int {
if len(lines) == 0 {
return 0
}
return lipgloss.Width(lines[0])
}
func statusViewName(name string, width int, ascii bool) string {
rule := "─"
if ascii {
rule = "-"
}
name = statusViewClip(name, width)
return name + "\n" + strings.Repeat(rule, max(1, min(ansi.StringWidth(name), width)))
}
func resolveStatusViewLogo(
document statusDocument,
theme style.Theme,
) statusViewLogo {
if document.Server != nil {
product, ok := serverpkg.ParseProduct(document.Server.Product.Name)
if ok {
logo := statusViewLogo{
product: product,
ecosystem: statusViewLogoEcosystem(document.Server),
version: versionpkg.Version(document.Server.Minecraft),
}
if terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
terminal.LogoSmallPlain,
) == "" {
fallback := catalog.Ecosystem(
strings.ToLower(document.Server.Product.Ecosystem),
)
if fallback.Valid() &&
fallback != catalog.EcosystemUnspecified &&
terminal.GetLogo(
logo.product,
fallback,
logo.version,
terminal.LogoSmallPlain,
) != "" {
logo.ecosystem = fallback
}
}
return statusViewLogoAssets(logo, theme)
}
}
if document.MCDR != nil {
return statusViewLogoAssets(statusViewLogo{
product: serverpkg.ProductMCDReforged,
ecosystem: catalog.EcosystemMCDR,
version: versionpkg.Unknown,
}, theme)
}
return statusViewLogo{}
}
// A full modding ecosystem selects the logo before the product's own ecosystem.
func statusViewLogoEcosystem(server *statusServer) catalog.Ecosystem {
var fallback catalog.Ecosystem
for _, offer := range server.CompatibleEcosystems {
ecosystem := catalog.Ecosystem(strings.ToLower(offer.Ecosystem))
if !ecosystem.Valid() || ecosystem == catalog.EcosystemUnspecified {
continue
}
if offer.Compatibility == string(workspace.CompatFull) &&
ecosystem.IsModding() {
return ecosystem
}
if fallback == catalog.EcosystemUnspecified {
fallback = ecosystem
}
}
productEcosystem := catalog.Ecosystem(
strings.ToLower(server.Product.Ecosystem),
)
if productEcosystem.Valid() &&
productEcosystem != catalog.EcosystemUnspecified {
return productEcosystem
}
return fallback
}
func statusViewLogoAssets(logo statusViewLogo, theme style.Theme) statusViewLogo {
if terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
terminal.LogoSmallPlain,
) == "" {
return statusViewLogo{}
}
smallVariant := terminal.LogoSmallPlain
largeVariant := terminal.LogoLargePlain
if theme.Colors() {
if terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
terminal.LogoSmallColored,
) != "" {
smallVariant = terminal.LogoSmallColored
}
if terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
terminal.LogoLargeColored,
) != "" {
largeVariant = terminal.LogoLargeColored
}
}
logo.small = statusViewLogoLines(terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
smallVariant,
))
logo.large = statusViewLogoLines(terminal.GetLogo(
logo.product,
logo.ecosystem,
logo.version,
largeVariant,
))
if len(logo.large) == 0 {
logo.large = logo.small
}
return logo
}
func statusViewLogoLines(raw string) []string {
raw = strings.ReplaceAll(raw, "\r", "")
lines := strings.Split(raw, "\n")
for len(lines) > 0 && strings.TrimSpace(ansi.Strip(lines[0])) == "" {
lines = lines[1:]
}
for len(lines) > 0 &&
strings.TrimSpace(ansi.Strip(lines[len(lines)-1])) == "" {
lines = lines[:len(lines)-1]
}
if len(lines) == 0 {
return nil
}
maxWidth := 0
for _, line := range lines {
maxWidth = max(maxWidth, lipgloss.Width(line))
}
for i, line := range lines {
if width := lipgloss.Width(line); width < maxWidth {
lines[i] = line + strings.Repeat(" ", maxWidth-width)
}
}
return lines
}
func statusViewVariantLines(logo statusViewLogo, large bool) []string {
if large {
if len(logo.large) > 0 {
return logo.large
}
return logo.small
}
if len(logo.small) > 0 {
return logo.small
}
return logo.large
}
func statusViewCompose(
info string,
logo statusViewLogo,
layout terminal.StatusLayoutParams,
logoMode terminal.StatusLogoMode,
) string {
infoLines := statusViewLines(info)
switch layout.Mode {
case terminal.LayoutLargeLogoSideBySide:
return statusViewJoin(statusViewSideBySide(
infoLines,
statusViewVariantLines(logo, true),
layout,
))
case terminal.LayoutSmallLogoSideBySide:
return statusViewJoin(statusViewSideBySide(
infoLines,
statusViewVariantLines(logo, false),
layout,
))
case terminal.LayoutVertical:
logoLines := statusViewVariantLines(
logo,
logoMode != terminal.StatusLogoSmall,
)
lines := make([]string, 0, len(logoLines)+len(infoLines)+1)
for _, line := range logoLines {
lines = append(lines, statusViewClip(line, layout.InfoWidth))
}
lines = append(lines, "")
lines = append(lines, infoLines...)
return statusViewJoin(lines)
case terminal.LayoutClipped:
return statusViewJoin(statusViewClipLines(infoLines, layout.InfoWidth))
default:
return statusViewJoin(infoLines)
}
}
func statusViewSideBySide(
infoLines []string,
logoLines []string,
layout terminal.StatusLayoutParams,
) []string {
logoWidth := layout.LogoWidth
if logoWidth <= 0 {
logoWidth = statusViewBlockWidth(logoLines)
}
gapWidth := max(layout.GapWidth, 0)
gap := strings.Repeat(" ", gapWidth)
rows := max(len(infoLines), len(logoLines))
lines := make([]string, 0, rows)
for i := range rows {
left := ""
if i < len(logoLines) {
left = statusViewClip(logoLines[i], logoWidth)
}
right := ""
if i < len(infoLines) {
right = infoLines[i]
}
var line string
switch {
case right == "":
line = left
case left == "":
line = strings.Repeat(" ", logoWidth+gapWidth) + right
default:
padding := max(logoWidth-ansi.StringWidth(left), 0)
line = left +
strings.Repeat(" ", padding) +
gap +
right
}
lines = append(lines, statusViewTrim(line))
}
return lines
}
func statusViewLines(value string) []string {
value = strings.TrimRight(value, "\n")
if value == "" {
return nil
}
lines := strings.Split(value, "\n")
for i, line := range lines {
lines[i] = statusViewTrim(line)
}
return lines
}
func statusViewJoin(lines []string) string {
for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
lines = lines[:len(lines)-1]
}
for i, line := range lines {
lines[i] = statusViewTrim(line)
}
return strings.Join(lines, "\n")
}
func statusViewTrim(line string) string {
return strings.TrimRight(line, " \t\r")
}
func statusViewClip(line string, width int) string {
if width <= 0 {
return ""
}
if ansi.StringWidth(line) <= width {
return line
}
return ansi.Truncate(line, width, "")
}
func statusViewClipLines(lines []string, width int) []string {
clipped := make([]string, len(lines))
for i, line := range lines {
clipped[i] = statusViewClip(line, width)
}
return clipped
}
func statusViewFacts(
document statusDocument,
packages []statusViewPackageGroup,
long bool,
width int,
theme style.Theme,
) [][]terminal.Fact {
runtime := []terminal.Fact{}
serverRow := -1
if server := document.Server; server != nil {
if server.Minecraft != "" {
runtime = append(runtime, terminal.Fact{Key: "Minecraft", Value: server.Minecraft})
}
serverRow = len(runtime)
runtime = append(
runtime,
terminal.Fact{Key: "Server"},
terminal.Fact{
Key: "Activity",
Value: statusViewActivity(document.Source, server.Activity, theme),
},
)
} else {
runtime = append(runtime, terminal.Fact{
Key: "Server",
Value: theme.Muted("no server found"),
})
}
if document.MCDR != nil {
runtime = append(runtime, statusViewMCDRFact(document.MCDR))
}
contents := []terminal.Fact{}
if document.Server != nil && len(document.Server.CompatibleEcosystems) > 0 {
contents = append(contents, terminal.Fact{
Key: "Ecosystems",
Value: statusViewCompatibility(
document.Server.CompatibleEcosystems,
theme,
),
})
}
packageStart := len(contents)
if !long {
for _, group := range packages {
contents = append(contents, terminal.Fact{Key: statusViewPackageGroupKey(group)})
}
}
groups := [][]terminal.Fact{runtime, contents}
valueWidth := statusViewValueWidth(groups, width)
if serverRow >= 0 {
runtime[serverRow].Value = statusViewServer(
document.Server,
valueWidth,
theme,
)
}
if !long {
for i, group := range packages {
contents[packageStart+i].Value = statusViewPackageGrid(
group.packages,
valueWidth,
theme,
)
}
}
return groups
}
func statusViewValueWidth(groups [][]terminal.Fact, width int) int {
keyWidth := 0
for _, group := range groups {
for _, fact := range group {
keyWidth = max(keyWidth, ansi.StringWidth(fact.Key))
}
}
keyWidth = min(keyWidth, max(1, width/3))
return max(1, width-keyWidth-2)
}
func statusViewServer(
server *statusServer,
width int,
theme style.Theme,
) string {
value := terminal.TruncateMiddle(statusViewProduct(server.Product), width)
if components := statusViewComponents(server); components != "" {
value += "\n" + theme.Muted(components)
}
return value
}
func statusViewProduct(product statusProduct) string {
name := strings.TrimSpace(product.Name)
if parsed, ok := serverpkg.ParseProduct(name); ok {
name = parsed.Title()
} else if name != "" {
name = style.Capitalize(name)
}
parts := make([]string, 0, 3)
if name != "" {
parts = append(parts, name)
}
if version := strings.TrimSpace(product.Version); version != "" {
parts = append(parts, version)
}
if len(parts) == 0 {
return "unknown"
}
return strings.Join(parts, " ")
}
func statusViewActivity(
source string,
activity string,
theme style.Theme,
) string {
activity = strings.ToLower(strings.TrimSpace(activity))
if strings.EqualFold(strings.TrimSpace(source), statusSourceLock) {
return theme.Muted("not observed")
}
switch activity {
case statusActivityRunning:
return theme.Success("● running")
case statusActivityStopped:
return theme.Muted("○ stopped")
case "", statusActivityUnknown:
return theme.Muted("unknown")
default:
return "○ " + activity
}
}
func statusViewProvider(provider string) string {
provider = strings.TrimSpace(provider)
if strings.EqualFold(provider, "any") || strings.EqualFold(provider, "unknown") {
return ""
}
return provider
}
func statusViewComponents(server *statusServer) string {
lines := make([]string, 0, len(server.Components))
for _, component := range server.Components {
minecraft := component.Ecosystem == "minecraft" && component.Version == server.Minecraft
primary := component.Ecosystem == server.Product.Ecosystem && component.Version == server.Product.Version
if minecraft || primary {
continue
}
lines = append(lines, statusViewProduct(statusProduct{
Name: component.Name,
Version: component.Version,
}))
}
return strings.Join(lines, ", ")
}
func statusViewCompatibility(
ecosystems []statusEcosystem,
theme style.Theme,
) string {
labels := make([]string, 0, len(ecosystems))
for _, offer := range ecosystems {
title := strings.TrimSpace(offer.Ecosystem)
if title == "" {
continue
}
if parsed := catalog.Ecosystem(strings.ToLower(title)); parsed.Valid() {
title = parsed.Title()
}
if compatibility := strings.TrimSpace(offer.Compatibility); compatibility != "" {
title += " " + theme.Muted("("+compatibility+")")
}
labels = append(labels, title)
}
return strings.Join(labels, ", ")
}
func statusViewPackageGroups(packages []statusPackage) []statusViewPackageGroup {
mods := make([]statusPackage, 0, len(packages))
plugins := make([]statusPackage, 0, len(packages))
mcdr := make([]statusPackage, 0, len(packages))
for _, pkg := range packages {
ecosystem := catalog.Ecosystem(strings.ToLower(pkg.Ecosystem))
switch {
case strings.EqualFold(
pkg.Environment,
string(serverpkg.EnvironmentMCDR),
) || ecosystem == catalog.EcosystemMCDR:
mcdr = append(mcdr, pkg)
case ecosystem.IsModding():
mods = append(mods, pkg)
default:
plugins = append(plugins, pkg)
}
}
groups := make([]statusViewPackageGroup, 0, 3)
for _, group := range []statusViewPackageGroup{
{title: "Mods", packages: mods},
{title: "Plugins", packages: plugins},
{title: "MCDR plugins", packages: mcdr},
} {
if len(group.packages) > 0 {
slices.SortFunc(group.packages, func(a, b statusPackage) int {
return cmp.Or(cmp.Compare(a.Name, b.Name), cmp.Compare(a.Path, b.Path))
})
groups = append(groups, group)
}
}
return groups
}
func statusViewPackageGroupKey(group statusViewPackageGroup) string {
return fmt.Sprintf("%s (%d)", group.title, len(group.packages))
}
func statusViewPackageTable(
root string,
packages []statusPackage,
width int,
theme style.Theme,
) string {
width = max(1, width-2)
nameWidth, versionWidth := 1, 1
for _, pkg := range packages {
nameWidth = max(nameWidth, ansi.StringWidth(statusViewPackageName(pkg)))
versionWidth = max(versionWidth, ansi.StringWidth(statusViewPackageVersion(pkg)))
}
nameWidth = min(nameWidth, max(1, width*2/5))
versionWidth = min(versionWidth, max(7, width/6))
gap := statusViewColumnGap
if width < 12 {
gap = 1
}
pathWidth := max(1, width-nameWidth-versionWidth-2*gap)
var table strings.Builder
for i, pkg := range packages {
if i > 0 {
table.WriteByte('\n')
}
table.WriteString(" ")
name := terminal.TruncateMiddle(statusViewPackageName(pkg), nameWidth)
if width < 5 {
table.WriteString(terminal.TruncateMiddle(name, width))
continue
}
version := terminal.TruncateMiddle(statusViewPackageVersion(pkg), versionWidth)
path := terminal.DisplayPath(root, pkg.Path)
table.WriteString(name)
table.WriteString(strings.Repeat(" ", nameWidth-ansi.StringWidth(name)+gap))
table.WriteString(version)
table.WriteString(strings.Repeat(" ", versionWidth-ansi.StringWidth(version)+gap))
table.WriteString(theme.Muted(terminal.TruncateMiddle(path, pathWidth)))
}
return table.String()
}
// statusViewPackageVersion names a missing version instead of leaving the
// column empty, so the path column keeps its alignment and meaning.
func statusViewPackageVersion(pkg statusPackage) string {
if version := strings.TrimSpace(pkg.Version); version != "" {
return version
}
return "unknown"
}
func statusViewPackageGrid(
packages []statusPackage,
width int,
theme style.Theme,
) string {
labels := statusViewPackageLabels(packages)
if len(labels) == 0 {
return ""
}
cellBudget := max(18, (width-2*statusViewColumnGap)/3)
longest := 0
for i, label := range labels {
labels[i] = terminal.TruncateMiddle(label, max(1, min(width, cellBudget)))
longest = max(longest, ansi.StringWidth(labels[i]))
}
columnWidth := longest + statusViewColumnGap
columns := (width + statusViewColumnGap) / max(columnWidth, 1)
columns = max(1, min(columns, len(labels)))
visible := min(len(labels), columns*statusViewPackageGridLines)
lines := make([]string, 0, statusViewPackageGridLines+1)
for start := 0; start < visible; start += columns {
end := min(start+columns, visible)
var row strings.Builder
for i := start; i < end; i++ {
row.WriteString(labels[i])
if i < end-1 {
padding := columnWidth - ansi.StringWidth(labels[i])
row.WriteString(strings.Repeat(" ", max(padding, 1)))
}
}
lines = append(lines, row.String())
}
if hidden := len(labels) - visible; hidden > 0 {
lines = append(lines, terminal.FoldHint(hidden, theme))
}
return strings.Join(lines, "\n")
}
func statusViewPackageLabels(packages []statusPackage) []string {
counts := make(map[string]int, len(packages))
for _, pkg := range packages {
counts[statusViewPackageName(pkg)]++
}
labels := make([]string, 0, len(packages))
for _, pkg := range packages {
name := statusViewPackageName(pkg)
label := name
if counts[name] > 1 {
if provider := statusViewProvider(pkg.Provider); provider != "" {
label = provider + ":" + name
} else if ecosystem := strings.TrimSpace(pkg.Ecosystem); ecosystem != "" {
label = ecosystem + "/" + name
}
}
labels = append(labels, label)
}
return labels
}
func statusViewPackageName(pkg statusPackage) string {
if name := strings.TrimSpace(pkg.Name); name != "" {
return name
}
if provider := statusViewProvider(pkg.Provider); provider != "" {
return provider
}
if ecosystem := strings.TrimSpace(pkg.Ecosystem); ecosystem != "" {
return ecosystem
}
return "unknown"
}
func statusViewMCDRFact(mcdr *statusMCDR) terminal.Fact {
value := strings.TrimSpace(mcdr.Version)
if value == "" {
value = "installed"
}
return terminal.Fact{Key: "MCDR", Value: value}
}
package cli
import (
"cmp"
"fmt"
"io"
"slices"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/cas"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
// storeObject is one stored object as the command presents it.
type storeObject struct {
Digest string `json:"digest"`
Size int64 `json:"size"`
}
// storeListJSON is the machine-readable `store list` result: every stored
// object in digest order.
var storeListJSON JSONResult[[]storeObject]
// storeGCJSON is the machine-readable result of one collection.
var storeGCJSON JSONResult[artifactstore.Report]
func NewStoreCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
storeListCmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: help.StoreListShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionStoreList(cmd, inv, args)
},
}
storeGCCmd := &cobra.Command{
Use: "gc",
Short: help.StoreGCShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionStoreGC(cmd, inv, deps, args)
},
}
storeCmd := &cobra.Command{
Use: "store",
Short: help.StoreShort,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
MarkHelpOnly(storeCmd)
storeListJSON.Bind(contracts, storeListCmd)
storeGCJSON.Bind(contracts, storeGCCmd)
storeCmd.AddCommand(storeListCmd, storeGCCmd)
return storeCmd
}
func actionStoreList(
cmd *cobra.Command,
inv *Invocation,
_ []string,
) error {
output := NewQueryOutput(cmd, inv)
store, err := artifactstore.Open()
if err != nil {
return err
}
defer store.Close()
objects := make([]cas.Object, 0)
if err := store.Walk(func(object cas.Object) error {
objects = append(objects, object)
return nil
}); err != nil {
return fmt.Errorf("list artifact store: %w", err)
}
slices.SortFunc(objects, func(a, b cas.Object) int {
return cmp.Compare(a.Digest.String(), b.Digest.String())
})
if output.JSON() {
presented := make([]storeObject, 0, len(objects))
for _, object := range objects {
presented = append(presented, storeObject{
Digest: object.Digest.String(),
Size: object.Size,
})
}
return storeListJSON.Write(output, presented)
}
if len(objects) == 0 {
_, err := fmt.Fprintln(output.Human(), "Artifact store is empty")
return err
}
var total int64
for _, object := range objects {
total += object.Size
}
facts := make([]terminal.Fact, 0, len(objects)+1)
facts = append(facts, terminal.Fact{
Key: "Store",
Value: fmt.Sprintf("%d objects, %s", len(objects), style.FormatBytesBinary(total)),
})
for _, object := range objects {
facts = append(facts, terminal.Fact{
Key: object.Digest.String(),
Value: style.FormatBytesBinary(object.Size),
})
}
return output.Document(func(out io.Writer, screen style.Terminal) error {
_, err := fmt.Fprintln(
out,
terminal.RenderFacts(facts, screen.Width, inv.Theme),
)
return err
})
}
func actionStoreGC(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
output := NewOperationOutput(cmd, inv)
registry, err := deps.ServerRegistry()
if err != nil {
return err
}
store, err := artifactstore.Open()
if err != nil {
return err
}
defer store.Close()
report, err := store.GC(registry)
if err != nil {
return err
}
if output.JSON() {
return storeGCJSON.Write(output, report)
}
if report.Removed == 0 {
_, err := fmt.Fprintln(output.Human(), "Artifact store has no unreferenced objects")
return err
}
_, err = fmt.Fprintf(
output.Human(),
"removed %d objects, freed up %s of space\n",
report.Removed,
style.FormatBytesBinary(report.Bytes),
)
return err
}
package cli
import (
"errors"
"strings"
"github.com/mclucy/lucy/internal/telemetry"
"github.com/mclucy/lucy/javaruntime"
"github.com/mclucy/lucy/operation"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
type telemetryWorkspace struct {
Product string `json:"product,omitempty"`
ProductVersion string `json:"product_version,omitempty"`
MinecraftVersion string `json:"minecraft_version,omitempty"`
Packages *int `json:"packages,omitempty"`
}
// MergeWorkspacePackages attaches an observed package count to this run's
// workspace context without replacing the runtime and environment facts a
// command already projected. A nil count changes nothing; an observed zero is
// a real measurement. An existing present context gains the count only when it
// has none of its own, so a command's final document stays authoritative. An
// absent context becomes present because the package count is itself evidence
// of a workspace; a failed observation keeps its failure.
func (inv *Invocation) MergeWorkspacePackages(packages *int) {
if inv == nil || !inv.TelemetryEnabled || packages == nil {
return
}
count := max(0, min(*packages, maxTelemetryScale))
for index := len(inv.TelemetryContexts) - 1; index >= 0; index-- {
context := &inv.TelemetryContexts[index]
if context.Kind != telemetry.ContextWorkspace {
continue
}
switch context.Status {
case telemetry.ContextFailed:
return
case telemetry.ContextPresent:
data, ok := context.Data.(telemetryWorkspace)
if !ok {
if pointer, pointerOK := context.Data.(*telemetryWorkspace); pointerOK && pointer != nil {
data = *pointer
} else {
data = telemetryWorkspace{}
}
}
if data.Packages != nil {
return
}
data.Packages = &count
context.Data = data
default:
context.Status = telemetry.ContextPresent
context.Reason = ""
context.Data = telemetryWorkspace{Packages: &count}
}
return
}
inv.TelemetryContexts = append(inv.TelemetryContexts, telemetry.Context{
Kind: telemetry.ContextWorkspace,
Status: telemetry.ContextPresent,
Data: telemetryWorkspace{Packages: &count},
})
}
func recordWorkspaceTelemetryFailure(inv *Invocation) {
if inv.TelemetryEnabled {
inv.TelemetryContexts = append(inv.TelemetryContexts, telemetry.Context{Kind: "workspace", Status: telemetry.ContextStatus("failed")})
}
}
func recordWorkspaceTelemetry(inv *Invocation, observed *workspace.Workspace, document statusDocument) {
if !inv.TelemetryEnabled {
return
}
context := telemetry.Context{Kind: "workspace", Status: telemetry.ContextStatus("present")}
if observed == nil || document.Server == nil {
context.Status = telemetry.ContextStatus("absent")
if observed != nil {
if selection, ok := errors.AsType[*discovery.SelectionError](observed.SelectionError()); ok && selection.State != discovery.SelectionNone {
context.Status = telemetry.ContextStatus("failed")
}
}
} else {
context.Data = telemetryWorkspace{
Product: observed.Runtime().Product().String(),
ProductVersion: telemetryVersion(document.Server.Product.Version),
MinecraftVersion: telemetryVersion(document.Server.Minecraft),
Packages: new(min(len(document.Packages), maxTelemetryScale)),
}
}
inv.TelemetryContexts = append(inv.TelemetryContexts, context)
}
// recordInitWorkspaceTelemetry projects the runtime selection that
// initialization already observed into one workspace context. It reads only
// the result the operation returned, so an early failure or prompt
// cancellation after selection still describes the chosen runtime without
// another observation or network probe. A run that never selected a runtime
// stays absent instead of claiming an installation.
func recordInitWorkspaceTelemetry(inv *Invocation, result *operation.InitResult) {
if !inv.TelemetryEnabled {
return
}
if result == nil {
return
}
context := telemetry.Context{
Kind: "workspace",
Status: telemetry.ContextStatus("absent"),
}
selection := result.Discovery.Selected()
if selection != nil {
product := selection.Product()
productVersion := selection.Installation.Identity.Primary.Version
minecraftVersion := selection.MinecraftVersion()
var packages *int
if lock := result.Lock; lock != nil {
product = lock.Server.Product
productVersion = lock.Server.CoreVersion
minecraftVersion = lock.Server.Minecraft
packages = new(min(len(lock.Packages), maxTelemetryScale))
}
context.Status = telemetry.ContextStatus("present")
context.Data = telemetryWorkspace{
Product: allowlistedProduct(product),
ProductVersion: telemetryVersion(productVersion.String()),
MinecraftVersion: telemetryVersion(minecraftVersion.String()),
Packages: packages,
}
}
inv.TelemetryContexts = append(inv.TelemetryContexts, context)
}
// allowlistedProduct names a product only when it belongs to the catalog the
// telemetry schema allows; any other spelling is omitted.
func allowlistedProduct(product serverpkg.Product) string {
known, ok := serverpkg.ParseProduct(product.String())
if !ok || known == serverpkg.ProductUnknown {
return ""
}
return known.String()
}
type telemetryJava struct {
Major int `json:"major"`
Version string `json:"version,omitempty"`
Distribution string `json:"distribution,omitempty"`
}
func recordJavaTelemetryFailure(inv *Invocation) {
if inv.TelemetryEnabled {
inv.TelemetryContexts = append(inv.TelemetryContexts, telemetry.Context{Kind: "java", Status: telemetry.ContextStatus("failed")})
}
}
func recordJavaTelemetry(inv *Invocation, selection *javaruntime.Check) {
if !inv.TelemetryEnabled || selection == nil {
return
}
context := telemetry.Context{Kind: "java", Status: telemetry.ContextStatus("absent")}
if selection.Runtime != nil {
context.Status = telemetry.ContextStatus("present")
context.Data = telemetryJava{
Major: selection.Runtime.Major,
Version: telemetryVersion(selection.Runtime.Version),
Distribution: string(selection.Runtime.Distribution),
}
}
inv.TelemetryContexts = append(inv.TelemetryContexts, context)
}
func telemetryVersion(value string) string {
if len(value) > 64 || !strings.ContainsAny(value, "0123456789") ||
strings.Trim(value, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.+-_") != "" {
return ""
}
return value
}
package cli
import (
"context"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/internal/telemetry"
"github.com/mclucy/lucy/log"
)
// Bounds shared by every observation projection. They mirror the wire
// contract and are applied before data leaves the process.
const (
maxTelemetryElapsedMS = 604800000
maxTelemetryPhaseCount = 24
maxTelemetryPhaseName = 64
maxTelemetryScale = 1000000
)
// TelemetryPhase is one phase of an invocation. Elapsed is observed time
// only; a phase that never reported completion stays active.
type TelemetryPhase struct {
Name string `json:"name"`
ElapsedMS int64 `json:"elapsed_ms"`
State string `json:"state"`
// started is the phase's own start, used only to measure an unfinished
// phase at projection time. It is never serialized.
started time.Time
}
// TelemetryExecution is the bounded execution snapshot of one invocation.
// Phases may overlap and an active phase means unfinished work, so the
// durations are not exclusive time. InputWaitMS is present only when a form
// actually ran, so an unmeasured wait differs from a measured zero.
type TelemetryExecution struct {
Phases []TelemetryPhase `json:"phases,omitempty"`
ActivePhase string `json:"active_phase,omitempty"`
CancelReason string `json:"cancel_reason,omitempty"`
FailureKind string `json:"failure_kind,omitempty"`
InputWaitMS *int64 `json:"input_wait_ms,omitempty"`
Files *int `json:"files,omitempty"`
HTTPMS *int64 `json:"http_ms,omitempty"`
LockMS *int64 `json:"lock_ms,omitempty"`
}
// TelemetryObservation accumulates the bounded facts one invocation observed
// about itself. It is independent of rendering: hooks may run on any
// goroutine, and every method is safe on a nil receiver so a disabled
// invocation allocates and records nothing.
type TelemetryObservation struct {
mu sync.Mutex
logger *log.Logger
phases []TelemetryPhase
active string
failure string
cancel string
promptTimer PromptTimer
files int
packages int
}
// NewTelemetryObservation starts one observation. Callers create it only when
// telemetry is enabled for the invocation.
func NewTelemetryObservation() *TelemetryObservation {
return &TelemetryObservation{
files: -1,
packages: -1,
}
}
// WithTelemetryObservation attaches the observation's input timer.
func WithTelemetryObservation(ctx context.Context, obs *TelemetryObservation) context.Context {
if obs == nil {
return ctx
}
return WithPromptTimer(ctx, &obs.promptTimer)
}
// AttachLogger lets the observation read bounded wait samples at projection
// time. A nil logger leaves the wait fields unmeasured.
func (o *TelemetryObservation) AttachLogger(logger *log.Logger) {
if o == nil {
return
}
o.mu.Lock()
o.logger = logger
o.mu.Unlock()
}
// SetFailureKind records the bounded failure class.
func (o *TelemetryObservation) SetFailureKind(kind string) {
if o == nil || !allowedTelemetryValue(kind, "usage", "panic", "handled", "command") {
return
}
o.mu.Lock()
o.failure = kind
o.mu.Unlock()
}
// SetCancelReason records the bounded cancellation class.
func (o *TelemetryObservation) SetCancelReason(reason string) {
if o == nil || !allowedTelemetryValue(
reason,
"prompt_aborted", "interrupted", "deadline", "context_canceled",
) {
return
}
o.mu.Lock()
o.cancel = reason
o.mu.Unlock()
}
func allowedTelemetryValue(value string, allowed ...string) bool {
for _, candidate := range allowed {
if value == candidate {
return true
}
}
return false
}
// PhaseStart records that a code-defined phase began. The entry stays active
// until PhaseDone reports it, so a failed or canceled trace keeps the
// unfinished phase visible. A phase beyond the projection cap leaves the
// previous active phase in place instead of naming an entry that is absent.
func (o *TelemetryObservation) PhaseStart(name string) {
if o == nil {
return
}
id, ok := telemetryPhaseName(name)
if !ok {
return
}
o.mu.Lock()
defer o.mu.Unlock()
index := o.phaseIndex(id)
switch {
case index >= 0:
if o.phases[index].State != "active" {
o.phases[index].started = time.Now()
}
o.phases[index].State = "active"
o.active = id
case len(o.phases) < maxTelemetryPhaseCount:
o.phases = append(o.phases, TelemetryPhase{
Name: id,
State: "active",
started: time.Now(),
})
o.active = id
}
}
// PhaseDone records the observed elapsed time of a phase. Repeated completions
// of the same phase accumulate, up to the wire bound.
func (o *TelemetryObservation) PhaseDone(name string, elapsed time.Duration) {
if o == nil {
return
}
id, ok := telemetryPhaseName(name)
if !ok {
return
}
milliseconds := telemetryMilliseconds(elapsed)
o.mu.Lock()
defer o.mu.Unlock()
index := o.phaseIndex(id)
if index < 0 {
if len(o.phases) >= maxTelemetryPhaseCount {
return
}
o.phases = append(o.phases, TelemetryPhase{Name: id, State: "complete"})
index = len(o.phases) - 1
}
phase := &o.phases[index]
phase.ElapsedMS = min(phase.ElapsedMS+milliseconds, maxTelemetryElapsedMS)
phase.State = "complete"
phase.started = time.Time{}
if o.active == id {
o.active = ""
for index := len(o.phases) - 1; index >= 0; index-- {
if o.phases[index].State == "active" {
o.active = o.phases[index].Name
break
}
}
}
}
// ObserveFiles records the largest meaningful file count a finished phase
// reported. A negative count is unobserved; zero is a real observed count.
func (o *TelemetryObservation) ObserveFiles(count int) {
if o == nil || count < 0 {
return
}
o.mu.Lock()
defer o.mu.Unlock()
if o.files < count {
o.files = min(count, maxTelemetryScale)
}
}
// ObservePackages records the largest meaningful package count the run
// observed. A negative count is unobserved; zero is a real observed count.
func (o *TelemetryObservation) ObservePackages(count int) {
if o == nil || count < 0 {
return
}
o.mu.Lock()
defer o.mu.Unlock()
if o.packages < count {
o.packages = min(count, maxTelemetryScale)
}
}
// Packages projects the observed package count for the workspace context. It
// is nil when no phase observed a count, so an empty workspace is distinct
// from one that was never inspected.
func (o *TelemetryObservation) Packages() *int {
if o == nil {
return nil
}
o.mu.Lock()
defer o.mu.Unlock()
return telemetryCountPointer(o.packages)
}
func telemetryCountPointer(value int) *int {
if value < 0 {
return nil
}
pointer := value
return &pointer
}
// Execution projects the bounded execution context. It is called once at the
// end of an invocation; the returned value owns its data.
func (o *TelemetryObservation) Execution(ended time.Time) telemetry.Context {
if o == nil {
return telemetry.Context{
Kind: "execution",
Status: telemetry.ContextAbsent,
Reason: telemetry.ContextReasonNotReached,
}
}
o.mu.Lock()
logger := o.logger
phases := make([]TelemetryPhase, len(o.phases))
copy(phases, o.phases)
for index := range phases {
if phases[index].State != "active" ||
phases[index].started.IsZero() ||
ended.IsZero() ||
!ended.After(phases[index].started) {
continue
}
active := telemetryMilliseconds(ended.Sub(phases[index].started))
phases[index].ElapsedMS = min(
phases[index].ElapsedMS+active,
maxTelemetryElapsedMS,
)
}
data := TelemetryExecution{
Phases: phases,
ActivePhase: o.active,
CancelReason: o.cancel,
FailureKind: o.failure,
Files: telemetryCountPointer(o.files),
}
o.mu.Unlock()
if elapsed, measured := o.promptTimer.wait(); measured {
milliseconds := telemetryMilliseconds(elapsed)
data.InputWaitMS = &milliseconds
}
if logger != nil {
http, lock := logger.WaitTimings()
data.HTTPMS = durationMilliseconds(http)
data.LockMS = durationMilliseconds(lock)
}
return telemetry.Context{
Kind: "execution",
Status: telemetry.ContextPresent,
Data: data,
}
}
func (o *TelemetryObservation) phaseIndex(id string) int {
for index := range o.phases {
if o.phases[index].Name == id {
return index
}
}
return -1
}
func telemetryMilliseconds(elapsed time.Duration) int64 {
if elapsed <= 0 {
return 0
}
return min(elapsed.Milliseconds(), maxTelemetryElapsedMS)
}
func durationMilliseconds(value *time.Duration) *int64 {
if value == nil {
return nil
}
milliseconds := telemetryMilliseconds(*value)
return &milliseconds
}
// telemetryPhaseName turns a code-defined phase label into the bounded code
// name the wire accepts. ASCII spaces become underscores once at this
// boundary; every other character must satisfy [a-z0-9][a-z0-9_-]{0,63}.
func telemetryPhaseName(name string) (string, bool) {
normalized := strings.ReplaceAll(name, " ", "_")
if normalized == "" || len(normalized) > maxTelemetryPhaseName {
return "", false
}
for index := range len(normalized) {
character := normalized[index]
if character >= 'a' && character <= 'z' ||
character >= '0' && character <= '9' {
continue
}
if index > 0 && (character == '_' || character == '-') {
continue
}
return "", false
}
return normalized, true
}
package cli
import (
"strconv"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// TelemetryExemptAnnotation marks a command tree excluded from automatic
// invocation telemetry.
const TelemetryExemptAnnotation = "lucy.io/telemetry-exempt"
// TelemetryArgumentKindAnnotation marks a flag whose parsed value has a closed,
// safe domain. Unmarked flags are recorded by name and kind only.
const TelemetryArgumentKindAnnotation = "lucy.io/telemetry-argument-kind"
// telemetryPositionArgumentAnnotation marks the semantic domain of one
// positional argument by its 1-based position.
const telemetryPositionArgumentAnnotation = "lucy.io/telemetry-position-argument-kind"
// Semantic value domains that may be recorded. Other values stay local.
const (
TelemetryArgumentSelector = "selector"
TelemetryArgumentVersion = "version"
)
// MarkTelemetryExempt excludes a command tree from automatic invocation
// telemetry. Explicit telemetry operations remain available.
func MarkTelemetryExempt(command *cobra.Command) {
if command.Annotations == nil {
command.Annotations = map[string]string{}
}
command.Annotations[TelemetryExemptAnnotation] = "true"
}
// MarkTelemetryFlagArgument declares that a flag carries a selector or version
// value that the telemetry boundary may record after validating its grammar.
func MarkTelemetryFlagArgument(command *cobra.Command, name, kind string) {
if command == nil || !telemetryArgumentKind(kind) {
return
}
flag := command.Flags().Lookup(name)
if flag == nil {
return
}
if flag.Annotations == nil {
flag.Annotations = map[string][]string{}
}
flag.Annotations[TelemetryArgumentKindAnnotation] = []string{kind}
}
// MarkTelemetryPositionArgument declares the semantic domain of one positional
// argument. Unmarked positions are free text and never record their values.
func MarkTelemetryPositionArgument(command *cobra.Command, position int, kind string) {
if command == nil || position < 1 || !telemetryArgumentKind(kind) {
return
}
if command.Annotations == nil {
command.Annotations = map[string]string{}
}
command.Annotations[telemetryPositionArgumentKey(position)] = kind
}
// TelemetryFlagArgumentKind returns the declared semantic domain of a flag, or
// an empty string when the flag is free text.
func TelemetryFlagArgumentKind(flag *pflag.Flag) string {
if flag == nil {
return ""
}
values := flag.Annotations[TelemetryArgumentKindAnnotation]
if len(values) != 1 || !telemetryArgumentKind(values[0]) {
return ""
}
return values[0]
}
// TelemetryPositionArgumentKind returns the declared semantic domain of a
// positional argument, or an empty string when the position is free text.
func TelemetryPositionArgumentKind(command *cobra.Command, position int) string {
if command == nil || position < 1 {
return ""
}
kind := command.Annotations[telemetryPositionArgumentKey(position)]
if !telemetryArgumentKind(kind) {
return ""
}
return kind
}
func telemetryPositionArgumentKey(position int) string {
return telemetryPositionArgumentAnnotation + "." + strconv.Itoa(position)
}
func telemetryArgumentKind(kind string) bool {
return kind == TelemetryArgumentSelector || kind == TelemetryArgumentVersion
}
// TelemetryExempt reports whether a command or an ancestor is marked.
func TelemetryExempt(command *cobra.Command) bool {
for current := command; current != nil; current = current.Parent() {
if current.Annotations[TelemetryExemptAnnotation] != "" {
return true
}
}
return false
}
package cli
import (
"fmt"
"io"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/depgraph"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
var treeJSON JSONResult[treeOutput]
func NewTreeCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
treeCmd := &cobra.Command{
Use: "tree",
Short: help.TreeShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionTree(cmd, inv, deps, args)
},
}
treeJSON.Bind(contracts, treeCmd)
treeCmd.Flags().Bool(
"live",
false,
"Observe the live workspace instead of reading the lock",
)
treeCmd.Flags().Int(
"depth",
0,
"Limit dependency tree depth (0 = unlimited)",
)
return treeCmd
}
func actionTree(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
_ []string,
) error {
ctx, stop := CommandContext(cmd)
defer stop()
forceLive, _ := cmd.Flags().GetBool("live")
output := NewQueryOutput(cmd, inv)
loaded, err := depgraph.Load(
ctx,
inv.Directory,
forceLive,
deps.Router.ResolveArtifactsByHash,
)
reportObservationFindings(loaded.Findings.Observation, output)
if err != nil {
return err
}
graph, origin := loaded.Graph, loaded.Origin
if output.JSON() {
return treeJSON.Write(output, treeDocument(graph, origin, output.Warnings()))
}
maxDepth, _ := cmd.Flags().GetInt("depth")
return output.Document(func(out io.Writer, _ style.Terminal) error {
fmt.Fprintf(out, "Using data from: %s\n\n", origin.String())
roots := graph.Roots
for i, root := range roots {
printTree(out, root, 0, i == len(roots)-1, "", make(map[string]bool), maxDepth)
}
fmt.Fprintf(out, "\n(from %s)\n", origin.String())
return nil
})
}
// nodeLabel renders one graph node. Node identity is always an explicit
// artifact coordinate or a native module ID; nothing is re-derived by
// parsing the label.
func nodeLabel(node *depgraph.Node) string {
label := fmt.Sprintf("%s@%s", node.ID, node.Version)
if node.Provider != catalog.ProviderUnspecified {
label += fmt.Sprintf(" (%s)", node.Provider)
}
if node.Module {
label += " [module]"
}
return label
}
func printTree(
w io.Writer,
node *depgraph.Node,
depth int,
isLast bool,
prefix string,
visited map[string]bool,
maxDepth int,
) {
branch := "├── "
if isLast {
branch = "└── "
}
label := nodeLabel(node)
key := node.Key()
if visited[key] {
fmt.Fprintf(w, "%s%s%s [shown above]\n", prefix, branch, label)
return
}
fmt.Fprintf(w, "%s%s%s\n", prefix, branch, label)
if maxDepth > 0 && depth >= maxDepth {
return
}
visited[key] = true
childPrefix := prefix + "│ "
if isLast {
childPrefix = prefix + " "
}
for i, child := range node.Children {
printTree(w, child, depth+1, i == len(node.Children)-1, childPrefix, visited, maxDepth)
}
delete(visited, key)
}
type treeNode struct {
ID string `json:"id"`
Version string `json:"version"`
Provider string `json:"provider,omitempty"`
Project string `json:"project,omitempty"`
Artifact string `json:"artifact,omitempty"`
Filename string `json:"filename,omitempty"`
Environment string `json:"environment"`
Ecosystem string `json:"ecosystem"`
Module bool `json:"module,omitzero"`
Root bool `json:"root,omitzero"`
Children []*treeNode `json:"children,omitempty"`
}
// treeOutput is the complete machine-readable `tree` result.
type treeOutput struct {
Origin string `json:"origin"`
Roots []*treeNode `json:"roots"`
Warnings []string `json:"warnings,omitempty"`
}
func treeDocument(
graph *depgraph.Graph,
origin depgraph.Origin,
warnings []string,
) treeOutput {
visited := make(map[string]bool)
roots := graph.Roots
jsonRoots := make([]*treeNode, 0, len(roots))
for _, root := range roots {
jsonRoots = append(jsonRoots, buildJSONNode(root, visited))
}
return treeOutput{
Origin: origin.String(),
Roots: jsonRoots,
Warnings: warnings,
}
}
func buildJSONNode(node *depgraph.Node, visited map[string]bool) *treeNode {
provider := ""
if node.Provider != catalog.ProviderUnspecified {
provider = node.Provider.String()
}
t := &treeNode{
ID: node.ID,
Version: node.Version,
Provider: provider,
Project: node.ProjectID,
Artifact: node.Artifact,
Filename: node.Filename,
Environment: string(node.Environment),
Ecosystem: node.Ecosystem.String(),
Module: node.Module,
Root: node.Root,
}
key := node.Key()
if visited[key] {
return t
}
visited[key] = true
for _, child := range node.Children {
t.Children = append(t.Children, buildJSONNode(child, visited))
}
delete(visited, key)
return t
}
package cli
import (
"context"
"errors"
"fmt"
"strings"
"charm.land/huh/v2"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/operation"
"github.com/spf13/cobra"
)
const (
flagUpgradeInteractiveName = "interactive"
flagUpgradeDryRunName = "dry-run"
flagUpgradePolicyName = "policy"
)
var upgradeFrontierJSON JSONResult[upgradeFrontierDocument]
func NewUpgradeCommand(
contracts *JSONContracts,
inv *Invocation,
deps *Dependencies,
) *cobra.Command {
upgradeCmd := &cobra.Command{
Use: "upgrade [packages...]",
Short: help.UpgradeShort,
Aliases: []string{"up", "update"},
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionUpgrade(cmd, inv, deps, args)
},
}
upgradeFrontierJSON.Bind(contracts, upgradeCmd)
installJSON.Bind(contracts, upgradeCmd)
upgradeCmd.Flags().Bool(
flagUpgradeInteractiveName,
false,
"Select manifest roots to upgrade",
)
upgradeCmd.Flags().Bool(
flagUpgradeDryRunName,
false,
"Resolve and show the plan without changing files",
)
upgradeCmd.Flags().String(
flagUpgradePolicyName,
"more",
"Upgrade policy: more, later, or options",
)
return upgradeCmd
}
func actionUpgrade(
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
args []string,
) error {
interactive, _ := cmd.Flags().GetBool(flagUpgradeInteractiveName)
dryRun, _ := cmd.Flags().GetBool(flagUpgradeDryRunName)
policy, _ := cmd.Flags().GetString(flagUpgradePolicyName)
noInteractive, _ := cmd.Flags().GetBool(FlagNoInteractive)
jsonMode := JSONMode(cmd) != JSONNone
switch {
case interactive && len(args) > 0:
return fmt.Errorf("--%s cannot be combined with package arguments", flagUpgradeInteractiveName)
case interactive && noInteractive:
return fmt.Errorf("--%s cannot be combined with --%s", flagUpgradeInteractiveName, FlagNoInteractive)
case policy != "more" && policy != "later" && policy != "options" && !isUpgradeHash(policy):
return fmt.Errorf("unknown upgrade policy %q", policy)
case policy == "options" && noInteractive && !dryRun && !jsonMode:
return fmt.Errorf("--%s options needs a selection; use --%s <hash>", flagUpgradePolicyName, flagUpgradePolicyName)
}
ctx, stop := CommandContext(cmd)
defer stop()
targets := args
if interactive {
selected, err := promptUpgradeRoots(ctx, cmd, inv, inv.Directory)
if err != nil {
return err
}
targets = selected
}
output := newInstallOutput(cmd, inv)
result, err := deps.Operations.PlanUpgrade(
ctx,
inv.Directory,
operation.UpgradeOptions{
Targets: targets,
Trace: output.Trace(),
},
)
if err != nil {
return output.Failure(err)
}
output.EndProgress()
if jsonMode && (dryRun || policy == "options") {
selectedHash := ""
if policy != "options" {
selected, err := operation.SelectUpgradeOption(result, policy)
if err != nil {
return err
}
selectedHash = selected.Hash
}
return upgradeFrontierJSON.Write(output.Output, upgradeFrontierDocument{
Schema: 1,
Kind: "upgrade-frontier",
Policy: policy,
SelectedHash: selectedHash,
BaseManifestFingerprint: result.BaseManifestFingerprint,
BaseLockFingerprint: result.BaseLockFingerprint,
Frontier: upgradeFrontierEntries(result.Options),
Warnings: warningMessages(result.Warnings),
})
}
if policy == "options" {
if dryRun {
output.RenderUpgradeFrontier(result)
printUpgradeWarnings(output, result.Warnings)
return nil
}
index, err := promptUpgradeChoice(ctx, cmd, inv, result.Options)
if err != nil {
return err
}
option := result.Options[index]
output.RenderUpgradePlan(option, "options", false)
printUpgradeWarnings(output, result.Warnings)
_, err = applyUpgradeOption(ctx, cmd, inv, deps, option, "options", result.Warnings)
return err
}
selected, err := operation.SelectUpgradeOption(result, policy)
if err != nil {
return err
}
if dryRun {
output.RenderUpgradePlan(*selected, policy, true)
printUpgradeWarnings(output, result.Warnings)
return nil
}
output.RenderUpgradePlan(*selected, policy, false)
if !selected.Plan.Result.Changed() {
printUpgradeWarnings(output, result.Warnings)
if jsonMode {
document := selected.Plan.Result
document.WarningMessages = append(warningMessages(document.Warnings), warningMessages(result.Warnings)...)
return installJSON.Write(output.Output, document)
}
return nil
}
if !noInteractive && !jsonMode {
if !NewPromptGate(cmd, inv).Available() {
return fmt.Errorf("apply without a prompt with --%s", FlagNoInteractive)
}
confirmed, err := promptUpgradeConfirm(ctx, cmd)
if err != nil {
return err
}
if !confirmed {
return nil
}
}
applied, err := applyUpgradeOption(ctx, cmd, inv, deps, *selected, policy, result.Warnings)
if err != nil {
return err
}
if jsonMode {
return installJSON.Write(output.Output, applied)
}
return nil
}
func applyUpgradeOption(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
deps *Dependencies,
option operation.UpgradeOption,
policy string,
warnings []error,
) (*install.Result, error) {
if option.Plan != nil && option.Plan.Result != nil {
option.Plan.Result.Warnings = append(option.Plan.Result.Warnings, warnings...)
}
if JSONMode(cmd) != JSONNone {
output := newInstallOutput(cmd, inv)
defer output.Close()
result, err := deps.Operations.ApplyUpgrade(
ctx,
inv.Directory,
option,
policy,
install.Options{Trace: output.Trace()},
)
if err != nil {
return nil, output.Failure(err)
}
result.WarningMessages = warningMessages(result.Warnings)
return result, nil
}
output := newInstallOutput(cmd, inv)
defer output.Close()
result, err := deps.Operations.ApplyUpgrade(
ctx,
inv.Directory,
option,
policy,
install.Options{Trace: output.Trace()},
)
if err != nil {
return nil, output.Failure(err)
}
if err := output.RenderUpgradeApplied(result, policy, option.Hash); err != nil {
return nil, err
}
return result, nil
}
func promptUpgradeRoots(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
root string,
) ([]string, error) {
if !NewPromptGate(cmd, inv).Available() {
return nil, errors.New("interactive selection needs a terminal; name packages instead")
}
refs, err := operation.ListUpgradeRoots(root)
if err != nil {
return nil, err
}
if len(refs) == 0 {
return nil, errors.New("the manifest has no enabled package roots")
}
options := make([]huh.Option[string], 0, len(refs))
for _, ref := range refs {
options = append(options, huh.NewOption(ref, ref))
}
var selected []string
form := huh.NewForm(huh.NewGroup(huh.NewMultiSelect[string]().
Title("Select packages to upgrade").
Options(options...).
Value(&selected))).
WithInput(cmd.InOrStdin()).
WithOutput(cmd.ErrOrStderr())
if err := RunPrompt(ctx, form); err != nil {
return nil, err
}
if len(selected) == 0 {
return nil, errors.New("no packages selected")
}
return selected, nil
}
func promptUpgradeChoice(
ctx context.Context,
cmd *cobra.Command,
inv *Invocation,
options []operation.UpgradeOption,
) (int, error) {
if !NewPromptGate(cmd, inv).Available() {
return 0, errors.New("interactive selection needs a terminal; use --policy <hash>")
}
huhOptions := make([]huh.Option[int], 0, len(options))
for i, option := range options {
huhOptions = append(huhOptions, huh.NewOption(
fmt.Sprintf("%d. %s", i+1, upgradeOptionSummary(option)),
i,
))
}
selected := 0
form := huh.NewForm(huh.NewGroup(huh.NewSelect[int]().
Title("Select an upgrade plan").
Options(huhOptions...).
Value(&selected))).
WithInput(cmd.InOrStdin()).
WithOutput(cmd.ErrOrStderr())
if err := RunPrompt(ctx, form); err != nil {
return 0, err
}
return selected, nil
}
func promptUpgradeConfirm(ctx context.Context, cmd *cobra.Command) (bool, error) {
confirmed := false
form := huh.NewForm(huh.NewGroup(huh.NewConfirm().
Title("Apply the planned upgrade?").
Value(&confirmed))).
WithInput(cmd.InOrStdin()).
WithOutput(cmd.ErrOrStderr())
if err := RunPrompt(ctx, form); err != nil {
return false, err
}
return confirmed, nil
}
func isUpgradeHash(value string) bool {
return strings.HasPrefix(value, "sha256:")
}
package cli
import (
"fmt"
"strings"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/operation"
)
type upgradeFrontierDocument struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
Policy string `json:"policy,omitempty"`
SelectedHash string `json:"selected_hash,omitempty"`
BaseManifestFingerprint string `json:"base_manifest_fingerprint"`
BaseLockFingerprint string `json:"base_lock_fingerprint"`
Frontier []upgradeFrontierEntry `json:"frontier"`
Warnings []string `json:"warnings,omitempty"`
}
type upgradeFrontierEntry struct {
Hash string `json:"hash"`
Metrics operation.UpgradeMetrics `json:"metrics"`
Result *install.Result `json:"result"`
}
func upgradeFrontierEntries(options []operation.UpgradeOption) []upgradeFrontierEntry {
entries := make([]upgradeFrontierEntry, 0, len(options))
for _, option := range options {
if option.Plan != nil && option.Plan.Result != nil {
option.Plan.Result.PlanHash = option.Hash
}
entries = append(entries, upgradeFrontierEntry{
Hash: option.Hash,
Metrics: option.Metrics,
Result: option.Plan.Result,
})
}
return entries
}
func (o *installOutput) RenderUpgradeFrontier(result *operation.UpgradeResult) {
fmt.Fprintln(o.Human(), "Upgrade options:")
for i, option := range result.Options {
fmt.Fprintf(o.Human(), " %d. %s\n", i+1, upgradeOptionSummary(option))
}
}
func (o *installOutput) RenderUpgradePlan(
option operation.UpgradeOption,
policy string,
dryRun bool,
) {
result := option.Plan.Result
if result == nil {
return
}
if !result.Changed() {
fmt.Fprintln(o.Human(), o.inv.Theme.Success("✓")+" Already up to date")
return
}
fmt.Fprintln(o.Human(), "Plan:")
for _, line := range packageChangeLines(result.Packages, o.inv.Theme) {
fmt.Fprintln(o.Human(), line)
}
for _, change := range result.ManifestChanges {
fmt.Fprintf(
o.Human(),
" %s manifest %s %s → %s\n",
o.inv.Theme.Warning("~"),
change.Reference,
change.PreviousSelector,
change.Selector,
)
}
fmt.Fprintln(o.Human(), o.inv.Theme.Muted(fmt.Sprintf(
"%d roots upgraded, %d version bumps",
option.Metrics.UpgradedRoots,
option.Metrics.VersionBumps,
)))
fmt.Fprintln(o.Human(), o.inv.Theme.Muted("Policy: "+policy))
fmt.Fprintln(o.Human(), o.inv.Theme.Muted("Plan: "+option.Hash))
if dryRun {
fmt.Fprintln(o.Human(), o.inv.Theme.Muted("No files were changed."))
}
}
func (o *installOutput) RenderUpgradeApplied(
result *install.Result,
policy string,
hash string,
) error {
if result == nil {
return nil
}
result.Warnings = append(result.Warnings, javaWarnings(result.Java)...)
result.WarningMessages = warningMessages(result.Warnings)
if o.JSON() {
return installJSON.Write(o.Output, result)
}
if result.MCDR != nil {
fmt.Fprintf(
o.Human(),
" %s mcdr python inputs %d → %d\n",
o.inv.Theme.Warning("~"),
result.MCDR.PreviousInputs,
result.MCDR.Inputs,
)
}
fmt.Fprintln(o.Human(), o.inv.Theme.Success("✓")+" Upgrade applied")
if changed := result.Files.Created + result.Files.Replaced + result.Files.Removed; changed > 0 {
fmt.Fprintln(o.Human(), o.inv.Theme.Muted(" "+fileCountLabel(changed)+" changed"))
}
if line := displacedFilesLine(len(result.Files.Displaced)); line != "" {
fmt.Fprintln(o.Human(), o.inv.Theme.Muted(line))
}
fmt.Fprintln(o.Human(), o.inv.Theme.Muted(" Policy: "+policy))
fmt.Fprintln(o.Human(), o.inv.Theme.Muted(" Plan: "+hash))
if trailer := publicationLine(result, o.inv.Theme); trailer != "" {
fmt.Fprintln(o.Human(), trailer)
}
o.Close()
for _, warning := range result.Warnings {
o.Warn(warning)
}
return nil
}
func printUpgradeWarnings(output *installOutput, warnings []error) {
for _, warning := range warnings {
output.Warn(warning)
}
}
func upgradeOptionSummary(option operation.UpgradeOption) string {
metrics := fmt.Sprintf(
"%d roots upgraded, %d version bumps",
option.Metrics.UpgradedRoots,
option.Metrics.VersionBumps,
)
result := option.Plan.Result
if result == nil {
return metrics
}
changes := make([]string, 0, 4)
for _, change := range result.Packages {
name := change.Name
if change.Previous != "" {
changes = append(changes, fmt.Sprintf("%s %s→%s", name, change.Previous, change.Version))
} else {
changes = append(changes, fmt.Sprintf("%s %s", name, change.Version))
}
if len(changes) == 3 {
break
}
}
if len(result.ManifestChanges) > 0 {
changes = append(changes, fmt.Sprintf("%d manifest repins", len(result.ManifestChanges)))
}
if len(changes) == 0 {
changes = append(changes, "no package changes")
}
return strings.Join(changes, ", ") + " (" + metrics + ")"
}
package compile
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/buildrepo"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/internal/toolchain"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/terminal/report"
"github.com/spf13/cobra"
)
type options struct {
output string
ecosystem string
project string
buildDir string
branch string
tag string
}
func NewCommand(inv *cli.Invocation) *cobra.Command {
var opts options
cmd := &cobra.Command{
Use: "compile <url|owner/repo>",
Short: help.CompileShort,
Long: help.CompileLong,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if cli.JSONMode(cmd) != cli.JSONNone {
return &report.Detail{
Code: "usage.unsupported_output",
Title: "compile does not support JSON output",
Hint: "Run without --json or --json-compact.",
}
}
ctx, stop := cli.CommandContext(cmd)
defer stop()
return run(
ctx,
args[0],
&opts,
inv,
cli.NewPromptGate(cmd, inv),
cmd.OutOrStdout(),
cmd.ErrOrStderr(),
)
},
}
cmd.Flags().StringVarP(&opts.output, "output", "o", "", "Write the compiled mod JAR to PATH, or to a directory under the project's artifact name")
cmd.Flags().StringVar(&opts.ecosystem, cli.FlagEcosystem, "", "Select fabric, quilt, forge, or neoforge")
cmd.Flags().StringVar(&opts.project, "project", "", "Select a Gradle project path, such as :fabric")
cmd.Flags().StringVar(&opts.buildDir, "build-dir", "", "Select a Gradle build directory relative to the checkout")
cmd.Flags().StringVar(&opts.branch, "branch", "", "Checkout Git branch BRANCH before compiling")
cmd.Flags().StringVar(&opts.tag, "tag", "", "Checkout Git tag TAG before compiling")
return cmd
}
// run compiles source and writes the resulting JAR. Progress is narrated on
// stderr; stdout carries only the artifact path so the command stays pipeable.
func run(
ctx context.Context,
source string,
opts *options,
inv *cli.Invocation,
gate cli.PromptGate,
stdout, stderr io.Writer,
) (err error) {
reporter := report.New(stderr, inv.Theme)
logger := inv.Logger
remote, err := parseRemote(source)
if err != nil {
return err
}
destination := parseOutputDestination(opts.output)
if opts.ecosystem != "" && !supportedEcosystem(catalog.Ecosystem(opts.ecosystem)) {
return errors.New("--ecosystem must be fabric, forge, or neoforge")
}
branch := strings.TrimSpace(opts.branch)
tag := strings.TrimSpace(opts.tag)
if branch != "" && tag != "" {
return errors.New("--branch and --tag are mutually exclusive")
}
if strings.HasPrefix(branch, "-") || strings.HasPrefix(tag, "-") {
return errors.New("branch and tag names must not start with '-'")
}
output := ""
if destination.file != "" {
if output, err = destination.resolve(inv.Directory, ""); err != nil {
return err
}
if err := ensureAbsent(output); err != nil {
return err
}
}
temporary, err := os.MkdirTemp("", "lucy-compile-*")
if err != nil {
return fmt.Errorf("create temporary checkout: %w", err)
}
defer func() {
if cleanupErr := os.RemoveAll(temporary); cleanupErr != nil {
err = errors.Join(err, fmt.Errorf("remove temporary checkout: %w", cleanupErr))
}
}()
checkout := filepath.Join(temporary, "repository")
ref := refSuffix(branch, tag)
logger.Info("compilation checkout started", "branch", branch, "tag", tag)
writeProgress(stderr, "Cloning "+source+ref)
if err := clone(
ctx,
remote,
checkout,
branch,
tag,
newProcessLog("git", logger, reporter),
); err != nil {
return err
}
logger.Info("compilation checkout completed", "directory", checkout)
writeProgress(stderr, "Cloned "+source+ref)
logger.Info("compilation repository inspection started", "directory", checkout)
layout, err := buildrepo.Probe(ctx, checkout)
if err != nil {
return fmt.Errorf("probe repository: %w", err)
}
reportFindings(layout.Root, layout.Findings, logger, reporter)
build, err := selectBuild(layout, opts.buildDir)
if err != nil {
return err
}
logger.Debug("Gradle build selected", "directory", build.Dir, "requested", opts.buildDir,
"reason", "requested directory or root/unique Gradle build")
logger.Info("compilation toolchain preparation started", "directory", build.Dir)
writeProgress(stderr, "Preparing the Gradle build")
gradleUserHome := os.Getenv("GRADLE_USER_HOME")
if gradleUserHome == "" {
home, homeErr := os.UserHomeDir()
if homeErr != nil {
return fmt.Errorf("find user home: %w", homeErr)
}
gradleUserHome = filepath.Join(home, ".gradle")
}
javaHome, err := configuredGradleJavaHome(build, gradleUserHome)
if err != nil {
return err
}
build.JavaHome = javaHome
inventory, err := toolchain.DiscoverBuildTools(ctx, javaHome)
if err != nil {
return fmt.Errorf("discover local toolchains: %w", err)
}
for _, warning := range toolchainWarnings(build, inventory) {
warnErr := errors.New(warning)
logger.Warn(warnErr)
reporter.Warn(warnErr)
}
runner, err := newGradleRunner(
build,
inventory,
temporary,
stderr,
logger,
reporter,
)
if err != nil {
return err
}
model, err := runner.inspect(ctx)
if err != nil {
return err
}
project, err := selectProject(ctx, model, opts, gate)
if err != nil {
return err
}
logger.Debug("compilation project selected", "project", project.Path, "task", project.BuildTask,
"reason", "project selection and supported mod artifact metadata")
// selectProject runs again on the rebuilt model; pin the pick so the
// second pass keeps the same project instead of listing candidates anew.
opts.project = project.Path
compilerProject, err := runner.inspectCompilers(ctx, project)
if err != nil {
return err
}
if err := checkCompiler(compilerProject, runner.daemon); err != nil {
return err
}
model, err = runner.build(ctx, project.BuildTask)
if err != nil {
return err
}
project, err = selectProject(ctx, model, opts, gate)
if err != nil {
return err
}
artifactPath, err := selectArtifact(project, catalog.Ecosystem(opts.ecosystem))
if err != nil {
return err
}
if output == "" {
if output, err = destination.resolve(inv.Directory, filepath.Base(artifactPath)); err != nil {
return err
}
if err := ensureAbsent(output); err != nil {
return err
}
}
if err := publishArtifact(ctx, artifactPath, output); err != nil {
return err
}
logger.Info("compiled artifact published", "path", output, "project", project.Path)
writeProgress(stderr, "Compiled "+filepath.Base(output))
if _, err := fmt.Fprintln(stdout, output); err != nil {
return fmt.Errorf("report output: %w", err)
}
return nil
}
// writeProgress narrates compilation progress on stderr. Progress text is
// advisory, so a write failure does not stop the build.
func writeProgress(writer io.Writer, line string) {
_, _ = fmt.Fprintln(writer, line)
}
// reportFindings surfaces what the static probe could not settle on its own.
// None of them stops a build, but each marks a decision left to Gradle, and
// silently discarding one would leave the user with a wrong model of what Lucy
// verified before running an untrusted build.
func reportFindings(
root string,
findings []buildrepo.Finding,
logger *log.Logger,
reporter *report.Reporter,
) {
for _, finding := range findings {
location := finding.File
if relative, err := filepath.Rel(root, finding.File); err == nil {
location = filepath.ToSlash(relative)
}
if finding.Line > 0 {
location += ":" + strconv.Itoa(finding.Line)
}
warning := fmt.Errorf("%s: %s", location, finding.Message)
logger.Warn(warning)
reporter.Warn(warning)
}
}
func supportedEcosystem(ecosystem catalog.Ecosystem) bool {
return ecosystem.IsModding()
}
func selectBuild(layout buildrepo.Layout, requested string) (buildrepo.GradleBuild, error) {
if requested != "" {
if !filepath.IsLocal(requested) {
return buildrepo.GradleBuild{}, errors.New("--build-dir must remain inside the checkout")
}
dir := filepath.Join(layout.Root, requested)
for _, build := range layout.Builds {
if build.Dir == dir {
return build, nil
}
}
return buildrepo.GradleBuild{}, fmt.Errorf("no Gradle build at %q", requested)
}
for _, build := range layout.Builds {
if build.Dir == layout.Root {
return build, nil
}
}
included := make(map[string]bool)
for _, build := range layout.Builds {
for _, dir := range build.IncludedBuilds {
included[dir] = true
}
}
candidates := make([]buildrepo.GradleBuild, 0, len(layout.Builds))
for _, build := range layout.Builds {
base := filepath.Base(build.Dir)
isBuildLogic := base == "buildSrc" || base == "build-logic" || base == "buildlogic"
if !included[build.Dir] && !isBuildLogic {
candidates = append(candidates, build)
}
}
if len(candidates) == 1 {
return candidates[0], nil
}
if len(candidates) == 0 {
return buildrepo.GradleBuild{}, errors.New("repository contains no Gradle build")
}
paths := make([]string, 0, len(candidates))
for _, build := range candidates {
relative, err := filepath.Rel(layout.Root, build.Dir)
if err != nil {
return buildrepo.GradleBuild{}, fmt.Errorf("describe build directory: %w", err)
}
paths = append(paths, relative)
}
return buildrepo.GradleBuild{}, fmt.Errorf("multiple Gradle builds found; select --build-dir: %s", strings.Join(paths, ", "))
}
package compile
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
)
// outputDestination is where the compiled JAR is written: either an explicit
// JAR file or a directory that receives the project's artifact name.
type outputDestination struct {
directory string
file string
}
// parseOutputDestination classifies the output flag. A path ending in `.jar`
// names the JAR to write; every other value, including an unset flag, names the
// directory that receives the project's artifact name.
func parseOutputDestination(value string) outputDestination {
trimmed := strings.TrimSpace(value)
if strings.EqualFold(filepath.Ext(trimmed), ".jar") {
return outputDestination{file: trimmed}
}
if trimmed == "" {
return outputDestination{directory: "."}
}
return outputDestination{directory: filepath.Clean(trimmed)}
}
// resolve returns the absolute destination for the artifact Gradle built as
// artifactName. A directory destination stores the JAR under that name, while
// an explicit destination keeps the file name the user asked for.
func (d outputDestination) resolve(base, artifactName string) (string, error) {
target := d.file
if d.directory != "" {
target = filepath.Join(d.directory, artifactName)
}
if !filepath.IsAbs(target) {
target = filepath.Join(base, target)
}
resolved, err := filepath.Abs(target)
if err != nil {
return "", fmt.Errorf("resolve output path: %w", err)
}
return resolved, nil
}
// ensureAbsent rejects an occupied destination; compile never overwrites files.
func ensureAbsent(path string) error {
if _, err := os.Lstat(path); err == nil {
return fmt.Errorf("output already exists: %s", path)
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect output: %w", err)
}
return nil
}
func selectArtifact(project gradleProject, ecosystem catalog.Ecosystem) (string, error) {
candidates := make([]archive, 0, len(project.Archives))
seen := make(map[string]bool, len(project.Archives))
for _, output := range project.Archives {
if !output.Enabled || !strings.EqualFold(filepath.Ext(output.File), ".jar") || developmentClassifier(output.Classifier) {
continue
}
if seen[output.File] {
continue
}
info, err := os.Stat(output.File)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return "", fmt.Errorf("inspect built archive %q: %w", output.File, err)
}
if !info.Mode().IsRegular() {
continue
}
packages, err := artifact.ReadInfo(output.File)
if err != nil {
return "", fmt.Errorf("verify built archive %q: %w", output.File, err)
}
packages = artifact.PreferredPackageInfos(packages, ecosystem)
matches := slices.ContainsFunc(packages, func(info artifact.PackageInfo) bool {
return supportedEcosystem(info.Ref.Ecosystem) && (ecosystem == "" || info.Ref.Ecosystem == ecosystem)
})
if matches {
seen[output.File] = true
candidates = append(candidates, output)
}
}
published := make([]archive, 0, len(candidates))
for _, candidate := range candidates {
if candidate.Published {
published = append(published, candidate)
}
}
if len(published) > 0 {
candidates = published
}
if len(candidates) == 1 {
return candidates[0].File, nil
}
if len(candidates) == 0 {
return "", fmt.Errorf("project %s produced no deployable mod JAR with matching metadata", project.Path)
}
paths := make([]string, 0, len(candidates))
for _, candidate := range candidates {
paths = append(paths, candidate.File)
}
slices.Sort(paths)
return "", fmt.Errorf("project %s produced multiple deployable mod JARs: %s", project.Path, strings.Join(paths, ", "))
}
func developmentClassifier(classifier string) bool {
classifier = strings.ToLower(classifier)
switch classifier {
case "sources", "javadoc", "dev", "dev-shadow", "api", "test", "tests", "test-fixtures":
return true
default:
return strings.HasSuffix(classifier, "-sources") || strings.HasSuffix(classifier, "-javadoc")
}
}
func publishArtifact(ctx context.Context, source, destination string) (err error) {
if err := ctx.Err(); err != nil {
return err
}
input, err := os.Open(source)
if err != nil {
return fmt.Errorf("open compiled artifact: %w", err)
}
defer func() { err = errors.Join(err, input.Close()) }()
parent := filepath.Dir(destination)
if err := os.MkdirAll(parent, 0o755); err != nil {
return fmt.Errorf("create output directory: %w", err)
}
output, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("create output artifact: %w", err)
}
defer func() {
if closeErr := output.Close(); closeErr != nil {
err = errors.Join(err, fmt.Errorf("close output artifact: %w", closeErr))
}
if err != nil {
if removeErr := os.Remove(destination); removeErr != nil {
err = errors.Join(err, fmt.Errorf("remove partial output: %w", removeErr))
}
}
}()
if _, err := io.Copy(output, contextReader{ctx: ctx, reader: input}); err != nil {
return fmt.Errorf("copy compiled artifact: %w", err)
}
return ctx.Err()
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r contextReader) Read(buffer []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.reader.Read(buffer)
}
package compile
import (
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
var githubReference = regexp.MustCompile(`^[A-Za-z0-9_-]+/[A-Za-z0-9_.-]+$`)
func parseRemote(source string) (string, error) {
if githubReference.MatchString(source) {
owner, repository, _ := strings.Cut(source, "/")
if repository == "." || repository == ".." {
return "", fmt.Errorf("invalid repository reference %q", source)
}
return "https://github.com/" + owner + "/" + strings.TrimSuffix(repository, ".git") + ".git", nil
}
remote, err := url.Parse(source)
if err != nil {
return "", fmt.Errorf("parse repository url: %w", err)
}
if remote.RawQuery != "" || remote.Fragment != "" || remote.Opaque != "" {
return "", fmt.Errorf("repository url must not contain a query, fragment, or opaque transport")
}
switch remote.Scheme {
case "https", "http", "ssh", "git":
if remote.Host == "" || strings.Trim(remote.Path, "/") == "" {
return "", fmt.Errorf("repository url must identify a host and repository path")
}
case "file":
if remote.Host != "" && remote.Host != "localhost" {
return "", fmt.Errorf("file repository url must refer to the local host")
}
if !isAbsoluteFilePath(remote.Path) {
return "", fmt.Errorf("file repository url must have an absolute path")
}
default:
return "", fmt.Errorf("source must be a Git repository url or GitHub owner/repo reference")
}
return remote.String(), nil
}
// isAbsoluteFilePath reports whether a file URL path is absolute. Windows paths
// carry their drive letter after a leading slash inside the URL, and no native
// absolute-path check accepts that spelling on Windows, so recognize it directly.
// The URL is handed to git unchanged either way, only its validity is judged here.
func isAbsoluteFilePath(path string) bool {
if len(path) >= 3 && path[0] == '/' && isDriveLetter(path[1]) && path[2] == ':' {
return true
}
return filepath.IsAbs(path)
}
func isDriveLetter(c byte) bool {
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')
}
// refSuffix describes the requested ref for the clone narration lines, so the
// user can see which branch or tag the checkout landed on.
func refSuffix(branch, tag string) string {
switch {
case branch != "":
return " (branch " + branch + ")"
case tag != "":
return " (tag " + tag + ")"
default:
return ""
}
}
// clone fetches remote into dir. Its raw output goes to output rather than
// straight to the terminal, so a large checkout stays quiet and a rejected
// remote is reported with git's own reason.
func clone(ctx context.Context, remote, dir, branch, tag string, output *processLog) error {
git, err := exec.LookPath("git")
if err != nil {
return fmt.Errorf("find git: %w", err)
}
env := cloneEnvironment()
// run labels one git invocation; a failure quotes the label along with the
// tail of git's own output.
run := func(label string, args []string) error {
cmd := exec.CommandContext(ctx, git, args...)
cmd.Env = env
cmd.Stdout = output
cmd.Stderr = output
cmd.WaitDelay = 5 * time.Second
configureProcess(cmd)
err := cmd.Run()
output.flush()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return reportFailure(output, fmt.Errorf("%s: %w", label, err))
}
return nil
}
// git resolves --branch under refs/heads before refs/tags, so a tag named
// like a branch would clone the branch. When a ref is requested, clone
// without a checkout, resolve the exact namespace, and only then check
// out that commit and initialize the submodules.
args := []string{"-c", "protocol.ext.allow=never", "clone"}
if branch == "" && tag == "" {
args = append(args, "--recurse-submodules")
} else {
args = append(args, "--no-checkout")
}
args = append(args, "--", remote, dir)
if err := run("clone repository", args); err != nil {
return err
}
if branch == "" && tag == "" {
return nil
}
// A clone keeps the fetched branches under the origin remote and copies the
// tags verbatim, so branches resolve through refs/remotes/origin and tags
// through refs/tags.
kind, namespace := "branch", "refs/remotes/origin/"
if branch == "" {
kind, namespace = "tag", "refs/tags/"
}
name := branch
if name == "" {
name = tag
}
ref := namespace + name
if err := run(fmt.Sprintf("remote has no %s %q", kind, name),
[]string{"-c", "protocol.ext.allow=never", "-C", dir, "show-ref", "--verify", "--quiet", ref},
); err != nil {
return err
}
if err := run(fmt.Sprintf("checkout %s %s", kind, name),
[]string{"-c", "protocol.ext.allow=never", "-C", dir, "checkout", "--detach", ref},
); err != nil {
return err
}
return run("initialize submodules",
[]string{"-c", "protocol.ext.allow=never", "-C", dir, "submodule", "update", "--init", "--recursive"},
)
}
// cloneEnvironment makes every git invocation of the clone non-interactive. The
// commands run in their own process group, so a prompt waiting on the terminal
// is stopped by the kernel (SIGTTIN) with no way to answer it and the command
// hangs until Ctrl+C; prompts instead fail fast. HTTPS credentials honor
// GIT_TERMINAL_PROMPT, host-key and passphrase prompts honor batch-mode ssh,
// and a user who configured their own GIT_SSH_COMMAND or GIT_SSH keeps it.
func cloneEnvironment() []string {
env := replaceEnvironment(os.Environ(), "GIT_TERMINAL_PROMPT", "0")
if _, configured := os.LookupEnv("GIT_SSH_COMMAND"); !configured {
if _, configured := os.LookupEnv("GIT_SSH"); !configured {
env = append(env, "GIT_SSH_COMMAND=ssh -o BatchMode=yes")
}
}
return env
}
package compile
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"github.com/mclucy/lucy/catalog"
_ "embed"
"github.com/Masterminds/semver/v3"
"github.com/mclucy/lucy/internal/buildrepo"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/toolchain"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/terminal/report"
)
//go:embed compile_model.gradle
var inspectionScript string
type gradleRunner struct {
dir string
executable string
arguments []string
env []string
version string
modelPath string
daemon toolchain.JavaInstallation
progress io.Writer
logger *log.Logger
reporter *report.Reporter
}
type gradleModel struct {
Projects []gradleProject `json:"projects"`
}
type gradleProject struct {
Path string `json:"path"`
Ecosystems []catalog.Ecosystem `json:"ecosystems"`
HasModMetadata bool `json:"hasModMetadata"`
BuildTask string `json:"buildTask"`
Compilers []compiler `json:"compilers"`
Archives []archive `json:"archives"`
}
type compiler struct {
Task string `json:"task"`
Major int `json:"major"`
Executable string `json:"executable"`
Release int `json:"release"`
Target string `json:"target"`
}
type archive struct {
File string `json:"file"`
Classifier string `json:"classifier"`
Published bool `json:"published"`
Enabled bool `json:"enabled"`
}
func newGradleRunner(
build buildrepo.GradleBuild,
inventory toolchain.Inventory,
temporary string,
progress io.Writer,
logger *log.Logger,
reporter *report.Reporter,
) (gradleRunner, error) {
runner := gradleRunner{
dir: build.Dir,
version: "unknown",
progress: progress,
logger: logger,
reporter: reporter,
}
version := ""
if build.Wrapper != nil {
wrapper := build.Wrapper
var scriptMode os.FileMode
for _, path := range []string{
wrapper.Script,
wrapper.Jar,
wrapper.Properties,
} {
if path == "" {
return runner, errors.New("repository Gradle wrapper is incomplete")
}
info, err := os.Stat(path)
if err != nil {
return runner, fmt.Errorf("inspect Gradle wrapper component %q: %w", path, err)
}
if !info.Mode().IsRegular() {
return runner, fmt.Errorf("gradle wrapper component is not a regular file: %s", path)
}
if path == wrapper.Script {
scriptMode = info.Mode()
}
}
if wrapper.DistributionURL == "" {
return runner, errors.New("gradle wrapper has no distribution url")
}
version = wrapper.Version
runner.executable = wrapper.Script
switch {
case runtime.GOOS == "windows":
runner.executable = "cmd.exe"
runner.arguments = []string{"/d", "/c", wrapper.Script}
case scriptMode.Perm()&0o111 == 0:
// Repositories sometimes commit the wrapper without the executable
// bit, so Lucy names the interpreter its shebang asks for.
runner.executable = wrapperInterpreter(wrapper.Script)
runner.arguments = []string{wrapper.Script}
}
} else if inventory.Gradle != nil {
runner.executable = inventory.Gradle.Path
version = inventory.Gradle.Version
extension := strings.ToLower(filepath.Ext(runner.executable))
if runtime.GOOS == "windows" && (extension == ".bat" || extension == ".cmd") {
runner.arguments = []string{"/d", "/c", runner.executable}
runner.executable = "cmd.exe"
}
} else {
return runner, errors.Join(
errors.New("repository has no Gradle wrapper and no local Gradle installation was found"),
errors.Join(inventory.Problems...),
)
}
if version != "" {
runner.version = version
}
launcher, daemon, err := selectJVMs(build, inventory, version)
if err != nil {
return runner, errors.Join(err, errors.Join(inventory.Problems...))
}
runner.daemon = daemon
logger.Debug("Gradle JVMs selected", "launcher", launcher.Java, "daemon", daemon.Java,
"reason", "Gradle compatibility and project toolchain requirements")
initPath := filepath.Join(temporary, "lucy-init.gradle")
if err := os.WriteFile(initPath, []byte(inspectionScript), 0o600); err != nil {
return runner, fmt.Errorf("write Gradle inspection script: %w", err)
}
runner.modelPath = filepath.Join(temporary, "gradle-model.json")
runner.arguments = append(
runner.arguments,
"--no-daemon", "--console=plain", "--no-configure-on-demand", "--init-script", initPath,
"-Dorg.gradle.java.installations.auto-download=false",
)
// --no-configuration-cache exists since Gradle 6.6. A wrapper distribution
// with a custom file name leaves the version unknown, and Gradle refuses
// an unsupported flag before running any task, so the flag is passed only
// when the version is known to accept it.
if parsed, err := semver.NewVersion(version); err == nil && parsed.GreaterThanEqual(semver.MustParse("6.6.0")) {
runner.arguments = append(runner.arguments, "--no-configuration-cache")
}
if build.Daemon == nil {
runner.arguments = append(runner.arguments, "-Dorg.gradle.java.home="+daemon.Home)
}
homes := make([]string, 0, len(inventory.Java))
for _, java := range inventory.Java {
if java.Javac != "" {
homes = append(homes, java.Home)
}
}
runner.env = replaceEnvironment(os.Environ(), "JAVA_HOME", launcher.Home)
installationPathsKey := "ORG_GRADLE_PROJECT_org.gradle.java.installations.paths"
if _, configured := os.LookupEnv(installationPathsKey); !configured && len(homes) > 0 {
runner.env = replaceEnvironment(runner.env, installationPathsKey, strings.Join(homes, ","))
}
runner.env = replaceEnvironment(runner.env, "LUCY_COMPILE_MODEL", runner.modelPath)
runner.env = replaceEnvironment(runner.env, "PATH", filepath.Dir(launcher.Java)+string(os.PathListSeparator)+os.Getenv("PATH"))
return runner, nil
}
// inspect evaluates the build model of every project so Lucy can choose one.
func (r gradleRunner) inspect(ctx context.Context) (gradleModel, error) {
writeProgress(r.progress, "Evaluating Gradle "+r.version+" build")
return r.execute(ctx, "Gradle build model", ":lucyCompileModel")
}
// inspectCompilers reports the compilers the selected project can use, which
// decides whether the local JDK can build it. The project's own build task
// joins the invocation as a dry run so the task graph names the compile tasks
// without running any of them: the JDK check must happen before the build.
func (r gradleRunner) inspectCompilers(ctx context.Context, project gradleProject) (gradleProject, error) {
writeProgress(r.progress, "Checking toolchain for "+nameProject(project.Path))
model, err := r.execute(
ctx,
"Gradle compiler inspection",
project.BuildTask,
":lucyCompileModel",
"-Plucy.compile.project="+project.Path,
"--dry-run",
)
if err != nil {
return gradleProject{}, err
}
for _, candidate := range model.Projects {
if candidate.Path == project.Path {
return candidate, nil
}
}
return gradleProject{}, fmt.Errorf("selected project %s disappeared from the build", project.Path)
}
// build runs task on the selected project and returns the archives it produced.
func (r gradleRunner) build(ctx context.Context, task string) (gradleModel, error) {
writeProgress(r.progress, "Building "+task)
return r.execute(ctx, "Gradle "+task, task, ":lucyCompileModel")
}
// execute runs label along with tasks. The label names only the work the user
// asked for: tasks also carries Lucy's own inspection task and its -P
// properties, which are implementation detail rather than something to report.
func (r gradleRunner) execute(ctx context.Context, label string, tasks ...string) (gradleModel, error) {
if err := os.Remove(r.modelPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return gradleModel{}, fmt.Errorf("remove previous Gradle model: %w", err)
}
arguments := make([]string, 0, len(r.arguments)+len(tasks))
arguments = append(arguments, r.arguments...)
arguments = append(arguments, tasks...)
output := newProcessLog("gradle", r.logger, r.reporter)
cmd := exec.CommandContext(ctx, r.executable, arguments...)
cmd.Dir = r.dir
cmd.Env = r.env
cmd.Stdout = output
cmd.Stderr = output
cmd.WaitDelay = 5 * time.Second
configureProcess(cmd)
r.logger.Info("Gradle stage started", "stage", label, "version", r.version)
r.logger.Debug("Gradle invocation prepared", "executable", r.executable, "tasks", tasks, "directory", r.dir)
err := cmd.Run()
output.flush()
if err != nil {
if ctx.Err() != nil {
return gradleModel{}, ctx.Err()
}
return gradleModel{}, reportFailure(
output,
fmt.Errorf("run %s: %w", label, err),
)
}
data, err := os.ReadFile(r.modelPath)
if err != nil {
return gradleModel{}, fmt.Errorf("read evaluated Gradle model: %w", err)
}
var model gradleModel
if err := json.Unmarshal(data, &model); err != nil {
return model, fmt.Errorf("decode evaluated Gradle model: %w", err)
}
r.logger.Info("Gradle stage completed", "stage", label, "projects", len(model.Projects))
return model, nil
}
// nameProject names a Gradle project for user-facing text. The root project
// carries the empty-looking path ":", which reads badly inside a sentence.
func nameProject(path string) string {
if path == "" || path == ":" {
return "the root project"
}
return path
}
func selectProject(ctx context.Context, model gradleModel, opts *options, gate cli.PromptGate) (gradleProject, error) {
candidates := make([]gradleProject, 0, len(model.Projects))
ecosystem := catalog.Ecosystem(opts.ecosystem)
for _, project := range model.Projects {
if opts.project != "" && project.Path != opts.project {
continue
}
if ecosystem != "" && !slices.Contains(project.Ecosystems, ecosystem) {
continue
}
hasModArchive := slices.ContainsFunc(project.Archives, func(output archive) bool {
return output.Enabled && filepath.Ext(output.File) == ".jar" && !developmentClassifier(output.Classifier)
})
if hasModArchive && slices.ContainsFunc(project.Ecosystems, supportedEcosystem) {
candidates = append(candidates, project)
}
}
if slices.ContainsFunc(candidates, func(project gradleProject) bool { return project.HasModMetadata }) {
candidates = slices.DeleteFunc(candidates, func(project gradleProject) bool { return !project.HasModMetadata })
}
if len(candidates) == 0 {
return gradleProject{}, errors.New("no matching Forge, NeoForge, or Fabric mod project was found")
}
if len(candidates) > 1 {
// An explicit --project never reaches this branch, so the prompt only
// ever replaces an absent flag.
if opts.project == "" && gate.Available() {
picked, err := promptModProject(ctx, candidates, gate)
if err != nil {
return gradleProject{}, err
}
opts.project = picked.Path
candidates = []gradleProject{picked}
} else {
paths := make([]string, 0, len(candidates))
for _, project := range candidates {
paths = append(paths, project.Path+" ["+joinEcosystems(project.Ecosystems)+"]")
}
return gradleProject{}, fmt.Errorf("multiple mod projects found; select --ecosystem or --project: %s", strings.Join(paths, ", "))
}
}
project := candidates[0]
if project.BuildTask == "" {
return project, fmt.Errorf("project %s has neither a build nor an assemble task", project.Path)
}
return project, nil
}
func joinEcosystems(ecosystems []catalog.Ecosystem) string {
values := make([]string, 0, len(ecosystems))
for _, ecosystem := range ecosystems {
values = append(values, string(ecosystem))
}
return strings.Join(values, ", ")
}
func replaceEnvironment(environment []string, key, value string) []string {
for i, entry := range environment {
name, _, _ := strings.Cut(entry, "=")
if strings.EqualFold(name, key) {
environment[i] = key + "=" + value
return environment
}
}
return append(environment, key+"="+value)
}
package compile
import (
"bufio"
"os"
"os/exec"
"path/filepath"
"strings"
)
// fallbackShell interprets Gradle wrappers that declare no usable shebang. It
// is the shell a wrapper without a shebang would expect anyway.
const fallbackShell = "/bin/sh"
// wrapperInterpreter returns the shell to run a Gradle wrapper that Lucy
// cannot execute directly. Gradle ships a bash script before 8.2 and a POSIX
// one from 8.2 on, so the shebang is the only reliable statement of which
// dialect the wrapper is written in; the fallback shell rejects the bash one
// wherever it is dash. Reading it here is a fallback, not the usual path: an
// executable wrapper is started directly and lets the system read it instead.
func wrapperInterpreter(script string) string {
if shell, ok := shebangShell(script); ok {
return shell
}
return fallbackShell
}
// shebangShell resolves the interpreter a script's shebang line names, and
// reports whether the script declares one that is present on this machine.
func shebangShell(script string) (string, bool) {
line, err := readFirstLine(script)
if err != nil {
return "", false
}
line, declared := strings.CutPrefix(line, "#!")
if !declared {
return "", false
}
fields := strings.Fields(line)
if len(fields) > 0 && filepath.Base(fields[0]) == "env" {
fields = fields[1:]
}
for _, field := range fields {
if strings.HasPrefix(field, "-") {
continue
}
resolved, err := exec.LookPath(field)
return resolved, err == nil
}
return "", false
}
// readFirstLine returns the first line of a script without its line ending.
func readFirstLine(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
line, err := bufio.NewReader(file).ReadString('\n')
if err != nil && line == "" {
return "", err
}
return strings.TrimRight(line, "\r\n"), nil
}
package compile
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/mclucy/lucy/internal/buildrepo"
"github.com/mclucy/lucy/internal/toolchain"
)
func selectJVMs(
build buildrepo.GradleBuild,
inventory toolchain.Inventory,
gradleVersion string,
) (toolchain.JavaInstallation, toolchain.JavaInstallation, error) {
var gradle *semver.Version
if parsed, err := semver.NewVersion(gradleVersion); err == nil {
gradle = parsed
}
var launcher toolchain.JavaInstallation
if configured := os.Getenv("JAVA_HOME"); configured != "" {
java, err := javaAtHome(inventory, configured)
if err != nil {
return launcher, launcher, fmt.Errorf("configured JAVA_HOME: %w", err)
}
if gradleSupportsJava(gradle, java.Major) {
launcher = java
}
}
if launcher.Home == "" {
for _, java := range inventory.Java {
if gradleSupportsJava(gradle, java.Major) {
launcher = java
break
}
}
}
if launcher.Home == "" {
return launcher, launcher, fmt.Errorf("no local Java installation can launch Gradle %s", gradleVersion)
}
daemon := launcher
if build.Daemon != nil {
var found bool
for _, java := range inventory.Java {
versionMatches := build.Daemon.Major == 0 || java.Major == build.Daemon.Major
if versionMatches && vendorMatches(build.Daemon.Vendor, java.Vendor) && gradleSupportsJava(gradle, java.Major) {
daemon = java
found = true
break
}
}
if !found {
description := fmt.Sprintf("Gradle daemon requires local Java %d", build.Daemon.Major)
if build.Daemon.Vendor != "" {
description += " from " + build.Daemon.Vendor
}
return launcher, daemon, errors.New(description)
}
} else if build.JavaHome != "" {
var err error
daemon, err = javaAtHome(inventory, build.JavaHome)
if err != nil {
return launcher, daemon, fmt.Errorf("configured Gradle java home: %w", err)
}
}
if !gradleSupportsJava(gradle, daemon.Major) {
return launcher, daemon, fmt.Errorf("gradle %s cannot run its daemon on Java %d", gradleVersion, daemon.Major)
}
return launcher, daemon, nil
}
func javaAtHome(inventory toolchain.Inventory, home string) (toolchain.JavaInstallation, error) {
resolved, err := filepath.EvalSymlinks(home)
if err != nil {
return toolchain.JavaInstallation{}, fmt.Errorf("resolve Java home %q: %w", home, err)
}
for _, java := range inventory.Java {
if java.Home == filepath.Clean(resolved) {
return java, nil
}
}
return toolchain.JavaInstallation{}, fmt.Errorf("no usable Java installation at %q", home)
}
func configuredGradleJavaHome(build buildrepo.GradleBuild, userHome string) (string, error) {
home := build.JavaHome
if userHome == "" {
return home, nil
}
path := filepath.Join(userHome, "gradle.properties")
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return home, nil
}
if err != nil {
return "", fmt.Errorf("read user Gradle properties: %w", err)
}
properties, err := buildrepo.ParseProperties(string(data))
if err != nil {
return "", fmt.Errorf("decode user Gradle properties: %w", err)
}
if configured, exists := properties["org.gradle.java.home"]; exists {
home = configured
}
if home != "" && !filepath.IsAbs(home) {
home = filepath.Join(build.Dir, home)
}
return home, nil
}
var minimumGradleByJava = [...]uint64{
8: 200, 9: 403, 10: 407, 11: 500, 12: 504,
13: 600, 14: 603, 15: 607, 16: 700, 17: 703,
18: 705, 19: 706, 20: 803, 21: 805, 22: 808,
23: 810, 24: 814, 25: 901, 26: 904, 27: 908,
}
func gradleSupportsJava(version *semver.Version, major int) bool {
if major < 8 || major >= len(minimumGradleByJava) {
return false
}
if version == nil {
return true
}
if version.Major() >= 9 && major < 17 {
return false
}
return version.Major()*100+version.Minor() >= minimumGradleByJava[major]
}
func vendorMatches(required, actual string) bool {
required = strings.ToLower(required)
actual = strings.ToLower(actual)
if required == "" || required == "any vendor" {
return true
}
for _, pair := range [][2]string{
{"adoptium", "eclipse"},
{"azul", "azul"},
{"zulu", "azul"},
{"amazon", "amazon"},
{"bellsoft", "bellsoft"},
{"oracle", "oracle"},
{"microsoft", "microsoft"},
{"graal", "graal"},
{"ibm", "ibm"},
} {
if strings.Contains(required, pair[0]) {
return strings.Contains(actual, pair[1])
}
}
return strings.Contains(actual, required)
}
func checkCompiler(project gradleProject, daemon toolchain.JavaInstallation) error {
for _, requirement := range project.Compilers {
major := daemon.Major
executable := daemon.Javac
if requirement.Executable != "" {
executable = requirement.Executable
major = requirement.Major
}
if executable == "" {
return fmt.Errorf("%s needs javac, but the Gradle JVM is a runtime-only installation", requirement.Task)
}
info, err := os.Stat(executable)
if err != nil {
return fmt.Errorf("inspect compiler for %s: %w", requirement.Task, err)
}
if !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0) {
return fmt.Errorf("compiler for %s is not executable: %s", requirement.Task, executable)
}
target := requirement.Release
if target == 0 {
if parsed, err := strconv.Atoi(strings.TrimPrefix(requirement.Target, "1.")); err == nil {
target = parsed
}
}
if target > major {
return fmt.Errorf("%s targets Java %d, but its compiler is Java %d", requirement.Task, target, major)
}
}
return nil
}
// toolchainWarnings reports projects that pin a Java toolchain no local JDK
// satisfies. Gradle enforces such a pin exactly: a newer JDK never substitutes,
// because its compiler emits newer bytecode than the project targets. Lucy turns
// Gradle's auto-provisioning off, so an unsatisfied pin otherwise surfaces as a
// "Cannot find a Java installation" error raised from inside a build script,
// naming a JDK the reader was never told to install.
//
// These are warnings rather than errors because the pin is read statically from
// a Groovy DSL that a convention plugin may also set, leaving Gradle the final
// authority. The check only moves the diagnosis ahead of the failure.
func toolchainWarnings(build buildrepo.GradleBuild, inventory toolchain.Inventory) []string {
var warnings []string
for _, project := range build.Projects {
required := project.Java.Toolchain
if required == nil || required.Major == 0 {
continue
}
var available []string
seen := map[int]bool{}
satisfied := false
for _, java := range inventory.Java {
if java.Javac == "" {
continue
}
if java.Major == required.Major && vendorMatches(required.Vendor, java.Vendor) {
satisfied = true
}
if seen[java.Major] {
continue
}
seen[java.Major] = true
available = append(available, strconv.Itoa(java.Major))
}
if satisfied {
continue
}
pin := fmt.Sprintf("%s pins a Java %d toolchain", project.Path, required.Major)
if required.Vendor != "" {
pin += " from " + required.Vendor
}
if len(available) == 0 {
pin += ", but no local JDK was found"
} else {
pin += ", but local installations are Java " + strings.Join(available, ", ")
}
location := project.BuildFile
if relative, err := filepath.Rel(build.Dir, project.BuildFile); err == nil {
location = filepath.ToSlash(relative)
}
warnings = append(warnings, location+": "+pin)
}
return warnings
}
package compile
import (
"errors"
"strings"
"sync"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/terminal/report"
)
// excerptLines bounds the tail of a failed tool quoted on the console. Git and
// Gradle both explain themselves at the end of their output.
const excerptLines = 20
// processLog captures the raw stdout and stderr of one external tool.
//
// Raw tool output is DEBUG diagnostics. A failed step reports its recent
// output even when diagnostic logging filters out DEBUG records.
//
// os/exec copies a child's stdout and stderr on separate goroutines, so every
// method is guarded.
type processLog struct {
tool string
logger *log.Logger
reporter *report.Reporter
mu sync.Mutex
partial string
recent []string
}
func newProcessLog(
tool string,
logger *log.Logger,
reporter *report.Reporter,
) *processLog {
return &processLog{tool: tool, logger: logger, reporter: reporter}
}
// Write forwards a raw chunk, splitting complete lines off for the log file
// and the excerpt while the trailing partial line waits for its terminator.
func (l *processLog) Write(chunk []byte) (int, error) {
l.consume(chunk, false)
return len(chunk), nil
}
// flush records a trailing line that arrived without a newline terminator.
func (l *processLog) flush() {
l.consume(nil, true)
}
func (l *processLog) consume(chunk []byte, flush bool) {
l.mu.Lock()
l.partial += string(chunk)
lines := strings.Split(l.partial, "\n")
l.partial = lines[len(lines)-1]
complete := lines[:len(lines)-1]
if flush && l.partial != "" {
complete = append(complete, l.partial)
l.partial = ""
}
l.recent = append(l.recent, complete...)
if len(l.recent) > excerptLines {
l.recent = l.recent[len(l.recent)-excerptLines:]
}
l.mu.Unlock()
if len(complete) > 0 {
l.logger.Debug("external tool output", "tool", l.tool, "lines", complete)
}
}
// excerpt quotes the most recent non-blank lines of tool output, or nothing
// when the tool stayed silent.
func (l *processLog) excerpt() string {
l.mu.Lock()
defer l.mu.Unlock()
lines := make([]string, 0, len(l.recent))
for _, line := range l.recent {
if trimmed := strings.TrimRight(line, "\r"); strings.TrimSpace(trimmed) != "" {
lines = append(lines, trimmed)
}
}
if len(lines) == 0 {
return ""
}
return "\n" + strings.Join(lines, "\n")
}
// reportFailure shows the tool's own account of a failure and returns err
// unchanged. The excerpt is its own block rather than part of the error, where
// a run of raw lines would be reflowed into a single paragraph.
func reportFailure(output *processLog, err error) error {
if excerpt := output.excerpt(); excerpt != "" {
output.reporter.Error(
errors.New(output.tool + " reported:\n" + indent(excerpt)),
)
}
return err
}
// indent prefixes every line so a block of quoted tool output reads as one.
func indent(block string) string {
lines := strings.Split(strings.Trim(block, "\n"), "\n")
for i, line := range lines {
lines[i] = " " + line
}
return strings.Join(lines, "\n")
}
//go:build !windows
package compile
import (
"errors"
"os"
"os/exec"
"syscall"
)
func configureProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
}
package compile
import (
"context"
"charm.land/huh/v2"
"github.com/mclucy/lucy/internal/cli"
)
// promptModProject asks which of several mod projects to compile. `huh` renders
// on stderr, so stdout keeps carrying only the artifact path. Aborting the
// selection cancels the compilation; there is no default to fall back to.
func promptModProject(
ctx context.Context,
candidates []gradleProject,
gate cli.PromptGate,
) (gradleProject, error) {
// gradleProject is not comparable (it holds slices), so the select carries
// the candidate index instead of the struct.
options := make([]huh.Option[int], 0, len(candidates))
for i, project := range candidates {
options = append(options, huh.NewOption(describeModProject(project), i))
}
var picked int
form := huh.NewForm(huh.NewGroup(
huh.NewSelect[int]().
Title("Select a mod project").
Description("Multiple Forge, NeoForge, or Fabric mod projects were found.").
Options(options...).
Filtering(true).
Value(&picked),
)).
WithInput(gate.Input()).
WithOutput(gate.Output())
if err := cli.RunPrompt(ctx, form); err != nil {
return gradleProject{}, err
}
return candidates[picked], nil
}
// describeModProject labels a candidate for the select prompt. Unlike the
// non-interactive error, it names the root project in words.
func describeModProject(project gradleProject) string {
return nameProject(project.Path) + " [" + joinEcosystems(project.Ecosystems) + "]"
}
package docs
import (
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/spf13/cobra"
)
// NewCommand returns the hidden documentation command.
func NewCommand(inv *cli.Invocation) *cobra.Command {
cmd := &cobra.Command{
Use: "docs",
Short: help.DocsShort,
Hidden: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Help()
},
}
cli.MarkHelpOnly(cmd)
cmd.AddCommand(
newListCommand(inv),
newGrepCommand(inv),
newReadCommand(inv),
)
return cmd
}
package docs
import (
"fmt"
"path"
"strings"
docscontent "github.com/mclucy/lucy/docs"
)
func findPage(pages []docscontent.Page, slug string) (docscontent.Page, bool) {
for _, candidate := range pages {
if candidate.Slug == slug {
return candidate, true
}
}
return docscontent.Page{}, false
}
func normalizeSlug(raw string) (string, error) {
slug := strings.TrimSpace(raw)
slug = strings.TrimPrefix(slug, "/")
slug = strings.TrimSuffix(slug, ".mdx")
slug = path.Clean(slug)
if slug == "." || slug == ".." || strings.HasPrefix(slug, "../") {
return "", fmt.Errorf("invalid documentation page %q", raw)
}
return slug, nil
}
package docs
import (
"errors"
"fmt"
"io"
"strings"
docscontent "github.com/mclucy/lucy/docs"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
type grepOptions struct {
ignoreCase bool
lineNumber bool
filesWithMatches bool
filesWithoutMatch bool
count bool
invert bool
fixed bool
word bool
wholeLine bool
patterns []string
before int
after int
context int
noFilename bool
withFilename bool
quiet bool
}
func newGrepCommand(inv *cli.Invocation) *cobra.Command {
var opts grepOptions
cmd := &cobra.Command{
Use: "grep <pattern> [page...]",
Short: help.DocsGrepShort,
Long: help.DocsGrepLong,
Args: func(_ *cobra.Command, args []string) error {
if len(opts.patterns) == 0 && len(args) == 0 {
return cli.ExitWith(2, errors.New("missing pattern"))
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return runGrep(cmd, inv, args, &opts)
},
}
cmd.SetFlagErrorFunc(func(_ *cobra.Command, err error) error {
return cli.ExitWith(2, err)
})
// Grep uses -h for --no-filename, so reserve the long flag for help.
cmd.Flags().Bool("help", false, "help for grep")
cmd.Flags().BoolVarP(
&opts.ignoreCase,
"ignore-case",
"i",
false,
"Ignore case distinctions",
)
cmd.Flags().BoolVarP(
&opts.lineNumber,
"line-number",
"n",
false,
"Prefix each output line with its line number",
)
cmd.Flags().BoolVarP(
&opts.filesWithMatches,
"files-with-matches",
"l",
false,
"Print only page slugs with matches",
)
cmd.Flags().BoolVarP(
&opts.filesWithoutMatch,
"files-without-match",
"L",
false,
"Print only page slugs without matches",
)
cmd.Flags().BoolVarP(
&opts.count,
"count",
"c",
false,
"Print a count of matching lines per page",
)
cmd.Flags().BoolVarP(
&opts.invert,
"invert-match",
"v",
false,
"Select non-matching lines",
)
cmd.Flags().BoolVarP(
&opts.fixed,
"fixed-strings",
"F",
false,
"Interpret patterns as fixed strings",
)
cmd.Flags().BoolVarP(
&opts.word,
"word-regexp",
"w",
false,
"Match whole words only",
)
cmd.Flags().BoolVarP(
&opts.wholeLine,
"line-regexp",
"x",
false,
"Match whole lines only",
)
cmd.Flags().StringArrayVarP(
&opts.patterns,
"regexp",
"e",
nil,
"Use PATTERN for matching; repeatable",
)
cmd.Flags().IntVarP(
&opts.after,
"after-context",
"A",
0,
"Print NUM lines after a match",
)
cmd.Flags().IntVarP(
&opts.before,
"before-context",
"B",
0,
"Print NUM lines before a match",
)
cmd.Flags().IntVarP(
&opts.context,
"context",
"C",
0,
"Print NUM lines before and after a match",
)
cmd.Flags().BoolVarP(
&opts.noFilename,
"no-filename",
"h",
false,
"Do not prefix output with page slugs",
)
cmd.Flags().BoolVarP(
&opts.withFilename,
"with-filename",
"H",
false,
"Prefix output with page slugs",
)
cmd.Flags().BoolVarP(
&opts.quiet,
"quiet",
"q",
false,
"Suppress output; exit 0 on the first match",
)
return cmd
}
func runGrep(cmd *cobra.Command, inv *cli.Invocation, args []string, opts *grepOptions) error {
if opts.filesWithMatches && opts.filesWithoutMatch {
return cli.ExitWith(2, errors.New("-l and -L are mutually exclusive"))
}
if opts.before < 0 || opts.after < 0 || opts.context < 0 {
return cli.ExitWith(2, errors.New("context values must not be negative"))
}
patterns := opts.patterns
pageArgs := args
if len(patterns) == 0 {
patterns = []string{args[0]}
pageArgs = args[1:]
}
match, err := newLineMatcher(patterns, opts)
if err != nil {
return cli.ExitWith(2, fmt.Errorf("invalid pattern: %w", err))
}
pages, err := docscontent.Load()
if err != nil {
return cli.ExitWith(2, err)
}
selected := pages
if len(pageArgs) > 0 {
selected = make([]docscontent.Page, 0, len(pageArgs))
for _, raw := range pageArgs {
slug, err := normalizeSlug(raw)
if err != nil {
return cli.ExitWith(2, err)
}
selectedPage, ok := findPage(pages, slug)
if !ok {
return cli.ExitWith(2, fmt.Errorf("unknown documentation page %q", raw))
}
selected = append(selected, selectedPage)
}
}
showFilename := opts.withFilename ||
(!opts.noFilename && len(selected) > 1)
success := false
if err := cli.PageDocument(cmd, inv, cmd.OutOrStdout(), func(out io.Writer, _ style.Terminal) error {
for _, selectedPage := range selected {
lines := splitLines(selectedPage.Content)
matched := make([]bool, len(lines))
anyMatch := false
for index, line := range lines {
hit := match(line)
if opts.invert {
hit = !hit
}
matched[index] = hit
if hit {
anyMatch = true
}
}
if opts.quiet {
if anyMatch {
success = true
return nil
}
continue
}
switch {
case opts.filesWithMatches:
if anyMatch {
success = true
if _, err := fmt.Fprintln(out, selectedPage.Slug); err != nil {
return err
}
}
case opts.filesWithoutMatch:
if !anyMatch {
success = true
if _, err := fmt.Fprintln(out, selectedPage.Slug); err != nil {
return err
}
}
case opts.count:
if anyMatch {
success = true
}
if err := writeCount(out, selectedPage.Slug, matched, showFilename); err != nil {
return err
}
default:
if anyMatch {
success = true
if err := writeMatches(
out,
selectedPage.Slug,
lines,
matched,
opts,
showFilename,
); err != nil {
return err
}
}
}
}
return nil
}); err != nil {
return err
}
if success {
return nil
}
return cli.SilentExit(1)
}
func splitLines(content []byte) []string {
if len(content) == 0 {
return nil
}
text := strings.TrimSuffix(string(content), "\n")
lines := strings.Split(text, "\n")
for index := range lines {
lines[index] = strings.TrimSuffix(lines[index], "\r")
}
return lines
}
package docs
import (
"regexp"
"strings"
)
type lineMatcher func(string) bool
func newLineMatcher(patterns []string, opts *grepOptions) (lineMatcher, error) {
if opts.fixed {
return newFixedMatcher(patterns, opts), nil
}
return newRegexpMatcher(patterns, opts)
}
func newFixedMatcher(patterns []string, opts *grepOptions) lineMatcher {
needles := make([]string, len(patterns))
for index, pattern := range patterns {
if opts.ignoreCase {
pattern = strings.ToLower(pattern)
}
needles[index] = pattern
}
return func(line string) bool {
if opts.ignoreCase {
line = strings.ToLower(line)
}
for _, needle := range needles {
if fixedLineMatches(line, needle, opts.word, opts.wholeLine) {
return true
}
}
return false
}
}
func fixedLineMatches(line, needle string, word, wholeLine bool) bool {
if needle == "" {
return !wholeLine || line == ""
}
if wholeLine {
return line == needle
}
if !word {
return strings.Contains(line, needle)
}
for start := 0; start <= len(line); {
index := strings.Index(line[start:], needle)
if index < 0 {
return false
}
index += start
before := index == 0 || !isWordByte(line[index-1])
end := index + len(needle)
after := end == len(line) || !isWordByte(line[end])
if before && after {
return true
}
start = index + 1
}
return false
}
func isWordByte(value byte) bool {
return value == '_' ||
(value >= '0' && value <= '9') ||
(value >= 'a' && value <= 'z') ||
(value >= 'A' && value <= 'Z')
}
func newRegexpMatcher(patterns []string, opts *grepOptions) (lineMatcher, error) {
expressions := make([]*regexp.Regexp, 0, len(patterns))
for _, pattern := range patterns {
expression := pattern
switch {
case opts.wholeLine:
expression = `^(?:` + expression + `)$`
case opts.word:
// Boundary matching is part of the regexp so alternatives are
// retried when a shorter match fails a boundary.
expression = `(?:^|\W)(?:` + expression + `)(?:\W|$)`
}
if opts.ignoreCase {
expression = `(?i)` + expression
}
compiled, err := regexp.Compile(expression)
if err != nil {
return nil, err
}
expressions = append(expressions, compiled)
}
return func(line string) bool {
for _, compiled := range expressions {
if compiled.MatchString(line) {
return true
}
}
return false
}, nil
}
package docs
import (
"fmt"
"io"
)
func writeCount(out io.Writer, slug string, matched []bool, showFilename bool) error {
count := 0
for _, hit := range matched {
if hit {
count++
}
}
if showFilename {
_, err := fmt.Fprintf(out, "%s:%d\n", slug, count)
return err
}
_, err := fmt.Fprintf(out, "%d\n", count)
return err
}
type matchPrinter struct {
out io.Writer
slug string
showFilename bool
showLineNumber bool
}
func (p *matchPrinter) line(text string, number int, match bool) error {
separator := "-"
if match {
separator = ":"
}
switch {
case p.showFilename && p.showLineNumber:
_, err := fmt.Fprintf(
p.out,
"%s%s%d%s%s\n",
p.slug,
separator,
number,
separator,
text,
)
return err
case p.showFilename:
_, err := fmt.Fprintf(p.out, "%s%s%s\n", p.slug, separator, text)
return err
case p.showLineNumber:
_, err := fmt.Fprintf(p.out, "%d%s%s\n", number, separator, text)
return err
default:
_, err := fmt.Fprintln(p.out, text)
return err
}
}
func writeMatches(
out io.Writer,
slug string,
lines []string,
matched []bool,
opts *grepOptions,
showFilename bool,
) error {
before := opts.before
after := opts.after
if opts.context > 0 {
before = max(before, opts.context)
after = max(after, opts.context)
}
printer := &matchPrinter{
out: out,
slug: slug,
showFilename: showFilename,
showLineNumber: opts.lineNumber,
}
if before == 0 && after == 0 {
for index, hit := range matched {
if !hit {
continue
}
if err := printer.line(lines[index], index+1, true); err != nil {
return err
}
}
return nil
}
type lineRange struct {
start int
end int
}
ranges := make([]lineRange, 0)
for index, hit := range matched {
if !hit {
continue
}
start := max(0, index-before)
end := min(len(lines)-1, index+after)
if len(ranges) > 0 && start <= ranges[len(ranges)-1].end+1 {
if end > ranges[len(ranges)-1].end {
ranges[len(ranges)-1].end = end
}
continue
}
ranges = append(
ranges,
lineRange{
start: start,
end: end,
},
)
}
for rangeIndex, group := range ranges {
if rangeIndex > 0 {
if _, err := fmt.Fprintln(out, "--"); err != nil {
return err
}
}
for lineIndex := group.start; lineIndex <= group.end; lineIndex++ {
if err := printer.line(
lines[lineIndex],
lineIndex+1,
matched[lineIndex],
); err != nil {
return err
}
}
}
return nil
}
package docs
import (
"fmt"
"io"
docscontent "github.com/mclucy/lucy/docs"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
func newListCommand(inv *cli.Invocation) *cobra.Command {
return &cobra.Command{
Use: "list",
Short: help.DocsListShort,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
pages, err := docscontent.Load()
if err != nil {
return err
}
return cli.PageDocument(cmd, inv, cmd.OutOrStdout(), func(out io.Writer, _ style.Terminal) error {
for _, page := range pages {
if _, err := fmt.Fprintln(out, page.Slug); err != nil {
return err
}
}
return nil
})
},
}
}
package docs
import (
"fmt"
"io"
docscontent "github.com/mclucy/lucy/docs"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
func newReadCommand(inv *cli.Invocation) *cobra.Command {
return &cobra.Command{
Use: "read <page> [page...]",
Short: help.DocsReadShort,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
pages, err := docscontent.Load()
if err != nil {
return err
}
// Resolve every argument before writing, so a mistyped page name
// never leaves half the request on stdout.
selected := make([]docscontent.Page, 0, len(args))
for _, arg := range args {
slug, err := normalizeSlug(arg)
if err != nil {
return err
}
found, ok := findPage(pages, slug)
if !ok {
return fmt.Errorf(
"unknown documentation page %q; run lucy docs list",
arg,
)
}
selected = append(selected, found)
}
return cli.PageDocument(cmd, inv, cmd.OutOrStdout(), func(out io.Writer, _ style.Terminal) error {
for _, current := range selected {
if len(selected) > 1 {
if _, err := fmt.Fprintf(out, "===== %s =====\n", current.Slug); err != nil {
return err
}
}
if _, err := out.Write(current.Content); err != nil {
return err
}
if len(current.Content) > 0 && current.Content[len(current.Content)-1] != '\n' {
if _, err := fmt.Fprintln(out); err != nil {
return err
}
}
if len(selected) > 1 {
if _, err := fmt.Fprintln(out); err != nil {
return err
}
}
}
return nil
})
},
}
}
// Package file adapts the tracked-file command surface onto cobra.
//
// Every subcommand forwards its explicit choices to the filetrack service and
// prints the result; the adapter holds no tracking policy, digest math, or
// content-address storage logic of its own.
package file
import (
"github.com/mclucy/lucy/internal/cli"
"github.com/spf13/cobra"
)
// Flag names of the file subcommands. Output flags come from the root
// persistent flags and are read through their shared constants.
const (
flagAll = "all"
flagFromSource = "from-source"
flagImmutable = "immutable"
flagNoHash = "no-hash"
flagRecoverURL = "recover-url"
flagRevision = "revision"
)
const (
FileShort = "Track files, accept revisions, and restore recorded content"
TrackShort = "Start tracking an existing file"
UntrackShort = "Stop tracking a file"
UpdateShort = "Accept current or fresh contents as the accepted revision"
RecoverShort = "Restore a file to its accepted contents"
RevertShort = "Restore and accept a historical revision"
LockShort = "Accept current contents and mark the file immutable"
UnlockShort = "Stop warning about changes to a file"
ListShort = "Show the state of tracked files"
HistoryShort = "List tracked file events and revisions"
)
const (
FileLong = "Run from a server workspace. Paths are relative to the " +
"directory containing lucy.yaml."
TrackLong = "Snapshot the current contents of existing regular files " +
"into the local content store and declare them in lucy.yaml. One " +
"invocation accepts every path atomically. Paths accept " +
"shell-style patterns relative to the workspace: * and ? match " +
"within one path component, [abc], [a-z], and [!abc] match one " +
"character, and ** matches any number of directories, including " +
"none. Directories are reported as skipped. A pattern that " +
"matches no file or directory fails. " +
"Hidden files require an explicit leading dot, and .lucy and .git " +
"are never selected. By default each entry " +
"is mutable with an accepted hash; --immutable requires an " +
"accepted hash and raises warnings on deviation, --no-hash tracks " +
"presence only, and --recover-url records an explicit recovery " +
"source. An already tracked path fails rather than being " +
"implicitly updated."
UntrackLong = "Remove the declarations from lucy.yaml. Paths accept " +
"shell-style patterns relative to the workspace. Working content " +
"and historical backups are preserved. Directories are reported " +
"as skipped, and files that are not currently tracked are skipped " +
"with a warning. A pattern that matches no file or directory fails."
UpdateLong = "Snapshot and accept current bytes for one or more tracked " +
"files, or accept every tracked file at once with --all. Paths " +
"accept shell-style patterns matched against tracked declarations " +
"rather than the working tree; hidden tracked paths need an " +
"explicit leading dot. The change policy " +
"and recover_url stay unchanged. --from-source fetches fresh bytes " +
"from recover_url, preserves the displaced working bytes, and " +
"accepts the new digest without requiring a match on the old one."
RecoverLong = "Restore one or more tracked files to their accepted " +
"digests without accepting a new revision. Paths accept " +
"shell-style patterns matched against tracked declarations, so a " +
"deleted working file still matches; hidden tracked paths need an " +
"explicit leading dot. Local content-addressed blobs " +
"are verified first; when none is available the recover_url is " +
"fetched directly and checked against the accepted digest. " +
"Displaced working bytes are preserved without being accepted. " +
"Presence-only entries are reported as skipped when selected by a " +
"pattern or by --all."
RevertLong = "Restore and accept a backed-up historical revision of a " +
"tracked file. Without a target the accepted revision's parent is " +
"followed, so repeated reverts navigate backward instead of " +
"toggling. A hash selects a digest, --revision selects one exact " +
"historical sequence."
LockLong = "Snapshot and accept the current bytes of one or more tracked " +
"files, then warn about any future deviation without restoring or " +
"replacing them. Paths accept shell-style patterns matched against " +
"tracked declarations; hidden tracked paths need an explicit leading " +
"dot. A matched declaration with no working file is reported as " +
"skipped."
UnlockLong = "Accept the existing hashes and recover_urls but stop " +
"warning about deviation. Paths accept shell-style patterns matched " +
"against tracked declarations; hidden tracked paths need an explicit " +
"leading dot."
ListLong = "Read-only inspection of every tracked file. Mutable files " +
"may deviate without warning; immutable files warn during " +
"installation."
HistoryLong = "List file tracking events in chronological order with " +
"their sequence number, timestamp, digest, and operation. An " +
"optional path restricts the listing to one file, including one " +
"that is no longer tracked. No network access happens."
)
// NewCommand returns the file command tree. Output flags are inherited from
// the root command and are never registered again here.
func NewCommand(
contracts *cli.JSONContracts,
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
trackCmd := newTrackCmd(inv, deps)
untrackCmd := newUntrackCmd(inv, deps)
updateCmd := newUpdateCmd(inv, deps)
recoverCmd := newRecoverCmd(inv, deps)
revertCmd := newRevertCmd(inv, deps)
lockCmd := newLockCmd(inv, deps)
unlockCmd := newUnlockCmd(inv, deps)
listCmd := newListCmd(inv, deps)
historyCmd := newHistoryCmd(inv, deps)
fileResultJSON.Bind(contracts, trackCmd)
fileResultJSON.Bind(contracts, untrackCmd)
fileResultJSON.Bind(contracts, updateCmd)
fileResultJSON.Bind(contracts, recoverCmd)
fileResultJSON.Bind(contracts, revertCmd)
fileResultJSON.Bind(contracts, lockCmd)
fileResultJSON.Bind(contracts, unlockCmd)
listJSON.Bind(contracts, listCmd)
historyJSON.Bind(contracts, historyCmd)
fileCmd := &cobra.Command{
Use: "file <subcommand>",
Short: FileShort,
Long: FileLong,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Help()
},
}
cli.MarkHelpOnly(fileCmd)
fileCmd.AddCommand(
trackCmd,
untrackCmd,
updateCmd,
recoverCmd,
revertCmd,
lockCmd,
unlockCmd,
listCmd,
historyCmd,
)
return fileCmd
}
package file
import (
"fmt"
"io"
"time"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
func newHistoryCmd(
inv *cli.Invocation,
_ *cli.Dependencies,
) *cobra.Command {
return &cobra.Command{
Use: "history [path]",
Short: HistoryShort,
Long: HistoryLong,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileHistory(cmd, inv, args)
},
}
}
var historyJSON cli.JSONResult[[]filetrack.Event]
func actionFileHistory(
cmd *cobra.Command,
inv *cli.Invocation,
args []string,
) error {
path := ""
if len(args) == 1 {
path = args[0]
}
events, err := filetrack.History(inv.Directory, path)
if err != nil {
return err
}
if events == nil {
events = []filetrack.Event{}
}
output := cli.NewQueryOutput(cmd, inv)
if output.JSON() {
return historyJSON.Write(output, events)
}
return output.Document(func(out io.Writer, _ style.Terminal) error {
if len(events) == 0 {
fmt.Fprintln(out, "No file tracking history.")
return nil
}
for _, event := range events {
fmt.Fprintf(
out,
"#%d %s %s\n",
event.Sequence,
event.Time.UTC().Format(time.RFC3339),
event.Operation,
)
for _, change := range event.Changes {
writeHistoryChange(out, change)
}
}
return nil
})
}
func writeHistoryChange(out io.Writer, change filetrack.Change) {
if change.Accepted && change.After != nil && change.After.Hash != "" {
fmt.Fprintf(
out,
" %s accepted %s as revision %d\n",
change.Path,
change.After.Hash,
change.Revision,
)
} else if change.Revision != 0 && change.After != nil {
fmt.Fprintf(out, " %s active revision %d: %s\n", change.Path, change.Revision, change.After.Hash)
}
if change.BackupHash != "" {
fmt.Fprintf(
out,
" %s working backup %s\n",
change.Path,
change.BackupHash,
)
} else if change.Revision == 0 {
fmt.Fprintf(out, " %s\n", change.Path)
}
}
package file
import (
"fmt"
"io"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
func newListCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
return &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: ListShort,
Long: ListLong,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileList(cmd, inv, deps, args)
},
}
}
type fileListDocument struct {
Statuses []filetrack.Status `json:"statuses"`
Warnings []string `json:"warnings"`
}
var listJSON cli.JSONResult[fileListDocument]
func actionFileList(
cmd *cobra.Command,
inv *cli.Invocation,
_ *cli.Dependencies,
_ []string,
) error {
files, err := filetrack.DeclaredFiles(inv.Directory)
if err != nil {
return err
}
statuses, err := filetrack.Inspect(inv.Directory, files)
if err != nil {
return err
}
if statuses == nil {
statuses = []filetrack.Status{}
}
output := cli.NewQueryOutput(cmd, inv)
for _, status := range statuses {
if status.Immutable && status.State == "modified" {
output.Warn(fmt.Errorf("%s: immutable contents differ; use lucy file update to accept them or lucy file recover to restore the accepted revision", status.Path))
}
}
if output.JSON() {
return listJSON.Write(output, fileListDocument{
Statuses: statuses,
Warnings: output.Warnings(),
})
}
return output.Document(func(out io.Writer, _ style.Terminal) error {
if len(statuses) == 0 {
fmt.Fprintln(out, "No tracked files.")
return nil
}
pathWidth, stateWidth := 0, 0
for _, status := range statuses {
pathWidth = max(pathWidth, len(status.Path))
stateWidth = max(stateWidth, len(status.State))
}
for _, status := range statuses {
fmt.Fprintf(
out,
"%-*s %-9s %-*s %s\n",
pathWidth,
status.Path,
statusPolicy(status.Immutable),
stateWidth,
status.State,
statusDetail(status),
)
}
return nil
})
}
func statusPolicy(immutable bool) string {
if immutable {
return "immutable"
}
return "mutable"
}
// statusDetail reports the accepted hash behind a state, plus the observed
// hash when it differs and the reason when the state could not be observed.
func statusDetail(status filetrack.Status) string {
if status.Error != "" {
return status.Error
}
if status.Hash == "" {
return "no accepted hash"
}
if status.ActualHash == "" || status.ActualHash == status.Hash {
return status.Hash
}
return status.Hash + " (actual " + status.ActualHash + ")"
}
package file
import (
"fmt"
"io"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/terminal/style"
"github.com/spf13/cobra"
)
type fileResultView struct {
Operation filetrack.Operation `json:"operation"`
Changes []filetrack.Change `json:"changes,omitempty"`
Skipped []string `json:"skipped,omitempty"`
SkippedDirectories []string `json:"skipped_directories,omitempty"`
Reclaimed filetrack.Reclaimed `json:"reclaimed,omitzero"`
}
var fileResultJSON cli.JSONResult[fileResultView]
func newFileResultView(result filetrack.Result) fileResultView {
return fileResultView{
Operation: result.Event.Operation,
Changes: result.Event.Changes,
Skipped: result.Skipped,
SkippedDirectories: result.SkippedDirectories,
Reclaimed: result.Reclaimed,
}
}
var resultVerbs = map[filetrack.Operation]string{
filetrack.Track: "tracked",
filetrack.Untrack: "untracked",
filetrack.Update: "updated",
filetrack.Recover: "recovered",
filetrack.Revert: "reverted",
filetrack.Lock: "locked",
filetrack.Unlock: "unlocked",
}
func reportFileResult(
cmd *cobra.Command,
inv *cli.Invocation,
result filetrack.Result,
) error {
output := cli.NewOperationOutput(cmd, inv)
if output.JSON() {
return fileResultJSON.Write(output, newFileResultView(result))
}
out := output.Human()
for _, change := range result.Event.Changes {
writeChangeLine(out, result.Event.Operation, change)
}
for _, skipped := range result.SkippedDirectories {
output.Warn(fmt.Errorf("skipped directory %s", skipped))
}
for _, skipped := range result.Skipped {
if result.Event.Operation == filetrack.Untrack {
output.Warn(fmt.Errorf("skipped untracked file %s", skipped))
continue
}
fmt.Fprintf(out, "skipped %s\n", skipped)
}
if result.Reclaimed.Objects > 0 {
noun := "objects"
if result.Reclaimed.Objects == 1 {
noun = "object"
}
fmt.Fprintf(
out,
"reclaimed %d %s (%s)\n",
result.Reclaimed.Objects,
noun,
style.FormatBytesBinary(result.Reclaimed.Bytes),
)
}
return nil
}
func writeChangeLine(
out io.Writer,
operation filetrack.Operation,
change filetrack.Change,
) {
fmt.Fprintf(out, "%s %s\n", resultVerbs[operation], change.Path)
switch {
case change.Accepted && change.After != nil && change.After.Hash != "":
fmt.Fprintf(out, " accepted %s as revision %d\n", change.After.Hash, change.Revision)
case change.Revision != 0 && change.After != nil && change.After.Hash != "":
fmt.Fprintf(out, " active revision %d: %s\n", change.Revision, change.After.Hash)
}
if displacedBytes(change) {
fmt.Fprintf(out, " working backup %s\n", change.BackupHash)
}
}
// displacedBytes reports whether the working backup holds bytes other than the
// ones the change published. Restoring unchanged content keeps a backup of
// itself, which is not news the user asked for.
func displacedBytes(change filetrack.Change) bool {
if change.BackupHash == "" {
return false
}
return change.After == nil || change.BackupHash != change.After.Hash
}
// pathOrAllArgs enforces the selection shared by update and recover: --all
// replaces every positional path instead of combining with them.
func pathOrAllArgs(cmd *cobra.Command, args []string) error {
all, _ := cmd.Flags().GetBool(flagAll)
if all {
if len(args) > 0 {
return fmt.Errorf("--%s conflicts with positional paths", flagAll)
}
return nil
}
if len(args) == 0 {
return fmt.Errorf("requires a path argument or --%s", flagAll)
}
return nil
}
// revertArgs enforces revert's optional targets: a path may carry one hash,
// and --revision selects a sequence instead of a recurrent digest.
func revertArgs(cmd *cobra.Command, args []string) error {
if len(args) < 1 || len(args) > 2 {
return fmt.Errorf("requires a path and an optional hash argument")
}
if len(args) == 2 && cmd.Flags().Changed(flagRevision) {
return fmt.Errorf("--%s conflicts with the hash argument", flagRevision)
}
return nil
}
package file
import (
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/cli"
"github.com/spf13/cobra"
)
func newTrackCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "track <path>...",
Short: TrackShort,
Long: TrackLong,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileTrack(cmd, inv, deps, args)
},
}
cmd.Flags().Bool(
flagImmutable,
false,
"Warn about any change to the tracked contents",
)
cmd.Flags().Bool(
flagNoHash,
false,
"Track presence only, without an accepted hash",
)
cmd.Flags().String(
flagRecoverURL,
"",
"Record an explicit recovery source URL for the file",
)
return cmd
}
func newUntrackCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
return &cobra.Command{
Use: "untrack <path>...",
Short: UntrackShort,
Long: UntrackLong,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileUntrack(cmd, inv, deps, args)
},
}
}
func newLockCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
return &cobra.Command{
Use: "lock <path>...",
Short: LockShort,
Long: LockLong,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileLock(cmd, inv, deps, args)
},
}
}
func newUnlockCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
return &cobra.Command{
Use: "unlock <path>...",
Short: UnlockShort,
Long: UnlockLong,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileUnlock(cmd, inv, deps, args)
},
}
}
func actionFileTrack(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
immutable, _ := cmd.Flags().GetBool(flagImmutable)
noHash, _ := cmd.Flags().GetBool(flagNoHash)
recoverURL, _ := cmd.Flags().GetString(flagRecoverURL)
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Track,
Paths: args,
Immutable: immutable,
NoHash: noHash,
RecoverURL: recoverURL,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
func actionFileUntrack(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Untrack,
Paths: args,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
func actionFileLock(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Lock,
Paths: args,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
func actionFileUnlock(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Unlock,
Paths: args,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
package file
import (
"fmt"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/cli"
"github.com/spf13/cobra"
)
func newUpdateCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "update [path...]",
Short: UpdateShort,
Long: UpdateLong,
Args: pathOrAllArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileUpdate(cmd, inv, deps, args)
},
}
cmd.Flags().Bool(
flagFromSource,
false,
"Fetch fresh bytes from recover_url instead of the working file",
)
cmd.Flags().Bool(
flagAll,
false,
"Update every tracked file atomically",
)
return cmd
}
func newRecoverCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "recover [path...]",
Short: RecoverShort,
Long: RecoverLong,
Args: pathOrAllArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileRecover(cmd, inv, deps, args)
},
}
cmd.Flags().Bool(
flagAll,
false,
"Restore every tracked file with an accepted hash atomically",
)
return cmd
}
func newRevertCmd(
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
cmd := &cobra.Command{
Use: "revert <path> [hash]",
Short: RevertShort,
Long: RevertLong,
Args: revertArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return actionFileRevert(cmd, inv, deps, args)
},
}
cmd.Flags().Uint64(
flagRevision,
0,
"Restore one exact historical revision sequence",
)
return cmd
}
func actionFileUpdate(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
fromSource, _ := cmd.Flags().GetBool(flagFromSource)
all, _ := cmd.Flags().GetBool(flagAll)
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Update,
Paths: args,
All: all,
FromSource: fromSource,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
func actionFileRecover(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
all, _ := cmd.Flags().GetBool(flagAll)
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Recover,
Paths: args,
All: all,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
func actionFileRevert(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
hash := ""
if len(args) == 2 {
hash = args[1]
}
revision, _ := cmd.Flags().GetUint64(flagRevision)
if cmd.Flags().Changed(flagRevision) && revision == 0 {
return fmt.Errorf("--revision requires a positive history sequence")
}
result, err := deps.Files.Run(
cmd.Context(),
inv.Directory,
filetrack.Request{
Operation: filetrack.Revert,
Paths: args[:1],
Hash: hash,
Revision: revision,
},
)
if err != nil {
return err
}
return reportFileResult(cmd, inv, result)
}
package cli
import (
"strings"
"github.com/spf13/cobra"
)
// Output style flag names. The whole family is registered once as root
// persistent flags and applies to every subcommand.
const (
FlagJSON = "json"
FlagJSONCompact = "json-compact"
FlagLong = "long"
FlagNoColor = "no-color"
FlagNoInteractive = "no-interactive"
FlagNoStyle = "no-style"
FlagLogo = "logo"
FlagLogFile = "log-file"
FlagPrintLogs = "print-logs"
FlagLogLevel = "log-level"
FlagEcosystem = "ecosystem"
)
// JSONRendering names the machine-readable rendering of a command result.
type JSONRendering int
const (
// JSONNone renders the human-facing view.
JSONNone JSONRendering = iota
// JSONPretty prints JSON indented with two spaces.
JSONPretty
// JSONCompact prints JSON on a single line.
JSONCompact
)
// JSONFlagsPresent reports whether the raw command line names a JSON flag.
// The parser is not involved, so this works before flag parsing fails.
func JSONFlagsPresent(args []string) bool {
for _, arg := range args {
if arg == "--" {
break
}
if arg == "--json" ||
strings.HasPrefix(arg, "--json=") ||
arg == "--json-compact" ||
strings.HasPrefix(arg, "--json-compact=") {
return true
}
}
return false
}
// JSONMode reports the JSON rendering a command's flags select.
// --json-compact wins over --json when both are set.
func JSONMode(cmd *cobra.Command) JSONRendering {
if compact, _ := cmd.Flags().GetBool(FlagJSONCompact); compact {
return JSONCompact
}
if pretty, _ := cmd.Flags().GetBool(FlagJSON); pretty {
return JSONPretty
}
return JSONNone
}
func AddLongFlag(cmd *cobra.Command) {
cmd.Flags().BoolP(FlagLong, "l", false, "Show hidden or collapsed output")
}
func AddLogoFlag(cmd *cobra.Command) {
cmd.Flags().String(
FlagLogo,
"small",
"Status ASCII logo: none, small, or large (large is opt-in)",
)
}
// AddEcosystemFlag adds an optional mod or plugin type to a command.
func AddEcosystemFlag(cmd *cobra.Command) {
cmd.Flags().String(FlagEcosystem, "", "Mod or plugin type (fabric, forge, neoforge, bukkit, paper, mcdr)")
}
package info
import (
"context"
"fmt"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
"github.com/spf13/cobra"
)
func NewCommand(
contracts *cli.JSONContracts,
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
infoCmd := &cobra.Command{
Use: "info <package|file>",
Short: help.InfoShort,
Long: help.InfoLong,
Args: cobra.ExactArgs(1),
ValidArgsFunction: func(
cmd *cobra.Command,
args []string,
toComplete string,
) ([]string, cobra.ShellCompDirective) {
if len(args) >= 1 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
candidates, _ := cli.CompletePackageIDSuggestions(
cmd.Context(),
inv.Directory,
toComplete,
)
return candidates, cobra.ShellCompDirectiveDefault
},
RunE: func(cmd *cobra.Command, args []string) error {
return actionInfo(cmd, inv, deps, args)
},
}
infoJSON.Bind(contracts, infoCmd)
cli.AddLongFlag(infoCmd)
return infoCmd
}
func actionInfo(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
ctx, stop := cli.CommandContext(cmd)
defer stop()
output := cli.NewQueryOutput(cmd, inv)
long, _ := cmd.Flags().GetBool(cli.FlagLong)
root := inv.Directory
if err := ctx.Err(); err != nil {
return infoCancellation(err)
}
isArtifact, err := isArtifactPath(root, args[0])
if err != nil {
return err
}
if isArtifact {
return actionArtifactInfo(
ctx,
output,
inv,
deps.Router,
long,
root,
resolveInfoPath(root, args[0]),
)
}
request, err := input.Parse(args[0])
if err != nil {
return infoReferenceFailure(args[0], err)
}
request, err = resolveAgainstLock(root, request)
if err != nil {
return err
}
return actionProjectInfo(ctx, output, inv, deps.Router, long, root, request)
}
// resolveAgainstLock expands a bare package name into the explicit
// "provider:project" reference the current lock binds it to. An explicit
// provider is always honored, and the requested version survives the
// expansion.
func resolveAgainstLock(
root string,
request catalog.VersionedRef,
) (catalog.VersionedRef, error) {
if request.Provider != catalog.ProviderUnspecified {
return request, nil
}
reference, err := cli.ResolveLockReference(root, request.Name.String())
if err != nil {
return catalog.VersionedRef{}, infoAmbiguousReferenceFailure(
request.Name.String(),
err,
)
}
if reference == "" {
return request, nil
}
resolved, err := input.Parse(reference)
if err != nil {
return request, nil
}
request.Provider = resolved.Provider
request.Name = resolved.Name
return request, nil
}
type infoFetchResult struct {
info upstream.Info
providerErrors []upstream.ProviderError
err error
}
func actionProjectInfo(
ctx context.Context,
output *cli.Output,
inv *cli.Invocation,
router *routing.Router,
long bool,
root string,
request catalog.VersionedRef,
) error {
providers, err := router.ResolveInfoProviders(
request.Ecosystem,
request.Provider,
)
if err != nil {
return infoProviderSelectionFailure(request, err)
}
info, providerErrors, fetchErr := router.GetInfoFirstSuccess(
ctx,
providers,
request.Ref,
)
result := infoFetchResult{info: info, providerErrors: providerErrors, err: fetchErr}
if result.err != nil {
if failure := infoOperationFailure(ctx, result.err); failure != nil {
return failure
}
return infoProviderFailure(request, result.providerErrors, result.err)
}
if failure := infoOperationFailure(ctx, ctx.Err()); failure != nil {
return failure
}
warnings := infoProviderWarnings(result.providerErrors)
observed := infoObserveWorkspace(root)
lock := infoReadLock(root)
resolvedVersion, versionWarnings, err := infoResolveProjectVersion(
ctx,
router,
request,
result.info.Ref.Provider,
observed,
lock,
)
if err != nil {
return err
}
warnings = append(warnings, versionWarnings...)
builds, buildWarnings, err := infoProjectBuilds(ctx, router, result.info.Ref)
if err != nil {
return err
}
warnings = append(warnings, buildWarnings...)
entry := infoProjectEntry(
result.info.Metadata,
result.info.Ref,
resolvedVersion,
)
entry.Builds = append(entry.Builds, builds...)
entry.buildCriteria = infoBuildCriteriaFromLock(lock)
entry.Installed = infoInstalledAt(
root,
request.Ref,
observed,
lock,
)
document := newInfoDocument(infoKindProject, "")
document.Entries = append(document.Entries, entry)
return infoWriteDocument(ctx, output, inv, document, warnings, long)
}
// infoProviderWarnings reports partial provider failures. A successful
// document still carries every partial failure; none of them are written to
// stderr directly.
func infoProviderWarnings(
providerErrors []upstream.ProviderError,
) []string {
warnings := make([]string, 0, len(providerErrors)+1)
notFound := make([]string, 0, len(providerErrors))
for _, providerErr := range providerErrors {
if infoIsNotFound(providerErr.Err) {
notFound = append(notFound, providerErr.Provider.Title())
continue
}
warnings = append(warnings, fmt.Sprintf(
"information from %s failed: %v",
providerErr.Provider.Title(),
providerErr.Err,
))
}
sort.Strings(warnings)
sort.Strings(notFound)
if len(notFound) > 0 {
warnings = append(
warnings,
"not found on "+strings.Join(notFound, ", "),
)
}
return warnings
}
func infoProviderFailure(
request catalog.VersionedRef,
providerErrors []upstream.ProviderError,
err error,
) error {
name := infoCleanLine(request.Name.String())
if name == "" {
name = "the requested project"
}
lines := make([]string, 0, len(providerErrors))
allNotFound := len(providerErrors) > 0
for _, providerErr := range providerErrors {
if !infoIsNotFound(providerErr.Err) {
allNotFound = false
}
lines = append(lines, infoCleanLine(fmt.Sprintf(
"%s: %v",
providerErr.Provider.Title(),
providerErr.Err,
)))
}
if len(lines) == 0 {
lines = append(lines, infoCleanLine(err.Error()))
}
sort.Strings(lines)
code := infoErrorProvider
title := "cannot retrieve information for " + name
hint := "Check the project reference, or pass provider:project to choose a source."
if allNotFound {
code = infoErrorNotFound
title = "project not found: " + name
hint = "Check the project name, or pass provider:project to choose a source."
}
return &report.Detail{
Title: title,
Lines: lines,
Hint: hint,
Code: code,
Cause: err,
}
}
func infoProviderSelectionFailure(
request catalog.VersionedRef,
err error,
) error {
requested := "automatic"
if infoProviderUsable(request.Provider) {
requested = request.Provider.String()
}
return &report.Detail{
Title: "cannot select an information source",
Lines: []string{
infoCleanLine(err.Error()),
"Requested provider: " + requested,
},
Hint: "Pass provider:project to choose a source, for example modrinth:project.",
Code: infoErrorProviderPick,
Cause: err,
}
}
func infoReferenceFailure(reference string, err error) error {
return &report.Detail{
Title: "cannot parse package reference",
Lines: []string{
infoCleanLine(reference),
infoCleanLine(err.Error()),
},
Hint: "Use provider:project@version, for example modrinth:fabric-api.",
Code: infoErrorReference,
Cause: err,
}
}
func infoAmbiguousReferenceFailure(name string, err error) error {
return &report.Detail{
Title: "cannot resolve " + infoCleanLine(name) + " in the current lock",
Lines: []string{infoCleanLine(err.Error())},
Hint: "Pass an explicit provider:project reference.",
Code: infoErrorAmbiguous,
Cause: err,
}
}
func infoIsNotFound(err error) bool {
if err == nil {
return false
}
return strings.Contains(strings.ToLower(err.Error()), "not found")
}
package info
import (
"context"
"fmt"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
"github.com/mclucy/lucy/workspace"
)
// infoBuildCriteria describes the runtime a lock declares. An empty
// dimension is unknown and never filters builds.
type infoBuildCriteria struct {
Minecraft string
Ecosystems []catalog.Ecosystem
}
// infoProjectBuilds lists every published build the source can report. The
// project document survives a listing failure; the failure becomes a warning.
func infoProjectBuilds(
ctx context.Context,
router *routing.Router,
ref catalog.Ref,
) ([]infoBuild, []string, error) {
if !infoProviderUsable(ref.Provider) {
return nil, nil, nil
}
builds, err := router.Builds(ctx, ref)
if err != nil {
if failure := infoOperationFailure(ctx, err); failure != nil {
return nil, nil, failure
}
return nil, []string{fmt.Sprintf(
"could not list builds from %s: %v",
infoProviderLabel(ref.Provider),
err,
)}, nil
}
return infoBuildsFromUpstream(builds), nil, nil
}
func infoBuildsFromUpstream(builds []upstream.Build) []infoBuild {
converted := make([]infoBuild, 0, len(builds))
for _, build := range builds {
converted = append(converted, infoBuild{
Version: infoCleanLine(build.Version),
GameVersions: infoCleanList(build.GameVersions),
Loaders: infoCleanList(build.Loaders),
Channel: infoCleanLine(build.Channel),
Published: build.Published,
})
}
return converted
}
func infoCleanList(values []string) []string {
cleaned := make([]string, 0, len(values))
for _, value := range values {
if value = infoCleanLine(value); value != "" {
cleaned = append(cleaned, value)
}
}
return cleaned
}
// infoBuildCriteriaFromLock reads the declared server runtime only. Installed
// packages and observed activity never narrow the available build list.
func infoBuildCriteriaFromLock(lock *document.Lock) *infoBuildCriteria {
if lock == nil {
return nil
}
criteria := &infoBuildCriteria{
Minecraft: infoVersionText(lock.Server.Minecraft),
Ecosystems: infoLockNativeEcosystems(lock),
}
if criteria.Minecraft == "" && len(criteria.Ecosystems) == 0 {
return nil
}
return criteria
}
// infoLockNativeEcosystems reports every ecosystem the locked server product
// serves natively. A product that serves several ecosystems (for example
// Arclight) keeps all of them; filtering never narrows to one.
func infoLockNativeEcosystems(lock *document.Lock) []catalog.Ecosystem {
product := catalog.VersionedRef{
Name: catalog.Name(lock.Server.Product.String()),
Version: lock.Server.CoreVersion,
}
if match, ok := server.NormalizeProduct(product); ok &&
match.Ecosystem != catalog.EcosystemUnspecified {
product.Ecosystem = match.Ecosystem
}
components := make([]catalog.VersionedRef, 0)
for _, input := range lock.Server.Inputs {
for _, module := range input.Modules {
components = append(components, catalog.VersionedRef{
Name: catalog.Name(module.ID),
Version: module.Version,
Ecosystem: module.Ecosystem,
})
}
}
ecosystems := make([]catalog.Ecosystem, 0, 3)
seen := make(map[catalog.Ecosystem]struct{}, 3)
add := func(ecosystem catalog.Ecosystem) {
if ecosystem == catalog.EcosystemUnspecified {
return
}
if _, ok := seen[ecosystem]; ok {
return
}
seen[ecosystem] = struct{}{}
ecosystems = append(ecosystems, ecosystem)
}
for _, offer := range workspace.ProductServedEcosystems(product, components) {
if offer.Compatibility != workspace.CompatFull {
continue
}
add(offer.Ecosystem)
}
add(product.Ecosystem)
if lock.MCDR != nil {
add(catalog.EcosystemMCDR)
}
return ecosystems
}
func infoBuildCriteriaText(criteria *infoBuildCriteria) string {
if criteria == nil {
return ""
}
parts := make([]string, 0, len(criteria.Ecosystems)+1)
for _, ecosystem := range criteria.Ecosystems {
if ecosystem == catalog.EcosystemUnspecified {
continue
}
parts = append(parts, ecosystem.Title())
}
if criteria.Minecraft != "" {
parts = append(parts, "Minecraft "+criteria.Minecraft)
}
return strings.Join(parts, ", ")
}
// Missing build metadata stays visible: a source that reports no game
// versions or loaders has not proven a mismatch.
func infoBuildCompatible(
build infoBuild,
criteria *infoBuildCriteria,
) bool {
if criteria == nil {
return true
}
if criteria.Minecraft != "" && len(build.GameVersions) > 0 {
matches := false
for _, gameVersion := range build.GameVersions {
if strings.EqualFold(
strings.TrimSpace(gameVersion),
criteria.Minecraft,
) {
matches = true
break
}
}
if !matches {
return false
}
}
return infoBuildMatchesEcosystems(build.Loaders, criteria.Ecosystems)
}
func infoBuildMatchesEcosystems(
loaders []string,
required []catalog.Ecosystem,
) bool {
if len(required) == 0 || len(loaders) == 0 {
return true
}
unknown := false
for _, loader := range loaders {
ecosystem, ok := infoBuildEcosystem(loader)
if !ok {
unknown = true
continue
}
for _, offer := range required {
if offer.Satisfy(ecosystem) {
return true
}
}
}
return unknown
}
// infoBuildEcosystem maps the loader spellings providers use onto the
// compatibility surfaces Lucy models. Unrecognized loaders stay unknown so
// the human view never claims a proven mismatch.
func infoBuildEcosystem(loader string) (catalog.Ecosystem, bool) {
product, ok := server.ParseProduct(loader)
if !ok {
return catalog.EcosystemUnspecified, false
}
ecosystem := product.Ecosystem()
if ecosystem == catalog.EcosystemUnspecified ||
ecosystem == catalog.EcosystemMinecraft {
// "minecraft" usually marks a resource pack or data pack rather than
// a loader. It stays unknown so a server product is not reported as
// incompatible with content it can still serve.
return catalog.EcosystemUnspecified, false
}
return ecosystem, true
}
// infoBuildsNewestFirst orders the bounded human view. Builds without a
// publication date stay last without inventing an order among themselves.
func infoBuildsNewestFirst(builds []infoBuild) []infoBuild {
sorted := append([]infoBuild(nil), builds...)
sort.SliceStable(sorted, func(left, right int) bool {
return sorted[left].Published.After(sorted[right].Published)
})
return sorted
}
package info
import (
"time"
"github.com/mclucy/lucy/internal/cli"
)
const (
infoDocumentSchema = 1
infoKindProject = "project"
infoKindArtifact = "artifact"
infoFormatMarkdown = "markdown"
infoFormatText = "text"
infoDistributionBundled = "bundled"
infoDistributionSeparate = "separate"
infoDistributionServer = "server"
infoLinkHomepage = "homepage"
infoLinkWiki = "wiki"
infoLinkIssues = "issues"
infoLinkSource = "source"
infoLinkDownload = "download"
infoLinkForum = "forum"
infoLinkFunding = "funding"
infoLinkOther = "other"
infoErrorReference = "info.invalid_reference"
infoErrorAmbiguous = "info.ambiguous_reference"
infoErrorProvider = "info.provider_failed"
infoErrorProviderPick = "info.provider_unavailable"
infoErrorNotFound = "info.not_found"
infoErrorWorkspace = "info.workspace_failed"
infoErrorWrite = "info.write_failed"
infoErrorArtifactMiss = "info.artifact_missing"
infoErrorArtifactRead = "info.artifact_unreadable"
infoErrorArtifactEmpty = "info.artifact_empty"
)
// infoDocument is the one wire format both project information and local
// archive inspection produce. Entries are never folded here; the human
// renderer bounds its own view.
type infoDocument struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
File string `json:"file,omitempty"`
Entries []infoEntry `json:"entries"`
Warnings []string `json:"warnings"`
}
var infoJSON cli.JSONResult[infoDocument]
type infoEntry struct {
Title string `json:"title"`
Summary string `json:"summary"`
Ref string `json:"ref"`
Installed *infoInstalled `json:"installed,omitempty"`
Needs []infoDependency `json:"needs"`
Optional []infoDependency `json:"optional"`
Links []infoLink `json:"links"`
Description string `json:"description"`
DescriptionFormat string `json:"description_format"`
Authors []infoAuthor `json:"authors"`
License string `json:"license"`
Identity *infoIdentity `json:"identity,omitempty"`
Upstream *infoUpstream `json:"upstream,omitempty"`
Dependencies []infoDependency `json:"dependencies"`
DependenciesKnown bool `json:"dependencies_known"`
// Builds preserves every build the source reported, in source order.
Builds []infoBuild `json:"builds"`
// buildCriteria is presentation context, never document data.
buildCriteria *infoBuildCriteria
}
// infoBuild mirrors one published project version as reported upstream.
// Empty metadata means the source did not report it.
type infoBuild struct {
Version string `json:"version"`
GameVersions []string `json:"game_versions"`
Loaders []string `json:"loaders"`
Channel string `json:"channel"`
Published time.Time `json:"published,omitzero"`
}
type infoInstalled struct {
Ref string `json:"ref"`
Version string `json:"version"`
Path string `json:"path"`
}
type infoDependency struct {
Ref string `json:"ref"`
Constraint string `json:"constraint,omitempty"`
Distribution string `json:"distribution"`
Required bool `json:"required"`
Relationship string `json:"relationship,omitempty"`
}
type infoLink struct {
Label string `json:"label"`
Kind string `json:"kind"`
URL string `json:"url"`
}
type infoAuthor struct {
Name string `json:"name"`
Role string `json:"role,omitempty"`
URL string `json:"url,omitempty"`
}
type infoIdentity struct {
Name string `json:"name"`
Version string `json:"version"`
Provider string `json:"provider"`
Ecosystem string `json:"ecosystem"`
}
type infoUpstream struct {
Ref string `json:"ref"`
Version string `json:"version"`
}
func newInfoDocument(kind, file string) infoDocument {
return infoDocument{
Schema: infoDocumentSchema,
Kind: kind,
File: file,
Entries: []infoEntry{},
Warnings: []string{},
}
}
func newInfoEntry() infoEntry {
return infoEntry{
Needs: []infoDependency{},
Optional: []infoDependency{},
Links: []infoLink{},
Authors: []infoAuthor{},
Dependencies: []infoDependency{},
Builds: []infoBuild{},
}
}
package info
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
)
func isArtifactPath(root, path string) (bool, error) {
if !artifact.SupportsPath(path) {
return false, nil
}
resolved := resolveInfoPath(root, path)
info, err := os.Stat(resolved)
if err != nil {
return true, infoArtifactPathFailure(root, path, err)
}
if !info.Mode().IsRegular() {
return true, &report.Detail{
Title: "artifact is not a regular file: " +
infoDisplayPath(root, path),
Lines: []string{"A directory or special file cannot be inspected."},
Hint: "Pass a packaged JAR, ZIP, PYZ, or MCDR file.",
Code: infoErrorArtifactRead,
}
}
return true, nil
}
func actionArtifactInfo(
ctx context.Context,
output *cli.Output,
inv *cli.Invocation,
router *routing.Router,
long bool,
root string,
filePath string,
) error {
if err := ctx.Err(); err != nil {
return infoCancellation(err)
}
infos, err := artifact.ReadInfo(filePath)
if err != nil {
return infoArtifactReadFailure(root, filePath, err)
}
infos = artifact.PreferredPackageInfos(
infos,
catalog.EcosystemUnspecified,
)
if len(infos) == 0 {
return infoArtifactEmptyFailure(root, filePath)
}
document, warnings, err := buildArtifactDocument(
ctx,
router,
root,
filePath,
infos,
)
if err != nil {
return err
}
return infoWriteDocument(ctx, output, inv, document, warnings, long)
}
// artifactLookup is the upstream result for one artifact file. Ref is the
// project that matched the file hash, nil when nothing matched. Info is that
// project's metadata, nil when the metadata lookup failed. Warnings holds the
// problems found during the lookup.
type artifactLookup struct {
Ref *catalog.VersionedRef
Info *upstream.Info
Warnings []string
}
func (l artifactLookup) Matched() bool {
return l.Ref != nil
}
func lookupArtifactUpstream(
ctx context.Context,
router *routing.Router,
filePath string,
) (artifactLookup, error) {
result := artifactLookup{}
hashLookup := router.ResolveArtifactByHash(
ctx,
artifact.File{Path: filePath},
)
if err := ctx.Err(); err != nil {
return result, infoCancellation(err)
}
for _, providerErr := range hashLookup.Errors {
result.Warnings = append(result.Warnings, fmt.Sprintf(
"could not look up this artifact on %s: %v",
providerErr.Provider.Title(),
providerErr.Err,
))
}
if !hashLookup.Matched {
if hashLookup.Complete() {
result.Warnings = append(
result.Warnings,
"no upstream project matched this artifact hash",
)
} else {
result.Warnings = append(
result.Warnings,
"could not determine whether this artifact exists upstream",
)
}
return result, nil
}
ref := hashLookup.Release.Ref
result.Ref = &ref
providers, err := router.ResolveInfoProviders(ref.Ecosystem, ref.Provider)
if err != nil {
result.Warnings = append(result.Warnings, fmt.Sprintf(
"cannot retrieve upstream metadata for %s: %v",
ref.StringBase(),
err,
))
return result, nil
}
info, providerErrors, lookupErr := router.GetInfoFirstSuccess(
ctx,
providers,
ref.Ref,
)
if err := ctx.Err(); err != nil {
return result, infoCancellation(err)
}
for _, providerErr := range providerErrors {
result.Warnings = append(result.Warnings, fmt.Sprintf(
"could not retrieve metadata from %s: %v",
providerErr.Provider.Title(),
providerErr.Err,
))
}
if lookupErr != nil {
if failure := infoOperationFailure(ctx, lookupErr); failure != nil {
return result, failure
}
if len(providerErrors) == 0 {
result.Warnings = append(result.Warnings, fmt.Sprintf(
"cannot retrieve upstream metadata for %s: %v",
ref.StringBase(),
lookupErr,
))
}
return result, nil
}
result.Info = &info
return result, nil
}
func buildArtifactDocument(
ctx context.Context,
router *routing.Router,
root string,
filePath string,
infos []artifact.PackageInfo,
) (infoDocument, []string, error) {
lookup, err := lookupArtifactUpstream(ctx, router, filePath)
if err != nil {
return infoDocument{}, nil, err
}
document := newInfoDocument(
infoKindArtifact,
infoDisplayPath(root, filePath),
)
warnings := append([]string{}, lookup.Warnings...)
single := len(infos) == 1
attributed := 0
for _, info := range infos {
upstreamRef, match := infoArtifactUpstream(info, single, lookup)
if upstreamRef != nil {
attributed++
}
document.Entries = append(
document.Entries,
infoArtifactEntry(info, upstreamRef, match),
)
}
if lookup.Ref != nil && !single && attributed == 0 {
warnings = append(warnings, fmt.Sprintf(
"the upstream hash match %s does not name any package in this archive; upstream details were not applied",
lookup.Ref.String(),
))
}
return document, warnings, nil
}
func infoArtifactPathFailure(root, path string, err error) *report.Detail {
label := infoDisplayPath(root, path)
if errors.Is(err, os.ErrNotExist) {
return &report.Detail{
Title: "artifact not found: " + label,
Lines: []string{infoCleanLine(err.Error())},
Hint: "Check the path, or pass a package reference instead.",
Code: infoErrorArtifactMiss,
Cause: err,
}
}
return &report.Detail{
Title: "cannot inspect artifact: " + label,
Lines: []string{infoCleanLine(err.Error())},
Hint: "Check that the file is readable.",
Code: infoErrorArtifactRead,
Cause: err,
}
}
func infoArtifactReadFailure(root, path string, err error) *report.Detail {
return &report.Detail{
Title: "cannot read artifact: " + infoDisplayPath(root, path),
Lines: []string{infoCleanLine(err.Error())},
Hint: "Pass a readable JAR, ZIP, PYZ, or MCDR file.",
Code: infoErrorArtifactRead,
Cause: err,
}
}
func infoArtifactEmptyFailure(root, path string) *report.Detail {
return &report.Detail{
Title: "no package information in " + infoDisplayPath(root, path),
Lines: []string{
"The archive contains no descriptor Lucy can read.",
},
Hint: "Check that the file is a packaged mod or plugin.",
Code: infoErrorArtifactEmpty,
}
}
// infoDisplayPath keeps the document's file field and error labels stable
// without exposing an absolute workspace path.
func infoDisplayPath(root, path string) string {
return infoCleanPath(terminal.DisplayPath(root, resolveInfoPath(root, path)))
}
// resolveInfoPath anchors a user-supplied artifact path at the invocation
// directory; absolute paths pass through unchanged.
func resolveInfoPath(root, path string) string {
if filepath.IsAbs(path) {
return filepath.Clean(path)
}
return filepath.Join(root, path)
}
package info
import (
"fmt"
"sort"
"strings"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
// infoProjectEntry projects upstream project metadata. Version is the exact
// version info genuinely resolved, or Any when the request stayed unpinned.
func infoProjectEntry(
metadata catalog.Metadata,
ref catalog.Ref,
resolved version.Version,
) infoEntry {
entry := newInfoEntry()
entry.Title = infoTitle(metadata.Title, ref.Name.String())
entry.Summary = infoCleanLine(metadata.Brief)
entry.Ref = infoProjectRef(
ref.Name.String(),
ref.Provider,
resolved,
)
entry.License = infoCleanLine(metadata.License)
entry.Description, entry.DescriptionFormat = infoDescription(metadata)
entry.Authors = infoAuthors(metadata.Authors)
entry.Links = infoLinks(metadata)
return entry
}
// infoArtifactEntry projects one archive descriptor. Upstream metadata is
// merged only when the hash match is attributable to this descriptor.
func infoArtifactEntry(
local artifact.PackageInfo,
upstreamRef *catalog.VersionedRef,
match *upstream.Info,
) infoEntry {
entry := newInfoEntry()
metadata := local.Metadata
if match != nil {
metadata = infoMergeMetadata(metadata, match.Metadata)
}
fallbackName := local.Ref.Name.String()
if upstreamRef != nil {
fallbackName = infoFirstNonEmpty(
upstreamRef.Name.String(),
fallbackName,
)
}
entry.Title = infoTitle(metadata.Title, fallbackName)
entry.Summary = infoCleanLine(metadata.Brief)
if upstreamRef != nil {
entry.Ref = infoProjectRef(
upstreamRef.Name.String(),
upstreamRef.Provider,
upstreamRef.Version,
)
entry.Upstream = &infoUpstream{
Ref: infoProjectRef(
upstreamRef.Name.String(),
upstreamRef.Provider,
version.Any,
),
Version: infoVersionText(upstreamRef.Version),
}
} else {
entry.Ref = infoProjectRef(
local.Ref.Name.String(),
local.Ref.Provider,
local.Ref.Version,
)
}
entry.License = infoCleanLine(metadata.License)
entry.Description, entry.DescriptionFormat = infoDescription(metadata)
entry.Authors = infoAuthors(metadata.Authors)
entry.Links = infoLinks(metadata)
entry.Identity = infoArtifactIdentity(local)
entry.Needs, entry.Optional, entry.Dependencies = infoArtifactDependencies(local.Dependencies)
entry.DependenciesKnown = true
return entry
}
func infoArtifactIdentity(local artifact.PackageInfo) *infoIdentity {
ecosystem := ""
if local.Ref.Ecosystem != catalog.EcosystemUnspecified {
ecosystem = local.Ref.Ecosystem.String()
}
return &infoIdentity{
Name: infoCleanLine(local.Ref.Name.String()),
Version: infoVersionText(local.Ref.Version),
Provider: infoProviderText(local.Ref.Provider),
Ecosystem: ecosystem,
}
}
// infoArtifactUpstream reports the hash match worth applying to this
// descriptor. A single-descriptor archive is unambiguous even when the local
// module id differs from the upstream slug. A multi-descriptor archive needs
// the descriptor to name the matched project.
func infoArtifactUpstream(
local artifact.PackageInfo,
single bool,
lookup artifactLookup,
) (*catalog.VersionedRef, *upstream.Info) {
if lookup.Ref == nil || !lookup.Matched() {
return nil, nil
}
if single {
return lookup.Ref, lookup.Info
}
if infoNormalizedName(local.Ref.Name.String()) ==
infoNormalizedName(lookup.Ref.Name.String()) {
return lookup.Ref, lookup.Info
}
return nil, nil
}
// infoMergeMetadata lets upstream project content win while the archive fills
// the gaps. The description is one unit: never mix one document's text with
// another document's URL or format.
func infoMergeMetadata(
local catalog.Metadata,
remote catalog.Metadata,
) catalog.Metadata {
merged := catalog.Metadata{
Title: infoFirstNonEmpty(remote.Title, local.Title),
Brief: infoFirstNonEmpty(remote.Brief, local.Brief),
License: infoFirstNonEmpty(remote.License, local.License),
Authors: infoFirstNonEmptySlice(remote.Authors, local.Authors),
URLs: infoFirstNonEmptySlice(remote.URLs, local.URLs),
}
if remote.Description != "" || remote.DescriptionURL != "" {
merged.Description = remote.Description
merged.DescriptionURL = remote.DescriptionURL
merged.DescriptionIsMarkdown = remote.DescriptionIsMarkdown
} else {
merged.Description = local.Description
merged.DescriptionURL = local.DescriptionURL
merged.DescriptionIsMarkdown = local.DescriptionIsMarkdown
}
return merged
}
func infoDescription(metadata catalog.Metadata) (string, string) {
format := infoFormatText
if metadata.DescriptionIsMarkdown {
format = infoFormatMarkdown
}
return infoCleanText(metadata.Description), format
}
func infoTitle(title, fallback string) string {
if title = infoCleanLine(title); title != "" {
return title
}
return infoHumanTitle(fallback)
}
func infoHumanTitle(name string) string {
cleaned := infoCleanLine(
strings.NewReplacer("-", " ", "_", " ").Replace(name),
)
if cleaned == "" {
return ""
}
runes := []rune(cleaned)
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
return string(runes)
}
func infoAuthors(persons []catalog.Person) []infoAuthor {
authors := make([]infoAuthor, 0, len(persons))
seen := make(map[string]struct{}, len(persons))
for _, person := range persons {
name := infoCleanLine(person.Name)
if name == "" {
continue
}
url := infoCleanLine(person.URL)
key := name + "\x00" + url
if _, exists := seen[key]; exists {
continue
}
seen[key] = struct{}{}
authors = append(authors, infoAuthor{
Name: name,
Role: infoCleanLine(person.Role),
URL: url,
})
}
return authors
}
var infoLinkRanks = map[string]int{
infoLinkHomepage: 0,
infoLinkSource: 1,
infoLinkIssues: 2,
infoLinkWiki: 3,
infoLinkDownload: 4,
infoLinkForum: 5,
infoLinkFunding: 6,
infoLinkOther: 7,
}
func infoLinks(metadata catalog.Metadata) []infoLink {
links := make([]infoLink, 0, len(metadata.URLs)+1)
for _, url := range metadata.URLs {
raw := infoCleanLine(url.URL)
if raw == "" {
continue
}
kind := infoLinkKind(url.Type)
label := infoCleanLine(url.Name)
if label == "" {
label = infoLinkLabel(kind)
}
links = append(links, infoLink{
Label: label,
Kind: kind,
URL: raw,
})
}
if strings.TrimSpace(metadata.Description) == "" {
if raw := infoCleanLine(metadata.DescriptionURL); raw != "" {
links = append(links, infoLink{
Label: "Full description",
Kind: infoLinkOther,
URL: raw,
})
}
}
sort.SliceStable(links, func(i, j int) bool {
left := infoLinkRanks[links[i].Kind]
right := infoLinkRanks[links[j].Kind]
return left < right
})
deduplicated := make([]infoLink, 0, len(links))
seen := make(map[string]struct{}, len(links))
for _, link := range links {
if _, exists := seen[link.URL]; exists {
continue
}
seen[link.URL] = struct{}{}
deduplicated = append(deduplicated, link)
}
return deduplicated
}
func infoLinkKind(urlType catalog.URLType) string {
switch urlType {
case catalog.URLHome:
return infoLinkHomepage
case catalog.URLSource:
return infoLinkSource
case catalog.URLIssues:
return infoLinkIssues
case catalog.URLWiki:
return infoLinkWiki
case catalog.URLFile:
return infoLinkDownload
case catalog.URLForum:
return infoLinkForum
case catalog.URLSponsor:
return infoLinkFunding
default:
return infoLinkOther
}
}
func infoLinkLabel(kind string) string {
switch kind {
case infoLinkHomepage:
return "Homepage"
case infoLinkSource:
return "Source"
case infoLinkIssues:
return "Issues"
case infoLinkWiki:
return "Wiki"
case infoLinkDownload:
return "Download"
case infoLinkForum:
return "Forum"
case infoLinkFunding:
return "Funding"
default:
return "Link"
}
}
func infoArtifactDependencies(
dependencies []artifact.Dependency,
) ([]infoDependency, []infoDependency, []infoDependency) {
all := make([]infoDependency, 0, len(dependencies))
needs := make([]infoDependency, 0, len(dependencies))
optional := make([]infoDependency, 0, len(dependencies))
for _, dependency := range dependencies {
ref := infoDependencyRef(dependency.Ref)
if ref == "" {
continue
}
constraint := dependency.Constraint
relationship := ""
switch dependency.Kind {
case catalog.DependencyKindIncompatible, catalog.DependencyKindConflict:
relationship = string(dependency.Kind)
constraint = constraint.Negate()
}
projected := infoDependency{
Ref: ref,
Constraint: infoConstraintText(constraint),
Distribution: infoDependencyDistribution(dependency.Origin),
Required: dependency.Mandatory,
Relationship: relationship,
}
all = append(all, projected)
if relationship != "" {
continue
}
switch projected.Distribution {
case infoDistributionBundled, infoDistributionServer:
continue
}
if projected.Required {
needs = append(needs, projected)
} else {
optional = append(optional, projected)
}
}
return needs, optional, all
}
func infoDependencyDistribution(
origin catalog.DependencyOrigin,
) string {
switch catalog.NormalizeDependencyOrigin(origin) {
case catalog.DependencyEmbedded:
return infoDistributionBundled
case catalog.DependencyServerProvided:
return infoDistributionServer
default:
return infoDistributionSeparate
}
}
// infoConstraintText renders a descriptor constraint as an actionable string.
// An unconstrained dependency keeps an empty constraint rather than claiming
// the literal selector "any".
func infoConstraintText(expr version.Expr) string {
if len(expr) == 0 {
return ""
}
alternatives := make([]string, 0, len(expr))
for _, conjunction := range expr {
terms := make([]string, 0, len(conjunction))
for _, term := range conjunction {
if term.Operator == version.OpNever {
terms = append(terms, "never")
continue
}
value, ok := term.Value.(fmt.Stringer)
if !ok || value.String() == "" {
continue
}
terms = append(terms, term.Operator.ToSign()+value.String())
}
if len(terms) > 0 {
alternatives = append(alternatives, strings.Join(terms, " and "))
}
}
return infoCleanLine(strings.Join(alternatives, " or "))
}
func infoDependencyRef(ref catalog.VersionedRef) string {
name := infoCleanLine(ref.Name.String())
if name == "" {
return ""
}
if infoProviderUsable(ref.Provider) {
return ref.Provider.String() + ":" + name
}
return name
}
func infoProjectRef(
name string,
provider catalog.Provider,
projectVersion version.Version,
) string {
name = infoCleanLine(name)
if name == "" {
return ""
}
ref := name
if infoProviderUsable(provider) {
ref = provider.String() + ":" + name
}
if resolved := infoVersionText(projectVersion); resolved != "" {
ref += "@" + resolved
}
return ref
}
// infoVersionText reports a concrete version. Selectors and invalid sentinels
// are not facts about a package and stay out of the document.
func infoVersionText(value version.Version) string {
if value == "" || value.CanInfer() || value.IsInvalid() {
return ""
}
return infoCleanLine(value.String())
}
func infoProviderUsable(provider catalog.Provider) bool {
return provider != catalog.ProviderUnspecified &&
provider != catalog.ProviderUnknown
}
func infoProviderText(provider catalog.Provider) string {
if !infoProviderUsable(provider) {
return ""
}
return provider.String()
}
func infoNormalizedName(name string) string {
return input.ToProjectName(name).String()
}
func infoFirstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}
func infoFirstNonEmptySlice[T any](slices ...[]T) []T {
for _, slice := range slices {
if len(slice) > 0 {
return slice
}
}
return nil
}
// infoCleanLine removes upstream terminal controls and collapses a value that
// belongs on one line.
func infoCleanLine(value string) string {
value = ansi.Strip(value)
var clean strings.Builder
clean.Grow(len(value))
for _, character := range value {
switch {
case character == '\n' || character == '\r' || character == '\t':
clean.WriteByte(' ')
case character < 0x20 || (character >= 0x7f && character <= 0x9f):
continue
default:
clean.WriteRune(character)
}
}
return strings.Join(strings.Fields(clean.String()), " ")
}
// infoCleanText keeps the structure of prose while removing terminal
// controls. The document carries the full description; the renderer bounds
// its own view.
func infoCleanText(value string) string {
value = strings.ReplaceAll(value, "\r\n", "\n")
value = strings.ReplaceAll(value, "\r", "\n")
value = ansi.Strip(value)
var clean strings.Builder
clean.Grow(len(value))
for _, character := range value {
switch {
case character == '\n' || character == '\t':
clean.WriteRune(character)
case character < 0x20 || (character >= 0x7f && character <= 0x9f):
continue
default:
clean.WriteRune(character)
}
}
return strings.TrimSpace(clean.String())
}
// infoCleanPath removes terminal controls from a local path without changing
// its meaningful whitespace.
func infoCleanPath(value string) string {
value = ansi.Strip(value)
var clean strings.Builder
clean.Grow(len(value))
for _, character := range value {
switch {
case character == '\n' || character == '\r' || character == '\t':
clean.WriteByte(' ')
case character < 0x20 || (character >= 0x7f && character <= 0x9f):
continue
default:
clean.WriteRune(character)
}
}
return strings.TrimSpace(clean.String())
}
package info
import (
"context"
"errors"
"fmt"
"io"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
)
// infoOperationFailure converts an interruption into the shared cancelled
// failure, including the cause that main maps to exit code 130.
func infoOperationFailure(ctx context.Context, err error) error {
if err == nil {
return nil
}
if ctx != nil && ctx.Err() != nil {
return infoCancellation(ctx.Err())
}
if errors.Is(err, context.Canceled) {
return infoCancellation(err)
}
return nil
}
func infoCancellation(cause error) *report.Detail {
if cause == nil {
cause = context.Canceled
}
return &report.Detail{
Title: "info interrupted",
Lines: []string{"The operation was cancelled."},
Code: cli.CodeOperationCancelled,
Cause: cause,
}
}
// infoNormalizeWarnings keeps the warning stream one line per entry and
// removes exact duplicates while preserving order.
func infoNormalizeWarnings(warnings []string) []string {
normalized := make([]string, 0, len(warnings))
seen := make(map[string]struct{}, len(warnings))
for _, warning := range warnings {
warning = infoCleanLine(warning)
if warning == "" {
continue
}
if _, exists := seen[warning]; exists {
continue
}
seen[warning] = struct{}{}
normalized = append(normalized, warning)
}
return normalized
}
func infoWriteDocument(
ctx context.Context,
output *cli.Output,
inv *cli.Invocation,
document infoDocument,
warnings []string,
long bool,
) error {
if err := ctx.Err(); err != nil {
return infoCancellation(err)
}
for _, warning := range infoNormalizeWarnings(warnings) {
output.Warn(errors.New(warning))
}
document.Warnings = output.Warnings()
if document.Entries == nil {
document.Entries = []infoEntry{}
}
if document.Warnings == nil {
document.Warnings = []string{}
}
if output.JSON() {
if err := infoJSON.Write(output, document); err != nil {
return infoWriteFailure(err)
}
return nil
}
return output.Document(func(out io.Writer, screen style.Terminal) error {
rendered := renderInfoDocument(
document,
long,
inv.Directory,
infoRenderContext{theme: inv.Theme, terminal: screen},
)
if rendered == "" {
return nil
}
if _, err := fmt.Fprintln(out, rendered); err != nil {
return infoWriteFailure(err)
}
return nil
})
}
func infoWriteFailure(err error) *report.Detail {
return &report.Detail{
Title: "cannot write info output",
Lines: []string{err.Error()},
Code: infoErrorWrite,
Cause: err,
}
}
package info
import (
"fmt"
"net/url"
"regexp"
"strings"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/terminal/style"
)
// Markdown renderers emit OSC 8 links for arbitrary targets. Prose keeps its
// styled text, but hyperlinks stay exclusive to the vetted Links fact.
var infoRenderHyperlink = regexp.MustCompile(
"\x1b\\]8;[^\x07\x1b]*(?:\x07|\x1b\\\\)",
)
// infoRenderContext carries the presentation state of one info rendering.
type infoRenderContext struct {
theme style.Theme
terminal style.Terminal
}
const (
infoRenderDefaultWidth = 80
infoRenderFallbackHeight = 24
infoRenderDefaultLinks = 4
infoRenderDefaultDependencies = 5
infoRenderDefaultBuilds = 5
infoRenderLongBuilds = 10
infoRenderDescriptionMinLines = 3
infoRenderDescriptionMaxLines = 24
infoRenderEntryMinHeight = 8
infoRenderIndent = " "
infoRenderUnknownDependencies = "unknown (not reported by this source)"
infoRenderUnknownRequirements = "unknown (additional requirements may apply)"
)
// renderInfoDocument renders the human info view from the same document that
// produces JSON. Warnings stay in the document and reach the user through the
// command's warning stream, matching the status view.
func renderInfoDocument(
document infoDocument,
long bool,
root string,
presentation infoRenderContext,
) string {
width := presentation.terminal.Width
if width <= 0 {
width = infoRenderDefaultWidth
}
if len(document.Entries) == 0 {
return ""
}
height := presentation.terminal.Height
if !presentation.terminal.IsTTY || height <= 0 {
height = infoRenderFallbackHeight
}
share := max(infoRenderEntryMinHeight, height/len(document.Entries))
file := ""
if document.File != "" {
file = terminal.DisplayPath(
root,
strings.TrimSpace(infoRenderText(document.File)),
)
}
blocks := make([]string, 0, len(document.Entries))
for index, entry := range document.Entries {
entryFile := ""
if index == 0 {
entryFile = file
}
blocks = append(
blocks,
renderInfoEntry(
entry,
long,
width,
presentation.terminal.IsTTY,
share,
root,
entryFile,
presentation,
),
)
}
return infoRenderTrim(strings.Join(blocks, "\n\n"))
}
func renderInfoEntry(
entry infoEntry,
long bool,
width int,
tty bool,
height int,
root string,
file string,
presentation infoRenderContext,
) string {
title := infoRenderInline(entry.Title)
if title == "" {
title = infoRenderInline(entry.Ref)
}
if title == "" && entry.Identity != nil {
title = infoRenderInline(entry.Identity.Name)
}
if title == "" {
title = "unnamed"
}
titleLines := strings.Split(lipgloss.Wrap(title, width, ""), "\n")
for i := range titleLines {
titleLines[i] = presentation.theme.Accent(titleLines[i])
}
summary := infoRenderInline(entry.Summary)
var summaryLines []string
if summary != "" && summary != title {
summaryLines = strings.Split(lipgloss.Wrap(summary, width, ""), "\n")
}
facts := infoRenderEntryFacts(
entry,
long,
width,
tty,
root,
file,
presentation,
)
factWidth := width
if !tty {
keyWidth, valueWidth := 0, 0
for _, fact := range facts {
keyWidth = max(keyWidth, ansi.StringWidth(fact.Key))
for _, line := range strings.Split(fact.Value, "\n") {
valueWidth = max(valueWidth, ansi.StringWidth(line))
}
}
factWidth = max(factWidth, keyWidth+2+valueWidth)
}
factsText := terminal.RenderFacts(facts, factWidth, presentation.theme)
var factLines []string
if factsText != "" {
factLines = strings.Split(factsText, "\n")
}
lines := make([]string, 0, len(titleLines)+len(summaryLines)+len(factLines)+8)
lines = append(lines, titleLines...)
lines = append(lines, summaryLines...)
if len(factLines) > 0 {
lines = append(lines, "")
lines = append(lines, factLines...)
}
description := infoRenderDescription(
entry,
width,
long,
height-len(lines)-2,
presentation,
)
if description != "" {
lines = append(lines, "", presentation.theme.Accent("About"))
lines = append(lines, infoRenderIndentLines(description)...)
}
return strings.Join(lines, "\n")
}
func infoRenderEntryFacts(
entry infoEntry,
long bool,
width int,
tty bool,
root string,
file string,
presentation infoRenderContext,
) []terminal.Fact {
ref := infoRenderInline(entry.Ref)
license := ""
if long {
license = infoRenderInline(entry.License)
}
authors := ""
if long {
authors = infoRenderAuthors(entry.Authors, tty, presentation)
}
identity := ""
if long {
identity = infoRenderIdentity(entry.Identity)
}
upstream := ""
if long {
upstream = infoRenderUpstream(entry.Upstream)
}
builds := infoRenderBuilds(entry, long, presentation)
needs := infoRenderActionableDependencies(entry.Needs, long)
optional := infoRenderActionableDependencies(entry.Optional, long)
bundled := infoRenderDistributionDependencies(entry.Dependencies, "bundled", long)
server := infoRenderDistributionDependencies(entry.Dependencies, "server", long)
leftover := infoRenderLeftoverDependencies(entry, needs, optional, long)
links := infoRenderLinkCandidates(entry.Links, long)
keys := make([]string, 0, 13)
if file != "" {
keys = append(keys, "File")
}
if ref != "" {
keys = append(keys, "Ref")
}
if entry.Installed != nil {
keys = append(keys, "Installed")
}
if license != "" {
keys = append(keys, "License")
}
if authors != "" {
keys = append(keys, "Authors")
}
if identity != "" {
keys = append(keys, "Identity")
}
if upstream != "" {
keys = append(keys, "Upstream")
}
if builds != "" {
keys = append(keys, "Builds")
}
keys = append(keys, "Needs")
if len(optional) > 0 {
keys = append(keys, "Optional")
}
if len(bundled) > 0 {
keys = append(keys, "Bundled")
}
if len(server) > 0 {
keys = append(keys, "Server")
}
if len(leftover) > 0 {
keys = append(keys, "Dependencies")
}
if len(links) > 0 {
keys = append(keys, "Links")
}
valueWidth := infoRenderValueWidth(keys, width)
facts := make([]terminal.Fact, 0, len(keys))
if file != "" {
facts = append(facts, terminal.Fact{
Key: "File",
Value: ansi.Wrap(file, valueWidth, "/-_."),
})
}
if ref != "" {
facts = append(facts, terminal.Fact{
Key: "Ref",
Value: ansi.Wrap(ref, valueWidth, ":@-/"),
})
}
if entry.Installed != nil {
facts = append(facts, terminal.Fact{
Key: "Installed",
Value: infoRenderInstalled(
entry.Installed,
ref,
valueWidth,
root,
),
})
}
if license != "" {
facts = append(facts, terminal.Fact{Key: "License", Value: license})
}
if authors != "" {
facts = append(facts, terminal.Fact{Key: "Authors", Value: authors})
}
if identity != "" {
facts = append(facts, terminal.Fact{Key: "Identity", Value: identity})
}
if upstream != "" {
facts = append(facts, terminal.Fact{Key: "Upstream", Value: upstream})
}
if builds != "" {
facts = append(facts, terminal.Fact{Key: "Builds", Value: builds})
}
needsNote := ""
if !entry.DependenciesKnown {
needsNote = infoRenderUnknownDependencies
if len(needs) > 0 {
needsNote = infoRenderUnknownRequirements
}
}
needsValue := "none"
if len(needs) > 0 || needsNote != "" {
needsValue = infoRenderDependencyValue(needs, long, needsNote, presentation)
}
facts = append(facts, terminal.Fact{Key: "Needs", Value: needsValue})
if len(optional) > 0 {
facts = append(facts, terminal.Fact{
Key: "Optional",
Value: infoRenderDependencyValue(optional, long, "", presentation),
})
}
if len(bundled) > 0 {
facts = append(facts, terminal.Fact{
Key: "Bundled",
Value: infoRenderDependencyValue(bundled, true, "", presentation),
})
}
if len(server) > 0 {
facts = append(facts, terminal.Fact{
Key: "Server",
Value: infoRenderDependencyValue(server, true, "", presentation),
})
}
if len(leftover) > 0 {
facts = append(facts, terminal.Fact{
Key: "Dependencies",
Value: infoRenderDependencyValue(leftover, true, "", presentation),
})
}
if len(links) > 0 {
facts = append(facts, terminal.Fact{
Key: "Links",
Value: infoRenderLinks(
links,
long,
valueWidth,
tty,
presentation,
),
})
}
return facts
}
// infoRenderValueWidth mirrors RenderFacts' width arithmetic so values that
// must not break mid-token, such as paths and references, wrap beforehand.
func infoRenderValueWidth(keys []string, width int) int {
keyWidth := 0
for _, key := range keys {
keyWidth = max(keyWidth, ansi.StringWidth(key))
}
keyWidth = min(keyWidth, max(1, width/3))
return max(1, width-keyWidth-2)
}
func infoRenderInstalled(
installed *infoInstalled,
entryRef string,
valueWidth int,
root string,
) string {
version := infoRenderInline(installed.Version)
ref := infoRenderInline(installed.Ref)
if ref == entryRef {
ref = ""
}
head := version
if ref != "" {
if head == "" {
head = ref
} else {
head += " (" + ref + ")"
}
}
path := terminal.DisplayPath(
root,
strings.TrimSpace(infoRenderText(installed.Path)),
)
if path != "" {
path = ansi.Wrap(path, valueWidth, "/-_.")
}
switch {
case head != "" && path != "":
return head + "\n" + path
case head != "":
return head
case path != "":
return path
default:
return "yes"
}
}
func infoRenderIdentity(identity *infoIdentity) string {
if identity == nil {
return ""
}
name := infoRenderInline(identity.Name)
version := infoRenderInline(identity.Version)
head := strings.TrimSpace(name + " " + version)
details := make([]string, 0, 2)
if provider := infoRenderInline(identity.Provider); provider != "" {
details = append(details, provider)
}
if ecosystem := infoRenderInline(identity.Ecosystem); ecosystem != "" {
details = append(details, ecosystem)
}
if len(details) == 0 {
return head
}
if head == "" {
return strings.Join(details, ", ")
}
return head + " (" + strings.Join(details, ", ") + ")"
}
func infoRenderUpstream(upstream *infoUpstream) string {
if upstream == nil {
return ""
}
ref := infoRenderInline(upstream.Ref)
version := infoRenderInline(upstream.Version)
switch {
case ref != "" && version != "":
return ref + " (" + version + ")"
default:
return strings.TrimSpace(ref + " " + version)
}
}
func infoRenderAuthors(
authors []infoAuthor,
tty bool,
presentation infoRenderContext,
) string {
lines := make([]string, 0, len(authors))
for _, author := range authors {
name := infoRenderInline(author.Name)
if name == "" {
continue
}
line := name
if role := infoRenderInline(author.Role); role != "" {
line += " (" + role + ")"
}
if raw := infoRenderInline(author.URL); raw != "" {
link := raw
if safe, ok := infoRenderSafeURL(raw); ok && tty {
link = ansi.SetHyperlink(safe) +
presentation.theme.Link(raw) +
ansi.ResetHyperlink()
}
line += " " + link
}
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
// infoRenderActionableDependencies drops embedded and server-provided entries
// from the default actionable lists. Long output keeps them with full detail.
func infoRenderActionableDependencies(
dependencies []infoDependency,
long bool,
) []infoDependency {
visible := make([]infoDependency, 0, len(dependencies))
for _, dependency := range dependencies {
if infoRenderInline(dependency.Ref) == "" {
continue
}
if !long && infoRenderEmbeddedDependency(dependency) {
continue
}
visible = append(visible, dependency)
}
return visible
}
func infoRenderEmbeddedDependency(dependency infoDependency) bool {
switch strings.ToLower(infoRenderInline(dependency.Distribution)) {
case "bundled", "server":
return true
default:
return false
}
}
func infoRenderDistributionDependencies(
dependencies []infoDependency,
distribution string,
long bool,
) []infoDependency {
if !long {
return nil
}
matches := make([]infoDependency, 0, len(dependencies))
for _, dependency := range dependencies {
if infoRenderInline(dependency.Ref) == "" {
continue
}
if !strings.EqualFold(
infoRenderInline(dependency.Distribution),
distribution,
) {
continue
}
matches = append(matches, dependency)
}
return matches
}
// infoRenderLeftoverDependencies reports long-detail dependencies the
// actionable lists and distribution groups did not already cover.
func infoRenderLeftoverDependencies(
entry infoEntry,
needs []infoDependency,
optional []infoDependency,
long bool,
) []infoDependency {
if !long {
return nil
}
shown := make(map[string]struct{}, len(needs)+len(optional))
for _, dependency := range needs {
shown[infoRenderDependencyKey(dependency)] = struct{}{}
}
for _, dependency := range optional {
shown[infoRenderDependencyKey(dependency)] = struct{}{}
}
leftover := make([]infoDependency, 0, len(entry.Dependencies))
for _, dependency := range entry.Dependencies {
if infoRenderInline(dependency.Ref) == "" {
continue
}
if infoRenderEmbeddedDependency(dependency) {
continue
}
if _, ok := shown[infoRenderDependencyKey(dependency)]; ok {
continue
}
leftover = append(leftover, dependency)
}
return leftover
}
func infoRenderDependencyKey(dependency infoDependency) string {
return infoRenderInline(dependency.Ref) + "\x00" +
infoRenderInline(dependency.Constraint)
}
func infoRenderDependencyValue(
dependencies []infoDependency,
long bool,
note string,
presentation infoRenderContext,
) string {
lines := make([]string, 0, len(dependencies)+2)
for _, dependency := range dependencies {
lines = append(lines, infoRenderDependency(dependency, long))
}
hidden := 0
if !long && len(lines) > infoRenderDefaultDependencies {
hidden = len(lines) - infoRenderDefaultDependencies
lines = lines[:infoRenderDefaultDependencies]
}
if note != "" {
lines = append(lines, presentation.theme.Muted(note))
}
if hidden > 0 {
lines = append(lines, terminal.FoldHint(hidden, presentation.theme))
}
return strings.Join(lines, "\n")
}
// infoRenderBuilds bounds the human view, even with --long, and applies the
// lock's declared runtime. Builds whose source omitted compatibility metadata
// stay visible and say so.
func infoRenderBuilds(
entry infoEntry,
long bool,
presentation infoRenderContext,
) string {
if len(entry.Builds) == 0 {
return ""
}
compatible := make([]infoBuild, 0, len(entry.Builds))
for _, build := range entry.Builds {
if infoBuildCompatible(build, entry.buildCriteria) {
compatible = append(compatible, build)
}
}
filtered := len(entry.Builds) - len(compatible)
criteria := infoBuildCriteriaText(entry.buildCriteria)
if len(compatible) == 0 {
return presentation.theme.Muted("none compatible with " + criteria)
}
compatible = infoBuildsNewestFirst(compatible)
limit := infoRenderDefaultBuilds
if long {
limit = infoRenderLongBuilds
}
hidden := 0
if len(compatible) > limit {
hidden = len(compatible) - limit
compatible = compatible[:limit]
}
lines := make([]string, 0, len(compatible)+2)
for _, build := range compatible {
lines = append(lines, infoRenderBuildLine(build))
}
if filtered > 0 {
lines = append(
lines,
presentation.theme.Muted("filtered to "+criteria),
)
}
if hidden > 0 {
if long {
lines = append(lines, presentation.theme.Muted(fmt.Sprintf(
"… %d more builds, see --json for the complete list",
hidden,
)))
} else {
lines = append(lines, terminal.FoldHint(hidden, presentation.theme))
}
}
return strings.Join(lines, "\n")
}
func infoRenderBuildLine(build infoBuild) string {
version := infoRenderInline(build.Version)
if version == "" {
version = "unknown version"
}
notes := make([]string, 0, 4)
if channel := infoRenderInline(build.Channel); channel != "" {
notes = append(notes, channel)
}
if len(build.GameVersions) > 0 {
notes = append(notes, infoRenderInline(strings.Join(
build.GameVersions,
", ",
)))
} else {
notes = append(notes, "Minecraft version unknown")
}
if len(build.Loaders) > 0 {
notes = append(notes, infoRenderInline(strings.Join(
build.Loaders,
", ",
)))
} else {
notes = append(notes, "loaders unknown")
}
if build.Published.IsZero() {
notes = append(notes, "published unknown")
} else {
notes = append(notes, build.Published.Format("2006-01-02"))
}
return version + " (" + strings.Join(notes, ", ") + ")"
}
func infoRenderDependency(dependency infoDependency, long bool) string {
ref := infoRenderInline(dependency.Ref)
if ref == "" {
ref = "unknown"
}
if !long {
return ref
}
notes := make([]string, 0, 3)
if constraint := infoRenderInline(dependency.Constraint); constraint != "" {
notes = append(notes, constraint)
}
if distribution := infoRenderInline(dependency.Distribution); distribution != "" {
notes = append(notes, distribution)
}
if relationship := infoRenderInline(dependency.Relationship); relationship != "" {
notes = append(notes, relationship)
} else if !dependency.Required {
notes = append(notes, "optional")
}
if len(notes) == 0 {
return ref
}
return ref + " (" + strings.Join(notes, ", ") + ")"
}
func infoRenderLinkCandidates(links []infoLink, long bool) []infoLink {
candidates := make([]infoLink, 0, len(links))
seen := make(map[string]struct{}, len(links))
for _, link := range links {
raw := infoRenderInline(link.URL)
if raw == "" {
continue
}
if !long && strings.EqualFold(infoRenderInline(link.Kind), "funding") {
continue
}
if _, ok := seen[raw]; ok {
continue
}
seen[raw] = struct{}{}
candidates = append(candidates, link)
}
return candidates
}
func infoRenderLinks(
links []infoLink,
long bool,
valueWidth int,
tty bool,
presentation infoRenderContext,
) string {
visible := links
hidden := 0
if !long && len(visible) > infoRenderDefaultLinks {
hidden = len(visible) - infoRenderDefaultLinks
visible = visible[:infoRenderDefaultLinks]
}
lines := make([]string, 0, len(visible)+1)
for _, link := range visible {
lines = append(
lines,
infoRenderLinkLine(link, valueWidth, tty, presentation),
)
}
if hidden > 0 {
lines = append(lines, terminal.FoldHint(hidden, presentation.theme))
}
return strings.Join(lines, "\n")
}
func infoRenderLinkLine(
link infoLink,
width int,
tty bool,
presentation infoRenderContext,
) string {
label := infoRenderInline(link.Label)
raw := infoRenderInline(link.URL)
if label == raw {
label = ""
}
if raw == "" {
return label
}
target, safe := infoRenderSafeURL(raw)
display := raw
if tty {
budget := max(1, width)
if label != "" {
label = terminal.TruncateMiddle(
label,
max(1, min(ansi.StringWidth(label), max(1, width/3))),
)
budget = max(1, width-ansi.StringWidth(label)-2)
}
display = terminal.TruncateMiddle(display, budget)
if safe {
display = ansi.SetHyperlink(target) +
presentation.theme.Link(display) +
ansi.ResetHyperlink()
}
}
if label == "" {
return display
}
return label + " " + display
}
// infoRenderSafeURL accepts only printable HTTP(S) URLs for OSC 8 output.
func infoRenderSafeURL(raw string) (string, bool) {
if raw == "" || strings.ContainsAny(raw, " \t\r\n") {
return "", false
}
parsed, err := url.Parse(raw)
if err != nil {
return "", false
}
switch strings.ToLower(parsed.Scheme) {
case "http", "https":
default:
return "", false
}
if parsed.Host == "" {
return "", false
}
return raw, true
}
func infoRenderDescription(
entry infoEntry,
width int,
long bool,
budget int,
presentation infoRenderContext,
) string {
description := strings.TrimSpace(infoRenderText(entry.Description))
if description == "" {
return ""
}
contentWidth := max(1, width-len(infoRenderIndent))
var rendered string
switch strings.ToLower(infoRenderInline(entry.DescriptionFormat)) {
case "markdown":
rendered = presentation.theme.Markdown(
description,
contentWidth,
presentation.terminal,
)
rendered = infoRenderHyperlink.ReplaceAllString(rendered, "")
default:
rendered = lipgloss.Wrap(description, contentWidth, "")
}
if rendered == "" {
return ""
}
if !long {
budget = min(
max(budget, infoRenderDescriptionMinLines),
infoRenderDescriptionMaxLines,
)
rendered = terminal.CenterElide(rendered, budget, presentation.theme)
}
return infoRenderTrim(rendered)
}
func infoRenderIndentLines(text string) []string {
lines := strings.Split(text, "\n")
for i := range lines {
if strings.TrimSpace(ansi.Strip(lines[i])) == "" {
lines[i] = ""
continue
}
lines[i] = infoRenderIndent + lines[i]
}
return lines
}
// infoRenderText removes upstream terminal controls while keeping the
// intentional style sequences this renderer adds afterwards.
func infoRenderText(value string) string {
value = ansi.Strip(value)
var clean strings.Builder
clean.Grow(len(value))
for _, character := range value {
switch {
case character == '\n':
clean.WriteRune(character)
case character == '\t':
clean.WriteString(" ")
case character < 0x20 || (character >= 0x7f && character <= 0x9f):
continue
default:
clean.WriteRune(character)
}
}
return clean.String()
}
func infoRenderInline(value string) string {
return strings.Join(strings.Fields(infoRenderText(value)), " ")
}
func infoRenderTrim(value string) string {
lines := strings.Split(value, "\n")
for i := range lines {
lines[i] = strings.TrimRight(lines[i], " \t\r")
}
for len(lines) > 0 &&
strings.TrimSpace(ansi.Strip(lines[len(lines)-1])) == "" {
lines = lines[:len(lines)-1]
}
for len(lines) > 0 &&
strings.TrimSpace(ansi.Strip(lines[0])) == "" {
lines = lines[1:]
}
return strings.Join(lines, "\n")
}
package info
import (
"context"
"fmt"
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/terminal"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
// infoObserveWorkspace is a read-only observation used for installed facts and
// for the version-resolution context. Failure to observe is not an info
// failure: the project document still renders without local facts.
func infoObserveWorkspace(root string) *workspace.Workspace {
if root == "" {
return nil
}
return workspace.Observe(
root,
discovery.Request{Policy: discovery.PolicyPreferModified},
)
}
// infoReadLock reports the workspace lock when one is readable. A missing or
// invalid lock only removes lock-derived matching; it never fails info.
func infoReadLock(root string) *document.Lock {
if root == "" {
return nil
}
lock, err := document.LockFile(root).Read()
if err != nil {
return nil
}
return lock
}
// infoInstalledAt reports an installed package only when the workspace
// contains the actual file. The lock may identify which file belongs to the
// project, but it never proves installation by itself.
func infoInstalledAt(
root string,
request catalog.Ref,
observed *workspace.Workspace,
lock *document.Lock,
) *infoInstalled {
if observed == nil || len(observed.Packages) == 0 {
return nil
}
locked := infoLockProjectPackages(lock, request)
matches := make([]workspace.DiscoveredPackage, 0, len(observed.Packages))
matchedLock := make([]*document.Package, 0, len(observed.Packages))
// A lock binding names the project; the recorded filename ties that
// binding to an observed file even when the descriptor uses another id.
for _, lockedPackage := range locked {
filename := filepath.Base(lockedPackage.Filename)
if filename == "" || filename == "." {
continue
}
for _, observedPackage := range observed.Packages {
if filepath.Base(observedPackage.Path) != filename {
continue
}
matches = append(matches, observedPackage)
matchedLock = append(matchedLock, lockedPackage)
}
}
if len(matches) == 0 {
var identityLock *document.Package
if len(locked) > 0 {
identityLock = locked[0]
}
for _, observedPackage := range observed.Packages {
if !infoInstalledNameMatches(request, observedPackage.ID) {
continue
}
matches = append(matches, observedPackage)
matchedLock = append(matchedLock, identityLock)
}
}
if len(matches) == 0 {
return nil
}
if len(matches) > 1 {
identityMatches := make([]workspace.DiscoveredPackage, 0, len(matches))
identityLocks := make([]*document.Package, 0, len(matches))
for index, match := range matches {
if !infoInstalledNameMatches(request, match.ID) {
continue
}
identityMatches = append(identityMatches, match)
identityLocks = append(identityLocks, matchedLock[index])
}
if len(identityMatches) > 0 {
matches = identityMatches
matchedLock = identityLocks
}
}
best := 0
for index := 1; index < len(matches); index++ {
if matches[index].Path < matches[best].Path {
best = index
}
}
installed := matches[best]
lockedPackage := matchedLock[best]
versionText := infoVersionText(installed.ID.Version)
for _, match := range matches {
if infoVersionText(match.ID.Version) != versionText {
versionText = ""
break
}
}
return &infoInstalled{
Ref: infoInstalledRef(installed, lockedPackage, request),
Version: versionText,
Path: infoCleanPath(terminal.DisplayPath(root, installed.Path)),
}
}
// infoInstalledRef qualifies the installed ref with the upstream project the
// lock or request matched. A local descriptor id may differ from that project
// slug, so it must not be paired with an inferred provider. Without upstream
// attribution the ref stays an honest, unqualified local identity.
func infoInstalledRef(
installed workspace.DiscoveredPackage,
lockedPackage *document.Package,
request catalog.Ref,
) string {
if lockedPackage != nil {
provider, name := infoLockPackageIdentity(lockedPackage, request)
if name != "" {
if !infoProviderUsable(provider) &&
infoProviderUsable(request.Provider) {
provider = request.Provider
}
return infoProjectRef(name, provider, version.Any)
}
}
if infoProviderUsable(request.Provider) {
return infoProjectRef(request.Name.String(), request.Provider, version.Any)
}
return infoProjectRef(
installed.ID.Name.String(),
catalog.ProviderUnspecified,
version.Any,
)
}
func infoLockProjectPackages(
lock *document.Lock,
request catalog.Ref,
) []*document.Package {
if lock == nil {
return nil
}
matches := make([]*document.Package, 0, len(lock.Packages))
for index := range lock.Packages {
lockedPackage := &lock.Packages[index]
if infoLockPackageMatches(lockedPackage, request) {
matches = append(matches, lockedPackage)
}
}
return matches
}
func infoLockPackageMatches(
lockedPackage *document.Package,
request catalog.Ref,
) bool {
for _, binding := range lockedPackage.Requirements {
provider, project, err := document.ParseReference(binding.Reference)
if err != nil {
continue
}
if infoProjectIdentityMatches(request, provider, project) {
return true
}
}
provider := lockedPackage.Provider
if !infoProviderUsable(provider) {
provider = request.Provider
}
if infoProviderUsable(request.Provider) &&
infoProviderUsable(provider) &&
request.Provider != provider {
return false
}
return infoNormalizedName(lockedPackage.ProjectID) ==
infoNormalizedName(request.Name.String())
}
func infoProjectIdentityMatches(
request catalog.Ref,
provider catalog.Provider,
project string,
) bool {
if infoProviderUsable(request.Provider) &&
infoProviderUsable(provider) &&
request.Provider != provider {
return false
}
return infoNormalizedName(project) ==
infoNormalizedName(request.Name.String())
}
func infoInstalledNameMatches(
request catalog.Ref,
identity catalog.VersionedRef,
) bool {
if infoNormalizedName(identity.Name.String()) !=
infoNormalizedName(request.Name.String()) {
return false
}
if !infoProviderUsable(request.Provider) {
return true
}
if !infoProviderUsable(identity.Provider) {
return true
}
return request.Provider == identity.Provider
}
func infoLockPackageProvider(
lockedPackage *document.Package,
) catalog.Provider {
if infoProviderUsable(lockedPackage.Provider) {
return lockedPackage.Provider
}
provider := catalog.ProviderUnspecified
for _, binding := range lockedPackage.Requirements {
candidate, _, err := document.ParseReference(binding.Reference)
if err != nil || !infoProviderUsable(candidate) {
continue
}
if provider != catalog.ProviderUnspecified && provider != candidate {
return catalog.ProviderUnspecified
}
provider = candidate
}
return provider
}
// infoLockPackageIdentity reports the project identity this lock package
// satisfies for the request. A binding that names the request wins over the
// package's opaque provider project id.
func infoLockPackageIdentity(
lockedPackage *document.Package,
request catalog.Ref,
) (catalog.Provider, string) {
for _, binding := range lockedPackage.Requirements {
provider, project, err := document.ParseReference(binding.Reference)
if err != nil {
continue
}
if infoProjectIdentityMatches(request, provider, project) {
return provider, project
}
}
return infoLockPackageProvider(lockedPackage), lockedPackage.ProjectID
}
// infoResolveProjectVersion turns an explicit version request into a concrete
// version only through the provider's context-aware catalogue. Anything less
// stays unpinned and produces a warning.
func infoResolveProjectVersion(
ctx context.Context,
router *routing.Router,
request catalog.VersionedRef,
provider catalog.Provider,
observed *workspace.Workspace,
lock *document.Lock,
) (version.Version, []string, error) {
if request.Version == "" || request.Version == version.Any {
return version.Any, nil, nil
}
registry, ok := infoCandidateRegistry(provider)
if !ok {
return version.Any, []string{fmt.Sprintf(
"%s has no version catalogue; version %s was not resolved, so the project ref stays unpinned",
infoProviderLabel(provider),
request.Version.String(),
)}, nil
}
minecraft := ""
if selection := infoRuntimeSelection(observed); selection != nil {
candidate := selection.MinecraftVersion()
if infoVersionText(candidate) != "" {
minecraft = candidate.String()
}
}
if minecraft == "" && lock != nil &&
infoVersionText(lock.Server.Minecraft) != "" {
minecraft = lock.Server.Minecraft.String()
}
loader := request.Ecosystem
if loader == catalog.EcosystemUnspecified {
loader = infoWorkspaceLoader(observed, lock)
}
if provider == catalog.ProviderMCDR {
loader = catalog.EcosystemMCDR
}
if provider != catalog.ProviderMCDR && minecraft == "" {
return version.Any, []string{fmt.Sprintf(
"no workspace Minecraft version is available to resolve version %s, so the project ref stays unpinned",
request.Version.String(),
)}, nil
}
projectName := request.Name.String()
if provider == catalog.ProviderMCDR {
projectName = request.Name.PythonName()
}
candidates, lookupErr := router.Candidates(
ctx,
registry,
projectName,
minecraft,
loader,
)
if lookupErr != nil {
if failure := infoOperationFailure(ctx, lookupErr); failure != nil {
return version.Any, nil, failure
}
return version.Any, []string{fmt.Sprintf(
"could not resolve version %s on %s: %v; the project ref stays unpinned",
request.Version.String(),
infoProviderLabel(provider),
lookupErr,
)}, nil
}
selected := infoSelectCandidate(candidates, request.Version)
if infoVersionText(selected) == "" {
return version.Any, []string{fmt.Sprintf(
"version %s was not found among the builds available for this workspace, so the project ref stays unpinned",
request.Version.String(),
)}, nil
}
return selected, nil, nil
}
func infoWorkspaceLoader(observed *workspace.Workspace, lock *document.Lock) catalog.Ecosystem {
if observed != nil {
if loader := infoLoaderFromOffers(observed.ServedEcosystems()); loader != catalog.EcosystemUnspecified {
return loader
}
}
if lock == nil {
return catalog.EcosystemUnspecified
}
components := make([]catalog.VersionedRef, 0)
for _, input := range lock.Server.Inputs {
for _, module := range input.Modules {
components = append(components, catalog.VersionedRef{
Name: catalog.Name(module.ID),
Version: module.Version,
Ecosystem: module.Ecosystem,
})
}
}
offers := workspace.ProductServedEcosystems(
catalog.VersionedRef{
Name: catalog.Name(lock.Server.Product.String()),
Version: lock.Server.CoreVersion,
},
components,
)
if loader := infoLoaderFromOffers(offers); loader != catalog.EcosystemUnspecified {
return loader
}
for _, module := range components {
if module.Ecosystem.IsModding() {
return module.Ecosystem
}
}
return catalog.EcosystemUnspecified
}
func infoLoaderFromOffers(offers []workspace.ServedEcosystem) catalog.Ecosystem {
for _, offer := range offers {
if offer.Compatibility == workspace.CompatFull &&
offer.Ecosystem != catalog.EcosystemMinecraft &&
offer.Ecosystem != catalog.EcosystemUnspecified {
return offer.Ecosystem
}
}
for _, offer := range offers {
if offer.Ecosystem != catalog.EcosystemMinecraft &&
offer.Ecosystem != catalog.EcosystemUnspecified {
return offer.Ecosystem
}
}
return catalog.EcosystemUnspecified
}
func infoCandidateRegistry(
provider catalog.Provider,
) (catalog.Registry, bool) {
switch provider {
case catalog.ProviderModrinth:
return catalog.RegistryModrinth, true
case catalog.ProviderCurseForge:
return catalog.RegistryCurseForge, true
case catalog.ProviderHangar:
return catalog.RegistryHangar, true
case catalog.ProviderSpiget:
return catalog.RegistrySpiget, true
case catalog.ProviderMCDR:
return catalog.RegistryMCDR, true
default:
return catalog.RegistryUnspecified, false
}
}
func infoRuntimeSelection(
observed *workspace.Workspace,
) *discovery.Selection {
if observed == nil {
return nil
}
selection := observed.Runtime()
if selection == nil || !selection.IsValid() {
return nil
}
return selection
}
func infoSelectCandidate(
candidates []upstream.Candidate,
requested version.Version,
) version.Version {
switch requested {
case version.Stable:
return infoNewestCandidate(
candidates,
func(channel upstream.ReleaseChannel) bool {
return channel == upstream.ReleaseChannelRelease
},
)
case version.Beta:
return infoNewestCandidate(
candidates,
func(upstream.ReleaseChannel) bool { return true },
)
case version.Version("latest"):
if selected := infoNewestCandidate(
candidates,
func(channel upstream.ReleaseChannel) bool {
return channel == upstream.ReleaseChannelRelease
},
); infoVersionText(selected) != "" {
return selected
}
return infoNewestCandidate(
candidates,
func(upstream.ReleaseChannel) bool { return true },
)
default:
requestedText := strings.TrimSpace(requested.String())
for _, candidate := range candidates {
if infoVersionText(candidate.Version) == "" {
continue
}
if strings.TrimSpace(candidate.Version.String()) == requestedText {
return candidate.Version
}
}
return ""
}
}
func infoNewestCandidate(
candidates []upstream.Candidate,
accept func(upstream.ReleaseChannel) bool,
) version.Version {
var newest *upstream.Candidate
for index := range candidates {
candidate := &candidates[index]
if infoVersionText(candidate.Version) == "" ||
!accept(candidate.Channel) {
continue
}
if newest == nil || candidate.PublishedAt.After(newest.PublishedAt) {
newest = candidate
}
}
if newest == nil {
return version.Any
}
return newest.Version
}
func infoProviderLabel(provider catalog.Provider) string {
if !infoProviderUsable(provider) {
return "the provider"
}
return provider.Title()
}
package search
import (
"errors"
"fmt"
"io"
"strconv"
"strings"
"time"
"charm.land/lipgloss/v2"
"charm.land/lipgloss/v2/table"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/internal/cli/help"
"github.com/mclucy/lucy/terminal/report"
"github.com/mclucy/lucy/terminal/style"
"github.com/mclucy/lucy/upstream"
"github.com/spf13/cobra"
)
const (
flagSortName = "sort"
flagIncludeClientName = "include-client"
flagEcosystemName = cli.FlagEcosystem
flagRegistryName = "registry"
)
func NewCommand(
contracts *cli.JSONContracts,
inv *cli.Invocation,
deps *cli.Dependencies,
) *cobra.Command {
searchCmd := &cobra.Command{
Use: "search",
Short: help.SearchShort,
Args: cobra.ExactArgs(1),
ValidArgsFunction: func(
cmd *cobra.Command,
args []string,
toComplete string,
) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
},
PreRunE: func(cmd *cobra.Command, args []string) error {
sort, _ := cmd.Flags().GetString(flagSortName)
if !Sort(sort).Valid() {
return errors.New("--sort must be one of \"relevance\", \"downloads\", \"newest\"")
}
ecosystem, _ := cmd.Flags().GetString(flagEcosystemName)
if _, err := searchEcosystem(ecosystem); err != nil {
return err
}
registry, _ := cmd.Flags().GetString(flagRegistryName)
_, err := searchRegistry(registry)
return err
},
RunE: func(cmd *cobra.Command, args []string) error {
return actionSearch(cmd, inv, deps, args)
},
}
searchJSON.Bind(contracts, searchCmd)
searchCmd.Flags().String(
flagSortName,
"relevance",
"Sort results by SORT (relevance, downloads, newest)",
)
searchCmd.Flags().BoolP(
flagIncludeClientName,
"c",
false,
"Also show client-only mods in results",
)
searchCmd.Flags().String(
flagEcosystemName,
"",
"Filter results by ecosystem (fabric, quilt, forge, neoforge, bukkit, paper)",
)
searchCmd.Flags().StringP(
flagRegistryName,
"s",
"",
"Restrict results to REGISTRY",
)
cli.AddLongFlag(searchCmd)
_ = searchCmd.RegisterFlagCompletionFunc(
flagRegistryName,
func(cmd *cobra.Command, args []string, toComplete string) (
[]string,
cobra.ShellCompDirective,
) {
candidates := cli.FilterByPrefix(
cli.StaticSearchRegistryCandidates(),
toComplete,
)
return cli.ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
},
)
_ = searchCmd.RegisterFlagCompletionFunc(
flagSortName,
func(cmd *cobra.Command, args []string, toComplete string) (
[]string,
cobra.ShellCompDirective,
) {
candidates := cli.FilterByPrefix(StaticSortCandidates(), toComplete)
return cli.ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
},
)
_ = searchCmd.RegisterFlagCompletionFunc(
flagEcosystemName,
func(cmd *cobra.Command, args []string, toComplete string) (
[]string,
cobra.ShellCompDirective,
) {
candidates := cli.FilterByPrefix(
cli.StaticSearchEcosystemCandidates(),
toComplete,
)
return cli.ToCobraCompletions(candidates), cobra.ShellCompDirectiveNoFileComp
},
)
return searchCmd
}
func actionSearch(
cmd *cobra.Command,
inv *cli.Invocation,
deps *cli.Dependencies,
args []string,
) error {
ctx, stop := cli.CommandContext(cmd)
defer stop()
sortOrder, _ := cmd.Flags().GetString(flagSortName)
client, _ := cmd.Flags().GetBool(flagIncludeClientName)
long, _ := cmd.Flags().GetBool(cli.FlagLong)
ecosystemArg, _ := cmd.Flags().GetString(flagEcosystemName)
resolvedEcosystem, err := searchEcosystem(ecosystemArg)
if err != nil {
return err
}
registryArg, _ := cmd.Flags().GetString(flagRegistryName)
specifiedRegistry, err := searchRegistry(registryArg)
if err != nil {
return err
}
query := upstream.Query{
Keyword: args[0],
IncludeClient: client,
FilterEcosystem: resolvedEcosystem,
}
providers, err := deps.Router.ResolveSearchProviders(
query.FilterEcosystem,
specifiedRegistry,
)
if err != nil {
errArg := query.FilterEcosystem.String()
if specifiedRegistry != catalog.RegistryUnspecified {
errArg = specifiedRegistry.String()
}
return fmt.Errorf("%w: %s", err, errArg)
}
results, errs := deps.Router.SearchMany(ctx, providers, query)
if err := ctx.Err(); err != nil {
return err
}
applySearchSort(results, Sort(sortOrder))
if err := searchResultError(results, errs); err != nil {
return err
}
output := cli.NewQueryOutput(cmd, inv)
var noResultSources []string
for _, err := range errs {
if isNoResultsError(err.Err) {
noResultSources = append(noResultSources, err.Provider.Title())
continue
}
providerWarn := fmt.Errorf(
"search on %s failed: %w",
err.Provider.Title(),
err.Err,
)
if output.JSON() {
inv.Logger.Warn(providerWarn)
continue
}
if len(results) > 0 {
inv.Logger.Warn(providerWarn)
}
report.New(cmd.ErrOrStderr(), inv.Theme).Warn(providerWarn)
}
if err := ctx.Err(); err != nil {
return err
}
if output.JSON() {
return searchJSON.Write(output, newSearchResultDocuments(results))
}
if err := ctx.Err(); err != nil {
return err
}
return output.Document(func(out io.Writer, screen style.Terminal) error {
var sb strings.Builder
for i, res := range results {
if i > 0 {
sb.WriteString("\n")
}
if long {
sb.WriteString(renderSearchLong(res, inv.Theme, screen))
} else {
sb.WriteString(renderSearchCompact(res, inv.Theme, screen))
}
}
if len(noResultSources) > 0 {
sb.WriteString(
inv.Theme.Muted(
"No results from "+strings.Join(noResultSources, ", "),
) + "\n",
)
}
_, err := io.WriteString(out, sb.String())
return err
})
}
func searchEcosystem(value string) (catalog.Ecosystem, error) {
if value == "" {
return catalog.EcosystemUnspecified, nil
}
ecosystem := catalog.Ecosystem(strings.ToLower(strings.TrimSpace(value)))
if !ecosystem.IsSearchable() {
return catalog.EcosystemUnspecified, fmt.Errorf("invalid --ecosystem %q", value)
}
return ecosystem, nil
}
func searchRegistry(value string) (catalog.Registry, error) {
if value == "" {
return catalog.RegistryUnspecified, nil
}
registry, ok := catalog.ParseRegistry(value)
if !ok {
return catalog.RegistryUnknown, fmt.Errorf("invalid --registry %q", value)
}
return registry, nil
}
func searchResultError(
results []upstream.SearchResponse,
providerErrors []upstream.ProviderError,
) error {
if len(results) > 0 || len(providerErrors) == 0 {
return nil
}
joined := make([]error, 0, len(providerErrors))
for _, providerErr := range providerErrors {
if isNoResultsError(providerErr.Err) {
continue
}
joined = append(joined, providerErr)
}
if len(joined) == 0 {
return nil
}
return errors.Join(joined...)
}
func isNoResultsError(err error) bool {
return err != nil && strings.HasPrefix(err.Error(), "no projects found")
}
// searchResultReference is the source-qualified identity package commands
// accept. Search shows it so a row is installable without another lookup.
func searchResultReference(item upstream.SearchResult) string {
return catalog.Ref{
Name: catalog.Name(item.ProjectName),
Provider: item.Provider,
}.String()
}
func renderSearchCompact(
res upstream.SearchResponse,
theme style.Theme,
screen style.Terminal,
) string {
var sb strings.Builder
sb.WriteString(searchSectionHeader(res, theme))
if len(res.Items) == 0 {
sb.WriteString(theme.Muted(" (no results)") + "\n")
return sb.String()
}
width := max(20, screen.Width)
nameWidth := 0
for _, item := range res.Items {
nameWidth = max(nameWidth, len(" "+searchResultReference(item)))
}
nameWidth = min(nameWidth, max(10, width/2))
descWidth := max(4, width-nameWidth-1)
t := table.New().
Border(lipgloss.HiddenBorder()).
BorderTop(false).
BorderBottom(false).
BorderLeft(false).
BorderRight(false).
BorderColumn(false).
BorderRow(false).
BorderHeader(false).
Wrap(false).
StyleFunc(
func(row, col int) lipgloss.Style {
if col == 0 {
return lipgloss.NewStyle().Bold(true).PaddingRight(1)
}
return lipgloss.NewStyle().Faint(true)
},
)
for _, item := range res.Items {
// The row label is the installable project name. A title only fills an
// absent description, because search exists to discover that name.
summary := item.Description
if summary == "" && item.Title != "" && item.Title != item.ProjectName {
summary = item.Title
}
t.Row(
truncateText(" "+searchResultReference(item), nameWidth),
truncateText(summary, descWidth),
)
}
sb.WriteString(t.String())
sb.WriteString("\n")
return sb.String()
}
func renderSearchLong(
res upstream.SearchResponse,
theme style.Theme,
terminal style.Terminal,
) string {
var sb strings.Builder
sb.WriteString(searchSectionHeader(res, theme))
if len(res.Items) == 0 {
sb.WriteString(theme.Muted(" (no results)") + "\n")
return sb.String()
}
for i, item := range res.Items {
if i > 0 {
sb.WriteString("\n")
}
displayName := item.ProjectName
if item.Title != "" {
displayName = item.Title
}
sb.WriteString(" " + theme.Accent(displayName) + "\n")
if item.Description != "" {
desc := strings.ReplaceAll(item.Description, "\n", " ")
desc = strings.ReplaceAll(desc, "\r", "")
wrapWidth := min(80, terminal.Width) - 2
wrapped := lipgloss.Wrap(desc, wrapWidth, "")
for line := range strings.SplitSeq(wrapped, "\n") {
sb.WriteString(" " + line + "\n")
}
}
stats := searchStatsLine(item)
if stats != "" {
sb.WriteString(" " + theme.Muted(stats) + "\n")
}
installID := searchResultReference(item)
sb.WriteString(" " + theme.Muted(installID) + "\n")
}
return sb.String()
}
func searchSectionHeader(
res upstream.SearchResponse,
theme style.Theme,
) string {
header := theme.Muted(
"Results from " + res.Provider.Title() +
" (" + strconv.Itoa(len(res.Items)) + ")",
)
var sb strings.Builder
sb.WriteString(header + "\n")
if res.Provider == catalog.ProviderModrinth && len(res.Items) == 100 {
sb.WriteString(theme.Muted("* only showing the top 100") + "\n")
}
return sb.String()
}
func searchStatsLine(item upstream.SearchResult) string {
var sb strings.Builder
if item.Downloads > 0 {
sb.WriteString(formatDownloads(item.Downloads) + " downloads")
}
if !item.LastUpdated.IsZero() {
if sb.Len() > 0 {
sb.WriteString(", last updated ")
} else {
sb.WriteString("Last updated ")
}
sb.WriteString(timeAgo(item.LastUpdated))
}
return sb.String()
}
func formatDownloads(n int64) string {
switch {
case n >= 1_000_000_000:
return fmt.Sprintf("%.1fB", float64(n)/1e9)
case n >= 1_000_000:
return fmt.Sprintf("%.1fM", float64(n)/1e6)
case n >= 1_000:
return fmt.Sprintf("%.1fK", float64(n)/1e3)
default:
return strconv.FormatInt(n, 10)
}
}
func timeAgo(t time.Time) string {
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
m := int(d.Minutes())
if m == 1 {
return "1 minute ago"
}
return strconv.Itoa(m) + " minutes ago"
case d < 24*time.Hour:
h := int(d.Hours())
if h == 1 {
return "1 hour ago"
}
return strconv.Itoa(h) + " hours ago"
case d < 30*24*time.Hour:
days := int(d.Hours() / 24)
if days == 1 {
return "1 day ago"
}
return strconv.Itoa(days) + " days ago"
case d < 365*24*time.Hour:
months := int(d.Hours() / 24 / 30)
if months <= 1 {
return "1 month ago"
}
return strconv.Itoa(months) + " months ago"
default:
years := int(d.Hours() / 24 / 365)
if years == 1 {
return "1 year ago"
}
return strconv.Itoa(years) + " years ago"
}
}
func truncateText(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\r", "")
if len(s) <= maxLen {
return s
}
if maxLen <= 3 {
return s[:maxLen]
}
return s[:maxLen-3] + "..."
}
package search
import (
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/upstream"
)
// searchResultDocument is the JSON wire shape for one provider's results.
// Warnings become messages because the error values themselves have no
// consumer-meaningful JSON representation.
type searchResultDocument struct {
Provider catalog.Provider `json:"provider"`
Items []upstream.SearchResult `json:"items"`
Warnings []string `json:"warnings,omitempty"`
}
var searchJSON cli.JSONResult[[]searchResultDocument]
func newSearchResultDocuments(
results []upstream.SearchResponse,
) []searchResultDocument {
if results == nil {
return nil
}
documents := make([]searchResultDocument, len(results))
for i, result := range results {
documents[i] = searchResultDocument{
Provider: result.Provider,
Items: result.Items,
Warnings: searchWarningMessages(result.Warnings),
}
}
return documents
}
func searchWarningMessages(warnings []error) []string {
if len(warnings) == 0 {
return nil
}
messages := make([]string, 0, len(warnings))
for _, warning := range warnings {
if warning == nil {
continue
}
messages = append(messages, warning.Error())
}
if len(messages) == 0 {
return nil
}
return messages
}
package search
import (
"cmp"
"sort"
"github.com/mclucy/lucy/internal/cli"
"github.com/mclucy/lucy/upstream"
)
// SearchSort is the user-facing sort order for `lucy search` results. It is
// applied consumer-side to items already returned by providers, which always
// return their own default (relevance) order.
type Sort string
const (
SortRelevance Sort = "relevance"
SortDownloads Sort = "downloads"
SortNewest Sort = "newest"
)
func (s Sort) Valid() bool {
switch s {
case SortRelevance, SortDownloads, SortNewest:
return true
}
return false
}
// applySearchSort reorders items in each response according to s. Relevance
// preserves the provider's order, and unrecognized sorts leave it in place.
func applySearchSort(results []upstream.SearchResponse, s Sort) {
switch s {
case "", SortRelevance:
return
case SortDownloads:
for i := range results {
items := results[i].Items
sort.SliceStable(items, func(a, b int) bool {
return cmp.Compare(items[b].Downloads, items[a].Downloads) < 0
})
}
case SortNewest:
for i := range results {
items := results[i].Items
sort.SliceStable(items, func(a, b int) bool {
return items[a].LastUpdated.After(items[b].LastUpdated)
})
}
}
}
func StaticSortCandidates() []cli.CompletionCandidate {
return []cli.CompletionCandidate{
{Value: string(SortRelevance), Description: "Sort by relevance"},
{
Value: string(SortDownloads),
Description: "Sort by download count",
},
{Value: string(SortNewest), Description: "Sort by newest"},
}
}
// Package telemetry adapts the local telemetry client to the `lucy telemetry`
// and `lucy agent-report` commands.
package telemetry
import (
"errors"
"fmt"
"github.com/mclucy/lucy/internal/cli"
telem "github.com/mclucy/lucy/internal/telemetry"
"github.com/spf13/cobra"
)
var (
statsJSON cli.JSONResult[*telem.Stats]
actionJSON cli.JSONResult[*action]
)
// State is the telemetry handle the root wiring publishes to this command
// tree. The wiring fills it before commands execute, so handlers read the
// client at action time rather than at construction.
type State struct {
// Client is the run's telemetry client. It stays nil until the root
// wiring initializes telemetry, and when construction failed.
Client *telem.Client
// Err reports why Client is unavailable.
Err error
// Local reports a local development build, which disables collection even
// when the saved preference is on.
Local bool
}
// client returns the run's telemetry client or the reason it is unavailable.
func (s *State) client() (*telem.Client, error) {
if s.Err != nil {
return nil, fmt.Errorf("telemetry state: %w", s.Err)
}
if s.Client == nil {
return nil, errors.New("telemetry state is unavailable")
}
return s.Client, nil
}
// NewCommand builds the telemetry command that controls collection and shows
// local statistics.
func NewCommand(
contracts *cli.JSONContracts,
inv *cli.Invocation,
state *State,
) *cobra.Command {
status := &cobra.Command{
Use: "telemetry", Short: "Control telemetry and inspect local statistics", Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return actionStats(cmd, inv, state) },
}
stats := &cobra.Command{
Use: "stats", Short: "Show local telemetry upload statistics", Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { return actionStats(cmd, inv, state) },
}
statsJSON.Bind(contracts, status)
statsJSON.Bind(contracts, stats)
status.AddCommand(stats)
for _, setting := range []struct {
name string
enabled bool
}{{"on", true}, {"off", false}} {
command := &cobra.Command{
Use: setting.name, Short: "Turn telemetry " + setting.name, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
client, err := state.client()
if err != nil {
return err
}
if err := client.SetEnabled(cmd.Context(), setting.enabled); err != nil {
return err
}
message := "Telemetry is enabled."
actionState := setting.name
if !setting.enabled {
message = "Telemetry is off; pending local records were deleted. Existing remote data was not changed."
} else if enabled, err := client.Enabled(cmd.Context()); err != nil {
return err
} else if !enabled {
actionState = "off"
if state.Local {
message = "The saved preference is on, but telemetry is disabled in local development builds."
} else {
message = "The saved preference is on, but telemetry remains off due to the environment."
}
}
return writeAction(cmd, inv, &action{
Action: setting.name,
State: actionState,
Message: message,
})
},
}
actionJSON.Bind(contracts, command)
status.AddCommand(command)
}
reset := &cobra.Command{
Use: "reset-id", Short: "Reset the client ID and local statistics", Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
client, err := state.client()
if err != nil {
return err
}
if _, err := client.ResetIdentity(cmd.Context()); err != nil {
return err
}
return writeAction(cmd, inv, &action{
Action: "reset-id",
State: "reset",
Message: "The client ID and local statistics were reset. Existing remote data was not changed.",
})
},
}
actionJSON.Bind(contracts, reset)
status.AddCommand(reset)
cli.MarkTelemetryExempt(status)
return status
}
// IsCommand reports whether command belongs to the telemetry command tree.
func IsCommand(command *cobra.Command) bool {
for current := command; current != nil; current = current.Parent() {
if current.Name() == "telemetry" || current.Name() == "agent-report" {
return true
}
}
return false
}
// action is the JSON result of a telemetry control command.
type action struct {
Action string `json:"action"`
State string `json:"state"`
RecordID string `json:"record_id,omitempty"`
Message string `json:"message,omitempty"`
}
func writeAction(cmd *cobra.Command, inv *cli.Invocation, value *action) error {
output := cli.NewQueryOutput(cmd, inv)
if output.JSON() {
return actionJSON.Write(output, value)
}
_, err := fmt.Fprintln(output.Human(), value.Message)
return err
}
package telemetry
import (
"context"
"time"
"github.com/mclucy/lucy/internal/cli"
telem "github.com/mclucy/lucy/internal/telemetry"
"github.com/spf13/cobra"
)
// NewAgentReportCommand builds the hidden command agents use to submit one
// privacy-filtered report.
func NewAgentReportCommand(
contracts *cli.JSONContracts,
inv *cli.Invocation,
state *State,
) *cobra.Command {
agentReport := &cobra.Command{
Use: "agent-report [CONTENT]", Short: "Submit an agent report", Hidden: true, Args: cobra.ExactArgs(1),
Long: "Submit one privacy-filtered report about a Lucy failure or friction in this session.\n" +
"The argument is the report body. Write one to three sentences: the command, the error code or\n" +
"observed behavior, and what you expected instead. Add --agent and --model when you know them.\n" +
"Leave out secrets, absolute paths, logs, transcripts, and user data; Lucy also redacts common\n" +
"patterns before upload. Skip failures caused by your own wrong directory, wrong flag, or missing\n" +
"prerequisite; report unexpected behavior even when a workaround works. Report each distinct\n" +
"problem once. The result is queued, accepted, or rejected, and a rejected report needs no repair.",
RunE: func(cmd *cobra.Command, args []string) error {
return actionAgentReport(cmd, inv, state, args[0])
},
}
agentReport.Flags().String("agent", "", "Agent name")
agentReport.Flags().String("model", "", "Model name")
actionJSON.Bind(contracts, agentReport)
cli.MarkTelemetryExempt(agentReport)
return agentReport
}
func actionAgentReport(
cmd *cobra.Command,
inv *cli.Invocation,
state *State,
body string,
) error {
client, err := state.client()
if err != nil {
return err
}
agentName, _ := cmd.Flags().GetString("agent")
model, _ := cmd.Flags().GetString("model")
result, err := client.SubmitReport(cmd.Context(), telem.Report{
Kind: telem.ReportKind("agent_feedback"),
Agent: agentName,
Model: model,
Body: body,
})
if err != nil {
return err
}
if !result.Queued {
message := "Report was not queued: " + string(result.Reason) + "."
if result.Reason == telem.SkipReason("disabled") || result.Reason == telem.SkipReason("environment_disabled") {
message = "Telemetry is off; the report was not submitted. This is not an error to repair. Never enable telemetry without explicit user instruction."
}
return writeAction(cmd, inv, &action{
Action: "agent-report",
State: "rejected",
Message: message,
})
}
flushCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
flush, flushErr := client.Flush(flushCtx)
actionState := "queued"
message := "Report queued locally; it has not been accepted remotely."
if flushErr == nil && flush.WasAccepted(result.RecordID) {
actionState = "accepted"
message = "Feedback received! Thank you!"
} else if flushErr == nil && flush.WasRejected(result.RecordID) {
actionState = "rejected"
message = "The service rejected the report; it is no longer queued."
}
if result.Truncated {
message += " The report was truncated to the allowed size."
}
return writeAction(cmd, inv, &action{
Action: "agent-report",
State: actionState,
RecordID: result.RecordID,
Message: message,
})
}
package telemetry
import (
"fmt"
"time"
"github.com/mclucy/lucy/internal/cli"
"github.com/spf13/cobra"
)
func actionStats(cmd *cobra.Command, inv *cli.Invocation, state *State) error {
client, err := state.client()
if err != nil {
return err
}
stats, err := client.Stats(cmd.Context())
if err != nil {
return err
}
output := cli.NewQueryOutput(cmd, inv)
if output.JSON() {
return statsJSON.Write(output, &stats)
}
telemetryState := "on"
if !stats.Enabled {
telemetryState = "off"
}
if stats.Reason != "" {
telemetryState += " (" + string(stats.Reason) + ")"
}
destination := stats.Endpoint
if destination == "" {
destination = "not configured"
}
_, err = fmt.Fprintf(
output.Human(),
"Telemetry: %s\nClient ID: %s\nStatistics since: %s\n"+
"Destination: %s\nAccepted records: %d (events: %d, reports: %d)\n"+
"Accepted event payload: %d bytes\nAccepted report content: %d bytes\n"+
"Upload request bodies: %d bytes in %d attempts (%d uncertain)\n"+
"Intake-limited upload attempts: %d\n"+
"Pending records: %d (events: %d, reports: %d; %d bytes)\n"+
"Dropped records: %d (%d bytes)\nRejected records: %d (%d bytes)"+
telemetryState, stats.InstallationID, stats.PeriodStart.Format(time.RFC3339),
destination, stats.Accepted.Records, stats.Accepted.Events, stats.Accepted.Reports,
stats.Accepted.EventPayloadBytes, stats.Accepted.ReportBodyBytes,
stats.Transport.RequestBodyBytes, stats.Transport.Requests, stats.Transport.Uncertain,
stats.Transport.Throttles,
stats.Queue.Records, stats.Queue.Events, stats.Queue.Reports, stats.Queue.PayloadBytes,
stats.Dropped.Records, stats.Dropped.Bytes, stats.Rejected.Records,
stats.Rejected.PayloadBytes,
)
return err
}
// Package depgraph models a resolved package graph and traverses it. It
// returns graph facts only; commands own presentation.
package depgraph
import (
"cmp"
"path/filepath"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/workspace"
)
// Node is one node of a resolved package graph. A node is either an artifact
// coordinate ("provider:project", taken from the lock's explicit provider
// fields) or a descriptor module (a module ID declared inside an artifact).
// Identity is always an explicit field; nothing is recovered by parsing a
// display string.
type Node struct {
// ID is the native module ID, or "provider:project" for an artifact.
ID string
Version string
// Provider and ProjectID carry the upstream coordinates of an artifact
// node. They are empty for a native module node, which belongs to the
// artifact recorded in Artifact.
Provider catalog.Provider
ProjectID string
// Requirements lists the manifest requirement references bound to this
// artifact. One artifact can satisfy several declared references.
Requirements []string
// Artifact is the coordinate node that ships this module. It is empty
// for artifact nodes themselves.
Artifact string
Filename string
// Environment scopes the node ("server" or "mcdr") and Ecosystem scopes
// it within that environment. Dependency edges only resolve inside one
// scope.
Environment server.Environment
Ecosystem catalog.Ecosystem
// Module reports whether the node is a native module rather than an
// artifact coordinate.
Module bool
// Root reports a node that an enabled manifest requirement selects.
Root bool
Children []*Node
Parents []*Node
}
// Graph is one resolved package universe. Nodes are unique by scoped
// identity, and Roots are the artifacts an enabled requirement selects.
type Graph struct {
// Nodes are keyed by the scoped node key, so identically named modules
// in different environments or ecosystems stay distinct.
Nodes map[string]*Node
// Roots are the artifacts an enabled manifest requirement selects.
Roots []*Node
}
// nodeKey scopes an identity so edges never cross environments or
// ecosystems.
func nodeKey(
environment server.Environment,
ecosystem catalog.Ecosystem,
id string,
) string {
return string(environment) + "|" + string(ecosystem) + "|" + id
}
// Key returns the scoped identity used to address the node within a graph.
func (n *Node) Key() string {
return nodeKey(n.Environment, n.Ecosystem, n.ID)
}
// artifactCoordinate renders an artifact's explicit provider coordinates.
func artifactCoordinate(provider catalog.Provider, projectID string) string {
return provider.String() + ":" + projectID
}
// BuildFromLock builds the graph from a lock's resolved packages.
//
// Roots are the artifacts selected by an enabled manifest requirement.
// Module dependency edges come from each artifact's native module
// descriptors. The server core and bootstrap inputs are lock inputs, not
// packages, so they never become graph nodes.
func BuildFromLock(lock *document.Lock) (*Graph, error) {
graph := &Graph{
Nodes: make(map[string]*Node),
}
dependencies := make(map[string][]catalog.DescriptorDependency)
for _, pkg := range lock.Packages {
coordinate := artifactCoordinate(pkg.Provider, pkg.ProjectID)
key := nodeKey(pkg.Environment, pkg.Ecosystem, coordinate)
node, ok := graph.Nodes[key]
if !ok {
node = &Node{
ID: coordinate,
Version: pkg.Version.String(),
Provider: pkg.Provider,
ProjectID: pkg.ProjectID,
Filename: pkg.Filename,
Environment: pkg.Environment,
Ecosystem: pkg.Ecosystem,
}
graph.Nodes[key] = node
}
for _, module := range pkg.Modules {
moduleKey := nodeKey(pkg.Environment, pkg.Ecosystem, module.ID)
if _, exists := graph.Nodes[moduleKey]; !exists {
graph.Nodes[moduleKey] = &Node{
ID: module.ID,
Version: module.Version.String(),
Artifact: coordinate,
Environment: pkg.Environment,
Ecosystem: pkg.Ecosystem,
Module: true,
Filename: pkg.Filename,
}
}
dependencies[moduleKey] = module.Dependencies
}
for _, binding := range pkg.Requirements {
if binding.Reference != "" &&
!slices.Contains(node.Requirements, binding.Reference) {
node.Requirements = append(node.Requirements, binding.Reference)
}
}
for _, binding := range pkg.Requirements {
if !binding.Enabled {
continue
}
node.Root = true
graph.Roots = append(graph.Roots, node)
break
}
}
// A root artifact hangs its own top-level modules so the tree has
// something to show beneath the requirement.
for _, root := range graph.Roots {
for _, node := range graph.Nodes {
if node.Module && node.Artifact == root.ID &&
node.Environment == root.Environment &&
node.Ecosystem == root.Ecosystem {
root.Children = append(root.Children, node)
node.Parents = append(node.Parents, root)
}
}
}
// Dependency edges stay inside one environment/ecosystem scope.
for _, node := range graph.Nodes {
if !node.Module {
continue
}
for _, dep := range dependencies[node.Key()] {
child := resolveDependencyNode(
graph,
node.Environment,
node.Ecosystem,
dep,
)
if child == nil || child == node {
continue
}
if !slices.Contains(child.Parents, node) {
node.Children = append(node.Children, child)
child.Parents = append(child.Parents, node)
}
}
}
sortNodes(graph.Roots)
return graph, nil
}
// resolveDependencyNode maps a declared dependency onto a graph node. A
// native dependency names a module ID; when it instead carries upstream
// project coordinates, it resolves to the artifact that ships them.
func resolveDependencyNode(
graph *Graph,
environment server.Environment,
ecosystem catalog.Ecosystem,
dep catalog.DescriptorDependency,
) *Node {
if dep.ModuleID != "" {
if node, ok := graph.Nodes[nodeKey(environment, ecosystem, dep.ModuleID)]; ok {
return node
}
}
if dep.Provider != catalog.ProviderUnspecified && dep.ProjectID != "" {
coordinate := artifactCoordinate(dep.Provider, dep.ProjectID)
if node, ok := graph.Nodes[nodeKey(environment, ecosystem, coordinate)]; ok {
return node
}
}
if dep.ModuleID == "" && dep.ID != "" {
if node, ok := graph.Nodes[nodeKey(environment, ecosystem, dep.ID)]; ok {
return node
}
}
return nil
}
// BuildFromObservation builds the graph from an observed server's packages.
// A package that no other package lists as a dependency is a root;
// parent-child relationships come from each package's Dependencies field.
func BuildFromObservation(info *workspace.Workspace) (*Graph, error) {
graph := &Graph{
Nodes: make(map[string]*Node),
}
for _, p := range info.Packages {
id := p.ID.StringBase()
node := &Node{
ID: id,
Version: p.ID.Version.String(),
Provider: p.ID.Provider,
ProjectID: p.ID.Name.String(),
Filename: filepath.Base(p.Path),
Environment: server.EnvironmentServer,
Ecosystem: p.ID.Ecosystem,
}
graph.Nodes[node.Key()] = node
}
// A probe observation has no runtime membership marker, so every node
// scopes to the server environment.
isDependency := make(map[string]bool)
for _, p := range info.Packages {
parentID := p.ID.StringBase()
parent, parentOK := graph.Nodes[nodeKey(
server.EnvironmentServer,
p.ID.Ecosystem,
parentID,
)]
if !parentOK {
continue
}
for _, dep := range p.Dependencies {
depID := dep.ID.StringBase()
depEcosystem := dep.ID.Ecosystem
if depEcosystem == catalog.EcosystemUnspecified {
depEcosystem = p.ID.Ecosystem
}
child, childOK := graph.Nodes[nodeKey(
server.EnvironmentServer,
depEcosystem,
depID,
)]
if !childOK || child == parent {
continue
}
isDependency[child.Key()] = true
if slices.Contains(parent.Children, child) {
continue
}
parent.Children = append(parent.Children, child)
child.Parents = append(child.Parents, parent)
}
}
for _, node := range graph.Nodes {
if !isDependency[node.Key()] {
node.Root = true
graph.Roots = append(graph.Roots, node)
}
}
sortNodes(graph.Roots)
return graph, nil
}
// sortNodes orders nodes by identifier, then by scoped identity.
func sortNodes(nodes []*Node) {
slices.SortFunc(nodes, compareNodes)
}
func compareNodes(a, b *Node) int {
if c := cmp.Compare(a.ID, b.ID); c != 0 {
return c
}
return cmp.Compare(a.Key(), b.Key())
}
package depgraph
import (
"context"
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/mclucy/lucy/workspace/identify"
)
// Origin names where a loaded graph came from.
type Origin int
const (
OriginLock Origin = iota
OriginLive
)
func (o Origin) String() string {
switch o {
case OriginLock:
return "lock file"
case OriginLive:
return "live probe"
default:
return "unknown"
}
}
// ServerEnvironment is the resolved server identity a graph belongs to.
// Values come from the manifest or lock when either is readable; a live
// probe fills the gaps when no lock exists.
type ServerEnvironment struct {
Core string
GameVersion string
Ecosystem catalog.Ecosystem
EcosystemVersion string
}
// Findings is the live observation evidence a graph was built from. It
// carries no presentation decisions; the command boundary renders its
// warnings and discovery conditions.
type Findings struct {
// Observation is the probe the graph was built from. It is nil when the
// graph came from the lock or no live probe ran.
Observation *workspace.Workspace
}
// LoadResult is one graph and the facts that produced it.
type LoadResult struct {
Graph *Graph
Origin Origin
Environment ServerEnvironment
Findings Findings
}
// Load builds the dependency graph from the lock file, falling back to a live
// workspace observation when the lock is missing or invalid. forceLive skips
// the lock file entirely.
//
// It also reports the server environment, derived from the manifest or lock
// when available and from the workspace probe otherwise. A live probe is
// returned as findings; the caller renders it.
func Load(
ctx context.Context,
workDir string,
forceLive bool,
lookup identify.HashLookup,
) (LoadResult, error) {
var result LoadResult
if err := ctx.Err(); err != nil {
return result, err
}
if !forceLive {
doc, err := document.LockFile(workDir).Read()
if err == nil {
result.Environment = environmentFromLock(doc)
graph, err := BuildFromLock(doc)
if err != nil {
return result, fmt.Errorf(
"failed to build graph from lock: %w",
err,
)
}
if err := ctx.Err(); err != nil {
return result, err
}
result.Graph = graph
return result, nil
}
}
result.Origin = OriginLive
info := workspace.Observe(workDir, discovery.Request{})
identify.Packages(ctx, info, lookup, nil)
if err := ctx.Err(); err != nil {
return result, err
}
result.Findings = Findings{Observation: info}
graph, err := BuildFromObservation(info)
if err != nil {
return result, fmt.Errorf("failed to build graph from observation: %w", err)
}
if err := ctx.Err(); err != nil {
return result, err
}
result.Graph = graph
result.Environment = environmentFromWorkspace(info, result.Environment)
return result, nil
}
// environmentFromLock reads the server identity from the lock's explicit
// fields. The lock always records exact versions, so nothing is inferred.
func environmentFromLock(lock *document.Lock) ServerEnvironment {
return ServerEnvironment{
Core: lock.Server.Product.String(),
GameVersion: lock.Server.Minecraft.String(),
Ecosystem: EcosystemFromLock(lock),
EcosystemVersion: ecosystemVersionFromLock(lock),
}
}
// EcosystemFromLock reports the ecosystem that scopes the server runtime.
// Server packages come first; the bootstrap inputs name the loader when the
// runtime has no packages of its own. It returns EcosystemUnspecified when
// the evidence disagrees.
func EcosystemFromLock(lock *document.Lock) catalog.Ecosystem {
var found catalog.Ecosystem
for _, pkg := range lock.Packages {
if pkg.Environment != serverpkg.EnvironmentServer ||
pkg.Ecosystem == catalog.EcosystemUnspecified {
continue
}
if found != catalog.EcosystemUnspecified && found != pkg.Ecosystem {
return catalog.EcosystemUnspecified
}
found = pkg.Ecosystem
}
if found != catalog.EcosystemUnspecified {
return found
}
for _, input := range lock.Server.Inputs {
for _, module := range input.Modules {
if module.Ecosystem == catalog.EcosystemUnspecified {
continue
}
if found != catalog.EcosystemUnspecified && found != module.Ecosystem {
return catalog.EcosystemUnspecified
}
found = module.Ecosystem
}
}
return found
}
func ecosystemVersionFromLock(lock *document.Lock) string {
ecosystem := EcosystemFromLock(lock)
if ecosystem == catalog.EcosystemUnspecified {
return ""
}
for _, input := range lock.Server.Inputs {
for _, module := range input.Modules {
if module.Ecosystem == ecosystem && module.Version != "" {
return module.Version.String()
}
}
}
return ""
}
// environmentFromWorkspace fills the environment gaps a lock could not
// supply by observing the live workspace. Values already known win.
func environmentFromWorkspace(ws *workspace.Workspace, env ServerEnvironment) ServerEnvironment {
if ws == nil {
return env
}
if env.Core == "" || env.GameVersion == "" ||
env.Ecosystem == catalog.EcosystemUnspecified {
if doc, err := document.ManifestFile(ws.ServerDir).Read(); err == nil {
if env.Core == "" {
env.Core = doc.Server.Core.Product.String()
}
if env.GameVersion == "" {
env.GameVersion = doc.Server.Minecraft.String()
}
}
}
server := ws.Runtime()
if server == nil {
return env
}
if env.GameVersion == "" {
if version := server.MinecraftVersion().String(); version != "" {
env.GameVersion = version
}
}
if env.Core == "" {
env.Core = server.Product().String()
}
if env.Ecosystem == catalog.EcosystemUnspecified {
env.Ecosystem = server.Ecosystem()
}
if env.EcosystemVersion == "" {
ecosystem := server.Ecosystem()
for _, component := range RuntimeComponents(server) {
if component.Ecosystem != ecosystem {
continue
}
switch component.Version {
case "", versionpkg.None, versionpkg.Unknown, versionpkg.Any,
versionpkg.Stable, versionpkg.Beta:
continue
default:
env.EcosystemVersion = component.Version.String()
}
}
}
return env
}
// RuntimeComponents normalizes the runtime identity into the versioned
// components it declares, including the primary runtime and Minecraft.
func RuntimeComponents(
selection *discovery.Selection,
) []catalog.VersionedRef {
if selection == nil || !selection.IsValid() {
return []catalog.VersionedRef{}
}
identity := selection.Installation.Identity
components := make([]catalog.VersionedRef, 0, len(identity.Components)+2)
components = append(components, identity.Components...)
primary := identity.Primary
switch strings.ToLower(primary.Name.String()) {
case "minecraft":
components = ensureRuntimeComponent(components, catalog.VersionedRef{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: primary.Version,
})
default:
if product, ok := serverpkg.ParseProduct(primary.Name.String()); ok {
if component := product.LoaderComponent(); component != "" {
components = ensureRuntimeComponent(components, catalog.VersionedRef{
Ecosystem: product.Ecosystem(),
Name: component,
Version: primary.Version,
})
}
}
}
if !hasRuntimeComponent(components, catalog.EcosystemMinecraft, "minecraft") {
components = ensureRuntimeComponent(components, catalog.VersionedRef{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: identity.MinecraftVersion(),
})
}
return components
}
func ensureRuntimeComponent(
components []catalog.VersionedRef,
component catalog.VersionedRef,
) []catalog.VersionedRef {
if component.Version == "" || component.Version == versionpkg.Unknown {
return components
}
if hasRuntimeComponent(components, component.Ecosystem, component.Name.String()) {
return components
}
return append(components, component)
}
func hasRuntimeComponent(
components []catalog.VersionedRef,
ecosystem catalog.Ecosystem,
name string,
) bool {
for _, component := range components {
if component.Ecosystem == ecosystem && component.Name == catalog.Name(name) {
return true
}
}
return false
}
package depgraph
import (
"slices"
)
// Leaves returns artifact nodes that declare no dependencies. A lock
// artifact is a leaf when none of the modules it ships has a dependency
// child; a probe artifact is a leaf when it has no dependency children.
// Being selected by a manifest requirement does not disqualify a package:
// leaves describe the dependency graph, not removability.
func (g *Graph) Leaves() []*Node {
var leaves []*Node
for _, node := range g.Nodes {
if node.Module || g.artifactHasDependencies(node) {
continue
}
leaves = append(leaves, node)
}
sortNodes(leaves)
return leaves
}
// artifactHasDependencies reports whether an artifact node has dependency
// children, either through the modules it ships or, for a probe graph,
// directly through the artifact's own dependency edges.
func (g *Graph) artifactHasDependencies(node *Node) bool {
shipped := false
for _, candidate := range g.Nodes {
if !candidate.Module || candidate.Artifact != node.ID ||
candidate.Environment != node.Environment ||
candidate.Ecosystem != node.Ecosystem {
continue
}
shipped = true
if len(candidate.Children) > 0 {
return true
}
}
if shipped {
return false
}
return len(node.Children) > 0
}
// OrderedArtifacts returns every artifact node in dependency-first order.
// Root selection is not enough: in a live observation, a directly declared
// requirement can also be another package's dependency.
//
// The order is computed on the artifact graph. Sorting the mixed graph and
// dropping modules afterwards is not enough: an artifact only becomes ready
// after every module it ships, while a dependent only waits for the module it
// needs, so a package shipping several modules can follow its own dependent.
// Collapsing each module onto its artifact first keeps the edge from that
// dependent to the package that provides the required module.
func (g *Graph) OrderedArtifacts() []*Node {
artifacts := make([]*Node, 0, len(g.Nodes))
for _, node := range g.Nodes {
if !node.Module {
artifacts = append(artifacts, node)
}
}
byID := func() []*Node {
sortNodes(artifacts)
return artifacts
}
// A module is represented by the artifact that ships it.
owner := make(map[string]*Node, len(g.Nodes))
for _, node := range g.Nodes {
if !node.Module {
owner[node.Key()] = node
continue
}
artifact, ok := g.Nodes[nodeKey(
node.Environment,
node.Ecosystem,
node.Artifact,
)]
if ok {
owner[node.Key()] = artifact
}
}
// Lift edges onto owning artifacts, dropping the tree-only
// artifact-to-own-module self edges.
dependencies := make(map[string]map[string]bool, len(artifacts))
dependents := make(map[string][]*Node, len(artifacts))
for _, node := range g.Nodes {
dependent := owner[node.Key()]
if dependent == nil {
continue
}
dependentKey := dependent.Key()
for _, child := range node.Children {
dependency := owner[child.Key()]
if dependency == nil || dependency == dependent {
continue
}
dependencyKey := dependency.Key()
if dependencies[dependentKey] == nil {
dependencies[dependentKey] = make(map[string]bool)
}
if dependencies[dependentKey][dependencyKey] {
continue
}
dependencies[dependentKey][dependencyKey] = true
dependents[dependencyKey] = append(dependents[dependencyKey], dependent)
}
}
remaining := make(map[string]int, len(artifacts))
queue := make([]*Node, 0, len(artifacts))
for _, artifact := range artifacts {
key := artifact.Key()
remaining[key] = len(dependencies[key])
if remaining[key] == 0 {
queue = append(queue, artifact)
}
}
sortNodes(queue)
// Each artifact enters the queue at most once, so insertion reuses the
// preallocated capacity.
ordered := make([]*Node, 0, len(artifacts))
for head := 0; head < len(queue); head++ {
artifact := queue[head]
ordered = append(ordered, artifact)
for _, dependent := range dependents[artifact.Key()] {
dependentKey := dependent.Key()
remaining[dependentKey]--
if remaining[dependentKey] != 0 {
continue
}
index, _ := slices.BinarySearchFunc(
queue[head+1:],
dependent,
compareNodes,
)
queue = slices.Insert(queue, head+1+index, dependent)
}
}
if len(ordered) != len(artifacts) {
return byID()
}
return ordered
}
package fileglob
import (
"strings"
"github.com/bmatcuk/doublestar/v4"
)
// explicitlySelectsHidden reports whether pattern selects every hidden
// component of name with an explicit leading dot. The WithNoHidden option of
// doublestar checks file attributes on Windows only, so this rule applies to
// every filesystem and to in-memory entries.
func explicitlySelectsHidden(pattern, name string) bool {
segments := strings.Split(pattern, "/")
components := strings.Split(name, "/")
type position struct{ segment, component int }
type outcome struct {
selects bool
known bool
}
memo := make(map[position]outcome, len(segments)*len(components))
var search func(segment, component int) bool
search = func(segment, component int) bool {
at := position{segment, component}
if result := memo[at]; result.known {
return result.selects
}
selects := false
switch {
case segment == len(segments):
selects = component == len(components)
case segments[segment] == "**":
selects = search(segment+1, component) ||
component < len(components) &&
!hiddenComponent(components[component]) &&
search(segment, component+1)
case component < len(components):
matched, err := doublestar.Match(segments[segment], components[component])
selects = err == nil && matched &&
(!hiddenComponent(components[component]) ||
explicitDotSegment(segments[segment])) &&
search(segment+1, component+1)
}
memo[at] = outcome{selects: selects, known: true}
return selects
}
return search(0, 0)
}
// hiddenComponent reports whether a path component starts with a dot.
func hiddenComponent(component string) bool {
return strings.HasPrefix(component, ".")
}
// explicitDotSegment reports whether a pattern segment selects a leading dot
// through a literal dot, an escaped dot, or a non-negated character class that
// includes one.
func explicitDotSegment(segment string) bool {
if strings.HasPrefix(segment, ".") {
return true
}
if strings.HasPrefix(segment, `\`) {
return len(segment) > 1 && segment[1] == '.'
}
class := leadingCharacterClass(segment)
if class == "" {
return false
}
content := class[1 : len(class)-1]
if strings.HasPrefix(content, "!") || strings.HasPrefix(content, "^") {
return false
}
matched, err := doublestar.Match(class, ".")
return err == nil && matched
}
// leadingCharacterClass returns the first character class of a pattern
// segment, including its brackets. It returns an empty string when the
// segment does not start with a character class.
func leadingCharacterClass(segment string) string {
if !strings.HasPrefix(segment, "[") {
return ""
}
index := 1
if index < len(segment) && (segment[index] == '!' || segment[index] == '^') {
index++
}
if index < len(segment) && segment[index] == ']' {
index++
}
for ; index < len(segment); index++ {
switch segment[index] {
case '\\':
index++
case ']':
return segment[:index+1]
}
}
return ""
}
// Package fileglob selects filesystem paths with shell-style patterns.
package fileglob
import (
"errors"
"fmt"
"io/fs"
"github.com/bmatcuk/doublestar/v4"
)
// Entry is a path that a pattern selects.
type Entry struct {
// Path is relative to the filesystem root and uses forward slashes.
Path string
// Dir reports whether Path is a directory.
Dir bool
}
// ErrInvalidPattern marks a malformed pattern.
var ErrInvalidPattern = errors.New("invalid pattern")
// Match returns the entries below fsys that pattern selects, in walk order.
// A pattern that selects nothing returns an empty result and no error.
//
// The supported syntax is *, ?, character classes, and **. A directory is
// returned when the pattern selects it. A hidden path component needs an
// explicit dot in the matching pattern segment. The .lucy and .git
// directories are never returned.
func Match(fsys fs.FS, pattern string) ([]Entry, error) {
matcher := globPattern(pattern)
pruned := &prunedFS{FS: fsys, dots: newDotPolicy(matcher)}
entries := make([]Entry, 0)
err := doublestar.GlobWalk(
pruned,
matcher,
func(name string, entry fs.DirEntry) error {
if reservedPath(name) || !explicitlySelectsHidden(matcher, name) {
return nil
}
switch {
case entry.IsDir():
entries = append(entries, Entry{Path: name, Dir: true})
case entry.Type().IsRegular():
entries = append(entries, Entry{Path: name})
}
return nil
},
doublestar.WithFailOnIOErrors(),
doublestar.WithNoFollow(),
doublestar.WithNoHidden(),
)
if errors.Is(err, doublestar.ErrBadPattern) {
return nil, fmt.Errorf("%w %q", ErrInvalidPattern, pattern)
}
if err != nil {
return nil, err
}
return entries, nil
}
// MatchPaths returns the paths that pattern selects, in input order. MatchPaths
// does not read a filesystem, so a declared path that no longer exists still
// matches. The hidden and syntax rules are the same as Match.
func MatchPaths(pattern string, paths []string) ([]string, error) {
matcher := globPattern(pattern)
if !doublestar.ValidatePattern(matcher) {
return nil, fmt.Errorf("%w %q", ErrInvalidPattern, pattern)
}
matched := make([]string, 0, len(paths))
for _, path := range paths {
if reservedPath(path) || !explicitlySelectsHidden(matcher, path) {
continue
}
matched = append(matched, path)
}
return matched, nil
}
package fileglob
import "strings"
// IsPattern reports whether value contains pattern metacharacters. A caller
// that finds an entry under the literal path skips this check, so a name
// with pattern characters stays addressable.
func IsPattern(value string) bool {
return strings.ContainsAny(value, "*?[")
}
// globPattern escapes the brace characters. Braced alternation is not part of
// the supported syntax, so braces match only themselves.
func globPattern(pattern string) string {
return strings.NewReplacer(
"{", `\{`,
"}", `\}`,
).Replace(pattern)
}
package fileglob
import (
"errors"
"io"
"io/fs"
"strings"
)
// prunedFS hides entries that the pattern cannot select before doublestar
// reads the directory. A callback never sees an excluded subtree, so hidden
// and reserved directories stay out of the walk even when they are
// intermediate path segments.
type prunedFS struct {
fs.FS
dots dotPolicy
}
func (p *prunedFS) Open(name string) (fs.File, error) {
file, err := p.FS.Open(name)
if err != nil {
return nil, err
}
directory, ok := file.(fs.ReadDirFile)
if !ok {
return file, nil
}
return &prunedDirectory{
ReadDirFile: directory,
allowHidden: p.dots.allows(depth(name)),
}, nil
}
// dotPolicy reports the depths at which a dot-prefixed entry can become a
// match. A depth that the pattern cannot dot explicitly holds no selectable
// entry.
type dotPolicy struct {
fixed map[int]struct{}
flex int
}
func newDotPolicy(pattern string) dotPolicy {
policy := dotPolicy{fixed: make(map[int]struct{}), flex: -1}
flexible := false
consumed := 0
for _, segment := range strings.Split(pattern, "/") {
if segment == "**" {
flexible = true
continue
}
if explicitDotSegment(segment) {
if flexible {
if policy.flex < 0 || consumed < policy.flex {
policy.flex = consumed
}
} else {
policy.fixed[consumed] = struct{}{}
}
}
consumed++
}
return policy
}
// allows reports whether a dot-prefixed entry at depth can become a match. A
// preceding ** shifts an explicit-dot segment to any later depth, so the
// policy allows every depth from the minimum.
func (p dotPolicy) allows(depth int) bool {
if _, exists := p.fixed[depth]; exists {
return true
}
return p.flex >= 0 && depth >= p.flex
}
// depth returns the component count of a relative fs path below the root.
func depth(name string) int {
if name == "." || name == "" {
return 0
}
return strings.Count(name, "/") + 1
}
type prunedDirectory struct {
fs.ReadDirFile
allowHidden bool
}
func (d *prunedDirectory) ReadDir(n int) ([]fs.DirEntry, error) {
for {
entries, err := d.ReadDirFile.ReadDir(n)
kept := make([]fs.DirEntry, 0, len(entries))
for _, entry := range entries {
if d.retain(entry) {
kept = append(kept, entry)
}
}
if n <= 0 || len(kept) > 0 || err != nil {
if errors.Is(err, io.EOF) && len(kept) > 0 {
err = nil
}
return kept, err
}
}
}
// retain reports whether an entry stays visible to the walk.
func (d *prunedDirectory) retain(entry fs.DirEntry) bool {
name := entry.Name()
if reservedName(name) {
return false
}
if !strings.HasPrefix(name, ".") {
return true
}
return d.allowHidden
}
// reservedPath reports whether a path contains reserved state. A pattern never
// selects such a path, and the walk never enters it.
func reservedPath(path string) bool {
for _, component := range strings.Split(path, "/") {
if reservedName(component) {
return true
}
}
return false
}
func reservedName(name string) bool {
switch strings.ToLower(name) {
case ".lucy", ".git":
return true
default:
return false
}
}
// Package fileidentity identifies one version of a file by the filesystem
// metadata that every write changes, and memoizes content digests per command
// so a file that nothing touched is read once.
package fileidentity
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
)
// memoRacyWindow keeps a digest out of the memo while the file's change time
// could share a timestamp granule with a later edit. Two seconds covers the
// coarsest filesystems Lucy targets.
const memoRacyWindow = 2 * time.Second
// Identity names one version of a file. Device and inode catch a replacement,
// size catches an append, and the timestamps catch an in-place write or mode
// change. YAML tags let a sidecar persist the evidence.
type Identity struct {
Device uint64 `yaml:"device"`
Inode uint64 `yaml:"inode"`
Size int64 `yaml:"size"`
MtimeNS int64 `yaml:"mtime_ns"`
CtimeNS int64 `yaml:"ctime_ns"`
}
// Of extracts a file's stat identity. It reports false on a platform or
// filesystem that exposes none, and callers then read the content every time.
func Of(info fs.FileInfo) (Identity, bool) {
return identityFromInfo(info)
}
// Same reports whether two identities describe the same file version.
func (i Identity) Same(other Identity) bool {
return i == other
}
// Racy reports whether the change time is too recent for the identity to
// exclude a write in the same timestamp granule.
func (i Identity) Racy(now time.Time) bool {
return !time.Unix(0, i.CtimeNS).Before(now.Add(-memoRacyWindow))
}
// OlderThan reports whether the file changed strictly before the recorded
// filesystem timestamp. A coarse timestamp makes the two equal, which refuses
// the evidence instead of risking a same-granule edit.
func (i Identity) OlderThan(timestampNS int64) bool {
return i.CtimeNS < timestampNS
}
// Observation is one observation of a path. Exists is false for a missing
// path; Regular is false for a directory or symbolic link. Identity is
// recorded even while a file is too recent for the memo, so a caller can
// persist the evidence once the write is old enough.
type Observation struct {
Exists bool
Regular bool
Mode fs.FileMode
Size int64
Hashes map[string]string
Identity Identity
HasIdentity bool
}
// Memo caches content digests by stat identity for one command.
type Memo struct {
mu sync.Mutex
files map[string]memoFile
}
type memoFile struct {
identity Identity
hashes map[string]string
}
// NewMemo returns an empty digest memo.
func NewMemo() *Memo {
return &Memo{files: make(map[string]memoFile)}
}
// ObserveRoot observes rel through files. It reads the content only when the
// memo holds no identity that matches the path now.
func (m *Memo) ObserveRoot(files *os.Root, rel string, algorithms []string) (Observation, error) {
rel = filepath.FromSlash(rel)
info, err := files.Lstat(rel)
if errors.Is(err, fs.ErrNotExist) {
return Observation{}, nil
}
if err != nil {
return Observation{}, err
}
key := files.Name() + "\x00" + rel
return m.observe(key, rel, info, files.Open, algorithms)
}
// ObserveRootInfo observes rel through files using an info the caller already
// observed for the same path.
func (m *Memo) ObserveRootInfo(
files *os.Root,
rel string,
info fs.FileInfo,
algorithms []string,
) (Observation, error) {
rel = filepath.FromSlash(rel)
key := files.Name() + "\x00" + rel
return m.observe(key, rel, info, files.Open, algorithms)
}
// ObservePath observes an absolute path.
func (m *Memo) ObservePath(path string, algorithms []string) (Observation, error) {
info, err := os.Lstat(path)
if errors.Is(err, fs.ErrNotExist) {
return Observation{}, nil
}
if err != nil {
return Observation{}, err
}
return m.observe(path, path, info, os.Open, algorithms)
}
func (m *Memo) observe(
key string,
name string,
info fs.FileInfo,
open func(string) (*os.File, error),
algorithms []string,
) (Observation, error) {
observation := Observation{
Exists: true,
Regular: info.Mode().IsRegular(),
Mode: info.Mode(),
Size: info.Size(),
HasIdentity: false,
}
if identity, ok := identityFromInfo(info); ok {
observation.Identity = identity
observation.HasIdentity = true
if hashes, hit := m.lookup(key, identity, algorithms); hit {
observation.Hashes = hashes
return observation, nil
}
}
if !observation.Regular {
return observation, nil
}
file, err := open(name)
if err != nil {
return Observation{}, err
}
read, readErr := digestFile(file, algorithms)
closeErr := file.Close()
if readErr != nil || closeErr != nil {
return Observation{}, errors.Join(readErr, closeErr)
}
observation.Hashes = read.hashes
// The pre-read stat describes no particular content once the read saw a
// change, so the mode, size, and identity come from the handle the bytes
// were read through.
observation.Mode = read.mode
observation.Size = read.size
observation.Identity = read.identity
observation.HasIdentity = read.identified
if read.identified && !read.identity.Racy(time.Now()) {
m.store(key, read.identity, read.hashes)
}
return observation, nil
}
func (m *Memo) lookup(key string, identity Identity, algorithms []string) (map[string]string, bool) {
if m == nil {
return nil, false
}
m.mu.Lock()
entry, ok := m.files[key]
m.mu.Unlock()
if !ok || !entry.identity.Same(identity) {
return nil, false
}
hashes := make(map[string]string, len(algorithms)+1)
hashes["sha256"] = entry.hashes["sha256"]
if hashes["sha256"] == "" {
return nil, false
}
for _, algorithm := range algorithms {
if algorithm == "sha256" {
continue
}
digest := entry.hashes[algorithm]
if digest == "" {
return nil, false
}
hashes[algorithm] = digest
}
return hashes, true
}
func (m *Memo) store(key string, identity Identity, hashes map[string]string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
m.files[key] = memoFile{
identity: identity,
hashes: cloneHashes(hashes),
}
}
func cloneHashes(hashes map[string]string) map[string]string {
clone := make(map[string]string, len(hashes))
for algorithm, digest := range hashes {
clone[algorithm] = digest
}
return clone
}
// digestAttempts bounds how often digestFile rereads a file that changes
// while it is read.
const digestAttempts = 3
// digestResult holds what one handle read produced. mode and size come from
// the last stat of that handle. identity is valid only when identified is
// true.
type digestResult struct {
hashes map[string]string
identity Identity
identified bool
mode fs.FileMode
size int64
}
// digestFile reads file and returns the SHA-256 and every requested
// algorithm. It reads the identity from the same handle before and after the
// bytes, and reports an identity only when both reads agree, so a write during
// the read can never pair an old digest with the identity of new content. A
// file that keeps changing returns the digest of the last read without an
// identity.
func digestFile(file *os.File, algorithms []string) (digestResult, error) {
factories := map[string]func() hash.Hash{"sha256": sha256.New}
for _, algorithm := range algorithms {
switch algorithm {
case "sha256":
case "sha1":
factories[algorithm] = sha1.New
case "sha512":
factories[algorithm] = sha512.New
case "md5":
factories[algorithm] = md5.New
default:
return digestResult{}, fmt.Errorf(
"unsupported artifact digest %s", algorithm,
)
}
}
var result digestResult
for attempt := range digestAttempts {
if attempt > 0 {
if _, err := file.Seek(0, io.SeekStart); err != nil {
return digestResult{}, err
}
}
before, err := file.Stat()
if err != nil {
return digestResult{}, err
}
hashes, err := readDigests(file, factories)
if err != nil {
return digestResult{}, err
}
after, err := file.Stat()
if err != nil {
return digestResult{}, err
}
result = digestResult{
hashes: hashes,
mode: after.Mode(),
size: after.Size(),
}
first, firstOK := identityFromInfo(before)
last, lastOK := identityFromInfo(after)
if !firstOK || !lastOK {
return result, nil
}
if first.Same(last) {
result.identity = last
result.identified = true
return result, nil
}
}
return result, nil
}
func readDigests(file *os.File, factories map[string]func() hash.Hash) (map[string]string, error) {
hashers := make(map[string]hash.Hash, len(factories))
writers := make([]io.Writer, 0, len(factories))
for algorithm, factory := range factories {
hasher := factory()
hashers[algorithm] = hasher
writers = append(writers, hasher)
}
if _, err := io.Copy(io.MultiWriter(writers...), file); err != nil {
return nil, err
}
hashes := make(map[string]string, len(hashers))
for algorithm, hasher := range hashers {
hashes[algorithm] = hex.EncodeToString(hasher.Sum(nil))
}
return hashes, nil
}
//go:build linux
package fileidentity
import (
"io/fs"
"syscall"
)
func identityFromInfo(info fs.FileInfo) (Identity, bool) {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return Identity{}, false
}
return Identity{
Device: uint64(stat.Dev),
Inode: stat.Ino,
Size: stat.Size,
MtimeNS: stat.Mtim.Sec*1_000_000_000 + stat.Mtim.Nsec,
CtimeNS: stat.Ctim.Sec*1_000_000_000 + stat.Ctim.Nsec,
}, true
}
package fileschema
import (
"encoding/json/v2"
"github.com/mclucy/lucy/internal/fn"
)
type FabricEnvironment string
const (
FabricEnvironmentClient FabricEnvironment = "client"
FabricEnvironmentServer FabricEnvironment = "server"
FabricEnvironmentAny FabricEnvironment = "*"
)
// FabricAuthor handles both a plain string and a person object {"name": "..."}
// as allowed by the fabric.mod.json spec.
type FabricAuthor string
func (a *FabricAuthor) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err == nil {
*a = FabricAuthor(s)
return nil
}
var obj struct {
Name string `json:"name"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return err
}
*a = FabricAuthor(obj.Name)
return nil
}
// FileFabricModIdentifier represents the structure of fabric.mod.json files found
// in Fabric mods' `.jar` files.
//
// Docs: https://fabricmc.net/wiki/documentation:fabric_mod_json_spec
type FileFabricModIdentifier struct {
SchemaVersion int `json:"schemaVersion"`
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
Description string `json:"description"`
Authors []FabricAuthor `json:"authors"`
// Fields officially supported:
// - "email"
// - "homepage"
// - "irc"
// - "issues"
// - "sources"
Contact map[string]string `json:"contact"`
// License uses the SPDX license expression format. Published descriptors
// also use other shapes, which the loader ignores.
License FileLicense `json:"license"`
// Icon may be a path or a size-to-path map. The loader treats it as
// presentation, so lucy does not read it.
Icon string `json:"-"`
Environment FabricEnvironment `json:"environment"`
Provides []string `json:"provides"`
Jars []struct {
File string `json:"file"`
} `json:"jars"`
Entrypoints map[string][]string `json:"-"`
Mixins []string `json:"-"`
AccessWidener string `json:"accessWidener"`
LanguageAdapters map[string]string `json:"-"`
// Depends > Recommends > Suggests
// Breaks > Conflicts
Depends map[string]fn.SingleOrSlice[string] `json:"depends"`
Recommends map[string]fn.SingleOrSlice[string] `json:"recommends"`
Suggests map[string]fn.SingleOrSlice[string] `json:"suggests"`
Breaks map[string]fn.SingleOrSlice[string] `json:"breaks"`
Conflicts map[string]fn.SingleOrSlice[string] `json:"conflicts"`
Custom any `json:"-"`
}
package fileschema
import (
"fmt"
"strings"
"github.com/pelletier/go-toml/v2"
)
// FileModLoaderAuthors accepts the documented string form and the array form
// some published jars use. Normalization converts a string to a one-element
// slice before decoding.
type FileModLoaderAuthors []string
// FileModLoaderIdentifier is for 1.13+ forge & neoforge mods. This is a toml file.
type FileModLoaderIdentifier struct {
ModLoader string `toml:"modLoader"`
LoaderVersion string `toml:"loaderVersion"`
IssueTrackerURL string `toml:"issueTrackerURL"`
LogoFile string `toml:"logoFile"`
License string `toml:"license"`
ClientSideOnly bool `toml:"clientSideOnly"`
Mods []forgeModInfo `toml:"mods"`
Dependencies map[string][]ForgeModDependency `toml:"dependencies"`
ModProperties map[string]string `toml:"-"` // ignored
}
// ParseFileModLoaderIdentifier decodes a Forge-family descriptor. Published
// descriptors deviate from the documented shapes in two tolerated ways: an
// ownerless top-level [[dependencies]] array and an authors array. The decoder
// normalizes those shapes before go-toml decodes the typed value.
func ParseFileModLoaderIdentifier(data []byte) (FileModLoaderIdentifier, error) {
normalized, err := normalizeForgeDescriptor(data)
if err != nil {
return FileModLoaderIdentifier{}, err
}
var identifier FileModLoaderIdentifier
if err := toml.Unmarshal(normalized, &identifier); err != nil {
return FileModLoaderIdentifier{}, err
}
return identifier, nil
}
// normalizeForgeDescriptor projects the fields the schema reads through the
// same accessors FML uses. FML reads a descriptor with NightConfig: a path
// resolves through tables only, so a list at an intermediate segment makes the
// path absent, while getConfigList requires a list at its final path and
// getConfigElement rejects a list of tables at a single-element path. The
// projection keeps only the schema fields and coerces list/scalar shapes, so
// go-toml decodes the documented struct.
func normalizeForgeDescriptor(data []byte) ([]byte, error) {
var document map[string]any
if err := toml.Unmarshal(data, &document); err != nil {
return nil, err
}
normalized := map[string]any{}
copyForgeStrings(normalized, document,
"modLoader", "loaderVersion", "issueTrackerURL", "logoFile", "license")
if clientOnly, ok := document["clientSideOnly"].(bool); ok {
normalized["clientSideOnly"] = clientOnly
}
mods, err := normalizeForgeMods(document)
if err != nil {
return nil, err
}
if len(mods) == 0 {
return toml.Marshal(normalized)
}
normalized["mods"] = mods
dependencies, err := normalizeForgeDependencies(document, mods)
if err != nil {
return nil, err
}
if len(dependencies) > 0 {
normalized["dependencies"] = dependencies
}
return toml.Marshal(normalized)
}
// configList mirrors NightConfigWrapper.getConfigList: the path resolves
// through tables and its final value must be a list. Forge rejects a present
// non-list value, so report it instead of dropping it.
func configList(document map[string]any, path ...string) ([]any, bool, error) {
value, ok := configPath(document, path...)
if !ok {
return nil, false, nil
}
list, ok := value.([]any)
if !ok {
return nil, true, fmt.Errorf("configuration path %v is invalid: expecting a collection", strings.Join(path, "."))
}
return list, true, nil
}
// configPath mirrors NightConfig's path lookup. A list at an intermediate
// segment is not a table, so the path does not exist. That is how FML ignores
// an ownerless [[dependencies]] array when it reads dependencies.<modId>.
func configPath(document map[string]any, path ...string) (any, bool) {
var current any = document
for _, key := range path {
table, ok := current.(map[string]any)
if !ok {
return nil, false
}
current, ok = table[key]
if !ok {
return nil, false
}
}
return current, true
}
func normalizeForgeMods(document map[string]any) ([]any, error) {
entries, exists, err := configList(document, "mods")
if err != nil {
return nil, err
}
if !exists {
return nil, nil
}
mods := make([]any, 0, len(entries))
for _, entry := range entries {
table, ok := entry.(map[string]any)
if !ok {
continue
}
mod := map[string]any{}
copyForgeStrings(mod, table,
"modId", "version", "displayName", "itemIcon", "displayURL",
"updateJSONURL", "logoFile", "credits", "description")
if clientOnly, ok := table["clientSideOnly"].(bool); ok {
mod["clientSideOnly"] = clientOnly
}
if authors := normalizeForgeAuthors(table["authors"]); len(authors) > 0 {
mod["authors"] = authors
}
if len(mod) > 0 {
mods = append(mods, mod)
}
}
return mods, nil
}
// normalizeForgeAuthors accepts the documented string form and the array form
// some published jars use. FML never reads authors, so an unknown shape carries
// no server behavior and is dropped.
func normalizeForgeAuthors(value any) []any {
switch authors := value.(type) {
case string:
return []any{authors}
case []any:
kept := make([]any, 0, len(authors))
for _, author := range authors {
if _, ok := author.(string); ok {
kept = append(kept, author)
}
}
return kept
default:
return nil
}
}
// normalizeForgeDependencies reads dependencies.<modId> for every declared mod,
// matching ModInfo's getConfigList call. An ownerless dependencies list, or any
// other non-table dependencies value, yields no path and contributes nothing;
// a present non-list dependency value is a Forge-rejected malformed descriptor.
func normalizeForgeDependencies(document map[string]any, mods []any) (map[string]any, error) {
dependencies := map[string]any{}
for _, entry := range mods {
mod, ok := entry.(map[string]any)
if !ok {
continue
}
modID, ok := mod["modId"].(string)
if !ok || modID == "" {
continue
}
entries, exists, err := configList(document, "dependencies", modID)
if err != nil {
return nil, err
}
if !exists {
continue
}
normalized, err := normalizeForgeDependencyEntries(entries)
if err != nil {
return nil, err
}
if len(normalized) > 0 {
dependencies[modID] = normalized
}
}
return dependencies, nil
}
func normalizeForgeDependencyEntries(entries []any) ([]any, error) {
normalized := make([]any, 0, len(entries))
for _, entry := range entries {
table, ok := entry.(map[string]any)
if !ok {
continue
}
modID, _ := table["modId"].(string)
// Forge reads mandatory as a Boolean, so a string must not become false.
if value, ok := table["mandatory"]; ok {
if _, ok := value.(bool); !ok {
return nil, fmt.Errorf("dependency %v: mandatory must be a boolean", modID)
}
}
dependency := map[string]any{}
copyForgeStrings(dependency, table,
"modId", "type", "versionRange", "ordering", "side")
if mandatory, ok := table["mandatory"].(bool); ok {
dependency["mandatory"] = mandatory
}
if len(dependency) > 0 {
normalized = append(normalized, dependency)
}
}
return normalized, nil
}
func copyForgeStrings(destination, source map[string]any, keys ...string) {
for _, key := range keys {
if value, ok := source[key].(string); ok {
destination[key] = value
}
}
}
type forgeModInfo struct {
ModID string `toml:"modId"`
Version string `toml:"version"`
DisplayName string `toml:"displayName"`
ItemIcon string `toml:"itemIcon"`
DisplayURL string `toml:"displayURL"`
UpdateJSONURL string `toml:"updateJSONURL"`
LogoFile string `toml:"logoFile"`
Credits string `toml:"credits"`
Authors FileModLoaderAuthors `toml:"authors"`
Description string `toml:"description"`
ClientSideOnly bool `toml:"clientSideOnly"`
}
// ForgeModDependency is one dependency a Forge-family descriptor declares.
type ForgeModDependency struct {
ModID string `toml:"modId"`
Mandatory bool `toml:"mandatory"`
Type string `toml:"type"`
VersionRange string `toml:"versionRange"`
Ordering string `toml:"ordering"`
Side string `toml:"side"`
}
// FileForgeModIdentifierOld is the JSON metadata shape used by Forge 1.12
// and earlier.
type FileForgeModIdentifierOld []struct {
ModId string `json:"modid"`
Name string `json:"name"`
Description string `json:"description"`
Version string `json:"version"`
McVersion string `json:"mcversion"`
URL string `json:"url"`
UpdateURL string `json:"updateUrl"`
AuthorList []string `json:"authorList"`
Credits string `json:"credits"`
LogoFile string `json:"logoFile"`
Screenshots []any `json:"screenshots"`
Dependencies []any `json:"dependencies"`
}
package fileschema
import "encoding/json/v2"
// FileLicense is a descriptor's license field. A loader does not reject a
// descriptor over its license, so decoding accepts what it can and never
// fails: a single name, a list, or an unrecognized shape the caller ignores.
type FileLicense []string
func (l *FileLicense) UnmarshalJSON(data []byte) error {
var single string
if err := json.Unmarshal(data, &single); err == nil {
*l = []string{single}
return nil
}
var many []string
if err := json.Unmarshal(data, &many); err == nil {
*l = many
}
return nil
}
package fn
import "io"
// Ternary returns `a` if `v == true`, `b` if `v == false`.
//
// Do not use this in a loop or a performance-critical code path, as it may cause
// unnecessary evaluations of a and b.
func Ternary[T any](v bool, a T, b T) T {
if v {
return a
}
return b
}
// CloseReader closes a reader and runs failAction() if error occurs. Call this
// with a defer statement.
func CloseReader(reader io.ReadCloser, failAction func(error)) {
err := reader.Close()
if err != nil {
failAction(err)
}
}
package fn
import "encoding/json/v2"
// SingleOrSlice represents a value that can be encoded as either:
// - a single element: `T`
// - or an array: `[]T`
//
// After unmarshalling, both forms are normalized into a slice shape.
// This type is intended for input-schema compatibility at decoding boundaries.
// Business logic should typically consume plain []T.
type SingleOrSlice[T any] []T
func (s *SingleOrSlice[T]) UnmarshalJSON(data []byte) error {
// Fast-path by JSON shape to avoid ambiguity for permissive T types.
for _, b := range data {
switch b {
case ' ', '\t', '\n', '\r':
continue
case '[':
var multiple []T
if err := json.Unmarshal(data, &multiple); err != nil {
return err
}
*s = multiple
return nil
default:
var single T
if err := json.Unmarshal(data, &single); err != nil {
return err
}
*s = []T{single}
return nil
}
}
// Empty JSON input is treated as an empty slice.
*s = nil
return nil
}
package fsutil
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"unicode/utf8"
)
// WorkspaceMarker names the directory that marks a lucy workspace root.
const WorkspaceMarker = ".lucy"
// StagingRelative is the directory inside a workspace that holds staged copies
// written through WriteRoot while the workspace writer lock is held.
const StagingRelative = ".lucy/tmp"
// StagingPrefix names the staged copy of a publish.
const StagingPrefix = ".lucy-stage-"
// MaxStagedBase caps the destination basename embedded in a staging name.
const MaxStagedBase = 64
// RenameRoot publishes a closed, synced file inside root and persists the rename.
// Parent directories must exist. Platform implementations preserve root confinement.
func RenameRoot(root *os.Root, from, to string) error {
return publishRoot(root, from, to, true)
}
// RenameRootNoReplace publishes only if the destination name is still absent.
func RenameRootNoReplace(root *os.Root, from, to string) error {
return publishRoot(root, from, to, false)
}
// RenameDirRoot renames a directory inside root and persists the rename. The
// destination must be absent. The directory's own entries must already be
// durable.
func RenameDirRoot(root *os.Root, from, to string) error {
if !filepath.IsLocal(from) || !filepath.IsLocal(to) {
return fmt.Errorf("rename paths must stay inside their root")
}
return renameDirRoot(root, filepath.Clean(from), filepath.Clean(to))
}
func publishRoot(root *os.Root, from, to string, replace bool) error {
if !filepath.IsLocal(from) || !filepath.IsLocal(to) {
return fmt.Errorf("rename paths must stay inside their root")
}
from = filepath.Clean(from)
to = filepath.Clean(to)
for _, name := range []string{from, to} {
info, err := root.Lstat(name)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err == nil && !info.Mode().IsRegular() {
return fmt.Errorf("rename endpoint must be a regular file")
}
for parent := filepath.Dir(name); parent != "."; parent = filepath.Dir(parent) {
info, err := root.Lstat(parent)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("rename parent must be a regular directory")
}
}
}
return renameRoot(root, from, to, replace)
}
// AtomicWrite replaces a file atomically and retains its permissions.
// New files use defaultMode.
func AtomicWrite(path string, data []byte, defaultMode os.FileMode) error {
mode := defaultMode
info, err := os.Lstat(path)
if err == nil {
if !info.Mode().IsRegular() {
return fmt.Errorf("write destination must be a regular file")
}
mode = info.Mode().Perm()
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect file permissions: %w", err)
}
return atomicCopy(bytes.NewReader(data), path, mode)
}
func atomicCopy(reader io.Reader, path string, mode os.FileMode) (resultErr error) {
if err := MkdirAllPrivate(filepath.Dir(path)); err != nil {
return fmt.Errorf("create file parent: %w", err)
}
root, err := os.OpenRoot(filepath.Dir(path))
if err != nil {
return fmt.Errorf("open file parent: %w", err)
}
defer func() { resultErr = errors.Join(resultErr, root.Close()) }()
base := filepath.Base(path)
return publish(root, stagedName(base), base, func(stage string) error {
return writeStage(root, stage, reader, mode)
}, true, nil)
}
// WriteOptions controls one publish.
type WriteOptions struct {
// Mode is the permission set applied to the published file.
Mode os.FileMode
// Replace publishes over an existing destination. Without it the publish
// succeeds only while the destination name is still absent, so a file that
// appears during provisioning survives.
Replace bool
// Check runs after the payload is staged and immediately before
// publication, so a caller can abandon a publish whose destination the
// world changed while the payload was being staged.
Check func() error
}
// WriteRoot publishes a payload at a path confined to root. The payload is
// staged inside the workspace staging directory when root is a workspace and
// beside the destination otherwise, so a publish never crosses a filesystem.
func WriteRoot(root *os.Root, relative string, reader io.Reader, opts WriteOptions) error {
if !filepath.IsLocal(relative) {
return fmt.Errorf("output path must stay inside the workspace")
}
parent := filepath.Dir(relative)
if err := root.MkdirAll(parent, 0o700); err != nil {
return err
}
stageRel, err := stagingRelative(root, parent)
if err != nil {
return err
}
return publish(
root,
filepath.Join(stageRel, stagedName(filepath.Base(relative))),
relative,
func(stage string) error {
return writeStage(root, stage, reader, opts.Mode)
},
opts.Replace,
opts.Check,
)
}
// WriteFileRoot publishes the content of src at a path confined to root under
// the same staging rules as WriteRoot. link selects how the bytes reach the
// staged name: a hardlink or a clone never copies them.
func WriteFileRoot(
root *os.Root,
relative, src string,
link LinkMode,
opts WriteOptions,
) error {
if !filepath.IsLocal(relative) {
return fmt.Errorf("output path must stay inside the workspace")
}
parent := filepath.Dir(relative)
if err := root.MkdirAll(parent, 0o700); err != nil {
return err
}
stageRel, err := stagingRelative(root, parent)
if err != nil {
return err
}
return publish(
root,
filepath.Join(stageRel, stagedName(filepath.Base(relative))),
relative,
func(stage string) error {
return stageFile(root, stage, src, opts.Mode, link)
},
opts.Replace,
opts.Check,
)
}
// stageFile places the content of src at the staged name inside root. A
// hardlink shares the source inode, so it applies only while src already
// carries mode; a clone takes mode; a byte copy writes the bytes. The staged
// directory is opened through root, so a path change cannot move the write
// outside root. The staged name stays unpublished until the caller renames it.
func stageFile(root *os.Root, stage, src string, mode os.FileMode, link LinkMode) (resultErr error) {
dir, err := root.Open(filepath.Dir(stage))
if err != nil {
return fmt.Errorf("open staging directory: %w", err)
}
defer func() { resultErr = errors.Join(resultErr, dir.Close()) }()
if placeFileAt(dir, filepath.Base(stage), src, mode.Perm(), link) {
if err := syncStaged(root, stage); err != nil {
return errors.Join(err, removeStaged(root, stage))
}
return nil
}
source, err := os.Open(src)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, source.Close()) }()
return writeStage(root, stage, source, mode)
}
// syncStaged orders linked or cloned content before publication. A link or a
// clone writes no bytes through a descriptor, and the source can be a stage
// file that never passed a Barrier, so the staged inode needs its own.
func syncStaged(root *os.Root, stage string) error {
file, err := root.Open(stage)
if err != nil {
return err
}
if err := Barrier(file); err != nil {
return errors.Join(fmt.Errorf("sync staged file: %w", err), file.Close())
}
return file.Close()
}
// writeStage writes reader into the staged file inside root, applies mode, and
// orders the content before publication. A failure removes the partial file.
func writeStage(root *os.Root, stage string, reader io.Reader, mode os.FileMode) (resultErr error) {
file, err := root.OpenFile(stage, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return fmt.Errorf("create staged file: %w", err)
}
complete := false
defer func() {
if !complete {
resultErr = errors.Join(resultErr, removeStaged(root, stage))
}
}()
if err := fillStage(file, reader, mode); err != nil {
return err
}
complete = true
return nil
}
// fillStage writes reader into an open staged file, applies mode, orders the
// content before publication, and closes the file. It closes the file even on
// failure.
func fillStage(file *os.File, reader io.Reader, mode os.FileMode) (resultErr error) {
closed := false
defer func() {
if !closed {
resultErr = errors.Join(resultErr, file.Close())
}
}()
if _, err := io.Copy(file, reader); err != nil {
return fmt.Errorf("write staged file: %w", err)
}
if err := file.Chmod(mode.Perm()); err != nil {
return fmt.Errorf("set staged permissions: %w", err)
}
if err := Barrier(file); err != nil {
return fmt.Errorf("sync staged file: %w", err)
}
if err := file.Close(); err != nil {
closed = true
return fmt.Errorf("close staged file: %w", err)
}
closed = true
return nil
}
// publish stages a payload through stagePayload and renames it into place. A
// reader therefore sees the previous content or the new content, never a
// partial write, and a stage that a crash abandons never masquerades as
// destination data. A failure after staging removes the staged name, and a
// payload that fails while being staged removes its own partial file.
func publish(
root *os.Root,
stage, dest string,
stagePayload func(stage string) error,
replace bool,
check func() error,
) (resultErr error) {
if err := stagePayload(stage); err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, removeStaged(root, stage)) }()
if check != nil {
if err := check(); err != nil {
return err
}
}
if replace {
return RenameRoot(root, stage, dest)
}
return RenameRootNoReplace(root, stage, dest)
}
// removeStaged deletes one staged name and tolerates a name that a completed
// publish already renamed away.
func removeStaged(root *os.Root, stage string) error {
if err := root.Remove(stage); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove staged file: %w", err)
}
return nil
}
// stagingRelative prefers the workspace staging directory, which keeps a
// staged payload out of the destination namespace, and falls back to the
// destination's own directory for a root that is not a workspace, or when the
// staging directory sits on another filesystem than the destination.
func stagingRelative(root *os.Root, parent string) (string, error) {
info, err := root.Stat(WorkspaceMarker)
if err == nil {
if !info.IsDir() {
return "", fmt.Errorf("%s is not a directory", WorkspaceMarker)
}
if err := root.MkdirAll(StagingRelative, 0o700); err != nil {
return "", fmt.Errorf("create staging directory: %w", err)
}
if sameDevice(filepath.Join(root.Name(), StagingRelative), filepath.Join(root.Name(), parent)) {
return StagingRelative, nil
}
return parent, nil
}
if !errors.Is(err, os.ErrNotExist) {
return "", err
}
return parent, nil
}
// stagedName carries the destination basename so that a stage abandoned by a
// killed process names the file it belongs to.
func stagedName(base string) string {
if len(base) > MaxStagedBase {
cut := MaxStagedBase
for cut > 0 && !utf8.RuneStart(base[cut]) {
cut--
}
base = base[:cut]
}
return StagingPrefix + base + "-" + rand.Text()
}
// SweepStaging removes staging copies that a killed publisher abandoned. The
// caller holds the workspace writer lock, which proves that no publisher is
// live and that every staging copy found is debris.
func SweepStaging(root *os.Root) (removed []string, resultErr error) {
dir, err := root.Open(StagingRelative)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("open staging directory: %w", err)
}
entries, err := dir.ReadDir(-1)
resultErr = errors.Join(err, dir.Close())
if err != nil {
return nil, fmt.Errorf("read staging directory: %w", resultErr)
}
for _, entry := range entries {
if entry.IsDir() || !IsStagingName(entry.Name()) {
continue
}
name := filepath.Join(StagingRelative, entry.Name())
if err := root.Remove(name); err != nil && !errors.Is(err, os.ErrNotExist) {
resultErr = errors.Join(resultErr, fmt.Errorf("remove staged file: %w", err))
continue
}
removed = append(removed, name)
}
return removed, resultErr
}
// IsStagingName reports whether name is a staged copy from the current policy.
// Crash debris carries such a name and is inert.
func IsStagingName(name string) bool {
return strings.HasPrefix(name, StagingPrefix)
}
package fsutil
import (
"io"
"os"
"path/filepath"
)
// AtomicCopyFile writes src to dst with mode, replacing dst through a
// temporary file beside dst. An interrupted copy never leaves a partial file,
// and other links to the previous dst keep their bytes.
func AtomicCopyFile(src, dst string, mode os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.CreateTemp(filepath.Dir(dst), "."+filepath.Base(dst)+".*")
if err != nil {
return err
}
temporary := out.Name()
defer func() {
if out != nil {
out.Close()
os.Remove(temporary)
}
}()
if err := out.Chmod(mode); err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
out = nil
return os.Rename(temporary, dst)
}
package fsutil
import (
"errors"
"fmt"
"os"
"path/filepath"
)
// MkdirAllPrivate persists newly created naming entries before callers publish data beneath them.
func MkdirAllPrivate(path string) error {
path, err := filepath.Abs(path)
if err != nil {
return err
}
var missing []string
for current := path; ; current = filepath.Dir(current) {
info, err := os.Stat(current)
if err == nil {
if !info.IsDir() {
return fmt.Errorf("directory ancestor is not a directory: %s", current)
}
break
}
if !errors.Is(err, os.ErrNotExist) {
return err
}
missing = append(missing, current)
if filepath.Dir(current) == current {
return fmt.Errorf("filesystem root does not exist: %s: %w", current, err)
}
}
if len(missing) == 0 {
return nil
}
return makePrivateDirectories(path, missing)
}
package fsutil
import (
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
)
// LinkMode selects how stored content reaches a destination.
type LinkMode string
const (
// LinkClone shares the stored blocks through a copy-on-write clone where
// the filesystem supports it and copies the bytes elsewhere. A later write
// to the destination never reaches the stored content.
LinkClone LinkMode = "clone"
// LinkHardlink shares the stored inode. A process that writes the
// destination in place also changes the stored content, so this mode is
// opt-in and deploys read-only files.
LinkHardlink LinkMode = "hardlink"
)
// ParseLinkMode reads a configured link mode. An empty value selects
// LinkClone.
func ParseLinkMode(value string) (LinkMode, error) {
switch LinkMode(value) {
case "", LinkClone:
return LinkClone, nil
case LinkHardlink:
return LinkHardlink, nil
default:
return "", fmt.Errorf("unknown link mode %q; use %q or %q", value, LinkClone, LinkHardlink)
}
}
// Perm reports the permission set a destination requests under this mode. A
// hardlink shares the store inode, so the destination is read-only; a clone or
// a copy keeps the requested permissions. A platform that cannot link files
// deploys a copy, so it keeps those permissions too.
func (m LinkMode) Perm(requested os.FileMode) os.FileMode {
if m == LinkHardlink && hardlinkSharesInode {
return requested &^ 0o222
}
return requested
}
// Materialize places the content of src at dst with permission bits perm and
// replaces dst atomically. src is never modified, and an interrupted call
// never leaves a partial dst.
//
// A hardlink deploys a read-only destination, so callers compute perm through
// LinkMode.Perm. LinkHardlink links only when src already has exactly perm,
// because a chmod on a shared inode would change src; otherwise it falls back
// to a clone. A clone falls back to a byte copy.
func Materialize(src, dst string, perm os.FileMode, mode LinkMode) error {
parent := filepath.Dir(dst)
if err := os.MkdirAll(parent, 0o755); err != nil {
return err
}
dir, err := os.Open(parent)
if err != nil {
return err
}
defer dir.Close()
temporary := "." + filepath.Base(dst) + "." + rand.Text()
if !placeFileAt(dir, temporary, src, perm, mode) {
return AtomicCopyFile(src, dst, perm)
}
if err := os.Rename(filepath.Join(parent, temporary), dst); err != nil {
return errors.Join(err, os.Remove(filepath.Join(parent, temporary)))
}
return nil
}
// placeFileAt creates name in dir with the content of src through a hardlink
// or a clone and reports whether one succeeded. name must be absent, and a
// failed attempt leaves it absent, so the caller copies the bytes instead.
// Each operation resolves name relative to dir, so a path change above dir
// cannot redirect the write.
func placeFileAt(dir *os.File, name, src string, perm os.FileMode, mode LinkMode) bool {
if mode == LinkHardlink && linkSourceHasPerm(src, perm) && linkAt(src, dir, name) == nil {
return true
}
return cloneAt(src, dir, name, perm) == nil
}
// linkSourceHasPerm reports whether src is a regular file that already
// carries perm. A hardlink applies only then, because the destination shares
// the source inode and its mode.
func linkSourceHasPerm(src string, perm os.FileMode) bool {
info, err := os.Lstat(src)
return err == nil && info.Mode().IsRegular() && info.Mode().Perm() == perm
}
//go:build linux
package fsutil
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
// cloneAt creates name in dir as a copy-on-write clone of src with perm. It
// reports an error and leaves name absent when the filesystem cannot clone.
func cloneAt(src string, dir *os.File, name string, perm os.FileMode) error {
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
fd, err := unix.Openat(
int(dir.Fd()),
name,
unix.O_CREAT|unix.O_EXCL|unix.O_WRONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC,
0o600,
)
if err != nil {
return err
}
target := os.NewFile(uintptr(fd), name)
err = unix.IoctlFileClone(fd, int(source.Fd()))
if err == nil {
err = target.Chmod(perm)
}
if err = errors.Join(err, target.Close()); err != nil {
return errors.Join(err, unix.Unlinkat(int(dir.Fd()), name, 0))
}
return nil
}
//go:build unix
package fsutil
import (
"os"
"golang.org/x/sys/unix"
)
// linkAt creates name in dir as a hardlink of src. name must be absent.
func linkAt(src string, dir *os.File, name string) error {
return unix.Linkat(unix.AT_FDCWD, src, int(dir.Fd()), name, 0)
}
// hardlinkSharesInode reports whether LinkHardlink can deploy a destination
// that shares the stored inode on this platform.
const hardlinkSharesInode = true
package fsutil
import (
"errors"
"fmt"
"os"
)
var ErrLocked = errors.New("file is locked")
// FileLock owns its file until Close. Do not copy a lock or close it concurrently.
type FileLock struct {
file *os.File
flush bool
}
// FlushOnClose makes Close Flush the device of the lock file before it
// releases the lock, so the writes of an owner that reports success survive
// a power loss. Writes under the lock then need only Barrier.
func (l *FileLock) FlushOnClose() *FileLock {
l.flush = true
return l
}
// LockFile waits for exclusive ownership of a private lock file.
func LockFile(path string) (*FileLock, error) {
return openLock(path, true)
}
// TryLockFile returns ErrLocked instead of waiting for another owner.
func TryLockFile(path string) (*FileLock, error) {
return openLock(path, false)
}
func openLock(path string, wait bool) (*FileLock, error) {
file, err := openLockFile(path)
if err != nil {
return nil, fmt.Errorf("open lock: %w", err)
}
return LockOpenedFile(file, wait)
}
// LockOpenedFile takes ownership of file even if acquisition fails.
func LockOpenedFile(file *os.File, wait bool) (*FileLock, error) {
if err := lockFile(file, wait); err != nil {
return nil, errors.Join(err, file.Close())
}
return &FileLock{file: file}, nil
}
func (l *FileLock) Close() error {
if l == nil || l.file == nil {
return nil
}
file := l.file
l.file = nil
var flushErr error
if l.flush {
flushErr = Flush(file)
}
return errors.Join(flushErr, unlockFile(file), file.Close())
}
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
package fsutil
import (
"errors"
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
func openLockFile(path string) (*os.File, error) {
return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
}
func lockFile(file *os.File, wait bool) error {
flags := unix.LOCK_EX
if !wait {
flags |= unix.LOCK_NB
}
err := unix.Flock(int(file.Fd()), flags)
if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) {
return fmt.Errorf("lock file: %w: %w", ErrLocked, err)
}
return err
}
func unlockFile(file *os.File) error {
return unix.Flock(int(file.Fd()), unix.LOCK_UN)
}
func renameRoot(root *os.Root, from, to string, replace bool) error {
if !replace {
if err := root.Link(from, to); err != nil {
return fmt.Errorf("publish absent name in root: %w", err)
}
if err := syncRenameChain(root, to); err != nil {
return err
}
if err := root.Remove(from); err != nil {
return err
}
return syncRenameChain(root, from)
}
if err := root.Rename(from, to); err != nil {
return fmt.Errorf("rename in root: %w", err)
}
return syncRenameChain(root, from, to)
}
func renameDirRoot(root *os.Root, from, to string) error {
if err := root.Rename(from, to); err != nil {
return fmt.Errorf("rename directory in root: %w", err)
}
return syncRenameChain(root, from, to)
}
// sameDevice reports whether both paths live on one filesystem, so that a
// staged copy reaches its destination through a rename. When either path
// cannot be stated, it reports false and the publish stages beside the
// destination instead, which is always on the destination filesystem.
func sameDevice(first, second string) bool {
var firstStat, secondStat unix.Stat_t
if err := unix.Stat(first, &firstStat); err != nil {
return false
}
if err := unix.Stat(second, &secondStat); err != nil {
return false
}
return firstStat.Dev == secondStat.Dev
}
// syncRenameChain flushes the directory entries that a rename changes: the
// parent directories of both endpoints and every directory from those parents
// up to root.
func syncRenameChain(root *os.Root, names ...string) error {
var resultErr error
for _, name := range names {
for dir := filepath.Dir(name); ; dir = filepath.Dir(dir) {
resultErr = errors.Join(resultErr, syncDir(root, dir))
if dir == "." {
break
}
}
}
return resultErr
}
func syncDir(root *os.Root, dir string) error {
file, err := root.OpenFile(dir, os.O_RDONLY, 0)
if err != nil {
return fmt.Errorf("open directory for sync: %w", err)
}
var resultErr error
if err := Barrier(file); err != nil {
resultErr = fmt.Errorf("sync directory: %w", err)
}
if err := file.Close(); err != nil {
resultErr = errors.Join(resultErr, fmt.Errorf("close directory: %w", err))
}
return resultErr
}
func makePrivateDirectories(path string, missing []string) error {
if err := os.MkdirAll(path, 0o700); err != nil {
return err
}
for _, directory := range missing {
parent, err := os.Open(filepath.Dir(directory))
if err != nil {
return err
}
syncErr := Barrier(parent)
closeErr := parent.Close()
if syncErr != nil || closeErr != nil {
return errors.Join(syncErr, closeErr)
}
}
return nil
}
package fsutil
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"math"
)
// MaxZipEntryBytes is the upper bound for reading a single entry from a JAR/ZIP
// when the full payload is required for parsing (metadata descriptors).
const MaxZipEntryBytes = 32 * 1024 * 1024
// MaxNestedZipEntryBytes is the upper bound for reading a ZIP entry that
// embeds another archive, such as a nested JAR or an installer payload.
const MaxNestedZipEntryBytes = 128 * 1024 * 1024
// ReadZipEntry returns the contents of the named entry. found reports whether
// the archive carries that entry. An entry declared larger than maxBytes fails
// before decompression starts; maxBytes <= 0 disables the bound.
func ReadZipEntry(
z *zip.Reader,
name string,
maxBytes int64,
) (data []byte, found bool, err error) {
for _, f := range z.File {
if f.Name != name {
continue
}
if maxBytes > 0 && f.UncompressedSize64 > uint64(maxBytes) {
return nil, true, fmt.Errorf(
"zip entry %s exceeds %d bytes",
name,
maxBytes,
)
}
r, err := f.Open()
if err != nil {
return nil, true, err
}
data, readErr := CopyBytes(r, maxBytes)
return data, true, errors.Join(readErr, r.Close())
}
return nil, false, nil
}
// CopyBytes reads r into memory. A positive maxBytes rejects larger streams.
func CopyBytes(r io.Reader, maxBytes int64) ([]byte, error) {
limited := r
if maxBytes > 0 {
limited = io.LimitReader(r, min(maxBytes, math.MaxInt64-1)+1)
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, limited); err != nil {
return nil, err
}
if maxBytes > 0 && int64(buf.Len()) > maxBytes {
return nil, fmt.Errorf("read exceeded %d bytes", maxBytes)
}
return buf.Bytes(), nil
}
//go:build !darwin
package fsutil
import "os"
// Barrier persists the writes to file before it returns. Platforms other
// than darwin have no cheaper ordering-only primitive.
func Barrier(file *os.File) error {
return file.Sync()
}
// Flush has no work because every Barrier is already durable.
func Flush(file *os.File) error {
return nil
}
package github
import (
"context"
"encoding/json/v2"
"fmt"
"net/http"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/log"
)
// Client fetches GitHub metadata through one configured network cache.
type Client struct {
network *cache.Client
logger *log.Logger
}
// New constructs a GitHub metadata client. network supplies the cached HTTP
// transport; logger may be nil, which records nothing.
func New(network *cache.Client, logger *log.Logger) *Client {
return &Client{network: network, logger: logger}
}
func checkGitHubMessage(data []byte) *GhApiMessage {
var msg *GhApiMessage
err := json.Unmarshal(data, &msg)
if err == nil && msg != nil && msg.Message != "" {
return msg
}
return nil
}
func (c *Client) GetFileFromGitHub(
ctx context.Context,
apiEndpoint string,
) (
err error,
msg *GhApiMessage,
data []byte,
) {
res, err := c.get(ctx, apiEndpoint)
if err != nil {
return err, nil, nil
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("github: request failed: status %d", res.StatusCode), nil, nil
}
data = res.Data
if msg := checkGitHubMessage(data); msg != nil {
return nil, msg, data
}
var item GhItem
err = json.Unmarshal(data, &item)
if err != nil {
return fmt.Errorf("%w: %w", ErrCannotDecode, err), nil, nil
}
res, err = c.get(ctx, item.DownloadUrl)
if err != nil {
return err, nil, nil
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("github: download failed: status %d", res.StatusCode), nil, nil
}
data = res.Data
return nil, nil, data
}
func (c *Client) GetDirectoryFromGitHub(
ctx context.Context,
apiEndpoint string,
) (
err error,
msg *GhApiMessage,
items []GhItem,
) {
res, err := c.get(ctx, apiEndpoint)
if err != nil {
return err, nil, nil
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("github: request failed: status %d", res.StatusCode), nil, nil
}
data := res.Data
if msg := checkGitHubMessage(data); msg != nil {
return nil, msg, nil
}
var decodedItems []GhItem
err = json.Unmarshal(data, &decodedItems)
if err != nil {
return fmt.Errorf("%w: %w", ErrCannotDecode, err), nil, nil
}
return nil, nil, decodedItems
}
func (c *Client) get(
ctx context.Context,
rawURL string,
) (*cache.BytesResponse, error) {
c.logger.Debug("github api: GET " + rawURL)
return c.network.CachedGetRequest(
ctx,
rawURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
}
package github
import (
"net/url"
"strings"
)
// ProxiedDownloadURL prefixes a release asset URL with proxy. A proxy without
// a trailing slash still separates the asset URL from its prefix. An unset
// proxy, or a rawURL outside HTTPS github.com /owner/repository/releases/download/
// paths, returns rawURL unchanged.
func ProxiedDownloadURL(rawURL, proxy string) string {
if proxy == "" || !isReleaseAssetURL(rawURL) {
return rawURL
}
if !strings.HasSuffix(proxy, "/") {
proxy += "/"
}
return proxy + rawURL
}
func isReleaseAssetURL(rawURL string) bool {
u, err := url.Parse(rawURL)
if err != nil || u.Scheme != "https" || !strings.EqualFold(u.Hostname(), "github.com") {
return false
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
return len(parts) >= 6 &&
parts[0] != "" &&
parts[1] != "" &&
parts[2] == "releases" &&
parts[3] == "download" &&
parts[4] != "" &&
parts[5] != ""
}
// Package importpack reads external server modpack sources into a staging tree.
package importpack
import (
"context"
"errors"
"fmt"
"io/fs"
"path/filepath"
"sort"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/server"
)
// Format identifies the source layout detected from archive contents.
type Format string
const (
FormatMrpack Format = "mrpack"
FormatTree Format = "tree"
)
// Plan describes a source before or after materialization.
//
// ServerFiles counts the files written to the destination, Overrides counts
// those taken from override folders, and Bytes sums their sizes. Tree sources
// leave Minecraft, Product, and CoreVersion empty; discovery determines them
// after materialization.
type Plan struct {
Format Format
Name string
VersionID string
Minecraft string
Product server.Product
CoreVersion string
ServerFiles int
SkippedClient int
Overrides int
Bytes int64
}
// Result reports what Materialize wrote and what it intentionally skipped.
// Skipped lists the source paths of client-only entries that were not written.
type Result struct {
Plan
Skipped []string
overridePaths map[string]struct{}
}
// RecordClientOnlyRemoval updates the counts after the caller removes files
// that had been materialized but cannot run on a dedicated server.
func (r *Result) RecordClientOnlyRemoval(paths []string) {
r.SkippedClient += len(paths)
r.ServerFiles -= len(paths)
r.Skipped = append(r.Skipped, paths...)
for _, path := range paths {
if _, ok := r.overridePaths[path]; ok {
r.Overrides--
delete(r.overridePaths, path)
}
}
}
// Progress receives facts about the downloads Materialize performs. Every hook
// is optional: a nil hook reports nothing. ReportDone runs after the file is
// verified and written, fromCache when no bytes crossed the network.
// Materialize may transfer independent files at once. It calls the hooks one at
// a time, and the events of one file keep their order, but events of different
// files interleave.
type Progress struct {
FileStarted func(name string, size int64)
FileProgress func(name string, read, total int64)
FileDone func(name string, fromCache bool)
}
func (p Progress) ReportStarted(name string, size int64) {
if p.FileStarted != nil {
p.FileStarted(name, size)
}
}
func (p Progress) ReportProgress(name string, read, total int64) {
if p.FileProgress != nil {
p.FileProgress(name, read, total)
}
}
func (p Progress) ReportDone(name string, fromCache bool) {
if p.FileDone != nil {
p.FileDone(name, fromCache)
}
}
// FormatError reports an archive whose contents are not a supported server
// source. Reason is user-facing and should name the observed format.
type FormatError struct {
Kind string
Reason string
}
func (e *FormatError) Error() string {
if e.Kind == "" {
return e.Reason
}
return fmt.Sprintf("%s: %s", e.Kind, e.Reason)
}
// Inspect detects the source format and reads declarative metadata without
// writing or downloading anything.
func Inspect(ctx context.Context, path string) (*Plan, error) {
return inspect(ctx, path)
}
// Materialize writes the server-side contents of path into dest. Unix file
// modes are sanitized; symlinks, devices, and paths escaping dest are
// rejected. network may be nil only when the source needs no downloads.
// progress may be zero; its hooks stay silent.
func Materialize(
ctx context.Context,
path, dest string,
network *cache.Client,
progress Progress,
) (*Result, error) {
return materialize(ctx, path, dest, network, progress)
}
const (
kindUnsupportedArchive = "unsupported archive"
kindClientPack = "client pack"
kindLauncherInstance = "launcher instance"
kindWorldOnly = "world-only archive"
kindUnrecognized = "unrecognized source"
kindInvalidModpack = "invalid modpack"
)
// Fixed import limits. A source beyond one of them is rejected before any
// file past the limit is written.
const (
// MaxSourceBytes is the largest archive an import accepts.
MaxSourceBytes int64 = 4 << 30
maxExtractedBytes int64 = 8 << 30
maxFileBytes int64 = 2 << 30
maxEntries = 50000
maxPathBytes = 1024
maxPathDepth = 32
maxMetadataBytes int64 = 16 << 20
)
var (
// ErrUnsafeEntry reports an archive path or entry type that could escape
// the destination or create a link.
ErrUnsafeEntry = errors.New("unsafe archive entry")
// ErrLimitExceeded reports a source beyond a fixed import limit.
ErrLimitExceeded = errors.New("import limit exceeded")
)
// Layers rank sources of the same destination path. A higher layer replaces a
// lower layer's file; within one layer a path may appear only once.
const (
layerBase = iota
layerOverrides
layerServerOverrides
)
// item is one directory or file planned for the destination.
type item struct {
rel string
dir bool
implicit bool
mode fs.FileMode
size int64
layer int
ordinal int
download *mrpackFile
}
// layout is a validated, ordered plan ready for materialization.
type layout struct {
plan Plan
items []*item
skipped []string
downloads int
}
func newLayout(items []*item, skipped []string) (*layout, error) {
lay := &layout{items: items, skipped: skipped}
for _, it := range items {
if it.dir {
continue
}
if it.size > maxFileBytes {
return nil, limitError(
"%s is %d bytes, above the %d byte file limit",
it.rel,
it.size,
maxFileBytes,
)
}
lay.plan.ServerFiles++
lay.plan.Bytes += it.size
if it.layer != layerBase {
lay.plan.Overrides++
}
if it.download != nil {
lay.downloads++
}
}
if lay.plan.Bytes > maxExtractedBytes {
return nil, limitError(
"server files total %d bytes, above the %d byte limit",
lay.plan.Bytes,
maxExtractedBytes,
)
}
lay.plan.SkippedClient = len(skipped)
return lay, nil
}
// pathTable holds every planned destination path, keyed by its case-folded
// form, so that case-only collisions and file/directory conflicts are caught.
type pathTable struct {
byKey map[string]*item
}
func newPathTable() *pathTable {
return &pathTable{byKey: map[string]*item{}}
}
// add places it in the table. It reports superseded when a higher layer
// already holds a file at the same path, in which case nothing is recorded.
func (t *pathTable) add(it *item) (bool, error) {
if err := checkDestPath(it.rel); err != nil {
return false, err
}
parts := strings.Split(it.rel, "/")
for i := 1; i < len(parts); i++ {
if err := t.addAncestor(strings.Join(parts[:i], "/"), it.layer); err != nil {
return false, err
}
}
key := foldKey(it.rel)
existing, ok := t.byKey[key]
if !ok {
t.byKey[key] = it
return false, nil
}
if existing.rel != it.rel {
return false, collision(it.rel, existing.rel)
}
switch {
case existing.dir && it.dir:
if existing.implicit {
t.byKey[key] = it
}
return false, nil
case !existing.dir && !it.dir && existing.layer > it.layer:
return true, nil
case !existing.dir && !it.dir:
return false, fmt.Errorf("%w: %q appears more than once", ErrUnsafeEntry, it.rel)
}
return false, fmt.Errorf("%w: %q is both a file and a directory", ErrUnsafeEntry, it.rel)
}
func (t *pathTable) addAncestor(rel string, layer int) error {
key := foldKey(rel)
existing, ok := t.byKey[key]
if !ok {
t.byKey[key] = &item{
rel: rel,
dir: true,
implicit: true,
mode: dirMode,
layer: layer,
ordinal: -1,
}
return nil
}
if existing.rel != rel {
return collision(rel, existing.rel)
}
if !existing.dir {
return fmt.Errorf("%w: %q is both a file and a directory", ErrUnsafeEntry, rel)
}
return nil
}
// items returns the explicit directories and files in path order. Parent
// directories that no entry names explicitly are created on demand.
func (t *pathTable) items() []*item {
var out []*item
for _, it := range t.byKey {
if !it.implicit {
out = append(out, it)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].rel < out[j].rel })
return out
}
func foldKey(rel string) string {
return strings.ToLower(rel)
}
func collision(rel, other string) error {
return fmt.Errorf("%w: %q collides with %q", ErrUnsafeEntry, rel, other)
}
// checkDestPath validates a normalized, slash-separated destination path.
func checkDestPath(rel string) error {
if len(rel) > maxPathBytes {
return limitError("path is longer than %d bytes: %q", maxPathBytes, rel)
}
if depth := strings.Count(rel, "/") + 1; depth > maxPathDepth {
return limitError("path %q is %d levels deep, above the %d level limit", rel, depth, maxPathDepth)
}
first, _, _ := strings.Cut(rel, "/")
if strings.EqualFold(first, fsutil.WorkspaceMarker) {
return fmt.Errorf("%w: %q targets reserved workspace metadata", ErrUnsafeEntry, rel)
}
if strings.EqualFold(first, document.ManifestFilename) ||
strings.EqualFold(first, document.LockFilename) {
return fmt.Errorf(
"%w: %q is a Lucy workspace document; import the tree without it",
ErrUnsafeEntry,
rel,
)
}
if err := document.SafeRelativePath(filepath.FromSlash(rel)); err != nil {
return fmt.Errorf("%w: %v", ErrUnsafeEntry, err)
}
return nil
}
func parentRel(rel string) string {
if i := strings.LastIndex(rel, "/"); i >= 0 {
return rel[:i]
}
return ""
}
func newFormatError(kind, format string, args ...any) *FormatError {
return &FormatError{Kind: kind, Reason: fmt.Sprintf(format, args...)}
}
func limitError(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrLimitExceeded, fmt.Sprintf(format, args...))
}
package importpack
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"context"
"encoding/binary"
"encoding/json/v2"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/internal/fsutil"
)
const dirMode fs.FileMode = 0o755
type containerKind uint8
const (
containerZip containerKind = iota + 1
containerTarGzip
)
func (k containerKind) String() string {
if k == containerZip {
return "zip"
}
return "tar.gz"
}
// archive is an opened source container whose entries passed the safety and
// limit checks of scan.
type archive struct {
path string
stem string
container containerKind
mrpack bool
file *os.File
zip *zip.Reader
entries []entry
// budget bounds the body bytes a tar scan may drain before it rejects.
budget int64
}
// entry is one file or directory of a source. name keeps any wrapper
// directory; rel is the path relative to the source root once the wrapper is
// removed. Entries that name only the wrapper itself are dropped.
type entry struct {
ordinal int
name string
rel string
dir bool
size int64
exec bool
}
// visited is one container header as read by visit, before wrapper removal.
type visited struct {
name string
dir bool
size int64
exec bool
}
type visitFunc func(ordinal int, v visited, body io.Reader) error
// serverRootFiles and serverRootDirs mark a directory as a server installation
// when they appear at the source root.
var serverRootFiles = map[string]bool{
"server.properties": true,
"eula.txt": true,
"ops.json": true,
"whitelist.json": true,
"banned-ips.json": true,
"banned-players.json": true,
"usercache.json": true,
"bukkit.yml": true,
"spigot.yml": true,
"paper-global.yml": true,
"server-icon.png": true,
"user_jvm_args.txt": true,
"start.sh": true,
"start.bat": true,
"run.sh": true,
"run.bat": true,
}
var serverRootDirs = []string{"mods", "plugins", "config", "libraries"}
func inspect(ctx context.Context, path string) (*Plan, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
a, err := openArchive(ctx, path)
if err != nil {
return nil, err
}
defer a.file.Close()
lay, err := buildLayout(a)
if err != nil {
return nil, err
}
plan := lay.plan
return &plan, nil
}
func materialize(
ctx context.Context,
path, dest string,
network *cache.Client,
progress Progress,
) (*Result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
a, err := openArchive(ctx, path)
if err != nil {
return nil, err
}
defer a.file.Close()
lay, err := buildLayout(a)
if err != nil {
return nil, err
}
if lay.downloads > 0 && network == nil {
return nil, fmt.Errorf(
"%s needs %d downloads, but no network client was provided",
filepath.Base(path),
lay.downloads,
)
}
m, err := newMaterializer(ctx, dest, network, progress)
if err != nil {
return nil, err
}
defer m.cleanup()
if err := m.run(a, lay); err != nil {
return nil, err
}
plan := lay.plan
plan.Bytes = m.budget.total()
result := &Result{Plan: plan, Skipped: lay.skipped}
if plan.Overrides > 0 {
result.overridePaths = make(map[string]struct{}, plan.Overrides)
for _, item := range lay.items {
if !item.dir && item.layer != layerBase {
result.overridePaths[item.rel] = struct{}{}
}
}
}
return result, nil
}
// openArchive checks the extension, the content signature, and the source size
// before scanning entries. The caller must close the returned archive's file.
func openArchive(ctx context.Context, path string) (*archive, error) {
base := filepath.Base(path)
lower := strings.ToLower(base)
a := &archive{path: path, budget: maxExtractedBytes}
var suffix string
switch {
case strings.HasSuffix(lower, ".tar.gz"):
a.container, suffix = containerTarGzip, ".tar.gz"
case strings.HasSuffix(lower, ".mrpack"):
a.container, suffix, a.mrpack = containerZip, ".mrpack", true
case strings.HasSuffix(lower, ".zip"):
a.container, suffix = containerZip, ".zip"
default:
container, err := sniffContainer(path)
if err != nil {
return nil, err
}
a.container = container
suffix = ""
}
a.stem = base[:len(base)-len(suffix)]
file, err := os.Open(path)
if err != nil {
return nil, err
}
a.file = file
if err := a.open(ctx); err != nil {
return nil, errors.Join(err, file.Close())
}
return a, nil
}
func (a *archive) open(ctx context.Context) error {
info, err := a.file.Stat()
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", a.path)
}
if info.Size() > MaxSourceBytes {
return limitError(
"%s is %d bytes, above the %d byte source limit",
a.path,
info.Size(),
MaxSourceBytes,
)
}
magic := make([]byte, 4)
n, _ := io.ReadFull(a.file, magic)
if !a.matchesMagic(magic[:n]) {
return newFormatError(
kindUnsupportedArchive,
"%s has a %s extension but its contents are not a %s archive",
filepath.Base(a.path),
a.container,
a.container,
)
}
if _, err := a.file.Seek(0, io.SeekStart); err != nil {
return err
}
if a.container == containerZip {
// The archive reader allocates one structure per entry the central
// directory declares, so the entry limit applies before it parses.
if entries, ok := zipDirectoryEntries(a.file, info.Size()); ok &&
entries > uint64(maxEntries) {
return limitError("archive has more than %d entries", maxEntries)
}
reader, err := zip.NewReader(a.file, info.Size())
if err != nil {
return fmt.Errorf("read zip archive %s: %w", a.path, err)
}
a.zip = reader
}
return a.scan(ctx)
}
func (a *archive) matchesMagic(magic []byte) bool {
switch a.container {
case containerZip:
return bytes.HasPrefix(magic, []byte("PK\x03\x04")) ||
bytes.HasPrefix(magic, []byte("PK\x05\x06"))
case containerTarGzip:
return bytes.HasPrefix(magic, []byte{0x1f, 0x8b})
}
return false
}
// zipDirectoryEntries reports how many entries a zip central directory
// declares. The end record holds the count unless the archive is too large for
// it, in which case the ZIP64 record holds it. A directory this scan cannot
// read reports false, leaving the archive reader to describe the input.
func zipDirectoryEntries(file *os.File, size int64) (uint64, bool) {
const (
endRecordSize = 22
maxCommentSize = 0xffff
zip64LocatorMax = 20
zip64RecordSize = 56
endRecordSig = 0x06054b50
zip64LocatorSig = 0x07064b50
zip64RecordSig = 0x06064b50
)
tailSize := min(size, int64(endRecordSize+maxCommentSize))
if tailSize < endRecordSize {
return 0, false
}
tail := make([]byte, tailSize)
if _, err := file.ReadAt(tail, size-tailSize); err != nil {
return 0, false
}
position := bytes.LastIndex(tail, []byte("PK\x05\x06"))
if position < 0 || len(tail)-position < endRecordSize {
return 0, false
}
record := tail[position:]
if binary.LittleEndian.Uint32(record) != endRecordSig {
return 0, false
}
entries := uint64(binary.LittleEndian.Uint16(record[10:12]))
locatorStart := position - zip64LocatorMax
if locatorStart < 0 {
return entries, true
}
locator := tail[locatorStart:]
if binary.LittleEndian.Uint32(locator) != zip64LocatorSig {
return entries, true
}
counted := make([]byte, zip64RecordSize)
offset := binary.LittleEndian.Uint64(locator[8:16])
if _, err := file.ReadAt(counted, int64(offset)); err != nil {
return entries, true
}
if binary.LittleEndian.Uint32(counted) != zip64RecordSig {
return entries, true
}
return binary.LittleEndian.Uint64(counted[32:40]), true
}
// scan validates every entry name and removes a single wrapper directory.
func (a *archive) scan(ctx context.Context) error {
var raw []entry
err := a.visit(ctx, false, func(ordinal int, v visited, _ io.Reader) error {
name, err := normalizeEntryName(v.name)
if err != nil {
return fmt.Errorf("entry %q: %w", v.name, err)
}
if name == "" {
return nil
}
raw = append(raw, entry{
ordinal: ordinal,
name: name,
dir: v.dir,
size: v.size,
exec: v.exec,
})
return nil
})
if err != nil {
return err
}
strip := wrapperRoot(raw)
a.entries = nil
for _, e := range raw {
e.rel = stripWrapper(e.name, strip)
if e.rel == "" {
continue
}
a.entries = append(a.entries, e)
}
return nil
}
// normalizeEntryName returns the slash-separated form of an archive name, or
// the empty string for the archive root. It rejects absolute, drive-qualified,
// backslash, and parent-traversing names.
func normalizeEntryName(raw string) (string, error) {
if raw == "" {
return "", fmt.Errorf("%w: empty path", ErrUnsafeEntry)
}
if strings.ContainsAny(raw, "\\\x00") {
return "", fmt.Errorf("%w: %q contains a backslash or NUL", ErrUnsafeEntry, raw)
}
if len(raw) > maxPathBytes {
return "", limitError("archive path is longer than %d bytes", maxPathBytes)
}
if strings.Count(raw, "/")+1 > maxPathDepth {
return "", limitError("archive path is deeper than %d components", maxPathDepth)
}
if strings.HasPrefix(raw, "/") {
return "", fmt.Errorf("%w: %q is absolute", ErrUnsafeEntry, raw)
}
if len(raw) >= 2 && isASCIILetter(raw[0]) && raw[1] == ':' {
return "", fmt.Errorf("%w: %q is drive-qualified", ErrUnsafeEntry, raw)
}
var parts []string
for _, part := range strings.Split(raw, "/") {
switch part {
case "", ".":
continue
case "..":
return "", fmt.Errorf("%w: %q escapes the source root", ErrUnsafeEntry, raw)
}
parts = append(parts, part)
}
return strings.Join(parts, "/"), nil
}
func isASCIILetter(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
// wrapperRoot returns the one top-level directory that holds every entry, or
// the empty string when the source has root files or several top levels.
func wrapperRoot(entries []entry) string {
top := ""
nested := false
for _, e := range entries {
first, _, hasChild := strings.Cut(e.name, "/")
if top == "" {
top = first
} else if first != top {
return ""
}
if !hasChild && !e.dir {
return ""
}
if hasChild {
nested = true
}
}
if !nested {
return ""
}
if serverRootDir(top) && !wrapsServerRoot(entries, top) {
// The lone folder is itself a server root, as a mods or plugins folder
// of jars is. Stripping it would scatter its files across the root.
return ""
}
return top
}
// wrapsServerRoot reports whether a lone top-level folder holds a server root
// at its own top level. A config folder that holds server.properties wraps one;
// a mods folder of jars does not.
func wrapsServerRoot(entries []entry, wrapper string) bool {
prefix := wrapper + "/"
for _, e := range entries {
rest, ok := strings.CutPrefix(e.name, prefix)
if !ok {
continue
}
child, _, _ := strings.Cut(rest, "/")
if serverRootFiles[child] || serverRootDir(child) {
return true
}
}
return false
}
// serverRootDir reports whether name is a directory that marks a server root.
func serverRootDir(name string) bool {
return slices.Contains(serverRootDirs, name)
}
func stripWrapper(name, wrapper string) string {
if wrapper == "" {
return name
}
if name == wrapper {
return ""
}
return strings.TrimPrefix(name, wrapper+"/")
}
// visit calls fn for every entry in container order. Bodies are readable only
// while fn runs, and only when read is true.
func (a *archive) visit(ctx context.Context, read bool, fn visitFunc) error {
if a.zip != nil {
return a.visitZip(ctx, read, fn)
}
return a.visitTar(ctx, read, fn)
}
func (a *archive) visitZip(ctx context.Context, read bool, fn visitFunc) error {
for i, f := range a.zip.File {
if err := ctx.Err(); err != nil {
return err
}
if i >= maxEntries {
return limitError("archive has more than %d entries", maxEntries)
}
mode := f.Mode()
dir := mode.IsDir() || strings.HasSuffix(f.Name, "/")
if mode.Type()&^fs.ModeDir != 0 {
return fmt.Errorf(
"%w: %q has special type %v; links, devices, and FIFOs are rejected",
ErrUnsafeEntry,
f.Name,
mode.Type(),
)
}
v := visited{name: f.Name, dir: dir, exec: mode.Perm()&0o111 != 0}
if !dir {
if f.UncompressedSize64 > uint64(maxFileBytes) {
return limitError(
"%q is %d bytes, above the %d byte file limit",
f.Name,
f.UncompressedSize64,
maxFileBytes,
)
}
v.size = int64(f.UncompressedSize64)
}
if !read || dir {
if err := fn(i, v, nil); err != nil {
return err
}
continue
}
if err := visitZipBody(f, i, v, fn); err != nil {
return err
}
}
return nil
}
func visitZipBody(f *zip.File, ordinal int, v visited, fn visitFunc) error {
r, err := f.Open()
if err != nil {
return fmt.Errorf("open %q: %w", f.Name, err)
}
fnErr := fn(ordinal, v, r)
return errors.Join(fnErr, r.Close())
}
func (a *archive) visitTar(ctx context.Context, read bool, fn visitFunc) error {
if _, err := a.file.Seek(0, io.SeekStart); err != nil {
return err
}
gz, err := gzip.NewReader(ctxReader{ctx: ctx, r: a.file})
if err != nil {
return fmt.Errorf("read gzip stream: %w", err)
}
defer gz.Close()
tr := tar.NewReader(gz)
ordinal := 0
// declared sums regular-file header sizes. It is checked after each header
// and before tr.Next drains that entry's body, so the scan drains at most
// budget bytes of bodies.
var declared int64
for {
if err := ctx.Err(); err != nil {
return err
}
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return fmt.Errorf("read tar archive: %w", err)
}
var v visited
switch hdr.Typeflag {
case tar.TypeXGlobalHeader:
continue
case tar.TypeDir:
v.dir = true
case tar.TypeReg, '\x00':
if hdr.Size < 0 || hdr.Size > maxFileBytes {
return limitError(
"%q is %d bytes, above the %d byte file limit",
hdr.Name,
hdr.Size,
maxFileBytes,
)
}
declared += hdr.Size
if declared > a.budget {
return limitError(
"%s declares more than %d extracted bytes",
a.path,
a.budget,
)
}
v.size = hdr.Size
default:
return fmt.Errorf(
"%w: %q has special type %q; links, devices, and FIFOs are rejected",
ErrUnsafeEntry,
hdr.Name,
hdr.Typeflag,
)
}
if ordinal >= maxEntries {
return limitError("archive has more than %d entries", maxEntries)
}
v.name = hdr.Name
v.exec = hdr.Mode&0o111 != 0
var body io.Reader
if read && !v.dir {
body = tr
}
if err := fn(ordinal, v, body); err != nil {
return err
}
ordinal++
}
}
// ctxReader fails each read once ctx is done, so decompression stops at the
// next read after cancellation.
type ctxReader struct {
ctx context.Context
r io.Reader
}
func (c ctxReader) Read(p []byte) (int, error) {
if err := c.ctx.Err(); err != nil {
return 0, err
}
return c.r.Read(p)
}
// readEntry returns the body of a zip entry no larger than limit.
func (a *archive) readEntry(e entry, limit int64) ([]byte, error) {
if a.zip == nil {
return nil, fmt.Errorf("%s: metadata is read only from zip archives", e.rel)
}
f := a.zip.File[e.ordinal]
if f.UncompressedSize64 > uint64(limit) {
return nil, limitError("%s is %d bytes, above the %d byte metadata limit", e.rel, f.UncompressedSize64, limit)
}
r, err := f.Open()
if err != nil {
return nil, fmt.Errorf("open %s: %w", e.rel, err)
}
data, readErr := fsutil.CopyBytes(r, limit)
return data, errors.Join(readErr, r.Close())
}
// extract streams the bodies of the wanted entries to write. Zip entries are
// independent and run through the bounded file workers in container order; a
// tar body is one stream and stays serial.
func (a *archive) extract(
ctx context.Context,
wanted map[int]*item,
write func(context.Context, *item, io.Reader) error,
) error {
if a.zip == nil {
found := 0
err := a.visit(ctx, true, func(ordinal int, _ visited, body io.Reader) error {
it, ok := wanted[ordinal]
if !ok {
return nil
}
found++
return write(ctx, it, body)
})
if err != nil {
return err
}
if found != len(wanted) {
return fmt.Errorf("%s changed between scans: found %d of %d files", a.path, found, len(wanted))
}
return nil
}
ordered := make([]*item, 0, len(wanted))
for _, e := range a.entries {
if it, ok := wanted[e.ordinal]; ok {
ordered = append(ordered, it)
}
}
if len(ordered) != len(wanted) {
return fmt.Errorf("%s changed between scans: found %d of %d files", a.path, len(ordered), len(wanted))
}
return runFileJobs(ctx, len(ordered), func(ctx context.Context, index int) error {
it := ordered[index]
f := a.zip.File[it.ordinal]
r, err := f.Open()
if err != nil {
return fmt.Errorf("open %q: %w", f.Name, err)
}
writeErr := write(ctx, it, r)
return errors.Join(writeErr, r.Close())
})
}
func (a *archive) rootFile(name string) (entry, bool) {
for _, e := range a.entries {
if e.rel == name && !e.dir {
return e, true
}
}
return entry{}, false
}
func (a *archive) hasPrefix(prefix string) bool {
for _, e := range a.entries {
if strings.HasPrefix(e.rel, prefix) {
return true
}
}
return false
}
func (a *archive) hasRootDir(name string) bool {
for _, e := range a.entries {
if (e.dir && e.rel == name) || strings.HasPrefix(e.rel, name+"/") {
return true
}
}
return false
}
func (a *archive) hasServerFiles() bool {
for _, e := range a.entries {
if e.dir || strings.Contains(e.rel, "/") {
continue
}
if serverRootFiles[e.rel] || strings.HasSuffix(strings.ToLower(e.rel), ".jar") {
return true
}
}
for _, dir := range serverRootDirs {
if a.hasRootDir(dir) {
return true
}
}
return false
}
func (a *archive) hasWorldFiles() bool {
if _, ok := a.rootFile("level.dat"); ok {
return true
}
return a.hasRootDir("region") || a.hasRootDir("playerdata")
}
func classify(a *archive) (Format, error) {
name := filepath.Base(a.path)
if _, ok := a.rootFile(modrinthIndexName); ok {
if a.container != containerZip {
return "", newFormatError(
kindInvalidModpack,
"%s contains %s, but Modrinth modpacks must be .mrpack (zip) archives",
name,
modrinthIndexName,
)
}
return FormatMrpack, nil
}
if err := a.rejectClientSource(); err != nil {
return "", err
}
if a.mrpack {
return "", newFormatError(kindInvalidModpack, "%s has no %s at its root", name, modrinthIndexName)
}
if a.hasServerFiles() {
return FormatTree, nil
}
if a.hasWorldFiles() {
return "", newFormatError(
kindWorldOnly,
"%s holds world data but no server files; include the server jar, server.properties, or the mods, plugins, or config folders",
name,
)
}
return "", newFormatError(
kindUnrecognized,
"%s has no recognizable server files at its root; expected a server jar, server.properties, eula.txt, or a mods, plugins, or config folder",
name,
)
}
// rejectClientSource reports client modpacks, launcher instance exports, and
// override folders that lack a Modrinth index.
func (a *archive) rejectClientSource() error {
name := filepath.Base(a.path)
if e, ok := a.rootFile("manifest.json"); ok && a.zip != nil {
data, err := a.readEntry(e, maxMetadataBytes)
if err != nil {
return err
}
if isCurseForgeManifest(data) {
return newFormatError(
kindClientPack,
"%s is a CurseForge client pack (manifest.json). lucy imports server packs, not client packs. Export a server pack from the launcher, or archive the server folder itself",
name,
)
}
}
if a.hasPrefix(mrpackOverridesPrefix) {
return newFormatError(
kindClientPack,
"%s has an overrides/ folder and no %s, which marks a client modpack. Export a server pack from the launcher, or archive the server folder itself",
name,
modrinthIndexName,
)
}
for _, marker := range []string{"mmc-pack.json", "instance.cfg"} {
if _, ok := a.rootFile(marker); ok {
return newFormatError(
kindLauncherInstance,
"%s is a launcher instance export (%s). lucy cannot import instances. Export a server pack from the launcher, or archive the server folder itself",
name,
marker,
)
}
}
if a.hasPrefix(mrpackServerOverridesPrefix) || a.hasPrefix(mrpackClientOverridesPrefix) {
return newFormatError(
kindInvalidModpack,
"%s has modpack override folders but no %s",
name,
modrinthIndexName,
)
}
return nil
}
func isCurseForgeManifest(data []byte) bool {
var manifest struct {
ManifestType string `json:"manifestType"`
Overrides string `json:"overrides"`
Files []any `json:"files"`
}
if err := json.Unmarshal(data, &manifest); err != nil {
return false
}
return manifest.ManifestType == "minecraftModpack" ||
(manifest.Overrides != "" && len(manifest.Files) > 0)
}
func buildLayout(a *archive) (*layout, error) {
format, err := classify(a)
if err != nil {
return nil, err
}
if format == FormatMrpack {
return buildMrpackLayout(a)
}
return buildTreeLayout(a)
}
// buildTreeLayout plans every entry of a server tree as written as-is.
func buildTreeLayout(a *archive) (*layout, error) {
table := newPathTable()
for _, e := range a.entries {
if _, err := table.add(entryItem(e, e.rel, layerBase)); err != nil {
return nil, err
}
}
lay, err := newLayout(table.items(), nil)
if err != nil {
return nil, err
}
if lay.plan.ServerFiles == 0 {
return nil, newFormatError(
kindUnrecognized,
"%s contains no server files",
filepath.Base(a.path),
)
}
lay.plan.Format = FormatTree
lay.plan.Name = a.stem
return lay, nil
}
func entryItem(e entry, rel string, layer int) *item {
it := &item{
rel: rel,
dir: e.dir,
mode: fileMode(e.exec),
size: e.size,
layer: layer,
ordinal: e.ordinal,
}
if e.dir {
it.mode = dirMode
it.size = 0
it.ordinal = -1
}
return it
}
// fileMode keeps only the executable bit of a source file.
func fileMode(exec bool) fs.FileMode {
if exec {
return 0o755
}
return 0o644
}
// materializer writes a layout beneath dest through an os.Root, so no write can
// follow a link out of the destination.
type materializer struct {
ctx context.Context
dest string
root *os.Root
stage string
network *cache.Client
progress Progress
progressMu sync.Mutex
budget *byteBudget
}
func newMaterializer(
ctx context.Context,
dest string,
network *cache.Client,
progress Progress,
) (*materializer, error) {
abs, err := filepath.Abs(dest)
if err != nil {
return nil, err
}
if err := prepareDestination(abs); err != nil {
return nil, err
}
root, err := os.OpenRoot(abs)
if err != nil {
return nil, err
}
return &materializer{
ctx: ctx,
dest: abs,
root: root,
network: network,
progress: progress,
budget: &byteBudget{left: maxExtractedBytes},
}, nil
}
// prepareDestination creates dest when absent and refuses a non-empty target,
// so that existing files are never replaced.
func prepareDestination(dest string) error {
info, err := os.Stat(dest)
if errors.Is(err, fs.ErrNotExist) {
return os.MkdirAll(dest, dirMode)
}
if err != nil {
return err
}
if !info.IsDir() {
return fmt.Errorf("destination %s is not a directory", dest)
}
entries, err := os.ReadDir(dest)
if err != nil {
return err
}
if len(entries) > 0 {
return fmt.Errorf("destination %s is not empty", dest)
}
return nil
}
func (m *materializer) cleanup() {
if m.stage != "" {
_ = os.RemoveAll(m.stage)
}
_ = m.root.Close()
}
func (m *materializer) run(a *archive, lay *layout) error {
wanted := make(map[int]*item)
var downloads []*item
for _, it := range lay.items {
if err := m.ctx.Err(); err != nil {
return err
}
if it.dir {
if err := m.ensureDir(it.rel); err != nil {
return err
}
continue
}
// Every parent directory exists before a worker starts, so concurrent
// writers never race on Mkdir and each owns one destination path.
if err := m.ensureDir(parentRel(it.rel)); err != nil {
return err
}
if it.download == nil {
wanted[it.ordinal] = it
} else {
downloads = append(downloads, it)
}
}
if len(downloads) > 0 {
if err := m.ensureStage(); err != nil {
return err
}
}
if err := runFileJobs(m.ctx, len(downloads), func(ctx context.Context, index int) error {
return m.fetch(ctx, downloads[index], index)
}); err != nil {
return err
}
return a.extract(m.ctx, wanted, m.writeFile)
}
func (m *materializer) ensureDir(rel string) error {
if rel == "" {
return nil
}
current := ""
for _, part := range strings.Split(rel, "/") {
if current == "" {
current = part
} else {
current += "/" + part
}
native := filepath.FromSlash(current)
info, err := m.root.Lstat(native)
if err == nil {
if !info.IsDir() {
return fmt.Errorf("%w: %s is not a directory", ErrUnsafeEntry, current)
}
continue
}
if !errors.Is(err, fs.ErrNotExist) {
return err
}
if err := m.root.Mkdir(native, dirMode); err != nil {
return err
}
if err := m.root.Chmod(native, dirMode); err != nil {
return err
}
}
return nil
}
func (m *materializer) writeFile(ctx context.Context, it *item, body io.Reader) error {
if err := ctx.Err(); err != nil {
return err
}
file, err := m.root.OpenFile(
filepath.FromSlash(it.rel),
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0o600,
)
if err != nil {
return fmt.Errorf("create %s: %w", it.rel, err)
}
_, copyErr := io.Copy(file, newChargedReader(ctx, body, m.budget))
chmodErr := file.Chmod(it.mode)
if err := errors.Join(copyErr, chmodErr, file.Close()); err != nil {
return fmt.Errorf("write %s: %w", it.rel, err)
}
return nil
}
func (m *materializer) reportStarted(name string, size int64) {
m.progressMu.Lock()
defer m.progressMu.Unlock()
m.progress.ReportStarted(name, size)
}
func (m *materializer) reportProgress(name string, read, total int64) {
m.progressMu.Lock()
defer m.progressMu.Unlock()
m.progress.ReportProgress(name, read, total)
}
func (m *materializer) reportDone(name string, fromCache bool) {
m.progressMu.Lock()
defer m.progressMu.Unlock()
m.progress.ReportDone(name, fromCache)
}
// ensureStage creates the private staging directory that holds downloads
// before they are renamed into place. It lives inside dest, so the rename never
// crosses a filesystem.
func (m *materializer) ensureStage() error {
if m.stage != "" {
return nil
}
stage, err := os.MkdirTemp(m.dest, ".importpack-stage-")
if err != nil {
return err
}
m.stage = stage
return nil
}
// byteBudget bounds the bytes the destination retains across all sources.
// Workers debit it concurrently, so each operation takes the lock.
type byteBudget struct {
mu sync.Mutex
left int64
used int64
}
func (b *byteBudget) spend(n int64) error {
b.mu.Lock()
defer b.mu.Unlock()
if n > b.left {
return limitError("extraction exceeds the %d byte limit", maxExtractedBytes)
}
b.left -= n
b.used += n
return nil
}
// remaining reports the bytes still available once the files already retained
// are accounted for. Transfers in flight do not debit the budget, so a failing
// attempt never shrinks this bound for another attempt.
func (b *byteBudget) remaining() int64 {
b.mu.Lock()
defer b.mu.Unlock()
return b.left
}
func (b *byteBudget) total() int64 {
b.mu.Lock()
defer b.mu.Unlock()
return b.used
}
// chargedReader debits every byte it returns from the budget before the
// caller can write it, and fails on the first byte beyond a file limit.
type chargedReader struct {
ctx context.Context
r io.Reader
budget *byteBudget
read int64
}
func newChargedReader(ctx context.Context, r io.Reader, budget *byteBudget) *chargedReader {
return &chargedReader{ctx: ctx, r: r, budget: budget}
}
func (c *chargedReader) Read(p []byte) (int, error) {
if err := c.ctx.Err(); err != nil {
return 0, err
}
n, err := c.r.Read(p)
if n == 0 {
return 0, err
}
n64 := int64(n)
if c.read+n64 > maxFileBytes {
return 0, limitError("file exceeds the %d byte file limit", maxFileBytes)
}
if spendErr := c.budget.spend(n64); spendErr != nil {
return 0, spendErr
}
c.read += n64
return n, err
}
func sniffContainer(path string) (containerKind, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
magic := make([]byte, 4)
n, err := io.ReadFull(file, magic)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
return 0, err
}
magic = magic[:n]
switch {
case bytes.HasPrefix(magic, []byte("PK\x03\x04")) || bytes.HasPrefix(magic, []byte("PK\x05\x06")):
return containerZip, nil
case bytes.HasPrefix(magic, []byte{0x1f, 0x8b}):
return containerTarGzip, nil
default:
return 0, newFormatError(
kindUnsupportedArchive,
"%s is not a zip, mrpack, or tar.gz archive",
filepath.Base(path),
)
}
}
package importpack
import (
"context"
"crypto/sha1"
"crypto/sha512"
"encoding/hex"
"encoding/json/v2"
"errors"
"fmt"
"hash"
"io"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/server"
)
const modrinthIndexName = "modrinth.index.json"
const (
mrpackOverridesPrefix = "overrides/"
mrpackServerOverridesPrefix = "server-overrides/"
mrpackClientOverridesPrefix = "client-overrides/"
)
// mrpackOverrideSources lists override folders from highest to lowest priority,
// so a lower-priority file at the same path is dropped before it is written or
// downloaded.
var mrpackOverrideSources = []struct {
prefix string
layer int
}{
{prefix: mrpackServerOverridesPrefix, layer: layerServerOverrides},
{prefix: mrpackOverridesPrefix, layer: layerOverrides},
}
// mrpackLoaderProducts maps a Modrinth dependency key to a server product name.
var mrpackLoaderProducts = map[string]string{
"fabric-loader": "fabric",
"quilt-loader": "quilt",
"forge": "forge",
"neoforge": "neoforge",
}
type mrpackIndex struct {
FormatVersion int `json:"formatVersion"`
Game string `json:"game"`
VersionID string `json:"versionId"`
Name string `json:"name"`
Files []mrpackIndexFile `json:"files"`
Dependencies map[string]string `json:"dependencies"`
}
type mrpackIndexFile struct {
Path string `json:"path"`
Hashes map[string]string `json:"hashes"`
Env map[string]string `json:"env"`
Downloads []string `json:"downloads"`
FileSize int64 `json:"fileSize"`
}
// mrpackFile is a download the index declares for one destination path.
type mrpackFile struct {
urls []string
algorithm cache.HashAlgorithm
digest string
}
func parseMrpackIndex(data []byte) (*mrpackIndex, error) {
var index mrpackIndex
if err := json.Unmarshal(data, &index); err != nil {
return nil, newFormatError(kindInvalidModpack, "%s is not valid JSON: %v", modrinthIndexName, err)
}
if index.FormatVersion != 1 {
return nil, newFormatError(
kindInvalidModpack,
"unsupported %s formatVersion %d; lucy reads version 1",
modrinthIndexName,
index.FormatVersion,
)
}
if index.Game != "minecraft" {
return nil, newFormatError(kindInvalidModpack, "game %q is not minecraft", index.Game)
}
if len(index.Files) > maxEntries {
return nil, limitError("%s lists %d files, above the %d entry limit", modrinthIndexName, len(index.Files), maxEntries)
}
return &index, nil
}
// mapDependencies converts the Modrinth dependency map to a Minecraft version
// and a server product. Without a loader the product is vanilla Minecraft,
// whose core version is the Minecraft version itself.
func mapDependencies(deps map[string]string) (string, server.Product, string, error) {
minecraft := strings.TrimSpace(deps["minecraft"])
if minecraft == "" {
return "", server.ProductUnknown, "", newFormatError(
kindInvalidModpack,
"dependencies do not name a minecraft version",
)
}
var loaders []string
for key := range deps {
if key != "minecraft" {
loaders = append(loaders, key)
}
}
sort.Strings(loaders)
switch len(loaders) {
case 0:
return minecraft, server.ProductMinecraft, minecraft, nil
case 1:
default:
return "", server.ProductUnknown, "", newFormatError(
kindInvalidModpack,
"dependencies name several loaders (%s); a server runs one loader",
strings.Join(loaders, ", "),
)
}
loader := loaders[0]
productName, ok := mrpackLoaderProducts[loader]
if !ok {
return "", server.ProductUnknown, "", newFormatError(
kindInvalidModpack,
"unsupported loader %q; supported loaders are fabric-loader, quilt-loader, forge, and neoforge",
loader,
)
}
product, known := server.ParseProduct(productName)
if !known {
return "", server.ProductUnknown, "", newFormatError(
kindInvalidModpack,
"loader %q is not a known server product",
loader,
)
}
core := strings.TrimSpace(deps[loader])
if core == "" {
return "", server.ProductUnknown, "", newFormatError(
kindInvalidModpack,
"loader %q has no version",
loader,
)
}
return minecraft, product, core, nil
}
// serverIncluded applies env.server: a missing value includes the file,
// "unsupported" excludes it, and any other value is rejected.
func serverIncluded(env map[string]string) (bool, error) {
switch env["server"] {
case "", "required", "optional":
return true, nil
case "unsupported":
return false, nil
default:
return false, newFormatError(
kindInvalidModpack,
"unknown env.server value %q",
env["server"],
)
}
}
func normalizeIndexPath(raw string) (string, error) {
if strings.HasSuffix(raw, "/") {
return "", newFormatError(kindInvalidModpack, "file path %q names a directory", raw)
}
rel, err := normalizeEntryName(raw)
if err != nil {
return "", fmt.Errorf("file path in %s: %w", modrinthIndexName, err)
}
if rel == "" {
return "", newFormatError(kindInvalidModpack, "file path %q is empty", raw)
}
if err := checkDestPath(rel); err != nil {
return "", err
}
return rel, nil
}
// selectDigest prefers sha512 and falls back to sha1. A file without either
// cannot be verified, so it is rejected.
func selectDigest(rel string, hashes map[string]string) (cache.HashAlgorithm, string, error) {
candidates := []struct {
name string
algorithm cache.HashAlgorithm
length int
}{
{name: "sha512", algorithm: cache.HashSHA512, length: sha512.Size * 2},
{name: "sha1", algorithm: cache.HashSHA1, length: sha1.Size * 2},
}
for _, c := range candidates {
digest := strings.ToLower(strings.TrimSpace(hashes[c.name]))
if digest == "" {
continue
}
if len(digest) != c.length {
return cache.HashNone, "", newFormatError(
kindInvalidModpack,
"%s hash for %s has %d hex digits, want %d",
c.name,
rel,
len(digest),
c.length,
)
}
if _, err := hex.DecodeString(digest); err != nil {
return cache.HashNone, "", newFormatError(
kindInvalidModpack,
"%s hash for %s is not hex",
c.name,
rel,
)
}
return c.algorithm, digest, nil
}
return cache.HashNone, "", newFormatError(
kindInvalidModpack,
"%s has no sha512 or sha1 hash to verify it against",
rel,
)
}
// buildMrpackLayout plans a Modrinth modpack. Override folders take precedence
// over index downloads, and client-only entries are reported as skipped.
func buildMrpackLayout(a *archive) (*layout, error) {
indexEntry, _ := a.rootFile(modrinthIndexName)
data, err := a.readEntry(indexEntry, maxMetadataBytes)
if err != nil {
return nil, err
}
index, err := parseMrpackIndex(data)
if err != nil {
return nil, err
}
minecraft, product, core, err := mapDependencies(index.Dependencies)
if err != nil {
return nil, err
}
table := newPathTable()
var skipped []string
for _, source := range mrpackOverrideSources {
for _, e := range a.entries {
rel, ok := strings.CutPrefix(e.rel, source.prefix)
if !ok || rel == "" {
continue
}
if _, err := table.add(entryItem(e, rel, source.layer)); err != nil {
return nil, err
}
}
}
for _, e := range a.entries {
if !e.dir && strings.HasPrefix(e.rel, mrpackClientOverridesPrefix) {
skipped = append(skipped, e.rel)
}
}
for _, f := range index.Files {
rel, err := normalizeIndexPath(f.Path)
if err != nil {
return nil, err
}
included, err := serverIncluded(f.Env)
if err != nil {
return nil, err
}
if !included {
skipped = append(skipped, rel)
continue
}
if len(f.Downloads) == 0 {
return nil, newFormatError(kindInvalidModpack, "%s has no download URL", rel)
}
if f.FileSize < 0 {
return nil, newFormatError(kindInvalidModpack, "%s has a negative fileSize", rel)
}
algorithm, digest, err := selectDigest(rel, f.Hashes)
if err != nil {
return nil, err
}
it := &item{
rel: rel,
mode: fileMode(false),
size: f.FileSize,
layer: layerBase,
ordinal: -1,
download: &mrpackFile{
urls: f.Downloads,
algorithm: algorithm,
digest: digest,
},
}
if _, err := table.add(it); err != nil {
return nil, err
}
}
lay, err := newLayout(table.items(), skipped)
if err != nil {
return nil, err
}
if lay.plan.ServerFiles == 0 {
return nil, newFormatError(kindInvalidModpack, "%s contains no server files", filepath.Base(a.path))
}
lay.plan.Format = FormatMrpack
lay.plan.Name = index.Name
lay.plan.VersionID = index.VersionID
lay.plan.Minecraft = minecraft
lay.plan.Product = product
lay.plan.CoreVersion = core
return lay, nil
}
// fetch downloads one index file into a private staging directory, verifies
// it, and renames it to its destination. Each URL is tried in order until one
// yields a verified file. The per-file stage directory keeps files that share
// a base name from writing the same staging path.
func (m *materializer) fetch(ctx context.Context, it *item, index int) error {
if err := ctx.Err(); err != nil {
return err
}
dir := filepath.Join(m.stage, strconv.Itoa(index))
if err := os.Mkdir(dir, dirMode); err != nil {
return fmt.Errorf("prepare stage for %s: %w", it.rel, err)
}
var failures []error
for _, url := range it.download.urls {
if err := ctx.Err(); err != nil {
return err
}
staged, err := m.downloadFrom(ctx, url, it, dir)
if err != nil {
failures = append(failures, fmt.Errorf("%s: %w", url, err))
continue
}
rel, err := filepath.Rel(m.dest, staged)
if err != nil || !filepath.IsLocal(rel) {
return fmt.Errorf("place %s: %w", it.rel, ErrUnsafeEntry)
}
if err := m.root.Rename(rel, filepath.FromSlash(it.rel)); err != nil {
return fmt.Errorf("place %s: %w", it.rel, err)
}
return nil
}
return fmt.Errorf("download %s: no source produced a verified file: %w", it.rel, errors.Join(failures...))
}
// downloadFrom fetches url into dir and returns the staged file's path.
func (m *materializer) downloadFrom(
ctx context.Context,
url string,
it *item,
dir string,
) (string, error) {
digest := it.download
name := path.Base(it.rel)
// Bound one transfer by the per-file limit and by the bytes left after
// files already retained. The aggregate is charged only on retention, so a
// failing attempt in flight cannot shrink another attempt's limit.
limit := min(maxFileBytes, m.budget.remaining())
if limit <= 0 {
return "", limitError("extraction exceeds the %d byte limit", maxExtractedBytes)
}
res, err := m.network.CachedDownload(ctx, url, dir, cache.DownloadOptions{
Kind: cache.KindArtifact,
ExpectedHash: digest.digest,
HashAlgorithm: digest.algorithm,
Filename: name,
FileMode: 0o644,
MaxBytes: limit,
WrapReader: func(r io.Reader, size int64) io.Reader {
m.reportStarted(it.rel, size)
return cache.ProgressReader(r, size, func(read, total int64) {
m.reportProgress(it.rel, read, total)
})
},
})
if err != nil {
// The cache cannot tell its per-file bound from the aggregate one; when
// the aggregate shrank the limit, report the shared import limit.
if limit < maxFileBytes && errors.Is(err, cache.ErrDownloadTooLarge) {
return "", fmt.Errorf("%w: %w", limitError("extraction exceeds the %d byte limit", maxExtractedBytes), err)
}
return "", err
}
staged := res.File.Name()
closeErr := res.File.Close()
if closeErr == nil {
closeErr = m.retainStage(staged, it.rel, digest, res.Verified)
}
if closeErr != nil {
_ = os.Remove(staged)
return "", closeErr
}
m.reportDone(it.rel, res.CacheHit)
return staged, nil
}
// retainStage charges a staged download to the aggregate budget before it can
// be renamed into place. Hosted bytes the cache did not verify are checked
// here, because the cache checks digests only when it stores an entry.
func (m *materializer) retainStage(
staged, rel string,
digest *mrpackFile,
verified bool,
) error {
info, err := os.Stat(staged)
if err != nil {
return err
}
if info.Size() > maxFileBytes {
return limitError("%s is %d bytes, above the %d byte file limit", rel, info.Size(), maxFileBytes)
}
if !verified {
if err := verifyDigest(staged, digest.algorithm, digest.digest); err != nil {
return err
}
}
if err := m.budget.spend(info.Size()); err != nil {
return fmt.Errorf("%s: %w", rel, err)
}
return nil
}
func verifyDigest(file string, algorithm cache.HashAlgorithm, expected string) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
var h hash.Hash
switch algorithm {
case cache.HashSHA512:
h = sha512.New()
case cache.HashSHA1:
h = sha1.New()
default:
return fmt.Errorf("unsupported digest algorithm %s", algorithm)
}
if _, err := io.Copy(h, f); err != nil {
return err
}
if actual := hex.EncodeToString(h.Sum(nil)); actual != expected {
return fmt.Errorf("%s mismatch: expected %s, got %s", algorithm, expected, actual)
}
return nil
}
package importpack
import (
"context"
"sync"
)
// materializeWorkers bounds work on independent source files. Entries of a
// streamed container, such as a tar body, stay serial: the next entry cannot
// be read before the current body ends.
const materializeWorkers = 4
// runFileJobs runs count jobs in waves of at most materializeWorkers.
//
// A wave waits for all of its jobs, so every file before the first failing file
// has completed and the returned error is the one a serial run would report.
// Context cancellation stops jobs that have not completed, and the context
// error wins over the failures it caused.
func runFileJobs(
ctx context.Context,
count int,
job func(context.Context, int) error,
) error {
for start := 0; start < count; start += materializeWorkers {
end := min(start+materializeWorkers, count)
errs := make([]error, end-start)
var workers sync.WaitGroup
for index := start; index < end; index++ {
workers.Go(func() {
errs[index-start] = job(ctx, index)
})
}
workers.Wait()
if err := ctx.Err(); err != nil {
return err
}
for _, err := range errs {
if err != nil {
return err
}
}
}
return nil
}
// Package javainstall installs a Java runtime through the most native method
// the host offers. The order is a Java version manager the user already runs,
// then the system package manager, then a vendor repository the user consented
// to, and last a per-user download. Lucy never changes the default Java of the
// user or the system.
package javainstall
import (
"cmp"
"context"
"slices"
"github.com/mclucy/lucy/java"
)
// Request names the Java runtime to install.
type Request struct {
Major int
Distribution java.Distribution
}
// Method names the mechanism that performs an installation.
type Method string
const (
MethodSDKMAN Method = "sdkman"
MethodMise Method = "mise"
MethodAsdf Method = "asdf"
MethodHomebrew Method = "brew"
MethodScoop Method = "scoop"
MethodWinget Method = "winget"
MethodApt Method = "apt"
MethodDnf Method = "dnf"
MethodZypper Method = "zypper"
MethodPacman Method = "pacman"
MethodApk Method = "apk"
MethodDownload Method = "download"
)
// Elevation names who obtains the rights a step needs.
type Elevation int
const (
// ElevationNone runs the step as the current user.
ElevationNone Elevation = iota
// ElevationRoot runs the step as root: directly when Lucy already runs as
// root, otherwise through sudo.
ElevationRoot
// ElevationSelf runs the step as the current user. The tool asks for rights
// or agreements itself, so the step needs an interactive terminal.
ElevationSelf
)
// Step is one command of a plan.
type Step struct {
Args []string
Elevation Elevation
// Input is fed to the standard input when set. An empty Input connects the
// terminal, so the tool can prompt.
Input string
}
// Repository is a vendor package repository that a plan adds before its steps.
type Repository struct {
// Name is shown to the user, for example "Eclipse Adoptium apt repository".
Name string
// URL is the repository location shown to the user.
URL string
// Key is the signing key that the repository files reference. It is nil
// when the package manager verifies the source itself.
Key *RepositoryKey
// Files are written as root after the key.
Files []RepositoryFile
// Steps run after the files, for example to refresh the package index.
Steps []Step
}
// RepositoryKey is an OpenPGP key that Lucy downloads and verifies against a
// pinned fingerprint before it writes the key.
type RepositoryKey struct {
URL string
// Fingerprint is the primary key fingerprint in upper-case hexadecimal
// without spaces.
Fingerprint string
// Path is where the verified key is written as root.
Path string
// Armored writes the key ASCII-armored; otherwise the key is written in
// binary form.
Armored bool
}
// RepositoryFile is one file a repository plan writes as root.
type RepositoryFile struct {
Path string
Content string
}
// Plan is one way to install the requested Java.
type Plan struct {
Method Method
// Package is the package, cask, candidate, or archive that the plan
// installs.
Package string
// Distribution is the build the plan installs. It is the unspecified
// distribution for unbranded builds.
Distribution java.Distribution
Major int
// Repository is added before the steps. A plan with a repository needs
// Policy.AllowRepository.
Repository *Repository
Steps []Step
// KeepDefault restores the system default Java captured before the steps,
// because package execution can move it before a later failure or
// cancellation. A step that exits from an unexpected signal blocks the
// restore because its child cannot be confirmed stopped.
KeepDefault bool
// root is the elevation fact captured while planning, so Commands renders
// the same sudo prefixes that execution uses.
root bool
// managedRoot is the per-user runtime directory captured while planning a
// download, so Commands and execution name the same destination.
managedRoot string
download *download
}
// SkipReason tells why a plan that could install the request is not usable.
type SkipReason int
const (
// SkipNeedsRoot means the plan needs root and Lucy can neither run as root
// nor use sudo.
SkipNeedsRoot SkipReason = iota + 1
// SkipNeedsTerminal means the tool prompts for rights or agreements and no
// interactive terminal is available.
SkipNeedsTerminal
// SkipNeedsRepositoryConsent means the plan adds a vendor repository and
// the user did not consent.
SkipNeedsRepositoryConsent
)
// Skipped is a plan that could install the request but is not usable on this
// run.
type Skipped struct {
Plan Plan
Reason SkipReason
}
// manager is one package manager or Java version manager.
// Managers are stateless; the Host carries the invocation's facts.
type manager interface {
method() Method
// system reports that the manager installs for the whole system rather
// than for the current user.
system() bool
// ownsJava reports that the manager already installed a Java runtime on
// this host.
ownsJava(ctx context.Context, host *Host) bool
// plans returns the ways the manager can install req. It returns nil when
// the manager is absent or offers no matching package.
plans(ctx context.Context, req Request, host *Host) ([]Plan, error)
}
func managers() []manager {
return []manager{
sdkman{},
mise{},
asdf{},
homebrew{},
scoop{},
apt{},
dnf{},
zypper{},
pacman{},
apk{},
winget{},
}
}
const (
tierOwningUser = iota
tierUser
tierSystem
tierRepository
tierDownload
)
// Plans lists the usable ways to install req, most native first, and the
// plans that this run cannot use. A manager that fails to answer is skipped,
// because another method can still install the request.
func (h *Host) Plans(
ctx context.Context,
req Request,
policy Policy,
) ([]Plan, []Skipped, error) {
type ranked struct {
plan Plan
tier int
}
var candidates []ranked
for _, m := range managers() {
plans, err := m.plans(ctx, req, h)
if ctx.Err() != nil {
return nil, nil, ctx.Err()
}
if err != nil {
h.logger.Debug(
"java install method unavailable",
"method", m.method(),
"reason", err,
)
continue
}
tier := tierUser
switch {
case m.system():
tier = tierSystem
case m.ownsJava(ctx, h):
tier = tierOwningUser
}
for _, plan := range plans {
plan.root = h.isRoot()
planTier := tier
if plan.Repository != nil {
planTier = tierRepository
}
candidates = append(candidates, ranked{plan: plan, tier: planTier})
}
}
download, err := h.downloadPlan(ctx, req)
if err != nil {
if ctx.Err() != nil {
return nil, nil, ctx.Err()
}
h.logger.Debug("java download unavailable", "reason", err)
} else if download != nil {
candidates = append(candidates, ranked{plan: *download, tier: tierDownload})
}
slices.SortStableFunc(candidates, func(a, b ranked) int {
return cmp.Compare(a.tier, b.tier)
})
var usable []Plan
var skipped []Skipped
for _, candidate := range candidates {
if err := ctx.Err(); err != nil {
return nil, nil, err
}
plan := candidate.plan
if plan.Major != req.Major || !req.Distribution.Accepts(plan.Distribution) {
h.logger.Debug(
"java install plan rejected",
"method", plan.Method,
"package", plan.Package,
"reason", "plan does not install the requested Java",
)
continue
}
reason, err := skipReason(ctx, plan, policy, h)
if err != nil {
return nil, nil, err
}
if reason != 0 {
skipped = append(skipped, Skipped{Plan: plan, Reason: reason})
continue
}
usable = append(usable, plan)
}
return usable, skipped, ctx.Err()
}
func skipReason(
ctx context.Context,
plan Plan,
policy Policy,
host *Host,
) (SkipReason, error) {
if plan.Repository != nil && !policy.AllowRepository {
return SkipNeedsRepositoryConsent, nil
}
for _, step := range plan.allSteps() {
switch step.Elevation {
case ElevationRoot:
available, err := host.rootAvailable(ctx, policy)
if err != nil {
return 0, err
}
if !available {
return SkipNeedsRoot, nil
}
case ElevationSelf:
if !policy.Interactive {
return SkipNeedsTerminal, nil
}
}
}
if plan.Repository != nil && (plan.Repository.Key != nil || len(plan.Repository.Files) > 0) {
available, err := host.rootAvailable(ctx, policy)
if err != nil {
return 0, err
}
if !available {
return SkipNeedsRoot, nil
}
}
return 0, nil
}
// allSteps returns the repository steps followed by the install steps.
func (p Plan) allSteps() []Step {
if p.Repository == nil {
return p.Steps
}
return append(slices.Clone(p.Repository.Steps), p.Steps...)
}
package javainstall
import (
"context"
"io"
"path/filepath"
"time"
)
// restoreTimeout bounds a best-effort restore. Package execution may have ended
// in failure or cancellation, so restoration detaches from that cancellation;
// the bound keeps a stuck package tool or credential prompt from blocking exit.
const restoreTimeout = 30 * time.Second
// systemDefaultJava returns the resolved target of /usr/bin/java, or an empty
// string when the host has no default Java.
func systemDefaultJava(host *Host) string {
if host.goos != "linux" {
return ""
}
target, err := filepath.EvalSymlinks("/usr/bin/java")
if err != nil {
return ""
}
return target
}
// restoreSystemDefault points the java alternative back at previous when a
// package moved it. It does nothing when the default did not change. A restore
// runs even when the package execution failed or was canceled, so it detaches
// from that cancellation and is bounded by restoreTimeout. It uses the
// invocation's elevation facts.
func restoreSystemDefault(
ctx context.Context,
previous string,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
if host.goos != "linux" || previous == "" {
return nil
}
current := systemDefaultJava(host)
if filepath.Clean(current) == filepath.Clean(previous) {
return nil
}
host.logger.Info("restoring system default java", "path", previous)
restoreCtx, cancel := context.WithTimeout(
context.WithoutCancel(ctx),
restoreTimeout,
)
defer cancel()
return runStep(
restoreCtx,
Step{
Args: []string{
"update-alternatives",
"--set",
"java",
previous,
},
Elevation: ElevationRoot,
},
policy,
host,
input,
out,
)
}
package javainstall
import (
"context"
"fmt"
"strings"
"github.com/mclucy/lucy/java"
)
// apk installs Java from the configured APK sources.
type apk struct{}
func (apk) method() Method { return MethodApk }
func (apk) system() bool { return true }
func (apk) ownsJava(context.Context, *Host) bool { return false }
func (apk) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if req.Major <= 0 ||
req.Distribution != java.DistributionAny ||
!host.systemToolAvailable("apk") {
return nil, nil
}
pkg := fmt.Sprintf("openjdk%d-jre-headless", req.Major)
if !apkPackageAvailable(ctx, host, pkg) {
return nil, nil
}
return []Plan{
{
Method: MethodApk,
Package: pkg,
Distribution: java.DistributionAny,
Major: req.Major,
Steps: []Step{
{
Args: []string{
"apk",
"add",
"--no-cache",
pkg,
},
Elevation: ElevationRoot,
},
},
},
}, nil
}
// apkPackageAvailable reports whether the configured sources offer pkg. The
// probe never changes the package index.
func apkPackageAvailable(
ctx context.Context,
host *Host,
pkg string,
) bool {
output, err := host.systemProbe(ctx, "apk", "search", "--exact", pkg)
if err != nil {
host.logger.Debug("apk package probe failed", "package", pkg, "reason", err)
return false
}
for line := range strings.Lines(string(output)) {
name := strings.TrimSpace(line)
if name == pkg || strings.HasPrefix(name, pkg+"-") {
return true
}
}
return false
}
package javainstall
import (
"context"
"fmt"
"strings"
"github.com/mclucy/lucy/java"
)
// apt installs Java from the configured APT sources.
type apt struct{}
func (apt) method() Method { return MethodApt }
func (apt) system() bool { return true }
func (apt) ownsJava(context.Context, *Host) bool { return false }
func (apt) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if req.Major <= 0 || !host.systemToolAvailable("apt-get", "apt-cache") {
return nil, nil
}
if req.Distribution == java.DistributionAny {
pkg := fmt.Sprintf("openjdk-%d-jre-headless", req.Major)
if !aptPackageAvailable(ctx, host, pkg) {
return nil, nil
}
return []Plan{
aptPlan(pkg, java.DistributionAny, req.Major, nil),
}, nil
}
packages, ok := aptBrandedPackages(req.Distribution, req.Major)
if !ok {
return nil, nil
}
for _, pkg := range packages {
if aptPackageAvailable(ctx, host, pkg) {
return []Plan{
aptPlan(pkg, req.Distribution, req.Major, nil),
}, nil
}
}
repository := aptRepository(req.Distribution, host)
if repository == nil {
return nil, nil
}
return []Plan{
aptPlan(packages[0], req.Distribution, req.Major, repository),
}, nil
}
func aptPlan(
pkg string,
distribution java.Distribution,
major int,
repository *Repository,
) Plan {
return Plan{
Method: MethodApt,
Package: pkg,
Distribution: distribution,
Major: major,
Repository: repository,
Steps: []Step{
{
Args: []string{
"env",
"DEBIAN_FRONTEND=noninteractive",
"apt-get",
"install",
"-y",
"--no-install-recommends",
pkg,
},
Elevation: ElevationRoot,
},
},
KeepDefault: true,
}
}
// aptPackageAvailable reports whether the configured sources offer pkg. The
// probe never changes the package index.
func aptPackageAvailable(
ctx context.Context,
host *Host,
pkg string,
) bool {
output, err := host.systemProbe(ctx, "apt-cache", "policy", pkg)
if err != nil {
host.logger.Debug("apt package probe failed", "package", pkg, "reason", err)
return false
}
for line := range strings.Lines(string(output)) {
candidate, ok := strings.CutPrefix(
strings.TrimSpace(line),
"Candidate:",
)
if !ok {
continue
}
candidate = strings.TrimSpace(candidate)
return candidate != "" && candidate != "(none)"
}
return false
}
// aptBrandedPackages returns the package names of a vendor build, most
// preferred first, and whether APT can provide that build.
func aptBrandedPackages(
distribution java.Distribution,
major int,
) ([]string, bool) {
switch distribution {
case java.DistributionTemurin:
return []string{
fmt.Sprintf("temurin-%d-jre", major),
fmt.Sprintf("temurin-%d-jdk", major),
}, true
case java.DistributionZulu:
return []string{
fmt.Sprintf("zulu%d-jre-headless", major),
fmt.Sprintf("zulu%d-jdk-headless", major),
}, true
case java.DistributionCorretto:
return []string{
fmt.Sprintf("java-%d-amazon-corretto-jdk", major),
}, true
default:
return nil, false
}
}
// aptRepository returns the vendor APT source for a build. It returns nil
// when the vendor documents no source for this host.
func aptRepository(distribution java.Distribution, host *Host) *Repository {
switch distribution {
case java.DistributionTemurin:
release := host.systemRelease()
suite := release["VERSION_CODENAME"]
if suite == "" {
suite = release["UBUNTU_CODENAME"]
}
if suite == "" {
return nil
}
return aptVendorRepository(
"Eclipse Adoptium apt repository",
"https://packages.adoptium.net/artifactory/deb",
"adoptium",
"3B04D753C9050D9A5D343F39843C48A565F8F04B",
"https://packages.adoptium.net/artifactory/api/gpg/key/public",
suite,
)
case java.DistributionZulu:
return aptVendorRepository(
"Azul Zulu apt repository",
"https://repos.azul.com/zulu/deb",
"azul",
"27BC0C8CB3D81623F59BDADCB1998361219BD9C9",
"https://repos.azul.com/azul-repo.key",
"stable",
)
case java.DistributionCorretto:
return aptVendorRepository(
"Amazon Corretto apt repository",
"https://apt.corretto.aws",
"corretto",
"6DC3636DAE534049C8B94623A122542AB04F24E3",
"https://apt.corretto.aws/corretto.key",
"stable",
)
default:
return nil
}
}
func aptVendorRepository(
name string,
repositoryURL string,
vendor string,
fingerprint string,
keyURL string,
suite string,
) *Repository {
keyPath := "/etc/apt/keyrings/" + vendor + ".asc"
return &Repository{
Name: name,
URL: repositoryURL,
Key: &RepositoryKey{
URL: keyURL,
Fingerprint: fingerprint,
Path: keyPath,
Armored: true,
},
Files: []RepositoryFile{
{
Path: "/etc/apt/sources.list.d/" + vendor + ".list",
Content: fmt.Sprintf(
"deb [signed-by=%s] %s %s main\n",
keyPath,
repositoryURL,
suite,
),
},
},
Steps: []Step{
{
Args: []string{"apt-get", "update"},
Elevation: ElevationRoot,
},
},
}
}
package javainstall
import (
"context"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/java"
)
// asdfVendors maps each distribution to the vendor prefix of its asdf-java
// version. asdf-java has no Red Hat build.
var asdfVendors = map[java.Distribution]string{
java.DistributionTemurin: "temurin",
java.DistributionZulu: "zulu",
java.DistributionCorretto: "corretto",
java.DistributionLiberica: "liberica",
java.DistributionMicrosoft: "microsoft",
java.DistributionOracle: "oracle",
java.DistributionOracleOpenJDK: "openjdk",
java.DistributionGraalVM: "oracle-graalvm",
java.DistributionGraalVMCommunity: "graalvm-community",
java.DistributionSemeru: "semeru-openj9",
java.DistributionSapMachine: "sapmachine",
java.DistributionDragonwell: "dragonwell",
java.DistributionKona: "kona",
java.DistributionJetBrains: "jetbrains",
}
type asdf struct{}
func (asdf) method() Method { return MethodAsdf }
func (asdf) system() bool { return false }
func (asdf) ownsJava(_ context.Context, _ *Host) bool {
dir := asdfDataDir()
if dir == "" {
return false
}
entries, err := os.ReadDir(filepath.Join(dir, "installs", "java"))
return err == nil && len(entries) > 0
}
func (asdf) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if _, err := exec.LookPath("asdf"); err != nil {
return nil, nil
}
plugins, err := asdfCommand(ctx, host, "plugin", "list")
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
host.logger.Debug("asdf plugins unavailable", "reason", err)
return nil, nil
}
if !asdfHasJavaPlugin(plugins) {
return nil, nil
}
prefix, distribution, ok := asdfVendor(req.Distribution)
if !ok {
return nil, nil
}
spec := prefix + "-" + strconv.Itoa(req.Major)
versions, err := asdfCommand(ctx, host, "list", "all", "java", spec)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
host.logger.Debug("asdf java versions unavailable", "spec", spec, "reason", err)
return nil, nil
}
if strings.TrimSpace(versions) == "" {
return nil, nil
}
return []Plan{{
Method: MethodAsdf,
Package: "java@" + spec,
Distribution: distribution,
Major: req.Major,
Steps: []Step{{
Args: []string{"asdf", "install", "java", "latest:" + spec},
Elevation: ElevationNone,
}},
}}, nil
}
// asdfVendor returns the vendor prefix for dist. The unspecified distribution
// installs Temurin, the plugin's default build.
func asdfVendor(dist java.Distribution) (string, java.Distribution, bool) {
if dist == java.DistributionAny {
return "temurin", java.DistributionTemurin, true
}
prefix, ok := asdfVendors[dist]
return prefix, dist, ok
}
func asdfDataDir() string {
if dir := os.Getenv("ASDF_DATA_DIR"); dir != "" {
return dir
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".asdf")
}
// asdfHasJavaPlugin reports whether the java plugin is installed. asdf prints
// one plugin name per line.
func asdfHasJavaPlugin(output string) bool {
for _, line := range strings.Split(output, "\n") {
if strings.TrimSpace(line) == "java" {
return true
}
}
return false
}
// asdfCommand runs a read-only asdf query with a bounded wait.
func asdfCommand(
ctx context.Context,
host *Host,
args ...string,
) (string, error) {
output, err := host.probe(ctx, 20*time.Second, nil, "asdf", args...)
return string(output), err
}
package javainstall
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/java"
)
// homebrewCasks maps a branded distribution to the base token of its macOS
// cask. Homebrew publishes no cask for the remaining distributions.
var homebrewCasks = map[java.Distribution]string{
java.DistributionTemurin: "temurin",
java.DistributionZulu: "zulu",
java.DistributionCorretto: "corretto",
java.DistributionMicrosoft: "microsoft-openjdk",
java.DistributionOracle: "oracle-jdk",
java.DistributionGraalVM: "graalvm-jdk",
java.DistributionSapMachine: "sapmachine-jdk",
java.DistributionSemeru: "semeru-jdk-open",
}
type homebrew struct{}
func (homebrew) method() Method { return MethodHomebrew }
func (homebrew) system() bool { return false }
func (homebrew) ownsJava(ctx context.Context, host *Host) bool {
if host.isRoot() {
return false
}
if _, err := exec.LookPath("brew"); err != nil {
return false
}
formulae, err := homebrewList(ctx, host, "--formula")
if err == nil {
for _, token := range strings.Fields(formulae) {
if strings.HasPrefix(token, "openjdk") {
return true
}
}
}
casks, err := homebrewList(ctx, host, "--cask")
if err != nil {
return false
}
for _, token := range strings.Fields(casks) {
if homebrewJavaCask(token) {
return true
}
}
return false
}
func (homebrew) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if host.goos != "darwin" && host.goos != "linux" {
return nil, nil
}
if host.isRoot() {
return nil, nil
}
if _, err := exec.LookPath("brew"); err != nil {
return nil, nil
}
if req.Distribution == java.DistributionAny {
token, ok := homebrewFormula(ctx, host, req.Major)
if !ok {
return nil, nil
}
return []Plan{homebrewPlan(token, req.Major, java.DistributionAny, false)}, nil
}
if host.goos != "darwin" {
return nil, nil
}
base, ok := homebrewCasks[req.Distribution]
if !ok {
return nil, nil
}
token, ok := homebrewCask(ctx, host, base, req.Major)
if !ok {
return nil, nil
}
return []Plan{homebrewPlan(token, req.Major, req.Distribution, true)}, nil
}
// homebrewFormula returns the formula that installs the requested major. The
// versioned formula is preferred; the unversioned openjdk formula qualifies
// only when its current major matches.
func homebrewFormula(ctx context.Context, host *Host, major int) (string, bool) {
token := "openjdk@" + strconv.Itoa(major)
if version, ok := homebrewBottledFormulaVersion(ctx, host, token); ok && homebrewMajor(version) == major {
return token, true
}
version, ok := homebrewBottledFormulaVersion(ctx, host, "openjdk")
if !ok || homebrewMajor(version) != major {
return "", false
}
return "openjdk", true
}
// homebrewCask returns the cask that installs the requested major. A versioned
// cask is preferred; the base cask qualifies only when its current major
// matches.
func homebrewCask(ctx context.Context, host *Host, base string, major int) (string, bool) {
for _, token := range []string{base + "@" + strconv.Itoa(major), base} {
version, ok := homebrewCaskVersion(ctx, host, token)
if ok && homebrewMajor(version) == major {
return token, true
}
}
return "", false
}
// homebrewBottledFormulaVersion returns the stable version of a formula that
// has a bottle. A formula without one compiles the JDK from source, which
// takes long and is not a native install.
func homebrewBottledFormulaVersion(ctx context.Context, host *Host, token string) (string, bool) {
output, err := homebrewInfo(ctx, host, "--formula", token)
if err != nil {
if ctx.Err() == nil {
host.logger.Debug("homebrew formula info unavailable", "formula", token, "reason", err)
}
return "", false
}
var info struct {
Formulae []struct {
Versions struct {
Stable string `json:"stable"`
} `json:"versions"`
Bottle struct {
Stable struct {
Files map[string]jsontext.Value `json:"files"`
} `json:"stable"`
} `json:"bottle"`
} `json:"formulae"`
}
if err := json.Unmarshal(output, &info); err != nil || len(info.Formulae) == 0 {
return "", false
}
formula := info.Formulae[0]
if len(formula.Bottle.Stable.Files) == 0 {
host.logger.Debug(
"homebrew formula skipped",
"formula", token,
"reason", "no bottle, so it would build from source",
)
return "", false
}
return formula.Versions.Stable, true
}
func homebrewCaskVersion(ctx context.Context, host *Host, token string) (string, bool) {
output, err := homebrewInfo(ctx, host, "--cask", token)
if err != nil {
if ctx.Err() == nil {
host.logger.Debug("homebrew cask info unavailable", "cask", token, "reason", err)
}
return "", false
}
var info struct {
Casks []struct {
Version string `json:"version"`
} `json:"casks"`
}
if err := json.Unmarshal(output, &info); err != nil || len(info.Casks) == 0 {
return "", false
}
return info.Casks[0].Version, true
}
// homebrewInfo reads local Homebrew metadata without updating taps.
func homebrewInfo(ctx context.Context, host *Host, kind, token string) ([]byte, error) {
environment := append(os.Environ(), "HOMEBREW_NO_AUTO_UPDATE=1")
return host.probe(ctx, 30*time.Second, environment, "brew", "info", "--json=v2", kind, token)
}
func homebrewList(ctx context.Context, host *Host, kind string) (string, error) {
output, err := host.probe(ctx, 20*time.Second, nil, "brew", "list", kind)
return string(output), err
}
// homebrewMajor returns the leading major of a formula or cask version, which
// may carry a revision after a comma. Java 8 builds use the legacy 1.8 scheme.
func homebrewMajor(version string) int {
version = strings.TrimPrefix(version, "1.")
end := 0
for end < len(version) && version[end] >= '0' && version[end] <= '9' {
end++
}
if end == 0 {
return 0
}
major, err := strconv.Atoi(version[:end])
if err != nil {
return 0
}
return major
}
func homebrewJavaCask(token string) bool {
for _, base := range []string{
"temurin",
"zulu",
"corretto",
"microsoft-openjdk",
"oracle-jdk",
"graalvm-jdk",
"sapmachine-jdk",
"semeru-jdk-open",
} {
if token == base || strings.HasPrefix(token, base+"@") {
return true
}
}
return false
}
func homebrewPlan(token string, major int, distribution java.Distribution, cask bool) Plan {
args := []string{"brew", "install"}
elevation := ElevationNone
if cask {
args = append(args, "--cask")
// The .pkg installer asks for the password itself.
elevation = ElevationSelf
}
args = append(args, token)
return Plan{
Method: MethodHomebrew,
Package: token,
Distribution: distribution,
Major: major,
Steps: []Step{{
Args: args,
Elevation: elevation,
}},
}
}
package javainstall
import (
"context"
"fmt"
"strings"
"github.com/mclucy/lucy/java"
)
// dnf installs Java from the configured DNF sources.
type dnf struct{}
func (dnf) method() Method { return MethodDnf }
func (dnf) system() bool { return true }
func (dnf) ownsJava(context.Context, *Host) bool { return false }
func (dnf) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if req.Major <= 0 || !host.systemToolAvailable("dnf") {
return nil, nil
}
if req.Distribution == java.DistributionAny {
pkg := fmt.Sprintf("java-%d-openjdk-headless", req.Major)
if !dnfPackageAvailable(ctx, host, pkg) {
return nil, nil
}
return []Plan{
dnfPlan(pkg, java.DistributionAny, req.Major, nil),
}, nil
}
packages, ok := dnfBrandedPackages(req.Distribution, req.Major)
if !ok {
return nil, nil
}
for _, pkg := range packages {
if dnfPackageAvailable(ctx, host, pkg) {
return []Plan{
dnfPlan(pkg, req.Distribution, req.Major, nil),
}, nil
}
}
repository := dnfRepository(req.Distribution, host)
if repository == nil {
return nil, nil
}
return []Plan{
dnfPlan(packages[0], req.Distribution, req.Major, repository),
}, nil
}
func dnfPlan(
pkg string,
distribution java.Distribution,
major int,
repository *Repository,
) Plan {
return Plan{
Method: MethodDnf,
Package: pkg,
Distribution: distribution,
Major: major,
Repository: repository,
Steps: []Step{
{
Args: []string{"dnf", "install", "-y", pkg},
Elevation: ElevationRoot,
},
},
KeepDefault: true,
}
}
// dnfPackageAvailable reports whether the configured sources offer pkg. The
// probe never installs or changes repository data.
func dnfPackageAvailable(
ctx context.Context,
host *Host,
pkg string,
) bool {
output, err := host.systemProbe(ctx, "dnf", "--quiet", "list", "--available", pkg)
if err != nil {
host.logger.Debug("dnf package probe failed", "package", pkg, "reason", err)
return false
}
for line := range strings.Lines(string(output)) {
name, _, _ := strings.Cut(strings.TrimSpace(line), ".")
if name == pkg {
return true
}
}
return false
}
// dnfBrandedPackages returns the package names of a vendor build, most
// preferred first, and whether DNF can provide that build.
func dnfBrandedPackages(
distribution java.Distribution,
major int,
) ([]string, bool) {
switch distribution {
case java.DistributionTemurin:
return []string{
fmt.Sprintf("temurin-%d-jre", major),
fmt.Sprintf("temurin-%d-jdk", major),
}, true
case java.DistributionZulu:
return []string{
fmt.Sprintf("zulu%d-jre-headless", major),
fmt.Sprintf("zulu%d-jdk-headless", major),
}, true
case java.DistributionCorretto:
return []string{
fmt.Sprintf("java-%d-amazon-corretto-devel", major),
}, true
default:
return nil, false
}
}
// dnfRepository returns the vendor DNF source for a build. It returns nil when
// the vendor documents no source for this host.
func dnfRepository(distribution java.Distribution, host *Host) *Repository {
switch distribution {
case java.DistributionTemurin:
repositoryURL := adoptiumRPMRepository(host)
if repositoryURL == "" {
return nil
}
return dnfVendorRepository(
"Eclipse Adoptium RPM repository",
repositoryURL,
"adoptium",
"3B04D753C9050D9A5D343F39843C48A565F8F04B",
"https://packages.adoptium.net/artifactory/api/gpg/key/public",
"Eclipse Adoptium",
)
case java.DistributionCorretto:
return dnfVendorRepository(
"Amazon Corretto RPM repository",
"https://yum.corretto.aws/$basearch",
"corretto",
"6DC3636DAE534049C8B94623A122542AB04F24E3",
"https://yum.corretto.aws/corretto.key",
"Amazon Corretto",
)
default:
return nil
}
}
// adoptiumRPMRepository returns the Adoptium RPM base URL for this host. The
// vendor publishes a directory per distribution and major version.
func adoptiumRPMRepository(host *Host) string {
release := host.systemRelease()
switch release["ID"] {
case "centos", "rhel", "fedora":
default:
return ""
}
major := systemVersionMajor(release["VERSION_ID"])
arch := systemRPMArch(host.goarch)
if major == "" || arch == "" {
return ""
}
return fmt.Sprintf(
"https://packages.adoptium.net/artifactory/rpm/%s/%s/%s",
release["ID"],
major,
arch,
)
}
func dnfVendorRepository(
name string,
repositoryURL string,
vendor string,
fingerprint string,
keyURL string,
repositoryName string,
) *Repository {
keyPath := "/etc/pki/rpm-gpg/" + vendor + ".asc"
content := fmt.Sprintf(
"[%s]\nname=%s\nbaseurl=%s\nenabled=1\ngpgcheck=1\ngpgkey=file://%s\n",
vendor,
repositoryName,
repositoryURL,
keyPath,
)
return &Repository{
Name: name,
URL: repositoryURL,
Key: &RepositoryKey{
URL: keyURL,
Fingerprint: fingerprint,
Path: keyPath,
Armored: true,
},
Files: []RepositoryFile{
{
Path: "/etc/yum.repos.d/" + vendor + ".repo",
Content: content,
},
},
Steps: []Step{
{
Args: []string{"rpm", "--import", keyPath},
Elevation: ElevationRoot,
},
},
}
}
package javainstall
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json/v2"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/java"
)
const (
foojayPackagesURL = "https://api.foojay.io/disco/v3.0/packages"
foojayIDURL = "https://api.foojay.io/disco/v3.0/ids/"
// The package metadata only changes with releases, so a short TTL keeps
// the latest build current without a network read on every plan.
foojayCacheTTL = 12 * time.Hour
)
type download struct {
url string
filename string
checksum string
archive string
size int64
javaVersion string
distribution java.Distribution
destination string
}
type foojayPackages struct {
Result []foojayPackage `json:"result"`
}
// foojayPackage is one package of the package list and of the detailed
// /ids response. The detailed response carries the download URI and checksum.
type foojayPackage struct {
ID string `json:"id"`
ArchiveType string `json:"archive_type"`
Distribution string `json:"distribution"`
Filename string `json:"filename"`
JavaVersion string `json:"java_version"`
PackageType string `json:"package_type"`
Checksum string `json:"checksum"`
ChecksumType string `json:"checksum_type"`
ChecksumURI string `json:"checksum_uri"`
DirectDownloadURI string `json:"direct_download_uri"`
Size int64 `json:"size"`
}
// anyDistributionOrder lists the distributions that a request for any
// distribution tries in turn. foojay has no Temurin build for some old majors
// and platforms, such as Java 8 on Apple silicon.
var anyDistributionOrder = []java.Distribution{
java.DistributionTemurin,
java.DistributionZulu,
java.DistributionCorretto,
java.DistributionLiberica,
}
func (h *Host) downloadPlan(ctx context.Context, req Request) (*Plan, error) {
architecture, ok := downloadArchitecture(h.goarch)
if !ok {
return nil, nil
}
operatingSystem, ok := downloadOperatingSystem(h.goos)
if !ok {
return nil, nil
}
distributions := []java.Distribution{req.Distribution}
if req.Distribution == java.DistributionAny {
distributions = anyDistributionOrder
}
return h.downloadPlanFor(ctx, req.Major, distributions, architecture, operatingSystem)
}
// downloadPlanFor finds a verifiable download of the first preferred
// distribution that has one. A runtime without the compiler is enough to run a
// server, so it asks for a JRE before the JDK of the same distribution. One
// package listing covers every preferred distribution for a package type, so
// trying the next distribution does not repeat the read. The package types keep
// separate listings because dropping the type filter reorders archive
// candidates within a distribution.
func (h *Host) downloadPlanFor(
ctx context.Context,
major int,
distributions []java.Distribution,
architecture string,
operatingSystem string,
) (*Plan, error) {
listings := make(map[string][]foojayPackage, 2)
for _, distribution := range distributions {
for _, packageType := range []string{"jre", "jdk"} {
packages, listed := listings[packageType]
if !listed {
var err error
packages, err = h.fetchDownloadPackages(
ctx,
major,
distributions,
architecture,
operatingSystem,
packageType,
)
if err != nil {
return nil, err
}
listings[packageType] = packages
}
for _, pkg := range packages {
if pkg.ID == "" ||
!strings.EqualFold(pkg.PackageType, packageType) ||
!strings.EqualFold(pkg.Distribution, string(distribution)) {
continue
}
build, err := h.fetchDownloadBuild(ctx, pkg.ID)
if err != nil {
h.logger.Debug(
"java download package unavailable",
"id", pkg.ID,
"reason", err,
)
continue
}
if build.Checksum == "" && build.ChecksumURI != "" {
build.Checksum, err = h.fetchChecksumFile(ctx, build.ChecksumURI)
if err != nil {
h.logger.Debug(
"java download checksum unavailable",
"id", pkg.ID,
"reason", err,
)
continue
}
}
download, ok := newDownload(pkg, build, distribution, major)
if !ok {
continue
}
root, err := h.managedRoot()
if err != nil {
return nil, fmt.Errorf("find the Java runtime directory: %w", err)
}
return &Plan{
Method: MethodDownload,
Package: download.filename,
Distribution: distribution,
Major: major,
root: h.isRoot(),
managedRoot: root,
download: download,
}, nil
}
}
}
return nil, nil
}
// newDownload combines the package list entry with the detailed build entry.
// It reports false when the build cannot be verified or downloaded.
func newDownload(
pkg foojayPackage,
build foojayPackage,
distribution java.Distribution,
major int,
) (*download, bool) {
checksumType := strings.ToLower(strings.TrimSpace(build.ChecksumType))
if checksumType == "" {
checksumType = strings.ToLower(strings.TrimSpace(pkg.ChecksumType))
}
if checksumType != "sha256" {
return nil, false
}
checksum := strings.TrimSpace(build.Checksum)
if checksum == "" {
checksum = strings.TrimSpace(pkg.Checksum)
}
if checksum == "" {
return nil, false
}
address := strings.TrimSpace(build.DirectDownloadURI)
if address == "" {
address = strings.TrimSpace(pkg.DirectDownloadURI)
}
if address == "" {
return nil, false
}
filename := build.Filename
if filename == "" {
filename = pkg.Filename
}
if filename == "" {
return nil, false
}
archive := pkg.ArchiveType
if archive == "" {
archive = downloadArchiveType(filename)
}
if archive != "tar.gz" && archive != "zip" {
return nil, false
}
version := pkg.JavaVersion
if version == "" {
version = build.JavaVersion
}
if version == "" {
version = strconv.Itoa(major)
}
return &download{
url: address,
filename: filename,
checksum: strings.ToLower(checksum),
archive: archive,
size: pkg.Size,
javaVersion: version,
distribution: distribution,
destination: downloadDirectoryName(distribution, version),
}, true
}
func (h *Host) fetchDownloadPackages(
ctx context.Context,
major int,
distributions []java.Distribution,
architecture string,
operatingSystem string,
packageType string,
) ([]foojayPackage, error) {
query := url.Values{}
query.Set("version", strconv.Itoa(major))
for _, distribution := range distributions {
query.Add("distribution", string(distribution))
}
query.Set("architecture", architecture)
query.Set("operating_system", operatingSystem)
musl := operatingSystem == "linux" && h.usesMusl()
query.Set("lib_c_type", downloadLibC(musl, operatingSystem))
query.Add("archive_type", "tar.gz")
query.Add("archive_type", "zip")
query.Set("package_type", packageType)
query.Set("release_status", "ga")
query.Set("latest", "available")
query.Set("javafx_bundled", "false")
query.Set("directly_downloadable", "true")
return h.fetchFoojay(ctx, foojayPackagesURL+"?"+query.Encode())
}
func (h *Host) fetchDownloadBuild(ctx context.Context, id string) (foojayPackage, error) {
builds, err := h.fetchFoojay(ctx, foojayIDURL+url.PathEscape(id))
if err != nil {
return foojayPackage{}, err
}
if len(builds) == 0 {
return foojayPackage{}, errors.New("download package has no build")
}
return builds[0], nil
}
func (h *Host) fetchFoojay(
ctx context.Context,
address string,
) ([]foojayPackage, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
data, err := h.fetchMetadata(ctx, address, foojayCacheTTL)
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", address, err)
}
var packages foojayPackages
if err := json.Unmarshal(data, &packages); err != nil {
return nil, fmt.Errorf("parse %s: %w", address, err)
}
return packages.Result, nil
}
// fetchChecksumFile reads the sha256 digest from a checksum file that a
// vendor publishes next to its archive. The file is "<digest>" or
// "<digest> <filename>". The digest then comes from the same origin as the
// archive, so it detects a damaged download but not a replaced release.
func (h *Host) fetchChecksumFile(ctx context.Context, address string) (string, error) {
if !strings.HasPrefix(address, "https://") {
return "", fmt.Errorf("checksum file %s is not served over HTTPS", address)
}
if err := ctx.Err(); err != nil {
return "", err
}
data, err := h.fetchMetadata(ctx, address, foojayCacheTTL)
if err != nil {
return "", fmt.Errorf("fetch %s: %w", address, err)
}
fields := strings.Fields(string(data))
if len(fields) == 0 {
return "", fmt.Errorf("checksum file %s is empty", address)
}
digest, err := hex.DecodeString(fields[0])
if err != nil || len(digest) != sha256.Size {
return "", fmt.Errorf("checksum file %s has no sha256 digest", address)
}
return strings.ToLower(fields[0]), nil
}
func downloadArchitecture(goarch string) (string, bool) {
switch goarch {
case "amd64":
return "x64", true
case "arm64":
return "aarch64", true
default:
return "", false
}
}
func downloadOperatingSystem(goos string) (string, bool) {
switch goos {
case "linux":
return "linux", true
case "darwin":
return "macos", true
case "windows":
return "windows", true
default:
return "", false
}
}
// downloadLibC returns the libc that the download must match. Windows has no
// libc, but the API still expects a value.
func downloadLibC(musl bool, operatingSystem string) string {
switch operatingSystem {
case "macos":
return "libc"
case "windows":
return "c_std_lib"
default:
if musl {
return "musl"
}
return "glibc"
}
}
func downloadArchiveType(filename string) string {
lower := strings.ToLower(filename)
switch {
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
return "tar.gz"
case strings.HasSuffix(lower, ".zip"):
return "zip"
default:
return ""
}
}
func downloadDirectoryName(
distribution java.Distribution,
version string,
) string {
name := string(distribution) + "-" + version
var builder strings.Builder
for _, character := range name {
switch {
case character >= 'a' && character <= 'z',
character >= 'A' && character <= 'Z',
character >= '0' && character <= '9',
character == '.',
character == '-',
character == '_',
character == '+':
builder.WriteRune(character)
default:
builder.WriteRune('-')
}
}
result := strings.Trim(builder.String(), ".-")
if result == "" {
return "java"
}
return result
}
func (d *download) describe(root string) []string {
directory := d.destination
if root != "" {
directory = filepath.Join(root, d.destination)
}
return []string{
"download " + d.url,
"verify sha256 " + d.checksum,
"extract into " + directory,
}
}
// runDownload downloads, verifies, and extracts the archive under the
// per-user root captured by the plan. A directory that already exists is a
// finished installation.
func runDownload(
ctx context.Context,
host *Host,
d *download,
root string,
out io.Writer,
) error {
if d == nil || d.url == "" || d.checksum == "" {
return errors.New("incomplete java download")
}
if root == "" {
return errors.New("java runtime directory is unknown")
}
if err := os.MkdirAll(root, 0o755); err != nil {
return fmt.Errorf("create java runtime directory: %w", err)
}
target := filepath.Join(root, d.destination)
if installed, err := downloadTargetExists(target); err != nil {
return err
} else if installed {
downloadProgress(out, "Already installed %s", target)
return nil
}
archive, err := os.CreateTemp(root, ".lucy-java-download-*")
if err != nil {
return err
}
archivePath := archive.Name()
defer os.Remove(archivePath)
downloadProgress(
out,
"Downloading %s (%s)",
d.filename,
downloadSize(d.size),
)
if err := fetchDownloadArchive(ctx, host, d, archive); err != nil {
archive.Close()
return err
}
if err := archive.Close(); err != nil {
return err
}
work, err := os.MkdirTemp(root, ".lucy-java-extract-*")
if err != nil {
return err
}
defer os.RemoveAll(work)
downloadProgress(out, "Extracting %s", d.filename)
if err := extractDownloadArchive(archivePath, d.archive, work); err != nil {
return fmt.Errorf("extract %s: %w", d.filename, err)
}
source := work
if entry, ok := downloadSingleDirectory(work); ok {
source = entry
}
if installed, err := downloadTargetExists(target); err != nil {
return err
} else if installed {
downloadProgress(out, "Already installed %s", target)
return nil
}
if err := os.Rename(source, target); err != nil {
return fmt.Errorf("install java into %s: %w", target, err)
}
downloadProgress(out, "Installed %s", target)
return nil
}
// downloadTargetExists reports whether path is an installed runtime. A file
// at path blocks the installation instead of counting as installed.
func downloadTargetExists(path string) (bool, error) {
info, err := os.Stat(path)
switch {
case err == nil && info.IsDir():
return true, nil
case err == nil:
return false, fmt.Errorf("%s exists and is not a directory", path)
case errors.Is(err, os.ErrNotExist):
return false, nil
default:
return false, err
}
}
// fetchDownloadArchive streams the archive into dst and verifies the sha256
// checksum while the bytes arrive. A mismatch leaves dst incomplete.
// The request uses the invocation's configured HTTP client and context.
func fetchDownloadArchive(
ctx context.Context,
host *Host,
d *download,
dst io.Writer,
) error {
response, err := host.request(ctx, d.url)
if err != nil {
return fmt.Errorf("download %s: %w", d.filename, err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf(
"download %s: server responded %s",
d.filename,
response.Status,
)
}
hash := sha256.New()
if _, err := io.Copy(io.MultiWriter(dst, hash), response.Body); err != nil {
return fmt.Errorf("download %s: %w", d.filename, err)
}
actual := hex.EncodeToString(hash.Sum(nil))
if !strings.EqualFold(actual, d.checksum) {
return fmt.Errorf(
"checksum of %s is %s, want %s",
d.filename,
actual,
d.checksum,
)
}
return nil
}
// extractDownloadArchive unpacks the archive into dir. Every file operation
// goes through a root, so an entry cannot reach outside dir, also not through
// a symbolic link that an earlier entry created.
func extractDownloadArchive(archivePath, archiveType, dir string) error {
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer root.Close()
switch archiveType {
case "tar.gz":
err = extractDownloadTarGz(archivePath, root)
case "zip":
err = extractDownloadZip(archivePath, root)
default:
err = fmt.Errorf("unsupported archive type %q", archiveType)
}
if err != nil {
return err
}
return verifyDownloadLinks(root)
}
func extractDownloadTarGz(archivePath string, root *os.Root) error {
archive, err := os.Open(archivePath)
if err != nil {
return err
}
defer archive.Close()
compressed, err := gzip.NewReader(archive)
if err != nil {
return err
}
defer compressed.Close()
reader := tar.NewReader(compressed)
for {
header, err := reader.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if err := extractDownloadTarEntry(reader, header, root); err != nil {
return err
}
}
}
func extractDownloadTarEntry(reader io.Reader, header *tar.Header, root *os.Root) error {
name, err := downloadEntryName(header.Name)
if err != nil {
return err
}
switch header.Typeflag {
case tar.TypeDir:
return root.MkdirAll(name, 0o755)
case tar.TypeReg:
return writeDownloadFile(root, name, reader, header.FileInfo().Mode())
case tar.TypeSymlink:
return writeDownloadSymlink(root, name, header.Linkname)
case tar.TypeLink:
target, err := downloadEntryName(header.Linkname)
if err != nil {
return err
}
if err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil {
return err
}
return root.Link(target, name)
default:
return fmt.Errorf(
"archive entry %q has unsupported type %d",
header.Name,
header.Typeflag,
)
}
}
func extractDownloadZip(archivePath string, root *os.Root) error {
archive, err := zip.OpenReader(archivePath)
if err != nil {
return err
}
defer archive.Close()
for _, entry := range archive.File {
if err := extractDownloadZipEntry(entry, root); err != nil {
return err
}
}
return nil
}
func extractDownloadZipEntry(entry *zip.File, root *os.Root) error {
name, err := downloadEntryName(entry.Name)
if err != nil {
return err
}
mode := entry.Mode()
if mode&os.ModeSymlink != 0 {
reader, err := entry.Open()
if err != nil {
return err
}
target, readErr := io.ReadAll(io.LimitReader(reader, 4096))
closeErr := reader.Close()
if readErr != nil {
return readErr
}
if closeErr != nil {
return closeErr
}
return writeDownloadSymlink(root, name, string(target))
}
if entry.FileInfo().IsDir() {
return root.MkdirAll(name, 0o755)
}
if !mode.IsRegular() {
return fmt.Errorf("archive entry %q has unsupported mode", entry.Name)
}
reader, err := entry.Open()
if err != nil {
return err
}
writeErr := writeDownloadFile(root, name, reader, mode)
return errors.Join(writeErr, reader.Close())
}
func writeDownloadFile(root *os.Root, name string, reader io.Reader, mode os.FileMode) error {
permissions := mode.Perm()
if permissions == 0 {
permissions = 0o644
}
if err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil {
return err
}
file, err := root.OpenFile(
name,
os.O_CREATE|os.O_WRONLY|os.O_TRUNC,
permissions,
)
if err != nil {
return err
}
if _, err := io.Copy(file, reader); err != nil {
return errors.Join(err, file.Close())
}
return file.Close()
}
// writeDownloadSymlink creates a link whose target stays inside the extraction
// directory when read from the link's own path. An absolute target would
// break after the rename. A link can still escape later, through a directory
// link that a later entry creates. verifyDownloadLinks catches that case.
func writeDownloadSymlink(root *os.Root, name, target string) error {
local := filepath.FromSlash(target)
if filepath.IsAbs(local) || filepath.VolumeName(local) != "" {
return fmt.Errorf("archive symlink %q has an absolute target", name)
}
if !downloadContained(filepath.Join(filepath.Dir(name), local)) {
return fmt.Errorf(
"archive symlink %q points outside the extraction directory",
name,
)
}
if err := root.MkdirAll(filepath.Dir(name), 0o755); err != nil {
return err
}
return root.Symlink(local, name)
}
// verifyDownloadLinks rejects a symbolic link that does not resolve inside the
// root. A link target that does not exist is allowed. The check runs after
// extraction, because an entry can create the directory link that another
// link needs in order to escape.
func verifyDownloadLinks(root *os.Root) error {
return fs.WalkDir(root.FS(), ".", func(name string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.Type()&fs.ModeSymlink == 0 {
return nil
}
if _, err := root.Stat(filepath.FromSlash(name)); err != nil &&
!errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf(
"archive symlink %q does not resolve inside the extraction directory: %w",
name,
err,
)
}
return nil
})
}
// downloadEntryName turns an archive name into a path relative to the
// extraction root. It rejects absolute names and names that leave the root.
func downloadEntryName(name string) (string, error) {
converted := filepath.FromSlash(name)
if filepath.IsAbs(converted) || filepath.VolumeName(converted) != "" {
return "", fmt.Errorf("archive entry %q is absolute", name)
}
cleaned := filepath.Clean(converted)
if !downloadContained(cleaned) {
return "", fmt.Errorf(
"archive entry %q escapes the extraction directory",
name,
)
}
return cleaned, nil
}
// downloadContained reports whether a cleaned relative path stays inside its
// root.
func downloadContained(relative string) bool {
return relative != ".." &&
!strings.HasPrefix(relative, ".."+string(filepath.Separator))
}
func downloadSingleDirectory(dir string) (string, bool) {
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 1 {
return "", false
}
if !entries[0].IsDir() {
return "", false
}
return filepath.Join(dir, entries[0].Name()), true
}
func downloadProgress(out io.Writer, format string, args ...any) {
if out == nil {
return
}
_, _ = fmt.Fprintf(out, format+"\n", args...)
}
func downloadSize(size int64) string {
const (
kilobyte = 1 << 10
megabyte = 1 << 20
)
switch {
case size >= megabyte:
return fmt.Sprintf("%.0f MB", float64(size)/megabyte)
case size >= kilobyte:
return fmt.Sprintf("%.0f KB", float64(size)/kilobyte)
case size > 0:
return fmt.Sprintf("%d bytes", size)
default:
return "unknown size"
}
}
package javainstall
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/mclucy/lucy/internal/shell"
)
// errChildUnconfirmed reports that a step process ended from a signal other
// than the SIGINT expected after a relayed cancellation. Such a process could
// not have waited for the child it started, so a later restore must not
// assume that child has stopped.
var errChildUnconfirmed = errors.New("process exited from an unexpected signal; a child it started may still be running")
// Execute runs plan, using input for interactive steps and out for output.
// It returns the installed Java home for a managed download.
func (h *Host) Execute(
ctx context.Context,
plan Plan,
policy Policy,
input io.Reader,
out io.Writer,
) (string, error) {
h.logger.Info(
"installing java",
"method", plan.Method,
"package", plan.Package,
"major", plan.Major,
"distribution", plan.Distribution.String(),
)
if plan.download != nil {
if err := runDownload(ctx, h, plan.download, plan.managedRoot, out); err != nil {
return "", err
}
h.logger.Info("java installed", "method", plan.Method, "package", plan.Package)
home := filepath.Join(plan.managedRoot, plan.download.destination)
if info, err := os.Stat(filepath.Join(home, "Contents", "Home")); err == nil && info.IsDir() {
home = filepath.Join(home, "Contents", "Home")
}
return home, nil
}
if plan.Repository != nil {
if err := addRepository(ctx, plan.Repository, policy, h, input, out); err != nil {
return "", fmt.Errorf("add %s: %w", plan.Repository.Name, err)
}
h.logger.Info(
"java repository added",
"repository", plan.Repository.Name,
"url", plan.Repository.URL,
)
}
previous := ""
if plan.KeepDefault {
previous = systemDefaultJava(h)
}
var installErr error
// A step that ended from an unexpected signal may still have a child
// running; do not restore over it.
restoreSafe := true
run := runStep
if plan.KeepDefault && previous != "" {
run = runStepWaitingForStop
}
for _, step := range plan.Steps {
if err := run(ctx, step, policy, h, input, out); err != nil {
installErr = err
restoreSafe = !errors.Is(err, errChildUnconfirmed)
break
}
}
if plan.KeepDefault && previous != "" && len(plan.Steps) > 0 {
if !restoreSafe {
installErr = errors.Join(installErr, fmt.Errorf(
"system default Java %s was not restored because an install process exited from an unexpected signal and its child could not be confirmed stopped",
previous,
))
} else if err := restoreSystemDefault(ctx, previous, policy, h, input, out); err != nil {
restoreErr := fmt.Errorf("restore the system default Java %s: %w", previous, err)
if installErr == nil {
installErr = restoreErr
} else {
installErr = errors.Join(installErr, restoreErr)
}
}
}
if installErr != nil {
return "", installErr
}
h.logger.Info("java installed", "method", plan.Method, "package", plan.Package)
return "", nil
}
// Commands describes what Execute runs, one shell-like line per action, in
// the order Execute runs them.
func (p Plan) Commands() []string {
if p.download != nil {
return p.download.describe(p.managedRoot)
}
var lines []string
if r := p.Repository; r != nil {
if r.Key != nil {
lines = append(
lines,
fmt.Sprintf("download %s and verify fingerprint %s", r.Key.URL, r.Key.Fingerprint),
rootPrefix(p.root)+"write "+r.Key.Path,
)
}
for _, file := range r.Files {
lines = append(lines, rootPrefix(p.root)+"write "+file.Path)
}
for _, step := range r.Steps {
lines = append(lines, step.command(p.root))
}
}
for _, step := range p.Steps {
lines = append(lines, step.command(p.root))
}
return lines
}
// command renders the step as a command line a user can run. root reports
// whether the plan was made as root.
func (s Step) command(root bool) string {
args := s.Args
if s.Elevation == ElevationRoot && !root {
args = append([]string{"sudo"}, args...)
}
quoted := make([]string, len(args))
for i, arg := range args {
quoted[i] = shell.Quote(arg)
}
return strings.Join(quoted, " ")
}
func rootPrefix(root bool) string {
if root {
return ""
}
return "sudo "
}
// runStep runs one step with the ordinary cancellation behavior: a canceled
// context kills the process.
func runStep(
ctx context.Context,
step Step,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
return runStepWithCancel(ctx, step, policy, host, input, out, false)
}
// runStepWaitingForStop runs a step whose completion gates a restore. A
// canceled context interrupts the process and waits for it to exit, so the
// restore cannot race an elevated child.
func runStepWaitingForStop(
ctx context.Context,
step Step,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
return runStepWithCancel(ctx, step, policy, host, input, out, true)
}
func runStepWithCancel(
ctx context.Context,
step Step,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
interruptOnCancel bool,
) error {
if len(step.Args) == 0 {
return errors.New("empty install step")
}
args := append([]string(nil), step.Args...)
path, err := exec.LookPath(args[0])
if err != nil {
return fmt.Errorf("%s: %w", step.command(host.isRoot()), err)
}
args[0] = path
root := host.isRoot()
if step.Elevation == ElevationRoot && !root {
sudo, err := exec.LookPath("sudo")
if err != nil {
return fmt.Errorf("%s: %w", step.command(root), err)
}
prefix := []string{sudo}
if !policy.Interactive {
prefix = append(prefix, "-n")
}
args = append(append(prefix, "--"), args...)
}
host.logger.Info("running java install step", "command", strings.Join(args, " "))
stdin := input
if step.Input != "" {
stdin = strings.NewReader(step.Input)
}
if err := runCommand(ctx, Command{
Args: args,
Env: os.Environ(),
Stdin: stdin,
Stdout: out,
Stderr: out,
InterruptOnCancel: interruptOnCancel,
}); err != nil {
return fmt.Errorf("%s: %w", step.command(root), err)
}
return nil
}
// writeRootFile writes data at path as root. A non-root process stages the
// bytes in a temporary file and copies them with install(1) through sudo.
func writeRootFile(
ctx context.Context,
path string,
data []byte,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
if host.isRoot() {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
staged, err := os.CreateTemp("", "lucy-java-*")
if err != nil {
return err
}
defer os.Remove(staged.Name())
if _, err := staged.Write(data); err != nil {
return errors.Join(err, staged.Close())
}
if err := staged.Close(); err != nil {
return err
}
return runStep(ctx, Step{
Args: []string{"install", "-D", "-m", "0644", staged.Name(), path},
Elevation: ElevationRoot,
}, policy, host, input, out)
}
package javainstall
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/internal/toolchain"
"github.com/mclucy/lucy/log"
)
// probeTimeout bounds a read-only package manager query. A query that exceeds
// it counts as a missing package.
const probeTimeout = 30 * time.Second
// Policy carries the command boundary's choices for a Java installation.
type Policy struct {
// Interactive reports that a terminal can answer password and agreement
// prompts.
Interactive bool
// AllowRepository records the user's consent to add a vendor package
// repository to the system package manager.
AllowRepository bool
}
// Command is one process invocation for the host. Args[0] names the
// executable.
type Command struct {
Args []string
Env []string
Dir string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// InterruptOnCancel asks Run to stop the process gracefully on
// cancellation and wait for it to exit. On Unix it sends an interrupt;
// a wrapper such as sudo relays the interrupt to the command it runs
// and waits for it, so Run returns only after that child has stopped.
// Platforms without process interrupts kill the direct process and
// still wait for it.
InterruptOnCancel bool
}
func runCommand(ctx context.Context, command Command) error {
if len(command.Args) == 0 {
return errors.New("empty command")
}
process := exec.CommandContext(
ctx,
command.Args[0],
command.Args[1:]...,
)
process.Env = command.Env
process.Dir = command.Dir
process.Stdin = command.Stdin
process.Stdout = command.Stdout
process.Stderr = command.Stderr
if command.InterruptOnCancel {
process.Cancel = func() error {
if process.Process == nil {
return os.ErrProcessDone
}
return interruptCommand(process.Process)
}
// WaitDelay stays zero on purpose: killing the process before it
// exits would orphan the child the interrupt mode exists to wait for.
}
err := process.Run()
if err == nil {
return nil
}
ctxErr := ctx.Err()
if ctxErr != nil && !errors.Is(err, ctxErr) {
err = fmt.Errorf("%w: %w", err, ctxErr)
}
if command.InterruptOnCancel && commandExitUnconfirmed(process.ProcessState, ctxErr != nil) {
return fmt.Errorf("%w: %w", errChildUnconfirmed, err)
}
return err
}
func readSystemRelease() (map[string]string, error) {
data, err := os.ReadFile("/etc/os-release")
if err != nil {
return nil, err
}
fields := map[string]string{}
for line := range strings.Lines(string(data)) {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
fields[key] = strings.Trim(strings.TrimSpace(value), `"'`)
}
return fields, nil
}
func detectMusl() bool {
if _, err := os.Stat("/etc/alpine-release"); err == nil {
return true
}
for _, pattern := range []string{
"/lib/ld-musl-*.so.1",
"/usr/lib/ld-musl-*.so.1",
"/lib64/ld-musl-*.so.1",
} {
matches, err := filepath.Glob(pattern)
if err == nil && len(matches) > 0 {
return true
}
}
return false
}
// Host is the per-invocation host boundary for Java provisioning. It finds
// executables, runs read-only probes, names the managed runtime directory,
// reads system release and elevation facts, and reaches the network through
// the invocation's cache client. Planning and execution share one Host, and
// every fact is probed only when a plan needs it. A Host must not be copied
// after first use.
type Host struct {
network *cache.Client
logger *log.Logger
goos string
goarch string
managedOnce sync.Once
managedPath string
managedErr error
releaseOnce sync.Once
release map[string]string
muslOnce sync.Once
musl bool
rootOnce sync.Once
root bool
sudoMu sync.Mutex
sudoKnown bool
sudo bool
}
// NewHost returns the host boundary for one invocation. It probes nothing
// until planning or execution needs a fact. network carries the invocation's
// HTTP transport and cache, and logger records planning decisions; a nil
// logger records nothing.
func NewHost(
network *cache.Client,
logger *log.Logger,
) *Host {
return &Host{
network: network,
logger: logger,
goos: runtime.GOOS,
goarch: runtime.GOARCH,
}
}
// managedRoot returns the per-user directory that holds downloaded Java
// runtimes.
func (h *Host) managedRoot() (string, error) {
h.managedOnce.Do(func() {
h.managedPath, h.managedErr = toolchain.ManagedJavaRoot()
})
return h.managedPath, h.managedErr
}
// systemRelease returns the fields of /etc/os-release. An absent file yields
// an empty map.
func (h *Host) systemRelease() map[string]string {
h.releaseOnce.Do(func() {
release, err := readSystemRelease()
if err != nil {
h.logger.Debug("read os-release failed", "reason", err)
release = nil
}
if release == nil {
release = map[string]string{}
}
h.release = release
})
return h.release
}
// usesMusl reports whether the host runs musl instead of glibc.
func (h *Host) usesMusl() bool {
h.muslOnce.Do(func() {
h.musl = detectMusl()
})
return h.musl
}
func (h *Host) isRoot() bool {
h.rootOnce.Do(func() {
h.root = os.Geteuid() == 0
})
return h.root
}
// rootAvailable reports whether a step that needs root can run. Without a
// terminal, sudo can only run when it does not ask for a password.
func (h *Host) rootAvailable(ctx context.Context, policy Policy) (bool, error) {
if h.isRoot() {
return true, nil
}
path, err := exec.LookPath("sudo")
if err != nil {
return false, nil
}
if policy.Interactive {
return true, nil
}
return h.passwordlessSudo(ctx, path)
}
func (h *Host) passwordlessSudo(ctx context.Context, sudo string) (bool, error) {
h.sudoMu.Lock()
defer h.sudoMu.Unlock()
if err := ctx.Err(); err != nil {
return false, err
}
if h.sudoKnown {
return h.sudo, nil
}
probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
err := runCommand(probeCtx, Command{
Args: []string{sudo, "-n", "true"},
Env: os.Environ(),
})
if err := probeCtx.Err(); err != nil {
return false, err
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false, err
}
h.sudo = err == nil
h.sudoKnown = true
return h.sudo, nil
}
// systemToolAvailable reports whether every named binary is on PATH. System
// package managers run only on Linux.
func (h *Host) systemToolAvailable(names ...string) bool {
if h.goos != "linux" {
return false
}
for _, name := range names {
if _, err := exec.LookPath(name); err != nil {
return false
}
}
return true
}
// systemProbe runs a read-only query with a bounded wait. The error carries
// stderr so the caller can report why the query failed.
func (h *Host) systemProbe(ctx context.Context, args ...string) ([]byte, error) {
if len(args) == 0 {
return nil, errors.New("empty system probe")
}
return h.probe(ctx, probeTimeout, nil, args[0], args[1:]...)
}
// probe runs one read-only command with a bounded wait. A nil environment
// uses the supplied system environment.
func (h *Host) probe(
ctx context.Context,
wait time.Duration,
environment []string,
name string,
args ...string,
) ([]byte, error) {
probeCtx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
path, err := exec.LookPath(name)
if err != nil {
return nil, err
}
if environment == nil {
environment = os.Environ()
}
var stdout, stderr bytes.Buffer
err = runCommand(probeCtx, Command{
Args: append([]string{path}, args...),
Env: environment,
Stdout: &stdout,
Stderr: &stderr,
})
if err != nil {
detail := strings.TrimSpace(stderr.String())
line := strings.Join(append([]string{name}, args...), " ")
if detail == "" {
return stdout.Bytes(), fmt.Errorf("%s: %w", line, err)
}
return stdout.Bytes(), fmt.Errorf("%s: %w: %s", line, err, detail)
}
return stdout.Bytes(), nil
}
func (h *Host) fetchMetadata(
ctx context.Context,
address string,
ttl time.Duration,
) ([]byte, error) {
return h.network.CachedGetBytes(ctx, address, cache.BytesRequestOptions{
Kind: cache.KindMetadata,
TTL: ttl,
})
}
func (h *Host) request(
ctx context.Context,
address string,
) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return nil, err
}
return h.network.Do(request)
}
package javainstall
import (
"context"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/java"
)
// miseVendors maps each distribution to the vendor prefix of its mise java
// version.
var miseVendors = map[java.Distribution]string{
java.DistributionTemurin: "temurin",
java.DistributionZulu: "zulu",
java.DistributionCorretto: "corretto",
java.DistributionLiberica: "liberica",
java.DistributionMicrosoft: "microsoft",
java.DistributionOracle: "oracle",
java.DistributionOracleOpenJDK: "openjdk",
java.DistributionGraalVM: "oracle-graalvm",
java.DistributionGraalVMCommunity: "graalvm-community",
java.DistributionSemeru: "semeru",
java.DistributionSapMachine: "sapmachine",
java.DistributionDragonwell: "dragonwell",
java.DistributionKona: "kona",
java.DistributionRedHat: "redhat",
java.DistributionJetBrains: "jetbrains",
}
type mise struct{}
func (mise) method() Method { return MethodMise }
func (mise) system() bool { return false }
func (mise) ownsJava(_ context.Context, _ *Host) bool {
dir := miseDataDir()
if dir == "" {
return false
}
entries, err := os.ReadDir(filepath.Join(dir, "installs", "java"))
return err == nil && len(entries) > 0
}
func (mise) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if _, err := exec.LookPath("mise"); err != nil {
return nil, nil
}
prefix, distribution, ok := miseVendor(req.Distribution)
if !ok {
return nil, nil
}
spec := prefix + "-" + strconv.Itoa(req.Major)
output, err := miseCommand(ctx, host, "ls-remote", "java", spec)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
host.logger.Debug("mise java versions unavailable", "spec", spec, "reason", err)
return nil, nil
}
if strings.TrimSpace(output) == "" {
return nil, nil
}
return []Plan{{
Method: MethodMise,
Package: "java@" + spec,
Distribution: distribution,
Major: req.Major,
Steps: []Step{{
Args: []string{"mise", "install", "java@" + spec},
Elevation: ElevationNone,
}},
}}, nil
}
// miseVendor returns the vendor prefix for dist. The unspecified distribution
// installs Temurin, the mise java default.
func miseVendor(dist java.Distribution) (string, java.Distribution, bool) {
if dist == java.DistributionAny {
return "temurin", java.DistributionTemurin, true
}
prefix, ok := miseVendors[dist]
return prefix, dist, ok
}
func miseDataDir() string {
if dir := os.Getenv("MISE_DATA_DIR"); dir != "" {
return dir
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".local", "share", "mise")
}
// miseCommand runs a read-only mise query with a bounded wait.
func miseCommand(
ctx context.Context,
host *Host,
args ...string,
) (string, error) {
output, err := host.probe(ctx, 20*time.Second, nil, "mise", args...)
return string(output), err
}
package javainstall
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/mclucy/lucy/java"
)
// pacman installs Java from the configured Pacman sources.
type pacman struct{}
func (pacman) method() Method { return MethodPacman }
func (pacman) system() bool { return true }
func (pacman) ownsJava(context.Context, *Host) bool { return false }
func (pacman) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if req.Major <= 0 ||
req.Distribution != java.DistributionAny ||
!host.systemToolAvailable("pacman") {
return nil, nil
}
pkg := fmt.Sprintf("jre%d-openjdk-headless", req.Major)
if !pacmanPackageAvailable(ctx, host, pkg) {
info, ok := pacmanPackageInfo(ctx, host, "jre-openjdk-headless")
if !ok || !pacmanProvidesMajor(info, req.Major) {
return nil, nil
}
pkg = "jre-openjdk-headless"
}
return []Plan{
{
Method: MethodPacman,
Package: pkg,
Distribution: java.DistributionAny,
Major: req.Major,
Steps: []Step{
{
Args: []string{
"pacman",
"-S",
"--needed",
"--noconfirm",
pkg,
},
Elevation: ElevationRoot,
},
},
},
}, nil
}
// pacmanPackageInfo returns the repository metadata of pkg, or false when the
// configured sources do not offer it.
func pacmanPackageInfo(
ctx context.Context,
host *Host,
pkg string,
) (string, bool) {
output, err := host.systemProbe(ctx, "pacman", "-Si", pkg)
if err != nil {
host.logger.Debug("pacman package probe failed", "package", pkg, "reason", err)
return "", false
}
return string(output), true
}
func pacmanPackageAvailable(ctx context.Context, host *Host, pkg string) bool {
_, ok := pacmanPackageInfo(ctx, host, pkg)
return ok
}
// pacmanProvidesMajor reports whether the package metadata names major in its
// Provides field, which the unversioned package uses to follow the latest
// release.
func pacmanProvidesMajor(info string, major int) bool {
want := strconv.Itoa(major)
inProvides := false
for line := range strings.Lines(info) {
trimmed := strings.TrimSpace(line)
field, value, hasField := strings.Cut(trimmed, ":")
if hasField {
field = strings.TrimSpace(field)
}
if hasField && !strings.Contains(field, " ") {
inProvides = field == "Provides"
if !inProvides {
continue
}
} else if inProvides {
value = trimmed
} else {
continue
}
for _, token := range strings.Fields(value) {
name, version, ok := strings.Cut(token, "=")
if !ok || version != want {
continue
}
switch name {
case "java-runtime",
"java-runtime-headless",
"jre-openjdk",
"jre-openjdk-headless":
return true
}
}
}
return false
}
//go:build unix
package javainstall
import (
"os"
"syscall"
)
// interruptCommand asks process to stop. The signal comes from a user
// process, so sudo relays it to the command it runs and waits for that
// command to exit.
func interruptCommand(process *os.Process) error {
return process.Signal(os.Interrupt)
}
// commandExitUnconfirmed reports whether the process ended from a signal
// that does not confirm it waited for a child. Only the SIGINT expected
// after a canceled context is treated as the relayed cancellation; any other
// signal may have bypassed that wait.
func commandExitUnconfirmed(state *os.ProcessState, canceled bool) bool {
if state == nil {
return false
}
status, ok := state.Sys().(syscall.WaitStatus)
if !ok || !status.Signaled() {
return false
}
return !canceled || status.Signal() != syscall.SIGINT
}
package javainstall
import (
"context"
"errors"
"fmt"
"io"
"strings"
)
// systemVersionMajor returns the leading release number, because vendor
// repositories name a distribution by its major version.
func systemVersionMajor(version string) string {
major, _, _ := strings.Cut(version, ".")
return major
}
// systemRPMArch maps the Go architecture to the RPM base architecture.
func systemRPMArch(goarch string) string {
switch goarch {
case "amd64":
return "x86_64"
case "386":
return "i686"
case "arm64":
return "aarch64"
case "ppc64le":
return "ppc64le"
case "s390x":
return "s390x"
default:
return ""
}
}
// addRepository writes the verified key and the source files, then runs the
// repository steps. Every write happens as root.
func addRepository(
ctx context.Context,
repo *Repository,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
if repo == nil {
return errors.New("no repository to add")
}
if repo.Key != nil {
if err := addRepositoryKey(ctx, repo.Key, policy, host, input, out); err != nil {
return err
}
}
for _, file := range repo.Files {
if err := writeRootFile(
ctx,
file.Path,
[]byte(file.Content),
policy,
host,
input,
out,
); err != nil {
return fmt.Errorf("write %s: %w", file.Path, err)
}
}
for _, step := range repo.Steps {
if err := runStep(ctx, step, policy, host, input, out); err != nil {
return err
}
}
return nil
}
//go:build linux
package javainstall
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/ProtonMail/gopenpgp/v3/armor"
"github.com/ProtonMail/gopenpgp/v3/crypto"
)
// repositoryKeyMaxBytes is the largest key file Lucy accepts. A vendor key is
// a few kilobytes.
const repositoryKeyMaxBytes = 1 << 20
func addRepositoryKey(
ctx context.Context,
key *RepositoryKey,
policy Policy,
host *Host,
input io.Reader,
out io.Writer,
) error {
entity, err := fetchRepositoryKey(ctx, key, host)
if err != nil {
return err
}
data, err := serializeRepositoryKey(entity, key.Armored)
if err != nil {
return err
}
return writeRootFile(ctx, key.Path, data, policy, host, input, out)
}
// fetchRepositoryKey downloads and verifies the pinned key. A key URL must
// use HTTPS, because the pin protects only the key that arrives.
func fetchRepositoryKey(
ctx context.Context,
key *RepositoryKey,
host *Host,
) (*crypto.Key, error) {
address, err := url.Parse(key.URL)
if err != nil {
return nil, fmt.Errorf("parse repository key URL: %w", err)
}
if !strings.EqualFold(address.Scheme, "https") || address.Host == "" {
return nil, fmt.Errorf(
"repository key URL must use HTTPS: %s",
key.URL,
)
}
host.logger.Debug("fetching repository key", "url", key.URL)
probeCtx, cancel := context.WithTimeout(ctx, probeTimeout)
defer cancel()
response, err := host.request(probeCtx, key.URL)
if err != nil {
return nil, fmt.Errorf("fetch repository key: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"fetch repository key: status %s",
response.Status,
)
}
data, err := io.ReadAll(
io.LimitReader(response.Body, repositoryKeyMaxBytes+1),
)
if err != nil {
return nil, fmt.Errorf("read repository key: %w", err)
}
if int64(len(data)) > repositoryKeyMaxBytes {
return nil, errors.New("repository key exceeds 1 MiB")
}
entity, err := verifyRepositoryKey(data, key.Fingerprint)
if err != nil {
return nil, err
}
return entity, nil
}
// verifyRepositoryKey returns the key whose primary fingerprint matches pin.
// The comparison ignores case and whitespace.
func verifyRepositoryKey(data []byte, pin string) (*crypto.Key, error) {
keys, err := repositoryKeys(data)
if err != nil {
return nil, err
}
want := normalizeFingerprint(pin)
if want == "" {
return nil, errors.New("repository key has no pinned fingerprint")
}
for _, key := range keys {
if strings.ToUpper(key.GetFingerprint()) == want {
return key, nil
}
}
return nil, fmt.Errorf(
"repository key fingerprint mismatch: want %s",
pin,
)
}
func repositoryKeys(data []byte) ([]*crypto.Key, error) {
binary, armorErr := armor.UnarmorBytes(data)
if armorErr == nil {
ring, err := crypto.NewKeyRingFromBinary(binary)
if err == nil {
return ring.GetKeys(), nil
}
}
ring, binaryErr := crypto.NewKeyRingFromBinary(data)
if binaryErr != nil {
return nil, fmt.Errorf(
"parse OpenPGP key: %w",
errors.Join(armorErr, binaryErr),
)
}
return ring.GetKeys(), nil
}
func normalizeFingerprint(fingerprint string) string {
return strings.ToUpper(strings.Join(strings.Fields(fingerprint), ""))
}
func serializeRepositoryKey(
key *crypto.Key,
armored bool,
) ([]byte, error) {
data, err := key.GetPublicKey()
if err != nil {
return nil, fmt.Errorf("serialize repository key: %w", err)
}
if !armored {
return data, nil
}
text, err := armor.ArmorWithTypeBytes(data, "PGP PUBLIC KEY BLOCK")
if err != nil {
return nil, fmt.Errorf("armor repository key: %w", err)
}
return text, nil
}
package javainstall
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/java"
)
// scoop is the Scoop package manager.
type scoop struct{}
// scoopJavaBucketURL is the repository that serves the java bucket.
const scoopJavaBucketURL = "https://github.com/ScoopInstaller/Java"
// scoopJavaPackage describes the manifests of one distribution in the java
// bucket. The formats carry one %d directive for the major. An empty format
// marks a build the bucket does not package.
type scoopJavaPackage struct {
distribution java.Distribution
jreFormat string
jdkFormat string
jreMajors []int
jdkMajors []int
}
// scoopJavaPackages lists the java bucket manifests that exist for each
// distribution.
var scoopJavaPackages = []scoopJavaPackage{
{
distribution: java.DistributionTemurin,
jreFormat: "temurin%d-jre",
jdkFormat: "temurin%d-jdk",
jreMajors: []int{8, 11, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
jdkMajors: []int{8, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
},
{
distribution: java.DistributionZulu,
jreFormat: "zulu%d-jre",
jdkFormat: "zulu%d-jdk",
jreMajors: []int{8, 11, 12, 13, 14, 15, 16, 17, 21, 22},
jdkMajors: []int{7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 21, 22, 25},
},
{
distribution: java.DistributionCorretto,
jreFormat: "corretto%d-jre",
jdkFormat: "corretto%d-jdk",
jreMajors: []int{8},
jdkMajors: []int{8, 11, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25},
},
{
distribution: java.DistributionLiberica,
jreFormat: "liberica%d-jre",
jdkFormat: "liberica%d-jdk",
jreMajors: []int{8, 11, 13, 14, 15, 16, 17, 21, 25},
jdkMajors: []int{8, 11, 12, 13, 14, 15, 16, 17, 21, 25},
},
{
distribution: java.DistributionMicrosoft,
jdkFormat: "microsoft%d-jdk",
jdkMajors: []int{11, 16, 17, 21},
},
{
distribution: java.DistributionSapMachine,
jreFormat: "sapmachine%d-jre",
jdkFormat: "sapmachine%d-jdk",
jreMajors: []int{11, 12, 13, 14, 15, 16, 17, 18},
jdkMajors: []int{11, 12, 13, 14, 15, 16, 17, 18},
},
{
distribution: java.DistributionSemeru,
jreFormat: "semeru%d-jre",
jdkFormat: "semeru%d-jdk",
jreMajors: []int{8, 11, 16, 17, 18, 19, 20, 21, 22, 23},
jdkMajors: []int{8, 11, 16, 17, 18, 19, 20, 21, 22, 23},
},
{
distribution: java.DistributionGraalVM,
jdkFormat: "graalvm-oracle-%djdk",
jdkMajors: []int{17, 20, 21, 22, 23, 24, 25},
},
{
distribution: java.DistributionGraalVMCommunity,
jdkFormat: "graalvm%d-jdk",
jdkMajors: []int{17, 20, 21, 22, 23, 24, 25},
},
{
distribution: java.DistributionDragonwell,
jdkFormat: "dragonwell%d-jdk",
jdkMajors: []int{8, 11, 17, 21},
},
{
distribution: java.DistributionRedHat,
jreFormat: "openjdk%d-redhat-jre",
jdkFormat: "openjdk%d-redhat",
jreMajors: []int{8},
jdkMajors: []int{8},
},
{
distribution: java.DistributionJetBrains,
jdkFormat: "intellij-jbr%d",
jdkMajors: []int{11, 17, 21, 25},
},
}
// scoopOpenJDKManifestMajors lists the majors with an unbranded openjdk
// manifest. The bucket serves the manifest as openjdk<major>.
var scoopOpenJDKManifestMajors = []int{
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
}
// scoopCandidate is one manifest that can satisfy a request.
type scoopCandidate struct {
manifest string
distribution java.Distribution
}
func (scoop) method() Method { return MethodScoop }
func (scoop) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if host.goos != "windows" {
return nil, nil
}
if _, err := exec.LookPath("scoop.cmd"); err != nil {
return nil, nil
}
hasManifest, err := scoopJavaBucket(ctx, host)
if err != nil {
return nil, err
}
return scoopPlans(req, hasManifest), nil
}
func (scoop) system() bool { return false }
// ownsJava reports whether scoop installed a Java runtime. Every scoop app
// links its active version through a current directory.
func (scoop) ownsJava(_ context.Context, host *Host) bool {
if host.goos != "windows" {
return false
}
root := scoopRoot()
if root == "" {
return false
}
matches, err := filepath.Glob(
filepath.Join(root, "apps", "*", "current", "bin", "java.exe"),
)
return err == nil && len(matches) > 0
}
// scoopPlans returns the plan that the java bucket installs req. At most one
// plan results. hasManifest reports whether the installed bucket has a
// manifest. A nil hasManifest means the bucket is absent, so the plan adds it
// and trusts the manifest names.
func scoopPlans(req Request, hasManifest func(string) bool) []Plan {
var chosen scoopCandidate
found := false
for _, candidate := range scoopCandidates(req) {
if hasManifest == nil || hasManifest(candidate.manifest) {
chosen = candidate
found = true
break
}
}
if !found {
return nil
}
// Steps run "scoop" directly. Go's LookPath on Windows resolves "scoop" to
// scoop.cmd via PATHEXT (.com;.exe;.bat;.cmd), and CreateProcess runs a
// .cmd file through cmd.exe. Arguments without cmd.exe metacharacters
// (such as "install" and "java/<name>") need no shell quoting. Other Go
// tools calling Scoop on GitHub (matcha, basecamp-cli, hey-cli, teamcity-cli,
// glazepkg) launch "scoop" the same way.
plan := Plan{
Method: MethodScoop,
Package: "java/" + chosen.manifest,
Distribution: chosen.distribution,
Major: req.Major,
Steps: []Step{{
Args: []string{"scoop", "install", "java/" + chosen.manifest},
Elevation: ElevationNone,
}},
}
if hasManifest == nil {
plan.Repository = &Repository{
Name: "Scoop java bucket",
URL: scoopJavaBucketURL,
Steps: []Step{{
Args: []string{"scoop", "bucket", "add", "java"},
Elevation: ElevationNone,
}},
}
}
return []Plan{plan}
}
// scoopCandidates lists the manifests that can install req, preferred first. A
// request for any build prefers Temurin and falls back to the unbranded
// openjdk manifest.
func scoopCandidates(req Request) []scoopCandidate {
distribution := req.Distribution
if distribution == java.DistributionAny {
distribution = java.DistributionTemurin
}
var candidates []scoopCandidate
for _, pkg := range scoopJavaPackages {
if pkg.distribution == distribution {
candidates = append(
candidates,
scoopPackageCandidates(pkg, req.Major)...,
)
break
}
}
if req.Distribution == java.DistributionAny &&
slices.Contains(scoopOpenJDKManifestMajors, req.Major) {
candidates = append(candidates, scoopCandidate{
manifest: fmt.Sprintf("openjdk%d", req.Major),
distribution: java.DistributionAny,
})
}
return candidates
}
// scoopPackageCandidates returns the JRE manifest before the JDK manifest.
func scoopPackageCandidates(pkg scoopJavaPackage, major int) []scoopCandidate {
var candidates []scoopCandidate
if pkg.jreFormat != "" && slices.Contains(pkg.jreMajors, major) {
candidates = append(candidates, scoopCandidate{
manifest: fmt.Sprintf(pkg.jreFormat, major),
distribution: pkg.distribution,
})
}
if pkg.jdkFormat != "" && slices.Contains(pkg.jdkMajors, major) {
candidates = append(candidates, scoopCandidate{
manifest: fmt.Sprintf(pkg.jdkFormat, major),
distribution: pkg.distribution,
})
}
return candidates
}
// scoopJavaBucket returns a manifest check for the installed java bucket. A
// nil check means the bucket is absent.
func scoopJavaBucket(ctx context.Context, host *Host) (func(string) bool, error) {
output, err := host.probe(
ctx,
probeTimeout,
nil,
"cmd.exe",
"/d",
"/s",
"/c",
"scoop bucket list",
)
if err != nil {
return nil, fmt.Errorf("list scoop buckets: %w", err)
}
if !scoopHasBucket(string(output), "java") {
return nil, nil
}
root := scoopRoot()
if root == "" {
return nil, nil
}
dir := filepath.Join(root, "buckets", "java", "bucket")
return func(manifest string) bool {
info, err := os.Stat(filepath.Join(dir, manifest+".json"))
return err == nil && info.Mode().IsRegular()
}, nil
}
// scoopHasBucket reports whether the bucket list output names bucket. The
// first column of each row is the bucket name.
func scoopHasBucket(output, bucket string) bool {
for _, line := range strings.Split(output, "\n") {
fields := strings.Fields(line)
if len(fields) > 0 && fields[0] == bucket {
return true
}
}
return false
}
// scoopRoot returns the scoop installation directory.
func scoopRoot() string {
if root := os.Getenv("SCOOP"); root != "" {
return root
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, "scoop")
}
package javainstall
import (
"cmp"
"context"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/internal/shell"
"github.com/mclucy/lucy/java"
)
// sdkmanVendors maps the vendor suffix of an SDKMAN candidate identifier to the
// build it names. SDKMAN has no vendor suffix for the remaining distributions.
var sdkmanVendors = map[string]java.Distribution{
"tem": java.DistributionTemurin,
"zulu": java.DistributionZulu,
"amzn": java.DistributionCorretto,
"librca": java.DistributionLiberica,
"ms": java.DistributionMicrosoft,
"oracle": java.DistributionOracle,
"open": java.DistributionOracleOpenJDK,
"graalce": java.DistributionGraalVMCommunity,
"graal": java.DistributionGraalVM,
"sem": java.DistributionSemeru,
"sapmchn": java.DistributionSapMachine,
"kona": java.DistributionKona,
"jbr": java.DistributionJetBrains,
}
type sdkman struct{}
func (sdkman) method() Method { return MethodSDKMAN }
func (sdkman) system() bool { return false }
func (sdkman) ownsJava(_ context.Context, _ *Host) bool {
home, ok := sdkmanHome()
if !ok {
return false
}
entries, err := os.ReadDir(filepath.Join(home, "candidates", "java"))
if err != nil {
return false
}
for _, entry := range entries {
if entry.Name() != "current" {
return true
}
}
return false
}
func (sdkman) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if host.goos == "windows" {
return nil, nil
}
home, ok := sdkmanHome()
if !ok {
return nil, nil
}
initScript := filepath.Join(home, "bin", "sdkman-init.sh")
if _, err := os.Stat(initScript); err != nil {
return nil, nil
}
platform, ok := sdkmanPlatform(host.goos, host.goarch)
if !ok {
return nil, nil
}
versions, err := sdkmanVersions(ctx, host, platform)
if err != nil {
host.logger.Debug(
"sdkman java versions unavailable",
"platform", platform,
"reason", err,
)
return nil, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
id, distribution, ok := sdkmanPick(versions, req)
if !ok {
return nil, nil
}
return []Plan{{
Method: MethodSDKMAN,
Package: id,
Distribution: distribution,
Major: req.Major,
Steps: []Step{{
Args: []string{
"bash",
"-c",
"source " + shell.Quote(initScript) +
" && sdk install java " + shell.Quote(id),
},
Elevation: ElevationNone,
// "n" keeps SDKMAN from making the new candidate the default.
Input: "n\n",
}},
}}, nil
}
// sdkmanHome returns the SDKMAN directory. It is unavailable when neither
// SDKMAN_DIR nor the home directory names one.
func sdkmanHome() (string, bool) {
if dir := os.Getenv("SDKMAN_DIR"); dir != "" {
return dir, true
}
home, err := os.UserHomeDir()
if err != nil {
return "", false
}
return filepath.Join(home, ".sdkman"), true
}
// sdkmanPlatform returns the SDKMAN platform segment for this host.
func sdkmanPlatform(goos, goarch string) (string, bool) {
switch goos + "/" + goarch {
case "darwin/arm64":
return "darwinarm64", true
case "darwin/amd64":
return "darwinx64", true
case "linux/amd64":
return "linuxx64", true
case "linux/arm64":
return "linuxarm64", true
default:
return "", false
}
}
func sdkmanVersions(
ctx context.Context,
host *Host,
platform string,
) ([]string, error) {
data, err := host.fetchMetadata(
ctx,
"https://api.sdkman.io/2/candidates/java/"+platform+"/versions/all",
time.Hour,
)
if err != nil {
return nil, err
}
return strings.Split(string(data), ","), nil
}
// sdkmanPick returns the newest plain candidate for the request. A candidate
// is plain when it is exactly a version and one vendor suffix.
func sdkmanPick(versions []string, req Request) (string, java.Distribution, bool) {
wanted := req.Distribution
if wanted == java.DistributionAny {
wanted = java.DistributionTemurin
}
best := ""
bestVersion := []int(nil)
for _, raw := range versions {
id := strings.TrimSpace(raw)
version, vendor, ok := sdkmanSplit(id)
if !ok {
continue
}
distribution, ok := sdkmanVendors[vendor]
if !ok || distribution != wanted {
continue
}
numbers := sdkmanNumbers(version)
if len(numbers) == 0 || numbers[0] != req.Major {
continue
}
if best == "" || sdkmanCompareVersions(numbers, bestVersion) > 0 {
best = id
bestVersion = numbers
}
}
return best, wanted, best != ""
}
// sdkmanSplit discards variant builds, which carry a second dash or a variant
// tag in the version.
func sdkmanSplit(id string) (string, string, bool) {
if strings.Count(id, "-") != 1 {
return "", "", false
}
version, vendor, ok := strings.Cut(id, "-")
if !ok || version == "" || vendor == "" {
return "", "", false
}
if strings.Contains(version, "fx") || strings.Contains(version, "crac") {
return "", "", false
}
return version, vendor, true
}
func sdkmanNumbers(version string) []int {
fields := strings.FieldsFunc(version, func(r rune) bool {
return r < '0' || r > '9'
})
numbers := make([]int, 0, len(fields))
for _, field := range fields {
number, err := strconv.Atoi(field)
if err != nil {
continue
}
numbers = append(numbers, number)
}
return numbers
}
func sdkmanCompareVersions(a, b []int) int {
for i := 0; i < len(a) && i < len(b); i++ {
if result := cmp.Compare(a[i], b[i]); result != 0 {
return result
}
}
return cmp.Compare(len(a), len(b))
}
package javainstall
import (
"context"
"fmt"
"os/exec"
"slices"
"github.com/mclucy/lucy/java"
)
// winget is the Windows Package Manager.
type winget struct{}
// wingetJavaPackage describes the package identifiers of one distribution.
// The formats carry one %d directive for the major. An empty format marks a
// build that winget does not package.
type wingetJavaPackage struct {
distribution java.Distribution
jreFormat string
jdkFormat string
jreMajors []int
jdkMajors []int
}
// wingetJavaPackages lists the package identifiers that exist for each
// distribution.
var wingetJavaPackages = []wingetJavaPackage{
{
distribution: java.DistributionTemurin,
jreFormat: "EclipseAdoptium.Temurin.%d.JRE",
jdkFormat: "EclipseAdoptium.Temurin.%d.JDK",
jreMajors: []int{8, 11, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
jdkMajors: []int{8, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26},
},
{
distribution: java.DistributionZulu,
jreFormat: "Azul.Zulu.%d.JRE",
jdkFormat: "Azul.Zulu.%d.JDK",
jreMajors: []int{7, 8, 9, 11, 12, 13, 15, 16, 17, 18, 21, 25},
jdkMajors: []int{
6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27,
},
},
{
distribution: java.DistributionCorretto,
jreFormat: "Amazon.Corretto.%d.JRE",
jdkFormat: "Amazon.Corretto.%d.JDK",
jreMajors: []int{8},
jdkMajors: []int{
8, 11, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
},
},
{
distribution: java.DistributionLiberica,
jreFormat: "BellSoft.LibericaJRE.%d",
jdkFormat: "BellSoft.LibericaJDK.%d",
jreMajors: []int{
8, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
},
jdkMajors: []int{
8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26,
},
},
{
distribution: java.DistributionMicrosoft,
jdkFormat: "Microsoft.OpenJDK.%d",
jdkMajors: []int{11, 16, 17, 21, 25},
},
{
distribution: java.DistributionOracle,
jdkFormat: "Oracle.JDK.%d",
jdkMajors: []int{
17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
},
},
{
distribution: java.DistributionSapMachine,
jreFormat: "SAP.SapMachine.%d.JRE",
jdkFormat: "SAP.SapMachine.%d.JDK",
jreMajors: []int{11, 17, 21, 22, 23, 24, 25, 26, 27},
jdkMajors: []int{11, 17, 21, 22, 23, 24, 25, 26, 27},
},
{
distribution: java.DistributionSemeru,
jreFormat: "IBM.Semeru.%d.JRE",
jdkFormat: "IBM.Semeru.%d.JDK",
jreMajors: []int{
8, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
},
jdkMajors: []int{
8, 11, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
},
},
}
func (winget) method() Method { return MethodWinget }
func (winget) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if host.goos != "windows" {
return nil, nil
}
if _, err := exec.LookPath("winget.exe"); err != nil {
return nil, nil
}
return wingetPlans(req), nil
}
func (winget) system() bool { return true }
func (winget) ownsJava(context.Context, *Host) bool { return false }
// wingetPlans returns the plan that winget installs req with. At most one
// plan results. A request for any build prefers the Temurin JRE.
func wingetPlans(req Request) []Plan {
identifier, distribution, ok := wingetJavaIdentifier(req)
if !ok {
return nil
}
return []Plan{{
Method: MethodWinget,
Package: identifier,
Distribution: distribution,
Major: req.Major,
Steps: []Step{{
Args: []string{
"winget",
"install",
"--exact",
"--id",
identifier,
"--source",
"winget",
},
Elevation: ElevationSelf,
}},
}}
}
// wingetJavaIdentifier returns the package identifier for req, the build it
// installs, and whether winget packages req. The JRE package is preferred to
// the JDK package.
func wingetJavaIdentifier(req Request) (string, java.Distribution, bool) {
distribution := req.Distribution
if distribution == java.DistributionAny {
distribution = java.DistributionTemurin
}
for _, pkg := range wingetJavaPackages {
if pkg.distribution != distribution {
continue
}
if pkg.jreFormat != "" && slices.Contains(pkg.jreMajors, req.Major) {
return fmt.Sprintf(pkg.jreFormat, req.Major), pkg.distribution, true
}
if pkg.jdkFormat != "" && slices.Contains(pkg.jdkMajors, req.Major) {
return fmt.Sprintf(pkg.jdkFormat, req.Major), pkg.distribution, true
}
}
return "", java.DistributionAny, false
}
package javainstall
import (
"context"
"fmt"
"github.com/mclucy/lucy/java"
)
// zypper installs Java from the configured Zypper sources.
type zypper struct{}
func (zypper) method() Method { return MethodZypper }
func (zypper) system() bool { return true }
func (zypper) ownsJava(context.Context, *Host) bool { return false }
func (zypper) plans(ctx context.Context, req Request, host *Host) ([]Plan, error) {
if req.Major <= 0 ||
req.Distribution != java.DistributionAny ||
!host.systemToolAvailable("zypper") {
return nil, nil
}
pkg := fmt.Sprintf("java-%d-openjdk-headless", req.Major)
if !zypperPackageAvailable(ctx, host, pkg) {
return nil, nil
}
return []Plan{
{
Method: MethodZypper,
Package: pkg,
Distribution: java.DistributionAny,
Major: req.Major,
Steps: []Step{
{
Args: []string{
"zypper",
"--non-interactive",
"install",
"--no-recommends",
pkg,
},
Elevation: ElevationRoot,
},
},
KeepDefault: true,
},
}, nil
}
// zypperPackageAvailable reports whether the configured sources offer pkg.
func zypperPackageAvailable(
ctx context.Context,
host *Host,
pkg string,
) bool {
_, err := host.systemProbe(
ctx,
"zypper",
"--non-interactive",
"--quiet",
"search",
"--match-exact",
"--type",
"package",
pkg,
)
if err != nil {
host.logger.Debug("zypper package probe failed", "package", pkg, "reason", err)
return false
}
return true
}
// Package maven converts Maven coordinates to repository paths.
package maven
import (
"fmt"
"path"
"strings"
)
// Path returns the repository path of a coordinate. A coordinate names
// group:artifact:version with an optional classifier, and an optional
// @extension overrides the default jar extension.
func Path(coordinate string) (string, error) {
base, extension, has := strings.Cut(coordinate, "@")
if !has {
extension = "jar"
}
parts := strings.Split(base, ":")
if len(parts) < 3 || len(parts) > 4 {
return "", fmt.Errorf("invalid Maven coordinate %q", coordinate)
}
name := parts[1] + "-" + parts[2]
if len(parts) == 4 {
name += "-" + parts[3]
}
return path.Join(
strings.ReplaceAll(parts[0], ".", "/"),
parts[1],
parts[2],
name+"."+extension,
), nil
}
package selfupdate
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/log"
)
// DefaultManifestURL is the promoted release manifest served by Cloudflare.
const DefaultManifestURL = "https://lucy.lc/latest.json"
// Doer performs one HTTP request. It is satisfied by *http.Client and by the
// cache client's uncached transport.
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
// Options selects the executable and the release the command operates on.
type Options struct {
// ManifestURL overrides DefaultManifestURL. Tests and mirrors use it.
ManifestURL string
// Executable overrides the running binary path. Tests use it.
Executable string
// Version, Commit, and Official describe the running build.
Version string
Commit string
Official bool
// Force reinstalls the selected release even when it is not newer.
Force bool
// OnResolved runs after installation and manifest checks pass, before the
// download starts. It receives the release that will be installed.
OnResolved func(*Result)
// Progress reports the archive transfer in bytes.
Progress func(name string, read, total int64)
}
// Result reports what the manifest offered and what the command did.
type Result struct {
CurrentVersion string
CurrentCommit string
LatestVersion string
LatestChannel string
LatestCommit string
UpdateAvailable bool
Action string
Asset string
Checksum string
Executable string
ReleaseURL string
Notes []string
}
// Service resolves and applies lucy releases for one platform.
type Service struct {
doer Doer
logger *log.Logger
goos string
goarch string
}
// New constructs a service. logger may be nil, which records nothing.
func New(doer Doer, logger *log.Logger) *Service {
return &Service{
doer: doer,
logger: logger,
goos: runtime.GOOS,
goarch: runtime.GOARCH,
}
}
// Check resolves the manifest and reports whether an update is available. It
// never writes to the installed binary.
func (s *Service) Check(ctx context.Context, opts Options) (*Result, error) {
resolved, err := s.resolve(ctx, opts)
if err != nil {
return nil, err
}
installation, err := s.detect(opts, false)
if err != nil {
return nil, err
}
result := resolved.result(opts)
result.Action = "checked"
result.Executable = installation.Executable
result.Notes = append(result.Notes, installation.Notes...)
return result, nil
}
// Apply resolves the manifest and replaces the running executable when the
// release is newer, or when the caller forces a reinstall.
func (s *Service) Apply(ctx context.Context, opts Options) (*Result, error) {
resolved, err := s.resolve(ctx, opts)
if err != nil {
return nil, err
}
result := resolved.result(opts)
if !resolved.updateAvailable && !opts.Force {
installation, err := s.detect(opts, false)
if err != nil {
return nil, err
}
result.Action = "up-to-date"
result.Executable = installation.Executable
result.Notes = append(result.Notes, installation.Notes...)
return result, nil
}
installation, err := s.detect(opts, true)
if err != nil {
return nil, err
}
switch {
case installation.Blocked:
return nil, fmt.Errorf("this lucy cannot replace itself; %s", installation.Guidance)
case installation.Managed:
return nil, fmt.Errorf(
"lucy self-update is unavailable for a %s installation; %s",
installation.Method,
installation.Guidance,
)
case !installation.Updatable && !opts.Force:
return nil, fmt.Errorf("this lucy cannot replace itself; %s", installation.Guidance)
}
result.Executable = installation.Executable
lock, err := acquireLock()
if err != nil {
return nil, err
}
defer func() {
if closeErr := lock.Close(); closeErr != nil && s.logger != nil {
s.logger.Warn(fmt.Errorf("self-update lock was not released: %w", closeErr))
}
}()
s.logDebug("self-update started",
"current", opts.Version,
"latest", resolved.manifest.Version,
"asset", resolved.file.Name,
"executable", installation.Executable,
)
if opts.OnResolved != nil {
opts.OnResolved(result)
}
if err := s.downloadAndReplace(ctx, opts, resolved, installation.Executable); err != nil {
return nil, err
}
result.Action = "updated"
s.logDebug("self-update installed",
"previous", opts.Version,
"version", resolved.manifest.Version,
"executable", installation.Executable,
)
return result, nil
}
func (s *Service) logDebug(message string, args ...any) {
if s.logger != nil {
s.logger.Debug(message, args...)
}
}
func acquireLock() (*fsutil.FileLock, error) {
lockPath := filepath.Join(filepath.Dir(cache.DefaultRoot()), "self-update.lock")
if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
return nil, fmt.Errorf("prepare the update lock: %w", err)
}
lock, err := fsutil.TryLockFile(lockPath)
if errors.Is(err, fsutil.ErrLocked) {
return nil, errors.New("another lucy update is already running")
}
if err != nil {
return nil, fmt.Errorf("acquire the update lock: %w", err)
}
return lock, nil
}
func (r *resolved) result(opts Options) *Result {
return &Result{
CurrentVersion: strings.TrimSpace(opts.Version),
CurrentCommit: opts.Commit,
LatestVersion: r.manifest.Version,
LatestChannel: r.manifest.Channel,
LatestCommit: r.manifest.Commit,
UpdateAvailable: r.updateAvailable,
Asset: r.file.Name,
Checksum: r.file.SHA256,
ReleaseURL: r.manifest.Release,
}
}
package selfupdate
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"unicode"
)
const (
maxDownloadSize = 256 << 20
maxBinarySize = 256 << 20
)
func (s *Service) downloadAndReplace(
ctx context.Context,
opts Options,
target *resolved,
executable string,
) error {
expected := strings.ToLower(strings.TrimSpace(target.file.SHA256))
if expected == "" {
if target.checksums == nil {
return fmt.Errorf("release %s has no checksum for %s", target.manifest.Version, target.file.Name)
}
digest, err := s.fetchChecksum(ctx, target.checksums.String(), target.file.Name)
if err != nil {
return err
}
expected = digest
}
assetURL := target.base.JoinPath(path.Base(target.file.Name)).String()
archive, err := os.CreateTemp("", "lucy-update-*")
if err != nil {
return fmt.Errorf("create the download file: %w", err)
}
archivePath := archive.Name()
defer os.Remove(archivePath)
if err := s.downloadFile(ctx, assetURL, expected, archive, target.file.Name, opts.Progress); err != nil {
_ = archive.Close()
return err
}
if err := archive.Close(); err != nil {
return fmt.Errorf("close the downloaded archive: %w", err)
}
staged, err := extractBinary(archivePath, s.goos, filepath.Dir(executable))
if err != nil {
return err
}
if err := s.verifyStaged(ctx, staged, target.manifest.Version); err != nil {
_ = os.Remove(staged)
return err
}
if err := replaceBinary(staged, executable); err != nil {
_ = os.Remove(staged)
return err
}
return nil
}
func (s *Service) downloadFile(
ctx context.Context,
rawURL string,
expected string,
dst *os.File,
name string,
progress func(string, int64, int64),
) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return fmt.Errorf("build the download request: %w", err)
}
req.Header.Set("user-agent", "lucy-self-update")
s.logDebug("downloading release asset", "url", rawURL)
resp, err := s.doer.Do(req)
if err != nil {
return fmt.Errorf("download %s: %w", name, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download %s: %s", name, resp.Status)
}
total := resp.ContentLength
if total < 0 {
total = 0
}
if total > maxDownloadSize {
return fmt.Errorf("download %s exceeds %d bytes", name, maxDownloadSize)
}
var reader io.Reader = io.LimitReader(resp.Body, maxDownloadSize+1)
if progress != nil {
reader = &progressReader{reader: reader, name: name, total: total, progress: progress}
}
hasher := sha256.New()
written, err := io.Copy(io.MultiWriter(dst, hasher), reader)
if err != nil {
return fmt.Errorf("download %s: %w", name, err)
}
if written > maxDownloadSize {
return fmt.Errorf("download %s exceeds %d bytes", name, maxDownloadSize)
}
if expected != "" {
actual := hex.EncodeToString(hasher.Sum(nil))
if !strings.EqualFold(actual, expected) {
return fmt.Errorf("checksum mismatch for %s: expected %s, got %s", name, expected, actual)
}
}
if err := dst.Sync(); err != nil {
return fmt.Errorf("sync %s: %w", name, err)
}
return nil
}
func (s *Service) fetchChecksum(ctx context.Context, rawURL, name string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return "", fmt.Errorf("build the checksum request: %w", err)
}
req.Header.Set("user-agent", "lucy-self-update")
resp, err := s.doer.Do(req)
if err != nil {
return "", fmt.Errorf("fetch checksums: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("fetch checksums: %s", resp.Status)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", fmt.Errorf("read checksums: %w", err)
}
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) != 2 || len(fields[0]) != 64 {
continue
}
if strings.TrimPrefix(fields[1], "*") == path.Base(name) {
return strings.ToLower(fields[0]), nil
}
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("read checksums: %w", err)
}
return "", fmt.Errorf("checksum missing for %s", name)
}
func extractBinary(archivePath, goos, dir string) (string, error) {
if goos == "windows" {
return extractZipBinary(archivePath, dir)
}
return extractTarBinary(archivePath, dir)
}
func extractTarBinary(archivePath, dir string) (string, error) {
file, err := os.Open(archivePath)
if err != nil {
return "", fmt.Errorf("open the release archive: %w", err)
}
defer file.Close()
gzipReader, err := gzip.NewReader(file)
if err != nil {
return "", fmt.Errorf("read the release archive: %w", err)
}
defer gzipReader.Close()
tarReader := tar.NewReader(gzipReader)
for {
header, err := tarReader.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", fmt.Errorf("read the release archive: %w", err)
}
if header.Typeflag != tar.TypeReg {
continue
}
if header.Name != "lucy" && header.Name != "./lucy" {
continue
}
return copyStaged(tarReader, dir, header.Size, "")
}
return "", errors.New("the release archive does not contain lucy")
}
func extractZipBinary(archivePath, dir string) (string, error) {
reader, err := zip.OpenReader(archivePath)
if err != nil {
return "", fmt.Errorf("open the release archive: %w", err)
}
defer reader.Close()
for _, file := range reader.File {
if file.Name != "lucy.exe" {
continue
}
body, err := file.Open()
if err != nil {
return "", fmt.Errorf("read the release archive: %w", err)
}
staged, copyErr := copyStaged(body, dir, int64(file.UncompressedSize64), ".exe")
closeErr := body.Close()
if copyErr != nil {
return "", copyErr
}
if closeErr != nil {
_ = os.Remove(staged)
return "", fmt.Errorf("read the release archive: %w", closeErr)
}
return staged, nil
}
return "", errors.New("the release archive does not contain lucy.exe")
}
func copyStaged(reader io.Reader, dir string, size int64, suffix string) (staged string, resultErr error) {
if size < 0 || size > maxBinarySize {
return "", fmt.Errorf("the new lucy is %d bytes", size)
}
file, err := os.CreateTemp(dir, ".lucy-update-*"+suffix)
if err != nil {
return "", fmt.Errorf("stage the new lucy: %w", err)
}
stagedPath := file.Name()
staged = stagedPath
defer func() {
if file != nil {
resultErr = errors.Join(resultErr, file.Close())
}
if resultErr != nil {
_ = os.Remove(stagedPath)
}
}()
written, err := io.Copy(file, io.LimitReader(reader, maxBinarySize+1))
if err != nil {
return "", fmt.Errorf("write the new lucy: %w", err)
}
if written == 0 {
return "", errors.New("the release archive contains an empty lucy")
}
if written > maxBinarySize {
return "", fmt.Errorf("the new lucy exceeds %d bytes", maxBinarySize)
}
if size > 0 && written != size {
return "", fmt.Errorf("the new lucy is %d bytes, expected %d", written, size)
}
if err := file.Chmod(0o755); err != nil {
return "", fmt.Errorf("make the new lucy executable: %w", err)
}
if err := file.Sync(); err != nil {
return "", fmt.Errorf("sync the new lucy: %w", err)
}
if err := file.Close(); err != nil {
file = nil
return "", fmt.Errorf("close the new lucy: %w", err)
}
file = nil
return staged, nil
}
func (s *Service) verifyStaged(ctx context.Context, staged, version string) error {
runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
command := exec.CommandContext(runCtx, staged, "--version")
command.Env = append(os.Environ(), "LUCY_SELF_UPDATE_STAGED=1")
output, err := command.CombinedOutput()
if err != nil {
return fmt.Errorf("the downloaded lucy did not start: %w", err)
}
if !hasVersionToken(string(output), version) {
return fmt.Errorf(
"the downloaded lucy reported %q instead of %s",
strings.TrimSpace(string(output)),
version,
)
}
return nil
}
func hasVersionToken(output, version string) bool {
version = strings.TrimPrefix(strings.TrimSpace(version), "v")
for _, field := range strings.FieldsFunc(output, func(r rune) bool {
return unicode.IsSpace(r) || r == '(' || r == ')'
}) {
if strings.TrimPrefix(field, "v") == version {
return true
}
}
return false
}
type progressReader struct {
reader io.Reader
name string
total int64
read int64
progress func(string, int64, int64)
}
func (p *progressReader) Read(buffer []byte) (int, error) {
n, err := p.reader.Read(buffer)
p.read += int64(n)
p.progress(p.name, p.read, p.total)
return n, err
}
package selfupdate
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// Installation describes where the running executable came from and whether
// this command may replace it.
type Installation struct {
Executable string
Method string
Managed bool
Updatable bool
Blocked bool
Guidance string
Notes []string
}
func (s *Service) detect(opts Options, probe bool) (Installation, error) {
executable := opts.Executable
if executable == "" {
found, err := os.Executable()
if err != nil {
return Installation{}, fmt.Errorf("locate the lucy executable: %w", err)
}
executable = found
}
executable, err := filepath.Abs(executable)
if err != nil {
return Installation{}, fmt.Errorf("resolve the lucy executable: %w", err)
}
if resolved, err := filepath.EvalSymlinks(executable); err == nil {
executable = resolved
}
path := filepath.ToSlash(executable)
installation := Installation{Executable: executable}
switch {
case strings.Contains(path, "/Caskroom/lucy/"), strings.Contains(path, "/Cellar/lucy/"):
installation.Method = "Homebrew"
installation.Managed = true
installation.Guidance = "run `brew upgrade --cask lucy`"
case strings.HasPrefix(path, "/nix/store/"):
installation.Method = "Nix"
installation.Managed = true
installation.Guidance = "upgrade the Nix profile or flake input"
case inContainer():
installation.Method = "container"
installation.Managed = true
installation.Guidance = "pull the latest image instead"
case !opts.Official:
installation.Method = "source"
installation.Guidance = "rebuild it with `task build`, reinstall it with `go install github.com/mclucy/lucy@latest`, or use --force"
default:
installation.Method = "archive"
if !probe {
installation.Updatable = true
break
}
if err := probeDirectory(filepath.Dir(executable)); err != nil {
installation.Blocked = true
installation.Guidance = fmt.Sprintf(
"cannot write to %s: %v; install lucy in a user-writable directory",
filepath.Dir(executable),
err,
)
return installation, nil
}
installation.Updatable = true
}
if !installation.Updatable {
installation.Notes = append(installation.Notes, installation.Guidance)
}
return installation, nil
}
func inContainer() bool {
for _, path := range []string{"/.dockerenv", "/run/.containerenv"} {
if _, err := os.Stat(path); err == nil {
return true
}
}
return false
}
func probeDirectory(dir string) error {
file, err := os.CreateTemp(dir, ".lucy-update-probe-*")
if err != nil {
return err
}
name := file.Name()
closeErr := file.Close()
removeErr := os.Remove(name)
return firstError(closeErr, removeErr)
}
func firstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
package selfupdate
import (
"context"
"encoding/json/v2"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/Masterminds/semver/v3"
)
const (
manifestSchema = 1
maxManifestSize = 1 << 20
)
var versionPattern = regexp.MustCompile(
`^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$`,
)
// Manifest is one release object served by the Worker as latest.json.
type Manifest struct {
Schema int `json:"schema"`
Kind string `json:"kind"`
Version string `json:"version"`
Tag string `json:"tag"`
Channel string `json:"channel"`
Commit string `json:"commit"`
PublishedAt string `json:"published_at"`
Base string `json:"base"`
Checksums string `json:"checksums"`
Release string `json:"release"`
Files []File `json:"files"`
}
// File is one downloadable release artifact.
type File struct {
Name string `json:"name"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}
type resolved struct {
manifest *Manifest
base *url.URL
checksums *url.URL
file File
updateAvailable bool
}
func (s *Service) resolve(ctx context.Context, opts Options) (*resolved, error) {
manifestURL := opts.ManifestURL
if manifestURL == "" {
manifestURL = DefaultManifestURL
}
manifest, manifestBase, base, err := s.fetchManifest(ctx, manifestURL)
if err != nil {
return nil, err
}
asset, err := AssetName(manifest.Version, s.goos, s.goarch)
if err != nil {
return nil, err
}
var selected File
for _, file := range manifest.Files {
if file.Name == asset {
selected = file
break
}
}
if selected.Name == "" {
return nil, fmt.Errorf(
"release %s has no %s asset for %s/%s",
manifest.Version,
asset,
s.goos,
s.goarch,
)
}
checksums, err := resolveReference(manifestBase, manifest.Checksums)
if err != nil {
return nil, err
}
if checksums == nil {
checksums = base.JoinPath("checksums.txt")
}
if err := validateDownloadURL(base); err != nil {
return nil, err
}
if err := validateDownloadURL(checksums); err != nil {
return nil, err
}
update, err := updateAvailable(opts.Version, manifest.Version, opts.Force)
if err != nil {
return nil, err
}
return &resolved{
manifest: manifest,
base: base,
checksums: checksums,
file: selected,
updateAvailable: update,
}, nil
}
func (s *Service) fetchManifest(
ctx context.Context,
rawURL string,
) (*Manifest, *url.URL, *url.URL, error) {
manifestURL, err := url.Parse(rawURL)
if err != nil {
return nil, nil, nil, fmt.Errorf("parse the release manifest URL: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("build the release manifest request: %w", err)
}
req.Header.Set("accept", "application/json")
req.Header.Set("user-agent", "lucy-self-update")
s.logDebug("fetching release manifest", "url", rawURL)
resp, err := s.doer.Do(req)
if err != nil {
return nil, nil, nil, fmt.Errorf("fetch the release manifest: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, nil, nil, fmt.Errorf("fetch the release manifest: %s", resp.Status)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, maxManifestSize+1))
if err != nil {
return nil, nil, nil, fmt.Errorf("read the release manifest: %w", err)
}
if len(data) > maxManifestSize {
return nil, nil, nil, fmt.Errorf("release manifest exceeds %d bytes", maxManifestSize)
}
var manifest Manifest
if err := json.Unmarshal(data, &manifest); err != nil {
return nil, nil, nil, fmt.Errorf("decode the release manifest: %w", err)
}
if manifest.Schema != manifestSchema {
return nil, nil, nil, fmt.Errorf(
"unsupported release manifest schema %d; update lucy with the install script",
manifest.Schema,
)
}
if kind := manifest.Kind; kind != "" && kind != "lucy-release" && kind != "lucy-channel" {
return nil, nil, nil, fmt.Errorf("unsupported release manifest kind %q", kind)
}
if manifest.Version == "" {
return nil, nil, nil, fmt.Errorf("release manifest has no version")
}
if !versionPattern.MatchString(manifest.Version) {
return nil, nil, nil, fmt.Errorf("release manifest has an invalid version %q", manifest.Version)
}
if manifest.Tag != "" && strings.TrimPrefix(manifest.Tag, "v") != manifest.Version {
return nil, nil, nil, fmt.Errorf(
"release manifest tag %q does not match version %q",
manifest.Tag,
manifest.Version,
)
}
if manifest.Base == "" {
return nil, nil, nil, fmt.Errorf("release manifest has no base path")
}
base, err := resolveReference(manifestURL, manifest.Base)
if err != nil {
return nil, nil, nil, err
}
if base == nil {
return nil, nil, nil, fmt.Errorf("release manifest has no base path")
}
return &manifest, manifestURL, base, nil
}
func resolveReference(base *url.URL, reference string) (*url.URL, error) {
if reference == "" {
return nil, nil
}
parsed, err := url.Parse(reference)
if err != nil {
return nil, fmt.Errorf("parse release path %q: %w", reference, err)
}
return base.ResolveReference(parsed), nil
}
// AssetName identifies the archive for one platform. The manifest must name
// the same file, so a release that misses a platform fails before download.
func AssetName(version, goos, goarch string) (string, error) {
switch goos {
case "linux", "darwin":
if goarch != "amd64" && goarch != "arm64" {
return "", fmt.Errorf("self-update is not supported on %s/%s", goos, goarch)
}
return fmt.Sprintf("lucy_%s_%s_%s.tar.gz", version, goos, goarch), nil
case "windows":
if goarch != "amd64" {
return "", fmt.Errorf("self-update is not supported on %s/%s", goos, goarch)
}
return fmt.Sprintf("lucy_%s_windows_amd64.zip", version), nil
default:
return "", fmt.Errorf("self-update is not supported on %s/%s", goos, goarch)
}
}
// validateDownloadURL keeps a manifest from redirecting the update to a
// non-transport scheme. Loopback HTTP is allowed for local mirrors and tests.
func validateDownloadURL(target *url.URL) error {
if target == nil {
return nil
}
if target.Scheme == "https" {
return nil
}
if target.Scheme == "http" {
switch strings.ToLower(target.Hostname()) {
case "127.0.0.1", "::1", "localhost":
return nil
}
}
return fmt.Errorf("release manifest points to an unsupported download URL %q", target.String())
}
func updateAvailable(current, latest string, force bool) (bool, error) {
if force {
return true, nil
}
latestVersion, err := semver.NewVersion(latest)
if err != nil {
return false, fmt.Errorf("release manifest has an invalid version %q: %w", latest, err)
}
current = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(current), "v"))
if current == "" {
return true, nil
}
currentVersion, err := semver.NewVersion(current)
if err != nil {
// A development stamp that is not valid semver cannot be compared;
// offer the release and let the installation check decide.
return true, nil
}
return latestVersion.GreaterThan(currentVersion), nil
}
//go:build !windows
package selfupdate
import (
"fmt"
"os"
"path/filepath"
)
// replaceBinary publishes the staged executable over the running one. Renaming
// over a running file is safe on Unix; the running process keeps the old inode.
func replaceBinary(staged, executable string) error {
info, err := os.Lstat(executable)
if err != nil {
return fmt.Errorf("inspect %s: %w", executable, err)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", executable)
}
if err := os.Rename(staged, executable); err != nil {
return fmt.Errorf("replace %s: %w", executable, err)
}
if dir, err := os.Open(filepath.Dir(executable)); err == nil {
_ = dir.Sync()
_ = dir.Close()
}
return nil
}
// Package shell formats text that a POSIX shell reads back.
package shell
import "strings"
// Quote returns s safe to paste into a POSIX shell command. Plain words stay
// bare so quoted output stays readable; anything a shell would interpret is
// single-quoted.
func Quote(s string) string {
if s != "" && !strings.ContainsAny(s, " \t\n'\"\\$`!*?[]{}()<>|&;#~") {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
package telemetry
import (
"context"
"errors"
"net/http"
"strings"
"time"
)
// Client is a concurrency-safe telemetry client. All state lives beneath its
// private directory. Create one client per process.
type Client struct {
disabled bool
directory string
endpoint string
channel string
version string
commit string
os string
arch string
logger Logger
http *http.Client
ownsHTTP bool
now func() time.Time
limits Limits
sem chan struct{}
}
// New validates config and builds a client. The first event or explicit
// operation initializes state lazily.
func New(config Config) (*Client, error) {
config, err := config.withDefaults()
if err != nil {
return nil, err
}
httpClient := config.HTTPClient
ownsHTTP := false
if httpClient == nil {
if transport, ok := http.DefaultTransport.(*http.Transport); ok {
httpClient = &http.Client{
Transport: transport.Clone(),
Timeout: config.Limits.RequestTimeout,
CheckRedirect: safeRedirect,
}
} else {
httpClient = &http.Client{Timeout: config.Limits.RequestTimeout, CheckRedirect: safeRedirect}
}
ownsHTTP = true
} else {
cloned := *httpClient
previous := cloned.CheckRedirect
cloned.CheckRedirect = func(request *http.Request, via []*http.Request) error {
if err := safeRedirect(request, via); err != nil {
return err
}
if previous != nil {
return previous(request, via)
}
return nil
}
httpClient = &cloned
}
return &Client{
disabled: config.Disabled,
directory: config.Directory,
endpoint: config.Endpoint,
channel: config.Channel,
version: config.LucyVersion,
commit: config.LucyCommit,
os: config.OS,
arch: config.Arch,
logger: config.Logger,
http: httpClient,
ownsHTTP: ownsHTTP,
now: config.Now,
limits: config.Limits,
sem: make(chan struct{}, 1),
}, nil
}
func (c *Client) Close() error {
if c.ownsHTTP && c.http != nil {
c.http.CloseIdleConnections()
}
return nil
}
// Enabled reports whether collection is currently allowed. An empty endpoint
// still permits durable local enqueueing.
func (c *Client) Enabled(ctx context.Context) (bool, error) {
if c.disabled || environmentDisabled() {
return false, nil
}
release, err := c.enterOperation(ctx, c.limits.LockWait)
if err != nil {
return false, err
}
defer release()
state, _, err := c.loadState(c.now())
if err != nil {
return false, err
}
enabled, _, _ := c.effective(state)
return enabled, nil
}
// RecordEvent records one invocation observation. Callers own InvocationID.
func (c *Client) RecordEvent(ctx context.Context, event Event) (Submission, error) {
return c.enqueue(ctx, recordTypeEvent, func(state *persistedState, _ string, now time.Time) (payloadResult, error) {
prepared, err := c.prepareEvent(event, now)
if err != nil {
return payloadResult{}, err
}
return payloadResult{Payload: c.buildEventPayload(prepared, state)}, nil
})
}
// SubmitReport records one explicitly supplied report. It sanitizes and bounds
// the body. When telemetry is off, it returns a non-error Submission whose
// Reason explains the refusal.
func (c *Client) SubmitReport(ctx context.Context, report Report) (Submission, error) {
return c.enqueue(ctx, recordTypeReport, func(state *persistedState, id string, now time.Time) (payloadResult, error) {
prepared, truncated, err := c.prepareReport(report, now)
if err != nil {
return payloadResult{}, err
}
return payloadResult{
Payload: reportPayload{
ReportID: id,
InstallationID: state.InstallationID,
InvocationID: prepared.invocationID,
Kind: string(prepared.kind),
Agent: prepared.agent,
Model: prepared.model,
CreatedAt: prepared.createdAt.Format(time.RFC3339),
SchemaVersion: SchemaVersion,
Body: prepared.body,
},
BodyBytes: int64(len(prepared.body)),
Truncated: truncated,
}, nil
})
}
// SetEnabled persists an explicit opt-in or opt-out. Disabling purges queued
// records and waits for any in-flight upload in this process or another
// cooperating process.
func (c *Client) SetEnabled(ctx context.Context, enabled bool) error {
release, err := c.enterOperation(ctx, -1)
if err != nil {
return err
}
defer release()
now := c.now()
state, _, err := c.loadState(now)
if err != nil {
if enabled || !errors.Is(err, errCorruptState) {
return err
}
state = newState(now)
}
if enabled {
state.optIn(now)
} else {
state.optOut()
}
if err := c.saveState(state, now); err != nil {
return err
}
if !enabled {
return c.finishDisabledPurge(state, now)
}
return nil
}
// ResetIdentity rotates the installation UUID and restarts the statistics
// window. Pending records keep their IDs and payloads and may be accepted
// later; they count in the new window.
func (c *Client) ResetIdentity(ctx context.Context) (Identity, error) {
release, err := c.enterOperation(ctx, -1)
if err != nil {
return Identity{}, err
}
defer release()
now := c.now()
state, _, err := c.loadState(now)
if err != nil {
return Identity{}, err
}
state.resetIdentity(now)
if err := c.saveState(state, now); err != nil {
return Identity{}, err
}
return Identity{
InstallationID: state.InstallationID,
CreatedAt: state.IdentityCreatedAt,
Policy: state.Policy,
}, nil
}
// Stats returns a transparent snapshot.
func (c *Client) Stats(ctx context.Context) (Stats, error) {
stats := Stats{
Policy: CollectionDefault,
Endpoint: c.endpoint,
EndpointConfigured: c.endpoint != "",
StateDirectory: c.directory,
}
release, err := c.enterOperation(ctx, c.limits.LockWait)
if err != nil {
return stats, err
}
defer release()
state, existed, err := c.loadState(c.now())
if err != nil {
return stats, err
}
enabled, policy, reason := c.effective(state)
stats.Enabled = enabled
stats.Reason = reason
stats.Policy = policy
stats.InstallationID = state.InstallationID
if existed {
stats.PeriodStart = state.PeriodStart
}
stats.Accepted = AcceptedStats{
Events: state.Accepted.Events,
Reports: state.Accepted.Reports,
Records: state.Accepted.Events + state.Accepted.Reports,
EventPayloadBytes: state.Accepted.EventPayloadBytes,
ReportBodyBytes: state.Accepted.ReportBodyBytes,
}
stats.Rejected = RejectedStats(state.Rejected)
stats.Dropped = DroppedStats(state.Dropped)
stats.Transport = TransportStats(state.Transport)
stats.Queue = queueStatistics(state)
stats.CooldownUntil = state.CooldownUntil
stats.LastError = state.LastError
return stats, nil
}
func (c *Client) effective(state *persistedState) (bool, CollectionPolicy, SkipReason) {
policy := state.Policy
if policy == "" {
policy = CollectionDefault
}
if c.disabled {
return false, policy, SkipDisabled
}
if environmentDisabled() {
return false, policy, SkipEnvironment
}
switch policy {
case CollectionOptOut:
return false, policy, SkipDisabled
case CollectionOptIn:
return true, policy, SkipNone
default:
if channelCollectsByDefault(c.channel) {
return true, policy, SkipNone
}
return false, policy, SkipDisabled
}
}
func (c *Client) debug(message string, fields ...any) {
if c.logger != nil {
c.logger.Debug(message, fields...)
}
}
func ignoreLockBusy(err error) bool {
return errors.Is(err, errLockBusy)
}
// safeRedirect keeps telemetry on the configured origin.
func safeRedirect(request *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return errors.New("telemetry: too many redirects")
}
if len(via) > 0 && (!strings.EqualFold(request.URL.Host, via[0].URL.Host) ||
!strings.EqualFold(request.URL.Scheme, via[0].URL.Scheme)) {
return errors.New("telemetry: redirect must stay on the configured origin")
}
if request.URL.Scheme == "https" {
return nil
}
if request.URL.Scheme == "http" && isLoopbackHost(request.URL.Hostname()) {
return nil
}
return errors.New("telemetry: redirect must use https outside loopback")
}
// Package telemetry implements Lucy's opt-out usage telemetry client.
//
// The client owns a private, per-user state directory. It records bounded,
// typed event records and explicit reports into a durable local queue, and
// uploads them only when the caller invokes Flush. It reads only its own state
// directory and keeps process arguments, environment variables, logs, and
// arbitrary host data out of collected records.
//
// Telemetry is enabled by default for pre-release channels (alpha and beta).
// LUCY_TELEMETRY can force it off for a process. Persisted opt-in and opt-out
// choices override channel defaults. Disabling telemetry (SetEnabled with
// false) purges queued records without rotating the installation identity.
// Resetting the identity rotates the UUID and restarts the statistics window,
// but keeps queued records and their original identities.
//
// Every error returned by this package is telemetry-local. A CLI must ignore
// it: regular commands keep their result when telemetry fails.
package telemetry
import (
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/mclucy/lucy/internal/appdata"
)
// EnvironmentVariable forces telemetry off when set to a false-like value.
// Recognized false values are 0, off, false, no, disabled, opt-out, and
// opt_out. An unrecognized non-empty value also disables telemetry (privacy
// favours failing closed). Recognized true values are 1, on, true, yes,
// enabled, opt-in, and opt_in; they leave a persisted opt-out in place.
const EnvironmentVariable = "LUCY_TELEMETRY"
// SchemaVersion is the wire and local-state schema version.
const SchemaVersion = 1
// DefaultEndpoint is the public Lucy telemetry ingestion endpoint. Builds may
// override it with a linker flag for a separate deployment.
var DefaultEndpoint = "https://telemetry.lucy.lc"
const (
stateDirectoryName = "telemetry"
defaultChannel = "alpha"
defaultMaxQueuedRecords = 512
defaultMaxQueuedBytes = 4 << 20
defaultMaxEventPayloadBytes = 16 << 10
defaultMaxReportBodyBytes = 64 << 10
defaultMaxRecordsPerRequest = 50
defaultMaxRequestBytes = 256 << 10
defaultMaxRecordBytes = 64 << 10
defaultMaxAcceptedIDHistory = 2048
defaultMaxRecordAge = 7 * 24 * time.Hour
defaultHealthTimeout = 2 * time.Second
defaultRequestTimeout = 5 * time.Second
defaultMaxAttempts = 3
defaultRetryBackoff = 250 * time.Millisecond
defaultCooldown = 10 * time.Minute
defaultLockWait = 2 * time.Second
defaultMaxBatches = 4
defaultFlushTimeout = 15 * time.Second
enqueueLockWait = 250 * time.Millisecond
truncationMarker = "\n[truncated]"
)
// Logger is the subset of the Lucy logger used by the client. A *log.Logger
// satisfies it.
type Logger interface {
Debug(content any, fields ...any)
Warn(err error)
}
// Limits bounds local collection and network requests. Zero values select the
// default. MaxRecordBytes applies to one serialized wire record, including its
// JSON envelope. MaxRequestBytes applies to one serialized upload request.
type Limits struct {
MaxQueuedRecords int
MaxQueuedBytes int64
MaxEventPayloadBytes int
MaxReportBodyBytes int
MaxRecordsPerRequest int
MaxRequestBytes int
MaxRecordBytes int
MaxRecordAge time.Duration
HealthTimeout time.Duration
RequestTimeout time.Duration
MaxAttempts int
RetryBackoff time.Duration
Cooldown time.Duration
LockWait time.Duration
MaxBatches int
FlushTimeout time.Duration
}
// Config configures a Client. Directory, Endpoint, and Channel default to the
// platform user data directory, DefaultEndpoint, and alpha. Endpoint must use
// HTTPS unless it points at a loopback host, which keeps tests hermetic.
type Config struct {
Disabled bool
Directory string
Endpoint string
Channel string
LucyVersion string
LucyCommit string
OS string
Arch string
Logger Logger
HTTPClient *http.Client
Now func() time.Time
Limits Limits
}
func (config Config) withDefaults() (Config, error) {
if config.Now == nil {
config.Now = time.Now
}
if strings.TrimSpace(config.Directory) == "" {
directory, err := defaultDirectory()
if err != nil {
return Config{}, err
}
config.Directory = directory
}
config.Directory = filepath.Clean(config.Directory)
config.Channel = strings.ToLower(strings.TrimSpace(config.Channel))
if config.Channel == "" {
config.Channel = defaultChannel
}
if !validChannel(config.Channel) {
return Config{}, fmt.Errorf("telemetry: invalid channel %q", config.Channel)
}
config.LucyVersion = sanitizeVersion(config.LucyVersion)
config.LucyCommit = sanitizeCommit(config.LucyCommit)
if config.OS == "" {
config.OS = runtime.GOOS
}
if config.Arch == "" {
config.Arch = runtime.GOARCH
}
config.OS = sanitizeToken(config.OS, 32)
config.Arch = sanitizeToken(config.Arch, 32)
endpoint := strings.TrimSpace(config.Endpoint)
if endpoint == "" {
endpoint = strings.TrimSpace(DefaultEndpoint)
}
normalizedEndpoint, err := normalizeEndpoint(endpoint)
if err != nil {
return Config{}, err
}
config.Endpoint = normalizedEndpoint
config.Limits = config.Limits.withDefaults()
return config, nil
}
func (limits Limits) withDefaults() Limits {
if limits.MaxQueuedRecords <= 0 {
limits.MaxQueuedRecords = defaultMaxQueuedRecords
}
if limits.MaxQueuedBytes <= 0 {
limits.MaxQueuedBytes = defaultMaxQueuedBytes
}
if limits.MaxEventPayloadBytes <= 0 {
limits.MaxEventPayloadBytes = defaultMaxEventPayloadBytes
}
if limits.MaxReportBodyBytes <= 0 {
limits.MaxReportBodyBytes = defaultMaxReportBodyBytes
}
if limits.MaxRecordsPerRequest <= 0 {
limits.MaxRecordsPerRequest = defaultMaxRecordsPerRequest
}
if limits.MaxRequestBytes <= 0 {
limits.MaxRequestBytes = defaultMaxRequestBytes
}
if limits.MaxRecordBytes <= 0 {
limits.MaxRecordBytes = defaultMaxRecordBytes
}
if limits.MaxRecordAge <= 0 {
limits.MaxRecordAge = defaultMaxRecordAge
}
if limits.HealthTimeout <= 0 {
limits.HealthTimeout = defaultHealthTimeout
}
if limits.RequestTimeout <= 0 {
limits.RequestTimeout = defaultRequestTimeout
}
if limits.MaxAttempts <= 0 {
limits.MaxAttempts = defaultMaxAttempts
}
if limits.RetryBackoff <= 0 {
limits.RetryBackoff = defaultRetryBackoff
}
if limits.Cooldown <= 0 {
limits.Cooldown = defaultCooldown
}
if limits.LockWait < 0 {
limits.LockWait = 0
} else if limits.LockWait == 0 {
limits.LockWait = defaultLockWait
}
if limits.MaxBatches <= 0 {
limits.MaxBatches = defaultMaxBatches
}
if limits.FlushTimeout <= 0 {
limits.FlushTimeout = defaultFlushTimeout
}
// One record must always fit in a request and in the local queue.
if limits.MaxRequestBytes < limits.MaxRecordBytes+1024 {
limits.MaxRequestBytes = limits.MaxRecordBytes + 1024
}
if limits.MaxQueuedBytes < int64(limits.MaxRecordBytes) {
limits.MaxQueuedBytes = int64(limits.MaxRecordBytes)
}
if limits.MaxReportBodyBytes > limits.MaxRecordBytes {
limits.MaxReportBodyBytes = limits.MaxRecordBytes
}
return limits
}
func defaultDirectory() (string, error) {
root, err := appdata.Root()
if err != nil {
return "", fmt.Errorf("telemetry: locate state directory: %w", err)
}
return filepath.Join(root, stateDirectoryName), nil
}
func normalizeEndpoint(raw string) (string, error) {
if raw == "" {
return "", nil
}
parsed, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("telemetry: invalid endpoint: %w", err)
}
parsed.Scheme = strings.ToLower(parsed.Scheme)
if parsed.Scheme != "https" && parsed.Scheme != "http" {
return "", errors.New("telemetry: endpoint must use https")
}
if parsed.Host == "" {
return "", errors.New("telemetry: endpoint has no host")
}
if parsed.Scheme == "http" && !isLoopbackHost(parsed.Hostname()) {
return "", errors.New("telemetry: endpoint must use https outside loopback")
}
if parsed.User != nil {
return "", errors.New("telemetry: endpoint must not contain credentials")
}
if parsed.Opaque != "" || parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" {
return "", errors.New("telemetry: endpoint must not contain a query or fragment")
}
return strings.TrimRight(parsed.String(), "/"), nil
}
func isLoopbackHost(host string) bool {
if strings.EqualFold(host, "localhost") {
return true
}
address := net.ParseIP(host)
return address != nil && address.IsLoopback()
}
func channelCollectsByDefault(channel string) bool {
return channel == "alpha" || channel == "beta"
}
func environmentDisabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(EnvironmentVariable))) {
case "":
return false
case "0", "off", "false", "no", "disabled", "opt-out", "opt_out":
return true
case "1", "on", "true", "yes", "enabled", "opt-in", "opt_in":
return false
default:
// An unrecognized explicit value is treated as a request to stop.
return true
}
}
func sanitizeVersion(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if len(raw) > 128 {
raw = raw[:128]
}
var builder strings.Builder
for _, character := range raw {
switch {
case character >= 'a' && character <= 'z':
case character >= 'A' && character <= 'Z':
case character >= '0' && character <= '9':
case strings.ContainsRune("._+-", character):
default:
return sanitizeToken(raw, 64)
}
builder.WriteRune(character)
if builder.Len() >= 64 {
break
}
}
return builder.String()
}
func sanitizeCommit(raw string) string {
raw = strings.ToLower(strings.TrimSpace(raw))
if len(raw) < 7 || len(raw) > 40 {
return ""
}
for _, character := range raw {
if (character < '0' || character > '9') && (character < 'a' || character > 'f') {
return ""
}
}
return raw
}
package telemetry
import (
"encoding/json/jsontext"
"fmt"
"strings"
"time"
)
const (
// maxContexts bounds the typed snapshots attached to one event.
maxContexts = 15
maxContextDataBytes = 8 << 10
maxContextTypeLength = 64
maxEventDuration = 7 * 24 * time.Hour
contextSchemaVersion = 1
)
type eventPayload struct {
InvocationID string `json:"invocation_id"`
InstallationID string `json:"installation_id"`
OccurredAt string `json:"occurred_at"`
Operation string `json:"operation"`
LucyVersion string `json:"lucy_version"`
LucyCommit string `json:"lucy_commit"`
Channel string `json:"channel"`
OS string `json:"os"`
Arch string `json:"arch"`
DurationMS *int64 `json:"duration_ms,omitempty"`
Outcome Outcome `json:"outcome"`
ErrorCode string `json:"error_code"`
SchemaVersion int `json:"schema_version"`
Contexts []contextPayload `json:"contexts,omitempty"`
}
type contextPayload struct {
Type string `json:"type"`
Status ContextStatus `json:"status"`
Version int `json:"version,omitempty"`
Reason ContextReason `json:"reason,omitempty"`
Data jsontext.Value `json:"data,omitzero"`
}
type reportPayload struct {
ReportID string `json:"report_id"`
InstallationID string `json:"installation_id"`
InvocationID string `json:"invocation_id,omitempty"`
Kind string `json:"kind"`
Agent string `json:"agent,omitempty"`
Model string `json:"model,omitempty"`
CreatedAt string `json:"created_at"`
SchemaVersion int `json:"schema_version"`
Body string `json:"body"`
}
type preparedEvent struct {
invocationID string
operation string
durationMS int64
durationMeasured bool
outcome Outcome
errorCode string
occurredAt time.Time
contexts []contextPayload
}
type preparedReport struct {
kind ReportKind
invocationID string
agent string
model string
body string
createdAt time.Time
}
func (c *Client) prepareEvent(event Event, now time.Time) (preparedEvent, error) {
invocationID, err := normalizeUUID(event.InvocationID)
if err != nil {
return preparedEvent{}, fmt.Errorf("%w: invocation id: %v", ErrInvalidEvent, err)
}
operation, err := normalizeCommand(event.Operation)
if err != nil {
return preparedEvent{}, fmt.Errorf("%w: operation must be a command path without arguments", ErrInvalidEvent)
}
if event.Duration < 0 || event.Duration > maxEventDuration {
return preparedEvent{}, fmt.Errorf("%w: duration out of range", ErrInvalidEvent)
}
switch event.Outcome {
case OutcomeSuccess, OutcomeFailure, OutcomeCanceled:
default:
return preparedEvent{}, fmt.Errorf("%w: unknown outcome %q", ErrInvalidEvent, event.Outcome)
}
if event.ErrorCode != "" && !validCode(event.ErrorCode, 64) {
return preparedEvent{}, fmt.Errorf("%w: invalid error code", ErrInvalidEvent)
}
contexts, err := normalizeContexts(event.Contexts)
if err != nil {
return preparedEvent{}, err
}
occurredAt := event.OccurredAt
if occurredAt.IsZero() {
occurredAt = now
}
durationMeasured := event.DurationMeasured || event.Duration > 0
return preparedEvent{
invocationID: invocationID,
operation: operation,
durationMS: event.Duration.Milliseconds(),
durationMeasured: durationMeasured,
outcome: event.Outcome,
errorCode: event.ErrorCode,
occurredAt: occurredAt.UTC(),
contexts: contexts,
}, nil
}
func normalizeContexts(contexts []Context) ([]contextPayload, error) {
if len(contexts) == 0 {
return nil, nil
}
if len(contexts) > maxContexts {
return nil, fmt.Errorf("%w: too many contexts", ErrInvalidEvent)
}
normalized := make([]contextPayload, 0, len(contexts))
for _, context := range contexts {
kind := strings.ToLower(strings.TrimSpace(string(context.Kind)))
if !validContextType(kind) {
return nil, fmt.Errorf("%w: invalid context type", ErrInvalidEvent)
}
if context.Version != 0 && context.Version != contextSchemaVersion {
return nil, fmt.Errorf("%w: unsupported context version", ErrInvalidEvent)
}
switch context.Status {
case ContextPresent, ContextAbsent, ContextFailed:
default:
return nil, fmt.Errorf("%w: invalid context status", ErrInvalidEvent)
}
reason, err := normalizeContextReason(context.Status, context.Reason)
if err != nil {
return nil, err
}
payload := contextPayload{Type: kind, Status: context.Status, Version: contextSchemaVersion, Reason: reason}
if context.Status == ContextAbsent {
if context.Data != nil {
return nil, fmt.Errorf("%w: absent context must not carry data", ErrInvalidEvent)
}
normalized = append(normalized, payload)
continue
}
if context.Data == nil {
if context.Status == ContextPresent {
return nil, fmt.Errorf("%w: present context requires data", ErrInvalidEvent)
}
normalized = append(normalized, payload)
continue
}
if context.Status == ContextFailed {
return nil, fmt.Errorf("%w: failed context must not carry data", ErrInvalidEvent)
}
encoded, err := marshalCanonical(context.Data)
if err != nil {
return nil, fmt.Errorf("%w: context data is not JSON: %v", ErrInvalidEvent, err)
}
if len(encoded) == 0 || string(encoded) == "null" {
return nil, fmt.Errorf("%w: present context requires data", ErrInvalidEvent)
}
if len(encoded) > maxContextDataBytes {
return nil, fmt.Errorf("%w: context data exceeds %d bytes", ErrInvalidEvent, maxContextDataBytes)
}
payload.Data = jsontext.Value(encoded)
normalized = append(normalized, payload)
}
return normalized, nil
}
// normalizeContextReason applies the status-specific default and validates the
// bounded reason vocabulary.
func normalizeContextReason(status ContextStatus, reason ContextReason) (ContextReason, error) {
switch status {
case ContextPresent:
if reason != "" {
return "", fmt.Errorf("%w: present context must not carry a reason", ErrInvalidEvent)
}
return "", nil
case ContextAbsent:
if reason == "" {
return ContextReasonNotObserved, nil
}
switch reason {
case ContextReasonNotObserved, ContextReasonNotReached,
ContextReasonNotApplicable, ContextReasonNoResult:
return reason, nil
}
case ContextFailed:
if reason == "" {
return ContextReasonObservationFailed, nil
}
if reason == ContextReasonObservationFailed {
return reason, nil
}
}
return "", fmt.Errorf("%w: invalid context reason", ErrInvalidEvent)
}
func validContextType(value string) bool {
if value == "" || len(value) > maxContextTypeLength {
return false
}
for index := 0; index < len(value); index++ {
character := value[index]
valid := character >= 'a' && character <= 'z' ||
character >= '0' && character <= '9'
if index > 0 {
valid = valid || character == '-' || character == '_' || character == '.'
}
if !valid {
return false
}
}
return true
}
func (c *Client) buildEventPayload(event preparedEvent, state *persistedState) eventPayload {
var durationMS *int64
if event.durationMeasured {
measured := event.durationMS
durationMS = &measured
}
return eventPayload{
InvocationID: event.invocationID,
InstallationID: state.InstallationID,
OccurredAt: event.occurredAt.Format(time.RFC3339),
Operation: event.operation,
LucyVersion: c.version,
LucyCommit: c.commit,
Channel: c.channel,
OS: c.os,
Arch: c.arch,
DurationMS: durationMS,
Outcome: event.outcome,
ErrorCode: event.errorCode,
SchemaVersion: SchemaVersion,
Contexts: event.contexts,
}
}
package telemetry
import (
"context"
"errors"
"fmt"
"os"
"time"
)
var errLockBusy = errors.New("telemetry: state is busy")
type stateLock struct {
file *os.File
}
func (lock *stateLock) release() {
unlockFile(lock.file)
_ = lock.file.Close()
}
// enterOperation serializes one state mutation inside the process and, when
// supported, across processes. wait semantics: zero tries once, a positive
// duration is one budget shared by both layers, and a negative duration waits
// until ctx ends.
func (c *Client) enterOperation(ctx context.Context, wait time.Duration) (func(), error) {
if ctx == nil {
ctx = context.Background()
}
var deadline time.Time
if wait > 0 {
deadline = time.Now().Add(wait)
}
if err := c.acquireProcessSlot(ctx, wait, deadline); err != nil {
return nil, err
}
lock, err := c.lockState(ctx, remainingWait(wait, deadline))
if err != nil {
<-c.sem
return nil, err
}
return func() {
lock.release()
<-c.sem
}, nil
}
// acquireProcessSlot claims the in-process slot under the same wait budget as
// the file lock.
func (c *Client) acquireProcessSlot(ctx context.Context, wait time.Duration, deadline time.Time) error {
if wait == 0 {
select {
case c.sem <- struct{}{}:
return nil
default:
return errLockBusy
}
}
var expired <-chan time.Time
if wait > 0 {
timer := time.NewTimer(time.Until(deadline))
defer timer.Stop()
expired = timer.C
}
select {
case c.sem <- struct{}{}:
return nil
case <-expired:
return errLockBusy
case <-ctx.Done():
return ctx.Err()
}
}
// remainingWait reports how much of the wait budget is left for the next lock
// layer. Zero means the budget is spent, so that layer tries once.
func remainingWait(wait time.Duration, deadline time.Time) time.Duration {
if wait <= 0 {
return wait
}
return max(time.Until(deadline), 0)
}
func (c *Client) lockState(ctx context.Context, wait time.Duration) (*stateLock, error) {
if err := c.ensureDirectories(); err != nil {
return nil, err
}
file, err := os.OpenFile(c.lockPath(), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, fmt.Errorf("telemetry: open lock: %w", err)
}
if err := file.Chmod(0o600); err != nil {
_ = file.Close()
return nil, fmt.Errorf("telemetry: secure lock: %w", err)
}
var deadline time.Time
if wait > 0 {
deadline = time.Now().Add(wait)
}
for {
locked, lockErr := tryFileLock(file)
if lockErr != nil {
_ = file.Close()
return nil, fmt.Errorf("telemetry: lock state: %w", lockErr)
}
if locked {
return &stateLock{file: file}, nil
}
if wait == 0 {
_ = file.Close()
return nil, errLockBusy
}
if wait > 0 && !time.Now().Before(deadline) {
_ = file.Close()
return nil, errLockBusy
}
poll := 20 * time.Millisecond
if wait > 0 {
poll = min(poll, max(time.Until(deadline), 0))
}
timer := time.NewTimer(poll)
select {
case <-ctx.Done():
timer.Stop()
_ = file.Close()
return nil, ctx.Err()
case <-timer.C:
}
}
}
//go:build linux || darwin || freebsd || netbsd || openbsd || dragonfly
package telemetry
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
func tryFileLock(file *os.File) (bool, error) {
err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
if err == nil {
return true, nil
}
if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) {
return false, nil
}
return false, err
}
func unlockFile(file *os.File) {
_ = unix.Flock(int(file.Fd()), unix.LOCK_UN)
}
package telemetry
import (
"errors"
"fmt"
"os"
"path/filepath"
)
// noticeMarkerName is the file whose presence means the one-time telemetry
// notice was already presented on this machine. The misspelling is deliberate:
// the file name is a compatibility surface, so correcting it would present the
// notice again on every machine that already dismissed it.
const noticeMarkerName = ".alpha_telemety_notice_shown"
// ClaimNotice reports whether this process must present the one-time telemetry
// notice, and records the claim so later processes skip the notice.
//
// The claim is the exclusive creation of the marker file beside the local
// state, so invocations that start together present the notice at most once.
// The marker exists before the caller renders anything: a claim is permanent
// even when the caller cannot print.
func (c *Client) ClaimNotice() (bool, error) {
if c.disabled {
return false, nil
}
if err := os.MkdirAll(c.directory, 0o700); err != nil {
return false, fmt.Errorf("telemetry: create state directory: %w", err)
}
file, err := os.OpenFile(
filepath.Join(c.directory, noticeMarkerName),
os.O_CREATE|os.O_EXCL|os.O_WRONLY,
0o600,
)
if err != nil {
if errors.Is(err, os.ErrExist) {
return false, nil
}
return false, fmt.Errorf("telemetry: claim notice: %w", err)
}
_ = file.Close()
syncDirectory(c.directory)
return true, nil
}
package telemetry
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
type recordType string
const (
recordTypeEvent recordType = payloadTypeEvent
recordTypeReport recordType = payloadTypeReport
)
// queuedRecord is one durable outbox entry. The payload is stored verbatim so
// retries send identical bytes with the same record ID.
type queuedRecord struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"id"`
Type recordType `json:"type"`
CreatedAt time.Time `json:"created_at"`
BodyBytes int64 `json:"body_bytes,omitempty"`
Payload jsontext.Value `json:"payload"`
}
type payloadResult struct {
Payload any
BodyBytes int64
Truncated bool
}
type payloadBuilder func(state *persistedState, id string, now time.Time) (payloadResult, error)
func (c *Client) enqueue(ctx context.Context, kind recordType, build payloadBuilder) (Submission, error) {
if c.disabled {
return Submission{Reason: SkipDisabled}, nil
}
release, err := c.enterOperation(ctx, min(c.limits.LockWait, enqueueLockWait))
if err != nil {
if ignoreLockBusy(err) {
return Submission{Reason: SkipBusy}, nil
}
return Submission{}, err
}
defer release()
now := c.now()
state, _, err := c.loadState(now)
if err != nil {
return Submission{}, err
}
enabled, _, reason := c.effective(state)
if !enabled {
return Submission{Reason: reason}, nil
}
state.ensureIdentity(now)
id := NewUUID()
built, err := build(state, id, now)
if err != nil {
return Submission{}, err
}
data, err := marshalCanonical(built.Payload)
if err != nil {
return Submission{}, fmt.Errorf("telemetry: encode record: %w", err)
}
if kind == recordTypeEvent && len(data) > c.limits.MaxEventPayloadBytes {
return Submission{}, fmt.Errorf("%w: payload is %d bytes, limit %d", ErrInvalidEvent, len(data), c.limits.MaxEventPayloadBytes)
}
data, bodyBytes, truncated, err := c.fitRecord(kind, id, built.Payload, data, built.BodyBytes, built.Truncated)
if err != nil {
return Submission{}, err
}
if kind == recordTypeReport && bodyBytes == 0 {
return Submission{}, fmt.Errorf("%w: body is empty after record fitting", ErrInvalidReport)
}
if int64(len(data)) > c.limits.MaxQueuedBytes {
return Submission{Reason: SkipQueueFull}, nil
}
record := queuedRecord{
SchemaVersion: SchemaVersion,
ID: id,
Type: kind,
CreatedAt: now.UTC(),
BodyBytes: bodyBytes,
Payload: jsontext.Value(data),
}
if err := c.writeQueueRecord(record); err != nil {
return Submission{}, err
}
state.Queue = append(state.Queue, queueEntry{
ID: id,
Type: kind,
Sequence: state.NextSequence,
CreatedAt: now.UTC(),
PayloadBytes: int64(len(data)),
BodyBytes: bodyBytes,
})
state.NextSequence++
removed := c.pruneQueue(state, now)
if !queueContains(state.Queue, id) {
_ = os.Remove(c.queueRecordPath(id))
return Submission{Reason: SkipQueueFull}, nil
}
if err := c.saveState(state, now); err != nil {
_ = os.Remove(c.queueRecordPath(id))
return Submission{}, err
}
c.deleteQueuePayloads(removed)
c.pruneQueueOrphans(state)
return Submission{
Queued: true,
RecordID: id,
Truncated: truncated,
QueuedRecords: len(state.Queue),
}, nil
}
// fitRecord trims a report body until the complete serialized wire record fits
// the server's per-record bound. Event payloads are already bounded strictly
// enough that they must fit without adjustment.
func (c *Client) fitRecord(kind recordType, id string, payload any, data []byte, bodyBytes int64, truncated bool) ([]byte, int64, bool, error) {
encoded, err := marshalRecord(id, kind, data)
if err != nil {
return nil, 0, truncated, err
}
if len(encoded) <= c.limits.MaxRecordBytes {
return data, bodyBytes, truncated, nil
}
report, ok := payload.(reportPayload)
if !ok {
return nil, 0, truncated, fmt.Errorf("%w: serialized record is %d bytes, limit %d", ErrInvalidEvent, len(encoded), c.limits.MaxRecordBytes)
}
report, data, err = c.trimReportToRecord(id, kind, report)
if err != nil {
return nil, 0, truncated, err
}
return data, int64(len(report.Body)), true, nil
}
// trimReportToRecord keeps the longest body prefix whose serialized record
// fits the per-record bound. Escaping makes a body's serialized size differ
// from its length, so every candidate is measured on the encoded envelope.
// Serialized size never shrinks as the body grows, which turns the search into
// a bisection over body length.
func (c *Client) trimReportToRecord(id string, kind recordType, report reportPayload) (reportPayload, []byte, error) {
trimmed := report
trimmed.Body = ""
trimmedData, err := marshalCanonical(trimmed)
if err != nil {
return reportPayload{}, nil, fmt.Errorf("telemetry: encode report: %w", err)
}
encoded, err := marshalRecord(id, kind, trimmedData)
if err != nil {
return reportPayload{}, nil, err
}
if len(encoded) > c.limits.MaxRecordBytes {
return reportPayload{}, nil, fmt.Errorf("%w: record metadata exceeds %d bytes", ErrInvalidReport, c.limits.MaxRecordBytes)
}
var best reportPayload
var bestData []byte
for low, high := 1, len(report.Body); low <= high; {
middle := low + (high-low)/2
candidate := report
candidate.Body = truncateUTF8(report.Body, middle)
data, err := marshalCanonical(candidate)
if err != nil {
return reportPayload{}, nil, fmt.Errorf("telemetry: encode report: %w", err)
}
encoded, err := marshalRecord(id, kind, data)
if err != nil {
return reportPayload{}, nil, err
}
if len(encoded) <= c.limits.MaxRecordBytes {
best, bestData = candidate, data
low = middle + 1
} else {
high = middle - 1
}
}
if len(best.Body) == 0 {
return reportPayload{}, nil, fmt.Errorf("%w: record metadata leaves no room for a body", ErrInvalidReport)
}
return best, bestData, nil
}
// marshalRecord encodes the wire envelope around an already encoded payload.
func marshalRecord(id string, kind recordType, data []byte) ([]byte, error) {
encoded, err := marshalCanonical(wireRecord{ID: id, Type: kind, Payload: jsontext.Value(data)})
if err != nil {
return nil, fmt.Errorf("telemetry: encode record envelope: %w", err)
}
return encoded, nil
}
func (c *Client) writeQueueRecord(record queuedRecord) error {
data, err := marshalCanonical(record)
if err != nil {
return fmt.Errorf("telemetry: encode outbox record: %w", err)
}
if err := writeFileAtomic(c.queueRecordPath(record.ID), data); err != nil {
return fmt.Errorf("telemetry: write outbox record: %w", err)
}
return nil
}
func (c *Client) readQueueRecord(id string) (queuedRecord, error) {
data, err := os.ReadFile(c.queueRecordPath(id))
if err != nil {
return queuedRecord{}, err
}
var record queuedRecord
if err := json.Unmarshal(data, &record); err != nil {
return queuedRecord{}, fmt.Errorf("decode outbox record %s: %w", id, err)
}
if record.ID != id || (record.Type != recordTypeEvent && record.Type != recordTypeReport) || len(record.Payload) == 0 {
return queuedRecord{}, fmt.Errorf("outbox record %s is inconsistent", id)
}
return record, nil
}
func (c *Client) deleteQueuePayloads(entries []queueEntry) {
for _, entry := range entries {
if err := os.Remove(c.queueRecordPath(entry.ID)); err != nil && !errors.Is(err, os.ErrNotExist) {
c.debug("telemetry: remove outbox record failed", "id", entry.ID, "error", err)
}
}
}
func (c *Client) finishDisabledPurge(state *persistedState, now time.Time) error {
if err := os.RemoveAll(c.queueDirectory()); err != nil {
return fmt.Errorf("telemetry is off, but pending records could not be deleted: %w", err)
}
state.completePurge()
return c.saveState(state, now)
}
// pruneQueue removes stale records first, then oldest records until both queue
// bounds hold. The record just enqueued has the highest sequence and survives
// unless a single record exceeds MaxQueuedBytes (checked by the caller).
func (c *Client) pruneQueue(state *persistedState, now time.Time) []queueEntry {
cutoff := now.Add(-c.limits.MaxRecordAge)
removed := make([]queueEntry, 0)
kept := state.Queue[:0]
var totalBytes int64
for _, entry := range state.Queue {
if entry.CreatedAt.Before(cutoff) {
removed = append(removed, entry)
continue
}
kept = append(kept, entry)
totalBytes += entry.PayloadBytes
}
state.Queue = kept
for len(state.Queue) > 0 && (len(state.Queue) > c.limits.MaxQueuedRecords || totalBytes > c.limits.MaxQueuedBytes) {
entry := state.Queue[0]
state.Queue = state.Queue[1:]
totalBytes -= entry.PayloadBytes
removed = append(removed, entry)
}
state.QueueBytes = totalBytes
state.countDropped(removed)
return removed
}
func (c *Client) pruneQueueOrphans(state *persistedState) {
entries, err := os.ReadDir(c.queueDirectory())
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
c.debug("telemetry: read outbox directory failed", "error", err)
}
return
}
known := make(map[string]struct{}, len(state.Queue))
for _, entry := range state.Queue {
known[entry.ID] = struct{}{}
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
path := filepath.Join(c.queueDirectory(), name)
if strings.HasPrefix(name, ".") {
_ = os.Remove(path)
continue
}
if !strings.HasSuffix(name, ".json") {
continue
}
id := strings.TrimSuffix(name, ".json")
if _, exists := known[id]; exists {
continue
}
_ = os.Remove(path)
}
}
func queueContains(queue []queueEntry, id string) bool {
for _, entry := range queue {
if entry.ID == id {
return true
}
}
return false
}
func queueStatistics(state *persistedState) QueueStats {
stats := QueueStats{
Records: len(state.Queue),
PayloadBytes: state.QueueBytes,
}
for _, entry := range state.Queue {
switch entry.Type {
case recordTypeEvent:
stats.Events++
case recordTypeReport:
stats.Reports++
stats.ReportBodyBytes += entry.BodyBytes
}
if stats.Oldest.IsZero() || entry.CreatedAt.Before(stats.Oldest) {
stats.Oldest = entry.CreatedAt
}
}
return stats
}
package telemetry
import (
"fmt"
"strings"
"time"
)
func (c *Client) prepareReport(report Report, now time.Time) (preparedReport, bool, error) {
switch report.Kind {
case ReportFailure, ReportPanic, ReportAgentFeedback:
default:
return preparedReport{}, false, fmt.Errorf("%w: unknown report kind %q", ErrInvalidReport, report.Kind)
}
invocationID := ""
if strings.TrimSpace(report.InvocationID) != "" {
normalized, err := normalizeUUID(report.InvocationID)
if err != nil {
return preparedReport{}, false, fmt.Errorf("%w: invocation id: %v", ErrInvalidReport, err)
}
invocationID = normalized
}
body, truncated := sanitizeReportText(report.Body, c.limits.MaxReportBodyBytes)
if body == "" {
return preparedReport{}, false, fmt.Errorf("%w: body is empty after sanitization", ErrInvalidReport)
}
createdAt := report.CreatedAt
if createdAt.IsZero() {
createdAt = now
}
return preparedReport{
kind: report.Kind,
invocationID: invocationID,
agent: sanitizeReportIdentifier(report.Agent),
model: sanitizeReportIdentifier(report.Model),
body: body,
createdAt: createdAt.UTC(),
}, truncated, nil
}
func sanitizeReportIdentifier(raw string) string {
if len(raw) > 256 {
raw = raw[:256]
}
var builder strings.Builder
for _, character := range strings.TrimSpace(raw) {
switch {
case character >= 'a' && character <= 'z':
case character >= 'A' && character <= 'Z':
case character >= '0' && character <= '9':
case strings.ContainsRune("._-/:@", character):
default:
continue
}
builder.WriteRune(character)
if builder.Len() >= 64 {
break
}
}
return builder.String()
}
package telemetry
import (
"regexp"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
var (
bearerPattern = regexp.MustCompile(`(?i)\bbearer\s+[A-Za-z0-9._~+/\-=]+`)
authorizationPattern = regexp.MustCompile(`(?i)\b([a-z0-9_-]*authorization)\b\s*[:=]\s*[^\r\n]+`)
flagCredentialPattern = regexp.MustCompile(`(?i)(--?(?:token|password|passwd|secret|api[_-]?key|access[_-]?key))(\s+|=)(?:"(?:\\.|[^"\\])*"?|'(?:\\.|[^'\\])*'?|[^\s"'])+`)
credentialPattern = regexp.MustCompile(`(?i)\b([a-z0-9_]*(?:api[_-]?key|access[_-]?key|private[_-]?key|secret|token|password|passwd|pwd|authorization|cookie|session[_-]?id)[a-z0-9_]*)\b["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*"?|'(?:\\.|[^'\\])*'?|[^\s,;"'])+`)
commonTokenPattern = regexp.MustCompile(`\b(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b`)
urlCredentialPattern = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://)[^/\s:@]+:[^/\s@]+@`)
privateKeyPattern = regexp.MustCompile(`(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)`)
ipv4Pattern = regexp.MustCompile(`\b(?:\d{1,3}\.){3}\d{1,3}\b`)
ipv6Candidate = regexp.MustCompile(`\b[0-9A-Fa-f:]{2,39}\b`)
unixPathPattern = regexp.MustCompile(`(^|[\s"'(\\[=:,<])(/(?:[A-Za-z0-9._-]+/)+[A-Za-z0-9._-]+)`)
homePathPattern = regexp.MustCompile(`~/[^\s"'<>]+`)
windowsPathPattern = regexp.MustCompile(`(?i)\b[A-Z]:\\[^\s"'<>]+`)
uncPathPattern = regexp.MustCompile(`\\\\[A-Za-z0-9._-]+\\[^\s"'<>]+`)
)
// sanitizeText converts free-form text into bounded, printable UTF-8. It
// normalizes line endings, removes ANSI escape sequences and control or
// formatting characters other than newline and tab, replaces invalid UTF-8,
// and appends a truncation marker when the byte bound is exceeded.
func sanitizeText(raw string, maxBytes int) (string, bool) {
if raw == "" || maxBytes <= 0 {
return "", false
}
truncated := false
if maxBytes <= (1<<30)/8 && len(raw) > maxBytes*8 {
raw = truncateUTF8(raw, maxBytes*8)
truncated = true
}
raw = strings.ReplaceAll(raw, "\r\n", "\n")
raw = strings.ReplaceAll(raw, "\r", "\n")
var builder strings.Builder
builder.Grow(min(len(raw), maxBytes))
for index := 0; index < len(raw); {
character, size := utf8.DecodeRuneInString(raw[index:])
if character == utf8.RuneError && size == 1 {
builder.WriteRune(utf8.RuneError)
index++
continue
}
index += size
switch {
case character == '\x1b':
index = skipEscapeSequence(raw, index)
case character == '\n' || character == '\t':
builder.WriteRune(character)
case character < 0x20 || character == 0x7f:
continue
case character >= 0x80 && character <= 0x9f:
continue
case unicode.Is(unicode.Cf, character):
continue
default:
builder.WriteRune(character)
}
}
text := strings.TrimSpace(builder.String())
if len(text) <= maxBytes {
return text, truncated
}
if maxBytes <= len(truncationMarker) {
return truncateUTF8(text, maxBytes), true
}
return truncateUTF8(text, maxBytes-len(truncationMarker)) + truncationMarker, true
}
func skipEscapeSequence(raw string, index int) int {
if index >= len(raw) {
return index
}
switch raw[index] {
case '[':
index++
for index < len(raw) {
character := raw[index]
index++
if character >= 0x40 && character <= 0x7e {
break
}
}
return index
case ']', 'P', '^', '_':
index++
for index < len(raw) {
if raw[index] == 0x07 {
return index + 1
}
if raw[index] == 0x1b && index+1 < len(raw) && raw[index+1] == '\\' {
return index + 2
}
index++
}
return index
default:
return index + 1
}
}
func truncateUTF8(value string, maxBytes int) string {
if maxBytes <= 0 {
return ""
}
if len(value) <= maxBytes {
return value
}
cut := value[:maxBytes]
for len(cut) > 0 && !utf8.ValidString(cut) {
cut = cut[:len(cut)-1]
}
return cut
}
func sanitizeToken(raw string, maxBytes int) string {
var builder strings.Builder
for _, character := range raw {
switch {
case character >= 'a' && character <= 'z':
case character >= 'A' && character <= 'Z':
case character >= '0' && character <= '9':
case strings.ContainsRune("-_.:", character):
default:
continue
}
builder.WriteRune(character)
if builder.Len() >= maxBytes {
break
}
}
return builder.String()
}
func validChannel(channel string) bool {
if channel == "" || len(channel) > 32 {
return false
}
for index, character := range channel {
valid := character >= 'a' && character <= 'z' ||
character >= '0' && character <= '9'
if index > 0 {
valid = valid || character == '-' || character == '_' || character == '.'
}
if !valid {
return false
}
}
return true
}
func normalizeCommand(raw string) (string, error) {
if len(raw) > 512 {
return "", ErrInvalidEvent
}
fields := strings.Fields(raw)
if len(fields) == 0 || len(fields) > 4 {
return "", ErrInvalidEvent
}
var builder strings.Builder
for index, field := range fields {
if len(field) > 32 || !validCommandToken(field) {
return "", ErrInvalidEvent
}
if index > 0 {
builder.WriteByte(' ')
}
builder.WriteString(field)
}
command := builder.String()
if len(command) > 96 {
return "", ErrInvalidEvent
}
return command, nil
}
func validCommandToken(token string) bool {
for index := 0; index < len(token); index++ {
character := token[index]
valid := character >= 'a' && character <= 'z' ||
character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9'
if index > 0 {
valid = valid || character == '-' || character == '_' || character == ':'
}
if !valid {
return false
}
}
return true
}
func validCode(raw string, maxBytes int) bool {
if raw == "" || len(raw) > maxBytes {
return false
}
for index := 0; index < len(raw); index++ {
character := raw[index]
valid := character >= 'a' && character <= 'z' ||
character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9'
if index > 0 {
valid = valid || character == '-' || character == '_' || character == '.' || character == ':'
}
if !valid {
return false
}
}
return true
}
func sanitizeErrorText(err error) string {
if err == nil {
return ""
}
text, _ := sanitizeText(err.Error(), 256)
return strings.Join(strings.Fields(text), " ")
}
// sanitizeReportText applies the printable-text filter and then redacts common
// secrets, network addresses, and absolute paths. Redaction is defense in
// depth, not anonymization: callers must still keep raw transcripts and file
// attachments out of reports.
func sanitizeReportText(raw string, maxBytes int) (string, bool) {
if raw == "" || maxBytes <= 0 {
return "", false
}
inputLimit := maxBytes * 8
truncated := len(raw) > inputLimit
if truncated {
raw = truncateUTF8(raw, inputLimit)
}
text, inputClipped := sanitizeText(raw, inputLimit)
truncated = truncated || inputClipped
if text == "" {
return "", truncated
}
text = redactReportText(text)
bounded, clipped := boundWithMarker(text, maxBytes)
return bounded, truncated || clipped
}
func redactReportText(text string) string {
text = privateKeyPattern.ReplaceAllString(text, "[redacted-private-key]")
text = bearerPattern.ReplaceAllString(text, "Bearer [redacted]")
text = authorizationPattern.ReplaceAllString(text, "${1}=[redacted]")
text = flagCredentialPattern.ReplaceAllString(text, "${1}${2}[redacted]")
text = credentialPattern.ReplaceAllString(text, "${1}=[redacted]")
text = commonTokenPattern.ReplaceAllString(text, "[redacted-token]")
text = urlCredentialPattern.ReplaceAllString(text, "${1}[redacted]@")
text = redactIPv4(text)
text = redactIPv6(text)
text = windowsPathPattern.ReplaceAllString(text, "[redacted-path]")
text = uncPathPattern.ReplaceAllString(text, "[redacted-path]")
text = homePathPattern.ReplaceAllString(text, "[redacted-path]")
text = unixPathPattern.ReplaceAllString(text, "${1}[redacted-path]")
return text
}
func redactIPv4(text string) string {
return ipv4Pattern.ReplaceAllStringFunc(text, func(candidate string) string {
for _, part := range strings.Split(candidate, ".") {
value, err := strconv.Atoi(part)
if err != nil || value > 255 {
return candidate
}
}
return "[redacted-ip]"
})
}
func redactIPv6(text string) string {
return ipv6Candidate.ReplaceAllStringFunc(text, func(candidate string) string {
if !strings.Contains(candidate, ":") {
return candidate
}
if strings.Contains(candidate, "::") {
return "[redacted-ip]"
}
groups := 0
for _, group := range strings.Split(candidate, ":") {
if group != "" {
groups++
}
}
if groups >= 4 && strings.Count(candidate, ":") >= 3 {
return "[redacted-ip]"
}
return candidate
})
}
func boundWithMarker(text string, maxBytes int) (string, bool) {
if len(text) <= maxBytes {
return text, false
}
text = strings.TrimSuffix(text, truncationMarker)
if maxBytes <= len(truncationMarker) {
return truncateUTF8(text, maxBytes), true
}
return truncateUTF8(text, maxBytes-len(truncationMarker)) + truncationMarker, true
}
package telemetry
import (
"cmp"
"encoding/json/v2"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"time"
)
var errCorruptState = errors.New("telemetry: state is corrupt; run `lucy telemetry off` to reset it")
type acceptedState struct {
Events int64 `json:"events"`
Reports int64 `json:"reports"`
EventPayloadBytes int64 `json:"event_payload_bytes"`
ReportBodyBytes int64 `json:"report_body_bytes"`
}
type rejectedState struct {
Records int64 `json:"records"`
PayloadBytes int64 `json:"payload_bytes"`
}
type droppedState struct {
Records int64 `json:"records"`
Bytes int64 `json:"bytes"`
}
type transportState struct {
Requests int64 `json:"requests"`
Succeeded int64 `json:"succeeded"`
RejectedRequests int64 `json:"rejected_requests"`
Uncertain int64 `json:"uncertain"`
Throttles int64 `json:"throttles"`
RequestBodyBytes int64 `json:"request_body_bytes"`
LastRequestBodyBytes int64 `json:"last_request_body_bytes"`
}
type queueEntry struct {
ID string `json:"id"`
Type recordType `json:"type"`
Sequence int64 `json:"sequence"`
CreatedAt time.Time `json:"created_at"`
PayloadBytes int64 `json:"payload_bytes"`
BodyBytes int64 `json:"body_bytes,omitempty"`
}
// persistedState is the single source of truth for identity, policy, counters,
// and the queue index. Queue payloads live in queue/<id>.json so accepting a
// record and counting it happen in one atomic state replacement.
type persistedState struct {
SchemaVersion int `json:"schema_version"`
InstallationID string `json:"installation_id,omitempty"`
IdentityCreatedAt time.Time `json:"identity_created_at,omitzero"`
Policy CollectionPolicy `json:"policy"`
PeriodStart time.Time `json:"period_start,omitzero"`
Accepted acceptedState `json:"accepted"`
Rejected rejectedState `json:"rejected"`
Dropped droppedState `json:"dropped"`
Transport transportState `json:"transport"`
PurgePending bool `json:"purge_pending,omitzero"`
Queue []queueEntry `json:"queue,omitempty"`
QueueBytes int64 `json:"queue_bytes"`
NextSequence int64 `json:"next_sequence"`
AcceptedIDs []string `json:"accepted_ids,omitempty"`
CooldownUntil time.Time `json:"cooldown_until,omitzero"`
LastError string `json:"last_error,omitempty"`
LastUploadAt time.Time `json:"last_upload_at,omitzero"`
UpdatedAt time.Time `json:"updated_at,omitzero"`
}
func newState(now time.Time) *persistedState {
return &persistedState{
SchemaVersion: SchemaVersion,
Policy: CollectionDefault,
PeriodStart: now.UTC(),
NextSequence: 1,
}
}
func (c *Client) statePath() string {
return filepath.Join(c.directory, "state.json")
}
func (c *Client) lockPath() string {
return filepath.Join(c.directory, "state.lock")
}
func (c *Client) queueDirectory() string {
return filepath.Join(c.directory, "queue")
}
func (c *Client) queueRecordPath(id string) string {
return filepath.Join(c.queueDirectory(), id+".json")
}
func (c *Client) ensureDirectories() error {
for _, directory := range []string{c.directory, c.queueDirectory()} {
if err := os.MkdirAll(directory, 0o700); err != nil {
return fmt.Errorf("telemetry: create state directory: %w", err)
}
if err := os.Chmod(directory, 0o700); err != nil {
return fmt.Errorf("telemetry: secure state directory: %w", err)
}
}
return nil
}
func (c *Client) loadState(now time.Time) (*persistedState, bool, error) {
data, err := os.ReadFile(c.statePath())
if errors.Is(err, os.ErrNotExist) {
return newState(now), false, nil
}
if err != nil {
return nil, false, fmt.Errorf("telemetry: read state: %w", err)
}
_ = os.Chmod(c.statePath(), 0o600)
var state persistedState
if err := json.Unmarshal(data, &state); err != nil {
return nil, true, fmt.Errorf("%w: %v", errCorruptState, err)
}
if state.SchemaVersion < 1 {
return nil, true, errCorruptState
}
switch state.Policy {
case CollectionDefault, CollectionOptIn, CollectionOptOut:
default:
return nil, true, errCorruptState
}
if state.SchemaVersion > SchemaVersion {
return nil, true, fmt.Errorf("telemetry: state schema %d is newer than supported schema %d", state.SchemaVersion, SchemaVersion)
}
if state.InstallationID != "" {
if _, err := normalizeUUID(state.InstallationID); err != nil {
return nil, true, errCorruptState
}
}
state.normalize(now)
if state.PurgePending {
if state.Policy != CollectionOptOut {
return nil, true, errCorruptState
}
if err := c.finishDisabledPurge(&state, now); err != nil {
return nil, true, err
}
}
return &state, true, nil
}
func (c *Client) saveState(state *persistedState, now time.Time) error {
state.SchemaVersion = SchemaVersion
state.UpdatedAt = now.UTC()
data, err := marshalCanonical(state)
if err != nil {
return fmt.Errorf("telemetry: encode state: %w", err)
}
if err := writeFileAtomic(c.statePath(), data); err != nil {
return fmt.Errorf("telemetry: write state: %w", err)
}
return nil
}
func (state *persistedState) normalize(now time.Time) {
if state.InstallationID != "" {
installationID, err := normalizeUUID(state.InstallationID)
if err != nil {
state.InstallationID = ""
state.IdentityCreatedAt = time.Time{}
} else {
state.InstallationID = installationID
}
}
if state.PeriodStart.IsZero() {
state.PeriodStart = now.UTC()
}
if state.InstallationID != "" && state.IdentityCreatedAt.IsZero() {
state.IdentityCreatedAt = state.PeriodStart
}
if state.InstallationID == "" {
state.IdentityCreatedAt = time.Time{}
}
if state.NextSequence < 1 {
state.NextSequence = 1
}
kept := state.Queue[:0]
var queueBytes int64
var maximumSequence int64
for _, entry := range state.Queue {
entryID, err := normalizeUUID(entry.ID)
if err != nil || entry.PayloadBytes <= 0 {
state.Dropped.Records++
continue
}
if entry.Type != recordTypeEvent && entry.Type != recordTypeReport {
state.Dropped.Records++
continue
}
if entry.Sequence < 1 {
state.Dropped.Records++
continue
}
entry.ID = entryID
if entry.CreatedAt.IsZero() {
entry.CreatedAt = now.UTC()
}
kept = append(kept, entry)
queueBytes += entry.PayloadBytes
maximumSequence = max(maximumSequence, entry.Sequence)
}
state.Queue = kept
state.QueueBytes = queueBytes
if state.NextSequence <= maximumSequence {
state.NextSequence = maximumSequence + 1
}
slices.SortFunc(state.Queue, func(left, right queueEntry) int {
return cmp.Compare(left.Sequence, right.Sequence)
})
state.normalizeAcceptedIDs()
}
func (state *persistedState) normalizeAcceptedIDs() {
if len(state.AcceptedIDs) == 0 {
state.AcceptedIDs = nil
return
}
seen := make(map[string]struct{}, len(state.AcceptedIDs))
kept := make([]string, 0, min(len(state.AcceptedIDs), defaultMaxAcceptedIDHistory))
start := max(0, len(state.AcceptedIDs)-defaultMaxAcceptedIDHistory)
for _, raw := range state.AcceptedIDs[start:] {
id, err := normalizeUUID(raw)
if err != nil {
continue
}
if _, exists := seen[id]; exists {
continue
}
seen[id] = struct{}{}
kept = append(kept, id)
}
state.AcceptedIDs = kept
}
func (state *persistedState) rememberAccepted(id string) bool {
for _, accepted := range state.AcceptedIDs {
if accepted == id {
return false
}
}
state.AcceptedIDs = append(state.AcceptedIDs, id)
if len(state.AcceptedIDs) > defaultMaxAcceptedIDHistory {
state.AcceptedIDs = state.AcceptedIDs[len(state.AcceptedIDs)-defaultMaxAcceptedIDHistory:]
}
return true
}
// countDropped adds records discarded locally without a server decision.
func (state *persistedState) countDropped(entries []queueEntry) {
state.Dropped.Records += int64(len(entries))
for _, entry := range entries {
state.Dropped.Bytes += entry.PayloadBytes
}
}
// countRejected adds one record the server permanently rejected.
func (state *persistedState) countRejected(payloadBytes int64) {
state.Rejected.Records++
state.Rejected.PayloadBytes += payloadBytes
}
func (state *persistedState) ensureIdentity(now time.Time) {
if state.InstallationID != "" {
return
}
state.InstallationID = NewUUID()
state.IdentityCreatedAt = now.UTC()
if state.Accepted == (acceptedState{}) && state.Rejected == (rejectedState{}) && state.Dropped == (droppedState{}) {
state.PeriodStart = now.UTC()
}
}
// clearBackoff forgets a pending retry deadline and its diagnostic. Explicit
// policy changes and identity resets supersede an earlier transport failure.
func (state *persistedState) clearBackoff() {
state.CooldownUntil = time.Time{}
state.LastError = ""
}
// deferRetry records a failed attempt and blocks uploads until the cooldown
// elapses. A failure that must not defer retries records LastError directly.
func (state *persistedState) deferRetry(now time.Time, cooldown time.Duration, message string) {
state.CooldownUntil = now.Add(cooldown)
state.LastError = message
}
// optIn records an explicit opt-in and creates an identity when none exists.
func (state *persistedState) optIn(now time.Time) {
state.Policy = CollectionOptIn
state.ensureIdentity(now)
state.clearBackoff()
}
// optOut records an explicit opt-out. PurgePending makes the queue purge
// resumable; the queue index is cleared only after its payloads are gone.
func (state *persistedState) optOut() {
state.Policy = CollectionOptOut
state.PurgePending = true
state.clearBackoff()
}
// completePurge clears the queue index and the purge marker after the payload
// directory has been removed.
func (state *persistedState) completePurge() {
state.Queue = nil
state.QueueBytes = 0
state.PurgePending = false
}
// resetIdentity rotates the installation UUID and restarts the statistics
// window. Queued records keep their IDs and payloads.
func (state *persistedState) resetIdentity(now time.Time) {
state.InstallationID = NewUUID()
state.IdentityCreatedAt = now.UTC()
state.PeriodStart = now.UTC()
state.Accepted = acceptedState{}
state.Rejected = rejectedState{}
state.Dropped = droppedState{}
state.Transport = transportState{}
state.AcceptedIDs = nil
state.clearBackoff()
state.LastUploadAt = time.Time{}
}
func marshalCanonical(value any) ([]byte, error) {
return json.Marshal(value, json.Deterministic(true))
}
func writeFileAtomic(path string, data []byte) error {
directory := filepath.Dir(path)
if err := os.MkdirAll(directory, 0o700); err != nil {
return err
}
file, err := os.CreateTemp(directory, "."+filepath.Base(path)+"-*")
if err != nil {
return err
}
temporaryPath := file.Name()
defer func() {
if temporaryPath != "" {
_ = os.Remove(temporaryPath)
}
}()
if err := file.Chmod(0o600); err != nil {
_ = file.Close()
return err
}
if _, err := file.Write(data); err != nil {
_ = file.Close()
return err
}
if err := file.Sync(); err != nil {
_ = file.Close()
return err
}
if err := file.Close(); err != nil {
return err
}
if err := os.Rename(temporaryPath, path); err != nil {
return err
}
temporaryPath = ""
syncDirectory(directory)
return nil
}
func syncDirectory(path string) {
directory, err := os.Open(path)
if err != nil {
return
}
_ = directory.Sync()
_ = directory.Close()
}
package telemetry
import (
"errors"
"slices"
"time"
)
// Schema and protocol values that appear on the wire.
const (
payloadTypeEvent = "event"
payloadTypeReport = "report"
)
// ErrInvalidEvent reports a caller-provided event that does not satisfy the
// telemetry schema. It is a programming error, not a telemetry outage.
var ErrInvalidEvent = errors.New("telemetry: invalid event")
// ErrInvalidReport reports a caller-provided report that does not satisfy the
// telemetry schema. It is a programming error, not a telemetry outage.
var ErrInvalidReport = errors.New("telemetry: invalid report")
// CollectionPolicy is the persisted reason telemetry is enabled or disabled.
// The wire value of a record is default or opt_in; opt_out records are never
// collected.
type CollectionPolicy string
const (
// CollectionDefault follows the channel default (on for alpha and beta).
CollectionDefault CollectionPolicy = "default"
// CollectionOptIn is an explicit user enablement.
CollectionOptIn CollectionPolicy = "opt_in"
// CollectionOptOut is an explicit user disablement.
CollectionOptOut CollectionPolicy = "opt_out"
)
// SkipReason explains why a record was not queued or an upload did not run.
type SkipReason string
const (
SkipNone SkipReason = ""
SkipDisabled SkipReason = "disabled"
SkipEnvironment SkipReason = "environment_disabled"
SkipEndpoint SkipReason = "endpoint_unconfigured"
SkipCooldown SkipReason = "cooldown"
SkipBusy SkipReason = "busy"
SkipEmpty SkipReason = "empty"
SkipQueueFull SkipReason = "queue_full"
)
// Outcome is the result of one Lucy invocation.
type Outcome string
const (
OutcomeSuccess Outcome = "success"
OutcomeFailure Outcome = "failure"
OutcomeCanceled Outcome = "canceled"
)
// ContextStatus describes whether a typed context snapshot was available.
type ContextStatus string
const (
ContextPresent ContextStatus = "present"
ContextAbsent ContextStatus = "absent"
ContextFailed ContextStatus = "failed"
)
// ContextKind names a typed context snapshot. The wire type is a bounded
// string; these constants name the kinds Lucy currently emits.
type ContextKind string
const (
ContextServer ContextKind = "server"
ContextRuntime ContextKind = "runtime"
ContextManifest ContextKind = "manifest"
ContextLockfile ContextKind = "lockfile"
ContextPackages ContextKind = "packages"
ContextWorkspace ContextKind = "workspace"
ContextInvocation ContextKind = "invocation"
ContextExecution ContextKind = "execution"
ContextPrompt ContextKind = "prompt"
ContextScale ContextKind = "scale"
ContextWarnings ContextKind = "warnings"
ContextCollection ContextKind = "collection"
)
// ContextReason explains why a typed snapshot is absent or failed. It is a
// bounded wire value; unrecognized reasons are rejected before enqueueing.
type ContextReason string
const (
ContextReasonNotObserved ContextReason = "not_observed"
ContextReasonNotReached ContextReason = "not_reached"
ContextReasonNotApplicable ContextReason = "not_applicable"
ContextReasonNoResult ContextReason = "no_result"
ContextReasonObservationFailed ContextReason = "observation_failed"
)
// Context is an optional typed snapshot attached to an event. Data must be
// JSON-marshalable and fit in 8 KiB. Data is required when Status is present
// and must be nil when Status is absent or failed. Reason is optional for
// absent contexts (the default is not_observed) and failed contexts (the
// default is observation_failed), and must be empty for present contexts.
// Version is stamped as 1 by the writer; zero selects the current version.
type Context struct {
Kind ContextKind
Status ContextStatus
Version int
Reason ContextReason
Data any
}
// Event describes one non-sensitive invocation observation. Operation is the
// trusted normalized command path only (for example "java list"); Event
// excludes arguments and their values.
type Event struct {
InvocationID string
Operation string
Duration time.Duration
// DurationMeasured emits duration_ms even when Duration is zero. A
// positive Duration is emitted regardless; an unmeasured zero is omitted.
DurationMeasured bool
Outcome Outcome
ErrorCode string
OccurredAt time.Time
Contexts []Context
}
// ReportKind classifies an explicitly submitted report.
type ReportKind string
const (
ReportFailure ReportKind = "failure"
ReportPanic ReportKind = "panic"
ReportAgentFeedback ReportKind = "agent_feedback"
)
// Report is a free-form, explicitly submitted diagnostic. Body is sanitized,
// bounded UTF-8 text with common secrets, IP addresses, and absolute paths
// redacted as defense in depth, not anonymization. Callers must not place raw
// transcripts or file attachments in Body. Agent and Model are optional
// bounded identifiers.
type Report struct {
Kind ReportKind
InvocationID string
Agent string
Model string
Body string
CreatedAt time.Time
}
// Submission reports whether a record was durably placed in the local queue.
// Queued means the record will be retried later; it does not mean the server
// has accepted it. When Queued is false, Reason explains why.
type Submission struct {
Queued bool `json:"queued"`
RecordID string `json:"record_id,omitempty"`
Reason SkipReason `json:"reason,omitempty"`
Truncated bool `json:"truncated,omitempty"`
QueuedRecords int `json:"queued_records"`
}
// FlushResult describes one bounded upload run. AcceptedIDs and RejectedIDs
// contain record IDs the server permanently accepted or rejected in this run,
// so a caller can check the fate of a specific report's Submission.RecordID.
// Details are diagnostic text with no effect on CLI outcomes.
type FlushResult struct {
Attempted int `json:"attempted"`
Accepted int `json:"accepted"`
Rejected int `json:"rejected"`
Remaining int `json:"remaining"`
Skipped bool `json:"skipped"`
Reason SkipReason `json:"reason,omitempty"`
Detail string `json:"detail,omitempty"`
AcceptedIDs []string `json:"accepted_ids,omitempty"`
RejectedIDs []string `json:"rejected_ids,omitempty"`
}
// WasAccepted reports whether the server durably accepted id during this run.
func (result FlushResult) WasAccepted(id string) bool {
return slices.Contains(result.AcceptedIDs, id)
}
// WasRejected reports whether the server permanently rejected id during this
// run. Rejected records are removed from the queue without a retry.
func (result FlushResult) WasRejected(id string) bool {
return slices.Contains(result.RejectedIDs, id)
}
// AcceptedStats counts records the server durably accepted in the current
// statistics window. Bytes cover logical payload and sanitized body lengths
// and exclude HTTP, TLS, and framing overhead.
type AcceptedStats struct {
Events int64 `json:"events"`
Reports int64 `json:"reports"`
Records int64 `json:"records"`
EventPayloadBytes int64 `json:"event_payload_bytes"`
ReportBodyBytes int64 `json:"report_body_bytes"`
}
// RejectedStats counts records the server permanently rejected in the current
// statistics window. Bytes are logical serialized payload bytes.
type RejectedStats struct {
Records int64 `json:"records"`
PayloadBytes int64 `json:"payload_bytes"`
}
// DroppedStats counts records discarded locally because they were stale,
// corrupt, or exceeded the bounded queue.
type DroppedStats struct {
Records int64 `json:"records"`
Bytes int64 `json:"bytes"`
}
// TransportStats counts locally persisted upload attempts. Requests, outcome
// counts, and RequestBodyBytes cover every HTTP attempt, including retries.
// RequestBodyBytes is the exact serialized JSON body handed to the HTTP
// transport; it excludes HTTP headers, framing, TLS, and other wire overhead.
// Uncertain counts attempts whose acceptance is unknown (transport error,
// timeout, or an unparseable success response).
// Throttles counts attempts a retryable response identified as intake-limited
// (HTTP 429, or a rejection reason of intake_limited) and counts denied
// delivery attempts by attempt. An attempt interrupted by process termination
// may be missing from these counters.
type TransportStats struct {
Requests int64 `json:"requests"`
Succeeded int64 `json:"succeeded"`
RejectedRequests int64 `json:"rejected_requests"`
Uncertain int64 `json:"uncertain"`
Throttles int64 `json:"throttles"`
RequestBodyBytes int64 `json:"request_body_bytes"`
LastRequestBodyBytes int64 `json:"last_request_body_bytes"`
}
// QueueStats describes locally queued records. PayloadBytes and ReportBodyBytes
// are logical lengths.
type QueueStats struct {
Records int `json:"records"`
Events int `json:"events"`
Reports int `json:"reports"`
PayloadBytes int64 `json:"payload_bytes"`
ReportBodyBytes int64 `json:"report_body_bytes"`
Oldest time.Time `json:"oldest,omitzero"`
}
// Stats is a transparent snapshot of telemetry state. Enabled reports whether
// collection is allowed; EndpointConfigured separately reports whether uploads
// can run. PeriodStart begins at identity creation or the last ResetIdentity;
// pending records from before a reset are accepted later and count in the new
// window.
type Stats struct {
Enabled bool `json:"enabled"`
Reason SkipReason `json:"reason,omitempty"`
Policy CollectionPolicy `json:"policy"`
Endpoint string `json:"endpoint,omitempty"`
EndpointConfigured bool `json:"endpoint_configured"`
InstallationID string `json:"installation_id,omitempty"`
PeriodStart time.Time `json:"period_start,omitzero"`
Accepted AcceptedStats `json:"accepted"`
Rejected RejectedStats `json:"rejected"`
Dropped DroppedStats `json:"dropped"`
Transport TransportStats `json:"transport"`
Queue QueueStats `json:"queue"`
CooldownUntil time.Time `json:"cooldown_until,omitzero"`
LastError string `json:"last_error,omitempty"`
StateDirectory string `json:"state_directory,omitempty"`
}
// Identity is the result of ResetIdentity.
type Identity struct {
InstallationID string `json:"installation_id"`
CreatedAt time.Time `json:"created_at"`
Policy CollectionPolicy `json:"policy"`
}
package telemetry
import (
"context"
"errors"
"fmt"
"time"
)
type preparedRecord struct {
entry queueEntry
payloadBytes int64
encoded []byte
}
type preparedBatch struct {
records []preparedRecord
body []byte
}
// Flush performs one bounded upload run. Network, health, and protocol failures
// appear in FlushResult; errors are limited to local state I/O.
func (c *Client) Flush(ctx context.Context) (FlushResult, error) {
if ctx == nil {
ctx = context.Background()
}
result := FlushResult{}
if c.disabled {
result.Skipped = true
result.Reason = SkipDisabled
return result, nil
}
if environmentDisabled() {
result.Skipped = true
result.Reason = SkipEnvironment
return result, nil
}
if c.endpoint == "" {
result.Skipped = true
result.Reason = SkipEndpoint
return result, nil
}
release, err := c.enterOperation(ctx, 0)
if err != nil {
if ignoreLockBusy(err) {
result.Skipped = true
result.Reason = SkipBusy
return result, nil
}
return result, err
}
defer release()
flushContext, cancel := context.WithTimeout(ctx, c.limits.FlushTimeout)
defer cancel()
now := c.now()
state, _, err := c.loadState(now)
if err != nil {
return result, err
}
enabled, _, reason := c.effective(state)
if !enabled {
result.Skipped = true
result.Reason = reason
return result, nil
}
removed := c.pruneQueue(state, now)
if len(state.Queue) == 0 {
if len(removed) > 0 {
if err := c.saveState(state, now); err != nil {
return result, err
}
c.deleteQueuePayloads(removed)
}
result.Skipped = true
result.Reason = SkipEmpty
return result, nil
}
if !state.CooldownUntil.IsZero() && now.Before(state.CooldownUntil) {
if err := c.saveState(state, now); err != nil {
return result, err
}
c.deleteQueuePayloads(removed)
result.Skipped = true
result.Reason = SkipCooldown
result.Detail = "retry after " + state.CooldownUntil.UTC().Format(time.RFC3339)
result.Remaining = len(state.Queue)
return result, nil
}
if ctx.Err() != nil {
return result, nil
}
if err := c.checkHealth(flushContext); err != nil {
if errors.Is(flushContext.Err(), context.Canceled) {
return result, nil
}
state.deferRetry(now, c.limits.Cooldown, "health check: "+sanitizeErrorText(err))
if saveErr := c.saveState(state, now); saveErr != nil {
return result, saveErr
}
c.deleteQueuePayloads(removed)
c.pruneQueueOrphans(state)
result.Skipped = true
result.Reason = SkipCooldown
result.Detail = state.LastError
result.Remaining = len(state.Queue)
return result, nil
}
state.CooldownUntil = time.Time{}
skipped := make(map[string]struct{})
for range c.limits.MaxBatches {
if flushContext.Err() != nil {
break
}
batch, missing := c.prepareBatch(state, skipped)
if len(missing) > 0 {
c.dropEntries(state, missing)
}
if len(batch.records) == 0 {
if err := c.saveState(state, now); err != nil {
return result, err
}
break
}
upload, uploadErr := c.uploadRecords(flushContext, batch.body, state)
result.Attempted += len(batch.records)
if uploadErr != nil {
if failure, isHTTP := errors.AsType[*httpError](uploadErr); isHTTP && failure.batchInvalid {
rejectedEntries := c.applyRejectedBatch(state, batch.records)
result.Rejected += len(rejectedEntries)
result.RejectedIDs = append(result.RejectedIDs, entryIDs(rejectedEntries)...)
state.LastError = sanitizeErrorText(uploadErr)
if err := c.saveState(state, now); err != nil {
return result, err
}
c.deleteQueuePayloads(rejectedEntries)
continue
}
message := sanitizeErrorText(uploadErr)
if errors.Is(flushContext.Err(), context.Canceled) {
state.LastError = message
} else {
state.deferRetry(now, c.limits.Cooldown, message)
}
if err := c.saveState(state, now); err != nil {
return result, err
}
result.Remaining = len(state.Queue)
result.Detail = state.LastError
return result, nil
}
acceptedEntries, rejectedEntries := c.applyUploadResult(state, batch.records, upload, skipped, now)
result.Accepted += len(acceptedEntries)
result.Rejected += len(rejectedEntries)
result.AcceptedIDs = append(result.AcceptedIDs, entryIDs(acceptedEntries)...)
result.RejectedIDs = append(result.RejectedIDs, entryIDs(rejectedEntries)...)
state.LastError = ""
if err := c.saveState(state, now); err != nil {
return result, err
}
c.deleteQueuePayloads(acceptedEntries)
c.deleteQueuePayloads(rejectedEntries)
classified := len(acceptedEntries) + len(rejectedEntries)
if classified == 0 {
result.Detail = "server did not acknowledge any record in the batch"
break
}
if classified < len(batch.records) {
result.Detail = fmt.Sprintf("server classified %d of %d records in the batch", classified, len(batch.records))
break
}
}
if err := c.saveState(state, now); err != nil {
return result, err
}
result.Remaining = len(state.Queue)
if result.Attempted == 0 && len(state.Queue) == 0 {
result.Skipped = true
result.Reason = SkipEmpty
}
c.pruneQueueOrphans(state)
return result, nil
}
// prepareBatch loads the oldest records that fit both server bounds. Records
// whose outbox files are missing or corrupt are returned for local dropping so
// they cannot block healthy records.
func (c *Client) prepareBatch(state *persistedState, skipped map[string]struct{}) (preparedBatch, []queueEntry) {
batch := preparedBatch{
records: make([]preparedRecord, 0, min(len(state.Queue), c.limits.MaxRecordsPerRequest)),
}
missing := make([]queueEntry, 0)
estimated := len(`{"records":[]}`)
for _, entry := range state.Queue {
if _, skip := skipped[entry.ID]; skip {
continue
}
if len(batch.records) >= c.limits.MaxRecordsPerRequest {
break
}
record, err := c.readQueueRecord(entry.ID)
if err != nil {
c.debug("telemetry: dropping unreadable outbox record", "id", entry.ID, "error", err)
missing = append(missing, entry)
continue
}
encoded, err := marshalCanonical(wireRecord{ID: entry.ID, Type: entry.Type, Payload: record.Payload})
if err != nil || len(encoded) > c.limits.MaxRecordBytes {
missing = append(missing, entry)
continue
}
additional := len(encoded)
if len(batch.records) > 0 {
additional++
}
if len(batch.records) > 0 && estimated+additional > c.limits.MaxRequestBytes {
break
}
estimated += additional
batch.records = append(batch.records, preparedRecord{
entry: entry,
payloadBytes: int64(len(record.Payload)),
encoded: encoded,
})
}
batch.body = make([]byte, 0, estimated)
batch.body = append(batch.body, `{"records":[`...)
for index := range batch.records {
if index > 0 {
batch.body = append(batch.body, ',')
}
batch.body = append(batch.body, batch.records[index].encoded...)
batch.records[index].encoded = nil
}
batch.body = append(batch.body, `]}`...)
return batch, missing
}
func (c *Client) dropEntries(state *persistedState, entries []queueEntry) {
if len(entries) == 0 {
return
}
drop := make(map[string]struct{}, len(entries))
for _, entry := range entries {
drop[entry.ID] = struct{}{}
}
c.removeQueueIDs(state, drop)
state.countDropped(entries)
}
func (c *Client) applyUploadResult(state *persistedState, prepared []preparedRecord, upload uploadResult, skipped map[string]struct{}, now time.Time) ([]queueEntry, []queueEntry) {
acceptedIDs := make(map[string]struct{}, len(upload.accepted))
for _, id := range upload.accepted {
acceptedIDs[id] = struct{}{}
}
rejectedIDs := make(map[string]struct{}, len(upload.rejected))
for _, rejection := range upload.rejected {
rejectedIDs[rejection.ID] = struct{}{}
}
accepted := make([]queueEntry, 0)
rejected := make([]queueEntry, 0)
remove := make(map[string]struct{})
for _, item := range prepared {
if _, ok := acceptedIDs[item.entry.ID]; ok {
delete(rejectedIDs, item.entry.ID)
if _, duplicate := remove[item.entry.ID]; duplicate {
continue
}
remove[item.entry.ID] = struct{}{}
accepted = append(accepted, item.entry)
if !state.rememberAccepted(item.entry.ID) {
continue
}
switch item.entry.Type {
case recordTypeEvent:
state.Accepted.Events++
state.Accepted.EventPayloadBytes += item.payloadBytes
case recordTypeReport:
state.Accepted.Reports++
state.Accepted.ReportBodyBytes += item.entry.BodyBytes
}
continue
}
if _, ok := rejectedIDs[item.entry.ID]; ok {
remove[item.entry.ID] = struct{}{}
rejected = append(rejected, item.entry)
state.countRejected(item.payloadBytes)
continue
}
skipped[item.entry.ID] = struct{}{}
}
c.removeQueueIDs(state, remove)
state.LastUploadAt = now.UTC()
return accepted, rejected
}
func (c *Client) applyRejectedBatch(state *persistedState, prepared []preparedRecord) []queueEntry {
remove := make(map[string]struct{}, len(prepared))
rejected := make([]queueEntry, 0, len(prepared))
for _, item := range prepared {
remove[item.entry.ID] = struct{}{}
rejected = append(rejected, item.entry)
state.countRejected(item.payloadBytes)
}
c.removeQueueIDs(state, remove)
return rejected
}
func (c *Client) removeQueueIDs(state *persistedState, remove map[string]struct{}) {
if len(remove) == 0 {
return
}
kept := state.Queue[:0]
var queueBytes int64
for _, entry := range state.Queue {
if _, drop := remove[entry.ID]; drop {
continue
}
kept = append(kept, entry)
queueBytes += entry.PayloadBytes
}
state.Queue = kept
state.QueueBytes = queueBytes
}
func entryIDs(entries []queueEntry) []string {
ids := make([]string, 0, len(entries))
for _, entry := range entries {
ids = append(ids, entry.ID)
}
return ids
}
package telemetry
import (
"fmt"
"strings"
"uuid"
)
// NewUUID returns a random RFC 9562 version 4 UUID from the standard library.
func NewUUID() string {
return uuid.NewV4().String()
}
func normalizeUUID(raw string) (string, error) {
parsed, err := uuid.Parse(strings.TrimSpace(raw))
if err != nil {
return "", fmt.Errorf("parse uuid: %w", err)
}
return parsed.String(), nil
}
package telemetry
import (
"bytes"
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"fmt"
"io"
"math"
"net/http"
"strings"
"time"
)
const (
maxResponseBytes = 1 << 20
intakeLimitedReason = "intake_limited"
)
type wireRecord struct {
ID string `json:"id"`
Type recordType `json:"type"`
Payload jsontext.Value `json:"payload"`
}
type wireRejection struct {
ID string `json:"id"`
Reason string `json:"reason"`
}
type wireResponse struct {
Accepted *[]string `json:"accepted"`
Rejected []wireRejection `json:"rejected"`
}
type attemptKind int
const (
attemptSucceeded attemptKind = iota + 1
attemptRejected
attemptUncertain
)
type attemptOutcome struct {
kind attemptKind
attempted bool
accepted []string
rejected []wireRejection
requestBytes int64
}
type httpError struct {
status int
detail string
retryable bool
batchInvalid bool
throttled bool
}
func (failure *httpError) Error() string {
if failure.status > 0 {
return fmt.Sprintf("telemetry: server returned %d: %s", failure.status, failure.detail)
}
return "telemetry: request failed: " + failure.detail
}
type uploadResult struct {
accepted []string
rejected []wireRejection
batchInvalid bool
}
func (c *Client) checkHealth(ctx context.Context) error {
requestContext, cancel := context.WithTimeout(ctx, c.limits.HealthTimeout)
defer cancel()
request, err := http.NewRequestWithContext(requestContext, http.MethodGet, c.endpoint+"/health", nil)
if err != nil {
return err
}
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.userAgent())
response, err := c.http.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return fmt.Errorf("telemetry: health check returned %s", response.Status)
}
return nil
}
func (c *Client) uploadRecords(ctx context.Context, body []byte, state *persistedState) (uploadResult, error) {
var lastErr error
for attempt := 1; attempt <= c.limits.MaxAttempts; attempt++ {
outcome, err := c.postOnce(ctx, body)
if outcome.attempted {
c.recordAttempt(state, outcome)
}
if failure, isHTTP := errors.AsType[*httpError](err); isHTTP && failure.throttled {
recordThrottledAttempt(state)
}
if err == nil {
return uploadResult{
accepted: outcome.accepted,
rejected: outcome.rejected,
}, nil
}
lastErr = err
failure, isHTTP := errors.AsType[*httpError](err)
retryable := isHTTP && failure.retryable
if !retryable || attempt == c.limits.MaxAttempts || ctx.Err() != nil {
if isHTTP {
return uploadResult{batchInvalid: failure.batchInvalid}, err
}
return uploadResult{}, err
}
delay := c.limits.RetryBackoff
for step := 1; step < attempt; step++ {
delay = min(delay*2, 2*time.Second)
}
if err := sleepContext(ctx, delay); err != nil {
return uploadResult{}, err
}
}
return uploadResult{}, lastErr
}
// recordThrottledAttempt counts one retryable delivery attempt the server
// identified as intake-limited, by HTTP 429 or an intake_limited rejection.
func recordThrottledAttempt(state *persistedState) {
if state.Transport.Throttles < math.MaxInt64 {
state.Transport.Throttles++
}
}
func (c *Client) recordAttempt(state *persistedState, outcome attemptOutcome) {
state.Transport.Requests++
state.Transport.RequestBodyBytes += outcome.requestBytes
state.Transport.LastRequestBodyBytes = outcome.requestBytes
switch outcome.kind {
case attemptSucceeded:
state.Transport.Succeeded++
case attemptRejected:
state.Transport.RejectedRequests++
case attemptUncertain:
state.Transport.Uncertain++
}
}
func (c *Client) postOnce(ctx context.Context, body []byte) (attemptOutcome, error) {
if len(body) > c.limits.MaxRequestBytes {
return attemptOutcome{}, fmt.Errorf("telemetry: request body is %d bytes, limit %d", len(body), c.limits.MaxRequestBytes)
}
requestContext, cancel := context.WithTimeout(ctx, c.limits.RequestTimeout)
defer cancel()
request, err := http.NewRequestWithContext(requestContext, http.MethodPost, c.endpoint+"/v1/records", bytes.NewReader(body))
if err != nil {
return attemptOutcome{}, err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.userAgent())
outcome := attemptOutcome{attempted: true, requestBytes: int64(len(body))}
response, err := c.http.Do(request)
if err != nil {
return attemptOutcome{kind: attemptUncertain, attempted: true, requestBytes: int64(len(body))}, &httpError{
detail: sanitizeErrorText(err),
retryable: true,
}
}
defer response.Body.Close()
responseBody, readErr := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
if readErr != nil {
outcome.kind = attemptUncertain
failure := &httpError{detail: "read response: " + sanitizeErrorText(readErr), retryable: true}
if response.StatusCode == http.StatusTooManyRequests {
failure.throttled = true
}
return outcome, failure
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
detail, _ := sanitizeText(string(responseBody), 256)
detail = strings.Join(strings.Fields(detail), " ")
if detail == "" {
detail = response.Status
}
failure := &httpError{
status: response.StatusCode,
detail: detail,
retryable: retryableStatus(response.StatusCode),
batchInvalid: response.StatusCode == http.StatusBadRequest,
}
if failure.retryable {
failure.throttled = response.StatusCode == http.StatusTooManyRequests
noteIntakeLimited(failure, responseBody)
}
outcome.kind = attemptRejected
return outcome, failure
}
if len(responseBody) > maxResponseBytes {
outcome.kind = attemptUncertain
return outcome, &httpError{detail: "response exceeds size limit", retryable: true}
}
var decoded wireResponse
if err := json.Unmarshal(responseBody, &decoded); err != nil {
outcome.kind = attemptUncertain
return outcome, &httpError{detail: "invalid response: " + sanitizeErrorText(err), retryable: true}
}
if decoded.Accepted == nil {
outcome.kind = attemptUncertain
return outcome, &httpError{detail: "response omitted accepted ids", retryable: true}
}
accepted := make([]string, 0, len(*decoded.Accepted))
for _, raw := range *decoded.Accepted {
id, err := normalizeUUID(raw)
if err != nil {
outcome.kind = attemptUncertain
return outcome, &httpError{detail: "response contained an invalid accepted id", retryable: true}
}
accepted = append(accepted, id)
}
rejected := make([]wireRejection, 0, len(decoded.Rejected))
for _, raw := range decoded.Rejected {
id, err := normalizeUUID(raw.ID)
if err != nil {
outcome.kind = attemptUncertain
return outcome, &httpError{detail: "response contained an invalid rejected id", retryable: true}
}
reason, _ := sanitizeText(raw.Reason, 128)
rejected = append(rejected, wireRejection{ID: id, Reason: strings.Join(strings.Fields(reason), " ")})
}
outcome.kind = attemptSucceeded
outcome.accepted = accepted
outcome.rejected = rejected
return outcome, nil
}
// noteIntakeLimited recognizes only the known intake_limited rejection reason
// on a retryable response. It leaves rejection status and the queue unchanged.
func noteIntakeLimited(failure *httpError, body []byte) {
var decoded wireResponse
if err := json.Unmarshal(body, &decoded); err != nil {
return
}
for _, rejection := range decoded.Rejected {
if strings.TrimSpace(rejection.Reason) == intakeLimitedReason {
failure.throttled = true
return
}
}
}
func retryableStatus(status int) bool {
switch status {
case http.StatusRequestTimeout, http.StatusTooEarly, http.StatusTooManyRequests:
return true
}
return status >= 500
}
func (c *Client) userAgent() string {
if c.version == "" {
return "lucy-telemetry"
}
return "lucy-telemetry/" + c.version
}
func sleepContext(ctx context.Context, delay time.Duration) error {
if delay <= 0 {
return nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
package toolchain
import (
"cmp"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
javapkg "github.com/mclucy/lucy/java"
)
const probeTimeout = 20 * time.Second
type JavaInstallation struct {
Home string
Java string
Javac string
Version string
Major int
Vendor string
Arch string
Distribution javapkg.Distribution
Implementor string
}
type GradleInstallation struct {
Path string
Version string
}
type Inventory struct {
Java []JavaInstallation
Gradle *GradleInstallation
JavaHome string
PathJava string
GradleUserHome string
Problems []error
}
// DiscoverJava probes installed Java runtimes without provisioning tools and
// without running their compilers. Missing tools and unusable candidates are
// inventory results; additional homes are local JDK hints. A command may
// discover several times, so results are memoized for this process.
func DiscoverJava(ctx context.Context, homes ...string) (Inventory, error) {
if err := ctx.Err(); err != nil {
return Inventory{}, err
}
environment, err := readEnv()
if err != nil {
return Inventory{}, err
}
key := discoveryKey(environment, homes)
javaDiscovery.Lock()
defer javaDiscovery.Unlock()
if inventory, ok := javaDiscovery.inventories[key]; ok {
return cloneInventory(inventory), nil
}
inventory, err := discover(ctx, environment, homes, false)
if err != nil {
return Inventory{}, err
}
if javaDiscovery.inventories == nil {
javaDiscovery.inventories = make(map[string]Inventory)
}
javaDiscovery.inventories[key] = inventory
return cloneInventory(inventory), nil
}
// DiscoverBuildTools probes installed Java runtimes, their compilers, and
// Gradle. Build commands use it; runtime selection uses DiscoverJava.
func DiscoverBuildTools(ctx context.Context, homes ...string) (Inventory, error) {
if err := ctx.Err(); err != nil {
return Inventory{}, err
}
environment, err := readEnv()
if err != nil {
return Inventory{}, err
}
return discover(ctx, environment, homes, true)
}
// javaDiscovery memoizes the Java discovery of one process. Its key carries
// every input that changes the candidate list.
var javaDiscovery struct {
sync.Mutex
inventories map[string]Inventory
}
// discoveryKey joins the environment values, roots, and hints that decide
// which Java candidates discovery considers, so a change reselects instead of
// reusing.
func discoveryKey(environment envVars, homes []string) string {
fields := []string{
environment.javaHome,
environment.pathJava,
environment.gradleUserHome,
environment.home,
environment.path,
}
fields = append(fields, javaRoots(environment)...)
fields = append(fields, homes...)
return strings.Join(fields, "\x00")
}
func cloneInventory(inventory Inventory) Inventory {
inventory.Java = slices.Clone(inventory.Java)
inventory.Problems = slices.Clone(inventory.Problems)
return inventory
}
func discover(ctx context.Context, environment envVars, homes []string, compilers bool) (Inventory, error) {
inventory := Inventory{
JavaHome: environment.javaHome, PathJava: environment.pathJava,
GradleUserHome: environment.gradleUserHome,
}
candidates := javaCandidates(environment, homes)
results := make([]JavaInstallation, len(candidates))
problems := make([]error, len(candidates))
cache := loadProbeCache()
defer cache.save()
concurrency := make(chan struct{}, 4)
var workers sync.WaitGroup
for i, candidate := range candidates {
workers.Go(func() {
select {
case concurrency <- struct{}{}:
defer func() { <-concurrency }()
case <-ctx.Done():
return
}
results[i], problems[i] = probeJava(ctx, candidate, compilers, cache)
})
}
workers.Wait()
if err := ctx.Err(); err != nil {
return Inventory{}, err
}
seen := make(map[string]bool, len(results))
for i, java := range results {
if problems[i] != nil {
inventory.Problems = append(inventory.Problems, problems[i])
continue
}
if java.Home != "" && !seen[java.Home] {
seen[java.Home] = true
inventory.Java = append(inventory.Java, java)
}
}
sort.Slice(inventory.Java, func(i, j int) bool {
a, b := &inventory.Java[i], &inventory.Java[j]
return cmp.Or(cmp.Compare(b.Major, a.Major), cmp.Compare(a.Home, b.Home)) < 0
})
if compilers {
var err error
inventory.Gradle, err = probeGradle(ctx)
if err != nil {
inventory.Problems = append(inventory.Problems, err)
}
}
if err := ctx.Err(); err != nil {
return Inventory{}, err
}
return inventory, nil
}
type envVars struct {
javaHome string
pathJava string
gradleUserHome string
home string
path string
}
func readEnv() (envVars, error) {
home, err := os.UserHomeDir()
if err != nil {
return envVars{}, fmt.Errorf("find user home: %w", err)
}
environment := envVars{
javaHome: os.Getenv("JAVA_HOME"), gradleUserHome: os.Getenv("GRADLE_USER_HOME"),
home: home, path: os.Getenv("PATH"),
}
if environment.gradleUserHome == "" {
environment.gradleUserHome = filepath.Join(home, ".gradle")
}
if java, err := exec.LookPath(javaExecutableName); err == nil {
environment.pathJava = java
}
return environment, nil
}
func canonical(path string) string {
resolved, err := filepath.EvalSymlinks(path)
if err == nil {
return filepath.Clean(resolved)
}
return filepath.Clean(path)
}
func probeEnv() []string {
environment := os.Environ()
return slices.DeleteFunc(environment, func(entry string) bool {
key, _, _ := strings.Cut(entry, "=")
switch strings.ToUpper(key) {
case "_JAVA_OPTIONS", "JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS":
return true
default:
return false
}
})
}
package toolchain
import (
"context"
"fmt"
"os/exec"
"strings"
)
func probeGradle(ctx context.Context) (*GradleInstallation, error) {
path, err := exec.LookPath("gradle")
if err != nil {
return nil, nil
}
if managerShim(path) {
return nil, fmt.Errorf("gradle on PATH is a version-manager shim; select an installed distribution")
}
output, err := runProbe(ctx, path, "--version")
if err != nil {
return nil, fmt.Errorf("probe Gradle %q: %w", path, err)
}
for line := range strings.SplitSeq(output, "\n") {
version, ok := strings.CutPrefix(strings.TrimSpace(line), "Gradle ")
if ok {
version, _, _ = strings.Cut(version, " ")
if version != "" {
return &GradleInstallation{
Path: canonical(path),
Version: version,
}, nil
}
}
}
return nil, fmt.Errorf("gradle %q reported no version", path)
}
//go:build linux
package toolchain
import (
"os"
"syscall"
)
// identityOf reads the stat identity of one inspected file.
func identityOf(info os.FileInfo) fileIdentity {
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return fileIdentity{Size: info.Size(), Modified: info.ModTime().UnixNano()}
}
return fileIdentity{
Device: uint64(stat.Dev),
Inode: stat.Ino,
Size: stat.Size,
Modified: stat.Mtim.Nano(),
Changed: stat.Ctim.Nano(),
}
}
package toolchain
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
type javaCandidate struct {
java string
source string
}
func javaCandidates(environment envVars, hints []string) []javaCandidate {
candidates := make([]javaCandidate, 0, len(hints)+2)
seen := make(map[string]bool)
add := func(executable, source string) {
if executable == "" || managerShim(executable) {
return
}
key := canonical(executable)
if !seen[key] {
seen[key] = true
candidates = append(candidates, javaCandidate{java: executable, source: source})
}
}
if environment.javaHome != "" {
add(filepath.Join(environment.javaHome, "bin", javaExecutableName), "JAVA_HOME")
}
add(environment.pathJava, "PATH")
for _, home := range hints {
if home != "" {
add(filepath.Join(home, "bin", javaExecutableName), "Gradle configuration")
}
}
for _, root := range javaRoots(environment) {
for _, home := range javaHomesUnder(root) {
add(filepath.Join(home, "bin", javaExecutableName), root)
}
}
return candidates
}
// javaRoots lists the directories that hold Java homes of the system and of
// version managers. Each child of a root holds one home, or a current link to
// one.
func javaRoots(environment envVars) []string {
roots := systemJavaRoots()
sdkman := os.Getenv("SDKMAN_DIR")
if sdkman == "" {
sdkman = filepath.Join(environment.home, ".sdkman")
}
mise := os.Getenv("MISE_DATA_DIR")
if mise == "" {
mise = filepath.Join(environment.home, ".local", "share", "mise")
}
asdf := os.Getenv("ASDF_DATA_DIR")
if asdf == "" {
asdf = filepath.Join(environment.home, ".asdf")
}
roots = append(roots,
filepath.Join(sdkman, "candidates", "java"),
filepath.Join(mise, "installs", "java"),
filepath.Join(asdf, "installs", "java"),
filepath.Join(environment.home, ".jabba", "jdk"),
filepath.Join(environment.gradleUserHome, "jdks"),
)
if managed, err := ManagedJavaRoot(); err == nil {
roots = append(roots, managed)
}
return roots
}
func javaHomesUnder(root string) []string {
homes := make([]string, 0)
add := func(dir string) bool {
for _, suffix := range []string{"", filepath.Join("Contents", "Home")} {
home := filepath.Join(dir, suffix)
if isExecutable(filepath.Join(home, "bin", javaExecutableName)) {
homes = append(homes, home)
return true
}
}
return false
}
if add(root) {
return homes
}
entries, err := os.ReadDir(root)
if err != nil {
return homes
}
for _, entry := range entries {
child := filepath.Join(root, entry.Name())
if add(child) {
continue
}
if add(filepath.Join(child, "current")) {
continue
}
if filepath.Base(root) != "jdks" {
continue
}
nested, err := os.ReadDir(child)
if err != nil {
continue
}
for _, entry := range nested {
add(filepath.Join(child, entry.Name()))
}
}
return homes
}
// probeJava probes one candidate. compilers adds the compiler probe that only
// a build needs. cache may be nil, which probes without caching.
func probeJava(ctx context.Context, candidate javaCandidate, compilers bool, cache *probeCache) (JavaInstallation, error) {
if !isExecutable(candidate.java) {
return JavaInstallation{}, fmt.Errorf("java candidate %q from %s is not executable", candidate.java, candidate.source)
}
installation, err := probeInstallation(ctx, candidate.java, cache)
if err != nil {
return JavaInstallation{}, err
}
if compilers {
installation.Javac = probeCompiler(ctx, installation.Home)
}
return installation, nil
}
// probeInstallation returns the installation that one Java executable
// reports, from the cache while the executable and the release file of its
// home keep their recorded identities.
func probeInstallation(ctx context.Context, executable string, cache *probeCache) (JavaInstallation, error) {
if installation, ok := cache.lookup(executable); ok {
return installation, nil
}
output, err := runProbe(ctx, executable, "-XshowSettings:properties", "-version")
if err != nil {
return JavaInstallation{}, fmt.Errorf("probe java %q: %w", executable, err)
}
properties := make(map[string]string)
for line := range strings.SplitSeq(output, "\n") {
key, value, ok := strings.Cut(strings.TrimSpace(line), " = ")
if ok {
properties[strings.TrimSpace(key)] = strings.TrimSpace(value)
}
}
if properties["java.home"] == "" {
return JavaInstallation{}, fmt.Errorf("java %q reported no installation home", executable)
}
home := canonical(properties["java.home"])
if filepath.Base(home) == "jre" {
parent := filepath.Dir(home)
if isExecutable(filepath.Join(parent, "bin", javacExecutableName)) {
home = parent
}
}
release := releaseProperties(home)
installation := JavaInstallation{
Home: home, Java: filepath.Join(home, "bin", javaExecutableName),
Version: properties["java.version"], Major: majorVersion(properties["java.version"]),
Vendor: properties["java.vendor"], Arch: properties["os.arch"],
Distribution: distributionFromRelease(release),
Implementor: release["IMPLEMENTOR"],
}
if installation.Major == 0 || !isExecutable(installation.Java) {
return JavaInstallation{}, fmt.Errorf("java %q reported an unusable installation", executable)
}
cache.store(executable, installation)
return installation, nil
}
// probeCompiler returns the javac of a Java home that runs, or "" when the
// home has no usable compiler.
func probeCompiler(ctx context.Context, home string) string {
javac := filepath.Join(home, "bin", javacExecutableName)
if !isExecutable(javac) {
return ""
}
if _, err := runProbe(ctx, javac, "-version"); err != nil {
return ""
}
return javac
}
// ProbeJava inspects the Java installation at path. path is a Java home or a
// java executable, and symlinks are allowed. An invalid path yields an error
// that names the defect.
func ProbeJava(ctx context.Context, path string) (JavaInstallation, error) {
if strings.TrimSpace(path) == "" {
return JavaInstallation{}, errors.New("probe Java: path is empty")
}
info, err := os.Stat(path)
if err != nil {
return JavaInstallation{}, fmt.Errorf("probe Java %q: %w", path, err)
}
executable := path
if info.IsDir() {
executable = filepath.Join(path, "bin", javaExecutableName)
if !isExecutable(executable) {
executable = filepath.Join(path, "Contents", "Home", "bin", javaExecutableName)
}
if !isExecutable(executable) {
return JavaInstallation{}, fmt.Errorf(
"probe Java home %q: no java executable under bin or Contents/Home/bin", path)
}
} else if !isExecutable(path) {
return JavaInstallation{}, fmt.Errorf("probe Java %q: not an executable file", path)
}
cache := loadProbeCache()
defer cache.save()
return probeJava(ctx, javaCandidate{java: executable, source: "requested path"}, false, cache)
}
func majorVersion(version string) int {
version = strings.TrimPrefix(version, "1.")
end := strings.IndexFunc(version, func(r rune) bool { return r < '0' || r > '9' })
if end >= 0 {
version = version[:end]
}
major, err := strconv.Atoi(version)
if err != nil {
return 0
}
return major
}
func runProbe(ctx context.Context, executable string, arguments ...string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, probeTimeout)
defer cancel()
cmd := probeCommand(ctx, executable, arguments...)
cmd.Env = probeEnv()
cmd.WaitDelay = time.Second
output, err := cmd.CombinedOutput()
if ctx.Err() != nil {
return "", ctx.Err()
}
return string(output), err
}
func isExecutable(path string) bool {
info, err := os.Stat(path)
if err != nil || !info.Mode().IsRegular() {
return false
}
if runtime.GOOS == "windows" {
switch strings.ToLower(filepath.Ext(path)) {
case ".exe", ".bat", ".cmd":
return true
default:
return false
}
}
return info.Mode().Perm()&0o111 != 0
}
func managerShim(path string) bool {
normalized := "/" + strings.ToLower(filepath.ToSlash(path)) + "/"
return strings.Contains(normalized, "/shims/")
}
package toolchain
import (
"context"
"os"
"os/exec"
"path/filepath"
)
const (
javaExecutableName = "java"
javacExecutableName = "javac"
)
func systemJavaRoots() []string {
roots := []string{"/usr/lib/jvm", "/usr/java", "/opt/java", "/home/linuxbrew/.linuxbrew/opt"}
if home, err := os.UserHomeDir(); err == nil {
roots = append(roots, filepath.Join(home, ".linuxbrew", "opt"))
}
return roots
}
func probeCommand(ctx context.Context, executable string, arguments ...string) *exec.Cmd {
return exec.CommandContext(ctx, executable, arguments...)
}
package toolchain
import (
"path/filepath"
"github.com/mclucy/lucy/internal/appdata"
)
// ManagedJavaRoot returns the per-user directory that holds the Java runtimes
// Lucy downloads. Each runtime is one child directory of the root.
func ManagedJavaRoot() (string, error) {
root, err := appdata.Root()
if err != nil {
return "", err
}
return filepath.Join(root, "java"), nil
}
package toolchain
import (
"encoding/json/v2"
"errors"
"os"
"path/filepath"
"sync"
"github.com/mclucy/lucy/internal/fsutil"
)
// probeCacheVersion is the layout version of the probe cache file. A file of
// another version is ignored.
const probeCacheVersion = 1
// probeCacheFilename names the probe cache inside the toolchain directory of
// Lucy's per-user cache.
const probeCacheFilename = "java-probes.json"
// probeCacheFile is the persisted form of the probe cache.
type probeCacheFile struct {
Version int `json:"version"`
Entries map[string]probeEntry `json:"entries"`
}
// probeEntry records one Java probe result. The map key is the resolved Java
// executable. JavaHome is the JAVA_HOME of the probing process: changing it
// makes a stub executable start another runtime, so it keys the entry too.
type probeEntry struct {
JavaHome string `json:"java_home"`
Executable fileIdentity `json:"executable"`
Release *fileIdentity `json:"release,omitempty"`
Installation JavaInstallation `json:"installation"`
}
// probeCache is the in-memory view of the probe cache file. Its methods are
// safe for concurrent use, and a nil cache stores nothing. Every cache
// failure costs a probe, never a result.
type probeCache struct {
mutex sync.Mutex
path string
entries map[string]probeEntry
dirty bool
}
// loadProbeCache reads the cache of this user. A missing, unreadable, or
// corrupt file yields an empty cache that the next save rewrites.
func loadProbeCache() *probeCache {
cache := &probeCache{
path: probeCachePath(),
entries: make(map[string]probeEntry),
}
if cache.path == "" {
return cache
}
data, err := os.ReadFile(cache.path)
if err != nil {
cache.dirty = !errors.Is(err, os.ErrNotExist)
return cache
}
var file probeCacheFile
if err := json.Unmarshal(data, &file); err != nil || file.Version != probeCacheVersion {
cache.dirty = true
return cache
}
for key, entry := range file.Entries {
cache.entries[key] = entry
}
return cache
}
// lookup returns the recorded installation of executable while the executable,
// the release file of its home, and JAVA_HOME keep the recorded values.
func (c *probeCache) lookup(executable string) (JavaInstallation, bool) {
if c == nil {
return JavaInstallation{}, false
}
key := canonical(executable)
c.mutex.Lock()
entry, ok := c.entries[key]
c.mutex.Unlock()
if !ok || entry.JavaHome != os.Getenv("JAVA_HOME") {
return JavaInstallation{}, false
}
identity, ok := identify(key)
if !ok || identity != entry.Executable {
return JavaInstallation{}, false
}
if !releaseMatches(entry.Installation.Home, entry.Release) {
return JavaInstallation{}, false
}
return entry.Installation, true
}
// store records a probe result without writing the file. The installation must
// carry no compiler: a compiler belongs to the build discovery that probed it.
func (c *probeCache) store(executable string, installation JavaInstallation) {
if c == nil {
return
}
key := canonical(executable)
identity, ok := identify(key)
if !ok {
return
}
entry := probeEntry{
JavaHome: os.Getenv("JAVA_HOME"),
Executable: identity,
Installation: installation,
}
if release, present := identify(filepath.Join(installation.Home, "release")); present {
entry.Release = &release
}
c.mutex.Lock()
c.entries[key] = entry
c.dirty = true
c.mutex.Unlock()
}
// save writes the cache atomically and drops entries whose executables are
// gone. It reports nothing: an unwritable cache only costs later probes.
func (c *probeCache) save() {
if c == nil {
return
}
c.mutex.Lock()
defer c.mutex.Unlock()
if !c.dirty || c.path == "" {
return
}
entries := make(map[string]probeEntry, len(c.entries))
for key, entry := range c.entries {
if _, err := os.Stat(key); err != nil {
continue
}
entries[key] = entry
}
data, err := json.Marshal(probeCacheFile{Version: probeCacheVersion, Entries: entries})
if err != nil {
return
}
if err := fsutil.AtomicWrite(c.path, data, 0o600); err != nil {
return
}
c.entries = entries
c.dirty = false
}
// releaseMatches reports whether the release file of home still has the
// recorded identity. A home without a release file matches only a recorded
// absence.
func releaseMatches(home string, recorded *fileIdentity) bool {
identity, present := identify(filepath.Join(home, "release"))
return present == (recorded != nil) && (!present || identity == *recorded)
}
// probeCachePath reports the probe cache file beneath Lucy's per-user cache
// directory, in the layout of the network cache. It reports "" when the
// platform names no cache directory.
func probeCachePath() string {
dir, err := os.UserCacheDir()
if err != nil {
return ""
}
return filepath.Join(dir, "lucy", "toolchain", probeCacheFilename)
}
// fileIdentity is the stat identity of a file. A rewrite, replacement, or
// touch changes at least one field, so equal identities describe the same
// generation of the file. Platforms without device or inode numbers leave
// those fields zero and rely on the remaining fields.
type fileIdentity struct {
Device uint64 `json:"device"`
Inode uint64 `json:"inode"`
Size int64 `json:"size"`
Modified int64 `json:"modified_ns"`
Changed int64 `json:"changed_ns"`
}
// identify reports the stat identity of path, and false when path cannot be
// inspected.
func identify(path string) (fileIdentity, bool) {
info, err := os.Stat(path)
if err != nil {
return fileIdentity{}, false
}
return identityOf(info), true
}
package toolchain
import (
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/java"
)
// releaseProperties reads the release file of a Java home. A missing or
// unreadable file yields an empty map. Lines are KEY="value"; quotes and
// surrounding blanks are optional, and CRLF is accepted.
func releaseProperties(home string) map[string]string {
properties := make(map[string]string)
data, err := os.ReadFile(filepath.Join(home, "release"))
if err != nil {
return properties
}
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
if key == "" {
continue
}
value = strings.TrimSpace(value)
value = strings.Trim(value, `"`)
properties[key] = value
}
return properties
}
// distributionFromRelease maps the IMPLEMENTOR value to a distribution. A
// vendor Lucy does not know is an unbranded build for the purpose of matching
// a requirement. Oracle builds need extra keys to tell their three products
// apart.
func distributionFromRelease(properties map[string]string) java.Distribution {
implementor := properties["IMPLEMENTOR"]
if distribution, ok := implementorDistributions[implementor]; ok {
return distribution
}
if implementor != "Oracle Corporation" {
return java.DistributionAny
}
switch {
case properties["GRAALVM_VERSION"] != "":
return java.DistributionGraalVM
case properties["BUILD_TYPE"] == "commercial":
return java.DistributionOracle
default:
return java.DistributionOracleOpenJDK
}
}
// implementorDistributions lists the IMPLEMENTOR values of the vendors Lucy
// installs. Downloadable Oracle GraalVM reports Oracle Corporation and needs
// the GRAALVM_VERSION key, so it is not listed here.
var implementorDistributions = map[string]java.Distribution{
"Eclipse Adoptium": java.DistributionTemurin,
"Azul Systems, Inc.": java.DistributionZulu,
"Amazon.com Inc.": java.DistributionCorretto,
"BellSoft": java.DistributionLiberica,
"Microsoft": java.DistributionMicrosoft,
"GraalVM Community": java.DistributionGraalVMCommunity,
"IBM Corporation": java.DistributionSemeru,
"SAP SE": java.DistributionSapMachine,
"Alibaba": java.DistributionDragonwell,
"Tencent": java.DistributionKona,
"Red Hat, Inc.": java.DistributionRedHat,
"JetBrains s.r.o.": java.DistributionJetBrains,
}
// Package workspaceguard enforces runtime inactivity before recovery or
// mutation rewrites workspace state.
package workspaceguard
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/workspace"
"go.yaml.in/yaml/v4"
)
// CheckInactive includes both declared runtime locations before replay can
// replace state. Callers name the operation that needs the pause so the error
// tells the user which command the server must stop for.
func CheckInactive(root string, during string) error {
directories := map[string]bool{root: true}
for _, name := range []string{document.ManifestFilename, document.LockFilename} {
if err := workspacewrite.SafePath(root, name); err != nil {
return err
}
data, err := os.ReadFile(filepath.Join(root, name))
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
var state struct {
Server struct {
Directory string `yaml:"directory"`
} `yaml:"server"`
}
if err := yaml.Unmarshal(data, &state); err != nil {
return err
}
if state.Server.Directory != "" {
directory := filepath.FromSlash(state.Server.Directory)
if err := workspacewrite.SafePath(root, directory); err != nil {
return err
}
directories[filepath.Join(root, directory)] = true
}
}
for directory := range directories {
if workspace.RunningAt(directory) {
return fmt.Errorf("stop the running Minecraft server before %s", during)
}
}
return nil
}
package workspaceguard
import (
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
)
// RecoverInstall must run with workspace ownership before reading state for a
// new mutation. It is the only entry point that replays an interrupted
// installation. Journal detection stays read-only, so a workspace without a
// pending journal needs no runtime check; replay itself performs the mandatory
// inactivity check before any mutation.
func RecoverInstall(root string, logger *log.Logger) error {
journal, err := workspacewrite.ReadInstallJournal(root)
if err != nil {
return err
}
if journal == nil {
return nil
}
return workspacewrite.ReplayInstallJournal(root, journal, logger, CheckInactive)
}
// Package workspacewrite coordinates recoverable filesystem writes without runtime ownership policy.
package workspacewrite
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/mclucy/lucy/internal/fileidentity"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/log"
"go.yaml.in/yaml/v4"
)
const (
InstallJournalName = ".lucy/commit.yaml"
// LockFileName names the writer lock inside the workspace state directory.
LockFileName = "writer.lock"
// DisplacedRoot holds one directory per committed installation that
// replaced files it did not own or that were edited after it owned them.
// Lucy never deletes this content; the user does.
DisplacedRoot = ".lucy/displaced"
// DisplacedIndexName names the index inside each installation directory
// under DisplacedRoot.
DisplacedIndexName = "index.yaml"
// DisplacedFilesName names the directory that holds the displaced files
// inside each installation directory. It keeps payload paths apart from
// DisplacedIndexName.
DisplacedFilesName = "files"
)
// InstallImage describes one content state of a path. A nil image means the
// path is absent.
type InstallImage struct {
SHA256 string `yaml:"sha256"`
Mode uint32 `yaml:"mode"`
}
// InstallJournalEntry records the before and after content and permission
// state of one path that a commit may touch. A nil Before marks a path the
// commit creates; a nil After marks a path the commit prunes. Content hashes
// and modes identify whether recovery may reverse the transition; Mode also
// supplies the permissions to restore. Displace keeps the Before content under
// DisplacedRoot once the commit point passes; it requires a Before image.
type InstallJournalEntry struct {
Path string `yaml:"path"`
Before *InstallImage `yaml:"before,omitempty"`
After *InstallImage `yaml:"after,omitempty"`
Displace bool `yaml:"displace,omitempty"`
}
// DisplacedFile records one file kept under DisplacedRoot. Path is the
// workspace path the file occupied and also its path below DisplacedFilesName
// in the installation directory.
type DisplacedFile struct {
Path string `yaml:"path"`
SHA256 string `yaml:"sha256"`
Mode uint32 `yaml:"mode"`
}
// DisplacedIndex lists the files one installation displaced.
type DisplacedIndex struct {
Files []DisplacedFile `yaml:"files"`
}
// InstallJournal is the installation rollback record. Backup is relative to
// the workspace root, so moving the workspace keeps it valid. Committed marks
// the commit point. Recovery preserves displaced files and removes the rollback
// data without changing installed files.
type InstallJournal struct {
Backup string `yaml:"backup"`
Committed bool `yaml:"committed,omitempty"`
Entries []InstallJournalEntry `yaml:"entries"`
}
// RecoveryCleanupError reports a cleanup failure after the commit point.
// Installed files and documents stay in place.
type RecoveryCleanupError struct{ Err error }
func (e *RecoveryCleanupError) Error() string { return e.Err.Error() }
func (e *RecoveryCleanupError) Unwrap() error { return e.Err }
// Lock is shared by installation and explicit file operations. It reclaims
// staging that a killed publisher abandoned, which is safe only under the
// writer lock it takes, because that lock proves no publisher is live.
func Lock(root string, logger *log.Logger) (*fsutil.FileLock, error) {
if err := SafePath(root, ".lucy"); err != nil {
return nil, err
}
if err := fsutil.MkdirAllPrivate(filepath.Join(root, ".lucy")); err != nil {
return nil, err
}
if err := SafePath(root, ".lucy/"+LockFileName); err != nil {
return nil, err
}
start := logger.WaitStart()
lock, err := fsutil.TryLockFile(filepath.Join(root, ".lucy", LockFileName))
logger.WaitDone(log.WaitFileLock, start)
if err != nil {
if errors.Is(err, fsutil.ErrLocked) {
return nil, fmt.Errorf("another Lucy operation owns this workspace: %w", err)
}
return nil, err
}
files, err := os.OpenRoot(root)
if err != nil {
return nil, errors.Join(err, lock.Close())
}
removed, sweepErr := fsutil.SweepStaging(files)
closeErr := files.Close()
if sweepErr != nil {
logger.Warn(fmt.Errorf("reclaim stale staging files: %w", sweepErr))
}
for _, name := range removed {
logger.Debug("removed stale staging file", "path", name)
}
if closeErr != nil {
return nil, errors.Join(closeErr, lock.Close())
}
return lock.FlushOnClose(), nil
}
// SafePath rejects existing symlink components before root-confined IO.
func SafePath(root, relative string) error {
if !filepath.IsLocal(relative) {
return fmt.Errorf("output path must stay inside the workspace")
}
current := root
for component := range strings.SplitSeq(filepath.Clean(relative), string(filepath.Separator)) {
current = filepath.Join(current, component)
info, err := os.Lstat(current)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("output path traverses symlink: %s", relative)
}
}
return nil
}
// RemoveRoot persists disappearance from its original name. A leftover stays
// in the private .lucy/tmp directory.
func RemoveRoot(root *os.Root, relative string) error {
if !filepath.IsLocal(relative) {
return fmt.Errorf("output path must stay inside the workspace")
}
if _, err := root.Lstat(relative); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return err
}
if err := root.MkdirAll(".lucy/tmp", 0o700); err != nil {
return err
}
garbage := ".lucy/tmp/removed-" + rand.Text()
if err := fsutil.RenameRoot(root, relative, garbage); err != nil {
return err
}
return root.Remove(garbage)
}
// InactivityCheck reports an error when a server still runs at a workspace
// location. Recovery supplies one to ReplayInstallJournal so replay cannot
// mutate state without proving inactivity first.
type InactivityCheck func(root, during string) error
// ReplayInstallJournal rewrites the state recorded by a previously detected
// installation journal. The caller must hold the workspace writer lock, and
// guard is mandatory: replay fails closed on a nil guard and checks inactivity
// after journal existence and before any mutation.
// workspaceguard.RecoverInstall is the supported entry point.
func ReplayInstallJournal(
root string,
journal *InstallJournal,
logger *log.Logger,
guard InactivityCheck,
) (resultErr error) {
if journal == nil {
return errors.New("installation recovery requires a journal")
}
if guard == nil {
return errors.New("installation recovery requires an inactivity guard")
}
if err := guard(root, "recovering an interrupted installation"); err != nil {
return err
}
files, err := os.OpenRoot(root)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
journalPath := filepath.Join(root, InstallJournalName)
if journal.Committed {
logger.Warn(
fmt.Errorf(
"completing cleanup of committed installation transaction %s",
journalPath,
),
)
if err := CleanupCommittedInstall(files, journal); err != nil {
return err
}
logger.Info(
"installation transaction cleanup completed",
"root", root,
"journal", journalPath,
)
return nil
}
backup, err := installJournalBackup(root, journal.Backup)
if err != nil {
return err
}
if err := validateInstallJournal(root, journal); err != nil {
return err
}
logger.Warn(
fmt.Errorf(
"recovering interrupted installation transaction %s: %d recorded paths",
journalPath, len(journal.Entries),
),
)
plan := make([]InstallJournalEntry, 0, len(journal.Entries))
refused := make([]string, 0)
for _, entry := range journal.Entries {
current, err := ObserveInstallImage(files, filepath.FromSlash(entry.Path))
if err != nil {
return err
}
switch classifyInstallEntry(current, entry.Before, entry.After) {
case installEntryUnapplied:
continue
case installEntryApplied:
if err := checkInstallPreImage(files, backup, entry); err != nil {
return err
}
plan = append(plan, entry)
default:
refused = append(refused, entry.Path)
}
}
if len(refused) > 0 {
return fmt.Errorf(
"installation recovery refused paths edited after the interruption in %s; keep the journal and resolve these edits: %s",
journalPath, strings.Join(refused, ", "),
)
}
for _, entry := range plan {
if err := restoreInstallEntry(files, backup, entry); err != nil {
return err
}
}
if err := files.RemoveAll(backup); err != nil {
return err
}
if err := RemoveRoot(files, InstallJournalName); err != nil {
return err
}
logger.Info(
"installation transaction recovered",
"root", root,
"journal", journalPath,
)
return nil
}
// InstallJournalCommitted reports whether a pending installation journal
// reached its commit point. It is a read-only query for a committing caller
// whose committed-marker publication reported an error after the atomic
// replacement may already have happened.
func InstallJournalCommitted(root string) (bool, error) {
journal, err := ReadInstallJournal(root)
if err != nil {
return false, err
}
return journal != nil && journal.Committed, nil
}
// ReadInstallJournal strictly decodes the pending installation journal. A nil
// journal with a nil error means the workspace has no interrupted installation.
// The caller must hold the workspace writer lock before using it as recovery
// input.
func ReadInstallJournal(root string) (*InstallJournal, error) {
if err := SafePath(root, InstallJournalName); err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(root, InstallJournalName))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var journal InstallJournal
decoder := yaml.NewDecoder(bytes.NewReader(raw))
decoder.KnownFields(true)
if err := decoder.Decode(&journal); err != nil {
return nil, fmt.Errorf("decode installation journal: %w", err)
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
if err == nil {
return nil, fmt.Errorf("installation journal must contain one YAML document")
}
return nil, fmt.Errorf("decode installation journal tail: %w", err)
}
return &journal, nil
}
// installJournalBackup returns the workspace-relative rollback directory.
// Journals never carry an absolute path or an alias outside .lucy.
func installJournalBackup(root, backup string) (string, error) {
relative := filepath.Clean(filepath.FromSlash(backup))
if !filepath.IsLocal(relative) ||
filepath.ToSlash(relative) != backup ||
filepath.Dir(relative) != ".lucy" ||
!strings.HasPrefix(filepath.Base(relative), "rollback-") {
return "", fmt.Errorf("invalid installation rollback directory")
}
if err := SafePath(root, relative); err != nil {
return "", err
}
return relative, nil
}
func validateInstallJournal(root string, journal *InstallJournal) error {
folded := map[string][]string{}
for _, entry := range journal.Entries {
if journal.Committed && !entry.Displace {
continue
}
if entry.Path == "" || entry.Path == "." || !filepath.IsLocal(filepath.FromSlash(entry.Path)) {
return fmt.Errorf("invalid installation journal path %q", entry.Path)
}
if filepath.ToSlash(filepath.Clean(filepath.FromSlash(entry.Path))) != entry.Path {
return fmt.Errorf("installation journal path %q is not canonical", entry.Path)
}
if entry.Path == InstallJournalName ||
(strings.EqualFold(entry.Path, InstallJournalName) &&
InstallPathsAlias(root, InstallJournalName, entry.Path)) {
return fmt.Errorf("installation journal cannot record itself")
}
key := strings.ToLower(entry.Path)
for _, prior := range folded[key] {
if InstallPathsAlias(root, prior, entry.Path) {
return fmt.Errorf(
"installation journal paths %q and %q alias the same filesystem entry",
prior, entry.Path,
)
}
}
folded[key] = append(folded[key], entry.Path)
if entry.Displace && entry.Before == nil {
return fmt.Errorf("installation journal path %q has no before image to displace", entry.Path)
}
if entry.Before == nil && entry.After == nil {
return fmt.Errorf(
"installation journal path %q has neither before nor after image",
entry.Path,
)
}
for _, image := range []*InstallImage{entry.Before, entry.After} {
if image == nil {
continue
}
if err := validateInstallImage(image); err != nil {
return fmt.Errorf(
"invalid installation journal image for %s: %w",
entry.Path, err,
)
}
}
if !journal.Committed {
if err := SafePath(root, filepath.FromSlash(entry.Path)); err != nil {
return err
}
}
}
return nil
}
func validateInstallImage(image *InstallImage) error {
if len(image.SHA256) != sha256.Size*2 {
return fmt.Errorf("sha256 must be %d hex characters", sha256.Size*2)
}
if _, err := hex.DecodeString(image.SHA256); err != nil {
return fmt.Errorf("sha256 is not hex: %w", err)
}
if image.Mode&^uint32(0o777) != 0 {
return fmt.Errorf("mode %#o has non-permission bits", image.Mode)
}
return nil
}
// CleanupCommittedInstall preserves displaced files before removing the
// rollback backup and its journal. The caller must hold the workspace writer
// lock and must have published the committed journal.
func CleanupCommittedInstall(files *os.Root, journal *InstallJournal) error {
if !journal.Committed {
return errors.New("installation cleanup requires a committed journal")
}
if err := cleanupCommittedInstall(files, journal); err != nil {
return &RecoveryCleanupError{Err: fmt.Errorf("installation committed; %w", err)}
}
return nil
}
func cleanupCommittedInstall(files *os.Root, journal *InstallJournal) error {
backup, err := installJournalBackup(files.Name(), journal.Backup)
if err != nil {
return err
}
if err := validateInstallJournal(files.Name(), journal); err != nil {
return err
}
if err := preserveDisplacedInstallFiles(files, backup, journal.Entries); err != nil {
return fmt.Errorf("preserve displaced files: %w", err)
}
if err := files.RemoveAll(backup); err != nil {
return fmt.Errorf("remove rollback backup %s: %w", backup, err)
}
if err := RemoveRoot(files, InstallJournalName); err != nil {
return fmt.Errorf("remove transaction journal: %w", err)
}
return nil
}
func preserveDisplacedInstallFiles(files *os.Root, backup string, entries []InstallJournalEntry) error {
index := DisplacedIndex{}
var directory string
for _, entry := range entries {
if !entry.Displace {
continue
}
if directory == "" {
id := strings.TrimPrefix(filepath.Base(backup), "rollback-")
if id == "." || !filepath.IsLocal(id) {
return fmt.Errorf("invalid displacement directory name %q", id)
}
directory = filepath.Join(DisplacedRoot, id)
}
target := filepath.Join(directory, DisplacedFilesName, filepath.FromSlash(entry.Path))
if err := preserveDisplacedInstallFile(files, backup, target, entry); err != nil {
return fmt.Errorf("displace %s: %w", entry.Path, err)
}
index.Files = append(index.Files, DisplacedFile{
Path: entry.Path,
SHA256: entry.Before.SHA256,
Mode: entry.Before.Mode,
})
}
if len(index.Files) == 0 {
return nil
}
raw, err := yaml.Marshal(index)
if err != nil {
return fmt.Errorf("encode displacement index: %w", err)
}
target := filepath.Join(directory, DisplacedIndexName)
if err := fsutil.WriteRoot(
files,
target,
bytes.NewReader(raw),
fsutil.WriteOptions{Mode: 0o600, Replace: true},
); err != nil {
return fmt.Errorf("write displacement index: %w", err)
}
return nil
}
func preserveDisplacedInstallFile(
files *os.Root,
backup, target string,
entry InstallJournalEntry,
) error {
if err := SafePath(files.Name(), target); err != nil {
return err
}
current, err := ObserveInstallImage(files, target)
if err != nil {
return err
}
if current != nil {
if current.SHA256 != entry.Before.SHA256 {
return fmt.Errorf("displaced file %s does not match its before image", target)
}
return nil
}
if err := checkInstallPreImage(files, backup, entry); err != nil {
return err
}
source, err := files.Open(filepath.Join(backup, entry.Before.SHA256))
if err != nil {
return err
}
hasher := sha256.New()
check := func() error {
if hex.EncodeToString(hasher.Sum(nil)) != entry.Before.SHA256 {
return fmt.Errorf("installation pre-image %s is incomplete", entry.Before.SHA256)
}
return nil
}
// Keep shared pre-images until every displaced file and the index exist.
copyErr := fsutil.WriteRoot(
files,
target,
io.TeeReader(source, hasher),
fsutil.WriteOptions{
Mode: os.FileMode(entry.Before.Mode),
Check: check,
},
)
return errors.Join(copyErr, source.Close())
}
// installEntryState describes how far a commit got with one journal path.
type installEntryState int
const (
// installEntryUnapplied means the path still holds its before image, so
// recovery leaves it alone.
installEntryUnapplied installEntryState = iota
// installEntryApplied means the path holds its after image, so recovery
// reverses the transition using the complete before image.
installEntryApplied
// installEntryModified means the path holds neither image, so something
// edited it after the interruption. Recovery must not destroy that edit.
installEntryModified
)
func classifyInstallEntry(current, before, after *InstallImage) installEntryState {
// Modes distinguish states only when content is equal. If content differs,
// some filesystems cannot represent the requested mode, so requiring a mode
// match would misclassify their own committed bytes as an external edit.
compareMode := before != nil && after != nil &&
before.SHA256 == after.SHA256
if InstallImagesMatch(current, before, compareMode) {
return installEntryUnapplied
}
if InstallImagesMatch(current, after, compareMode) {
return installEntryApplied
}
return installEntryModified
}
// InstallPathsAlias reports whether two workspace-relative paths would resolve
// to the same filesystem entry. Existing shared entries are detected directly.
// Otherwise each case-differing component is checked against the filesystem of
// its parent directory, so a nested mount's semantics win over the workspace
// root's. An unprovable parent is treated as aliasing so callers refuse rather
// than risk data loss.
func InstallPathsAlias(root, left, right string) bool {
leftInfo, leftErr := os.Lstat(filepath.Join(root, filepath.FromSlash(left)))
rightInfo, rightErr := os.Lstat(filepath.Join(root, filepath.FromSlash(right)))
if leftErr == nil && rightErr == nil && os.SameFile(leftInfo, rightInfo) {
return true
}
leftParts := strings.Split(filepath.ToSlash(left), "/")
rightParts := strings.Split(filepath.ToSlash(right), "/")
if len(leftParts) != len(rightParts) {
return false
}
prefix := ""
for i := range leftParts {
leftPart, rightPart := leftParts[i], rightParts[i]
if leftPart == rightPart {
prefix = nextInstallPrefix(prefix, leftPart)
continue
}
if !strings.EqualFold(leftPart, rightPart) {
return false
}
folded, known := installPrefixFoldsCase(root, prefix)
if !known {
return true
}
if !folded {
return false
}
prefix = nextInstallPrefix(prefix, leftPart)
}
return true
}
func nextInstallPrefix(prefix, component string) string {
if prefix == "" {
return component
}
return prefix + "/" + component
}
func installPrefixFoldsCase(root, prefix string) (folded, known bool) {
if prefix == "" {
return installRootFoldsCase(root)
}
return installPathFoldsCase(
root,
filepath.Join(filepath.FromSlash(prefix), "case-probe"),
)
}
// installPathFoldsCase reports whether the nearest existing parent directory
// of relative treats case variants as the same name. known is false when the
// directory has no usable entry to prove either behavior.
func installPathFoldsCase(root, relative string) (folded, known bool) {
dir := filepath.Dir(filepath.FromSlash(relative))
for {
if dir == "." || dir == string(filepath.Separator) {
return installRootFoldsCase(root)
}
absolute := filepath.Join(root, dir)
info, err := os.Lstat(absolute)
switch {
case err == nil:
if !info.IsDir() {
return true, false
}
return installDirectoryFoldsCase(absolute)
case errors.Is(err, os.ErrNotExist):
parent := filepath.Dir(dir)
if parent == dir {
return installRootFoldsCase(root)
}
dir = parent
default:
return true, false
}
}
}
// installRootFoldsCase probes the workspace state directory, which the writer
// lock guarantees exists. A case variant of .lucy resolving to the same
// directory proves a case-insensitive root filesystem.
func installRootFoldsCase(root string) (folded, known bool) {
lower, err := os.Lstat(filepath.Join(root, ".lucy"))
if err != nil {
return true, false
}
upper, err := os.Lstat(filepath.Join(root, ".LUCY"))
switch {
case err == nil:
return os.SameFile(lower, upper), true
case errors.Is(err, os.ErrNotExist):
return false, true
default:
return true, false
}
}
// installDirectoryFoldsCase probes one existing directory with one of its own
// entries. An entry whose case variant resolves to the same file proves a
// case-insensitive directory filesystem; a missing or distinct variant proves
// a case-sensitive one.
func installDirectoryFoldsCase(directory string) (folded, known bool) {
entries, err := os.ReadDir(directory)
if err != nil {
return true, false
}
for _, entry := range entries {
variant := flipNameCase(entry.Name())
if variant == "" || variant == entry.Name() {
continue
}
original, err := entry.Info()
if err != nil {
continue
}
probe, err := os.Lstat(filepath.Join(directory, variant))
switch {
case err == nil:
return os.SameFile(original, probe), true
case errors.Is(err, os.ErrNotExist):
return false, true
}
}
return true, false
}
// flipNameCase changes the case of the first ASCII letter in name.
func flipNameCase(name string) string {
for i := range len(name) {
switch {
case name[i] >= 'a' && name[i] <= 'z':
return name[:i] + string(name[i]-'a'+'A') + name[i+1:]
case name[i] >= 'A' && name[i] <= 'Z':
return name[:i] + string(name[i]-'A'+'a') + name[i+1:]
}
}
return ""
}
// InstallImagesEqual reports whether two recorded states match exactly,
// including permission mode. Commit planning uses it to decide whether a
// publication would change anything.
func InstallImagesEqual(left, right *InstallImage) bool {
return InstallImagesMatch(left, right, true)
}
// InstallImagesMatch reports whether current matches expected. When
// compareMode is false only content is compared; recovery uses that because
// some filesystems cannot represent the requested mode, so their own committed
// bytes must not be classified as an external edit. Planning that requires an
// exact answer uses InstallImagesEqual.
func InstallImagesMatch(
current, expected *InstallImage,
compareMode bool,
) bool {
if current == nil || expected == nil {
return current == nil && expected == nil
}
if current.SHA256 != expected.SHA256 {
return false
}
return !compareMode || current.Mode == expected.Mode
}
// ObserveInstallImage observes the content hash and effective permission mode
// of relative beneath files. A nil image with a nil error means the path is
// absent. A present non-regular path is an error because installation images
// describe files.
func ObserveInstallImage(files *os.Root, relative string) (*InstallImage, error) {
image, _, _, err := ObserveInstallImageEvidence(files, relative, nil)
return image, err
}
// ObserveInstallImageCached observes relative through memo, so a file whose
// stat identity the memo already proved is not read again.
func ObserveInstallImageCached(
files *os.Root,
relative string,
memo *fileidentity.Memo,
) (*InstallImage, error) {
image, _, _, err := ObserveInstallImageEvidence(files, relative, memo)
return image, err
}
// ObserveInstallImageEvidence observes relative and also returns the identity
// read from the same handle as the content, so a caller can record the
// evidence for a later command. hasIdentity is false when the platform
// exposes no stat identity.
func ObserveInstallImageEvidence(
files *os.Root,
relative string,
memo *fileidentity.Memo,
) (image *InstallImage, identity fileidentity.Identity, hasIdentity bool, err error) {
observation, err := memo.ObserveRoot(files, relative, nil)
if err != nil {
return nil, fileidentity.Identity{}, false, err
}
if !observation.Exists {
return nil, fileidentity.Identity{}, false, nil
}
if !observation.Regular {
return nil, fileidentity.Identity{}, false, fmt.Errorf(
"installation path %s is not a regular file",
relative,
)
}
return &InstallImage{
SHA256: observation.Hashes["sha256"],
Mode: EffectiveInstallMode(observation.Mode.Perm()),
}, observation.Identity, observation.HasIdentity, nil
}
// InstallBytesImage describes the content and effective permission mode that
// publishing data at mode produces.
func InstallBytesImage(data []byte, mode os.FileMode) *InstallImage {
sum := sha256.Sum256(data)
return &InstallImage{
SHA256: hex.EncodeToString(sum[:]),
Mode: EffectiveInstallMode(mode),
}
}
// EffectiveInstallMode reports the permission bits the platform exposes after
// a chmod to mode. Windows represents regular files as writable (0666) or
// read-only (0444); Unix preserves the requested bits.
func EffectiveInstallMode(mode os.FileMode) uint32 {
if runtime.GOOS == "windows" {
if mode&0o200 != 0 {
return 0o666
}
return 0o444
}
return uint32(mode.Perm())
}
func checkInstallPreImage(
files *os.Root,
backup string,
entry InstallJournalEntry,
) error {
if entry.Before == nil {
return nil
}
info, err := files.Lstat(filepath.Join(backup, entry.Before.SHA256))
if err != nil {
return fmt.Errorf(
"installation pre-image %s for %s is unavailable: %w",
entry.Before.SHA256, entry.Path, err,
)
}
if !info.Mode().IsRegular() {
return fmt.Errorf(
"installation pre-image %s for %s is not a regular file",
entry.Before.SHA256, entry.Path,
)
}
return nil
}
func restoreInstallEntry(
files *os.Root,
backup string,
entry InstallJournalEntry,
) (resultErr error) {
relative := filepath.FromSlash(entry.Path)
if entry.Before == nil {
current, err := ObserveInstallImage(files, relative)
if err != nil {
return err
}
if classifyInstallEntry(current, entry.Before, entry.After) != installEntryApplied {
return fmt.Errorf(
"file %s changed during installation recovery; keep the journal and resolve the edit",
entry.Path,
)
}
return RemoveRoot(files, relative)
}
source, err := files.Open(filepath.Join(backup, entry.Before.SHA256))
if err != nil {
return fmt.Errorf("open installation pre-image %s: %w", entry.Path, err)
}
hasher := sha256.New()
check := func() error {
if actual := hex.EncodeToString(hasher.Sum(nil)); actual != entry.Before.SHA256 {
return fmt.Errorf(
"installation pre-image %s for %s is incomplete",
entry.Before.SHA256, entry.Path,
)
}
current, err := ObserveInstallImage(files, relative)
if err != nil {
return err
}
if classifyInstallEntry(current, entry.Before, entry.After) != installEntryApplied {
return fmt.Errorf(
"file %s changed during installation recovery; keep the journal and resolve the edit",
entry.Path,
)
}
return nil
}
copyErr := fsutil.WriteRoot(
files,
relative,
io.TeeReader(source, hasher),
fsutil.WriteOptions{
Mode: os.FileMode(entry.Before.Mode),
Replace: true,
Check: check,
},
)
closeErr := source.Close()
if copyErr != nil || closeErr != nil {
return errors.Join(copyErr, closeErr)
}
return nil
}
// Package java names the branded Java builds that a server may require. It
// is vocabulary only; runtime selection lives in package javaruntime.
package java
import (
"slices"
"strings"
)
// Distribution identifies a branded Java build by its foojay name. The
// unspecified distribution accepts any build, including unbranded builds from
// operating system package managers.
type Distribution string
const (
DistributionAny Distribution = ""
DistributionTemurin Distribution = "temurin"
DistributionZulu Distribution = "zulu"
DistributionCorretto Distribution = "corretto"
DistributionLiberica Distribution = "liberica"
DistributionMicrosoft Distribution = "microsoft"
DistributionOracle Distribution = "oracle"
DistributionOracleOpenJDK Distribution = "oracle_open_jdk"
DistributionGraalVM Distribution = "graalvm"
DistributionGraalVMCommunity Distribution = "graalvm_community"
DistributionSemeru Distribution = "semeru"
DistributionSapMachine Distribution = "sap_machine"
DistributionDragonwell Distribution = "dragonwell"
DistributionKona Distribution = "kona"
DistributionRedHat Distribution = "redhat"
DistributionJetBrains Distribution = "jetbrains"
)
// Distributions lists every distribution a requirement may name.
var Distributions = []Distribution{
DistributionTemurin,
DistributionZulu,
DistributionCorretto,
DistributionLiberica,
DistributionMicrosoft,
DistributionOracle,
DistributionOracleOpenJDK,
DistributionGraalVM,
DistributionGraalVMCommunity,
DistributionSemeru,
DistributionSapMachine,
DistributionDragonwell,
DistributionKona,
DistributionRedHat,
DistributionJetBrains,
}
// String returns the persisted key. The unspecified distribution renders as
// "any" for display only.
func (d Distribution) String() string {
if d == DistributionAny {
return "any"
}
return string(d)
}
// Title returns the human-facing distribution name.
func (d Distribution) Title() string {
switch d {
case DistributionAny:
return "Any"
case DistributionTemurin:
return "Eclipse Temurin"
case DistributionZulu:
return "Azul Zulu"
case DistributionCorretto:
return "Amazon Corretto"
case DistributionLiberica:
return "BellSoft Liberica"
case DistributionMicrosoft:
return "Microsoft Build of OpenJDK"
case DistributionOracle:
return "Oracle JDK"
case DistributionOracleOpenJDK:
return "Oracle OpenJDK"
case DistributionGraalVM:
return "Oracle GraalVM"
case DistributionGraalVMCommunity:
return "GraalVM Community"
case DistributionSemeru:
return "IBM Semeru"
case DistributionSapMachine:
return "SapMachine"
case DistributionDragonwell:
return "Alibaba Dragonwell"
case DistributionKona:
return "Tencent Kona"
case DistributionRedHat:
return "Red Hat build of OpenJDK"
case DistributionJetBrains:
return "JetBrains Runtime"
default:
return string(d)
}
}
// Accepts reports whether a build of distribution actual satisfies d.
func (d Distribution) Accepts(actual Distribution) bool {
return d == DistributionAny || d == actual
}
// ParseDistribution maps a distribution key to its typed value. Keys are
// case-insensitive, and "any" or the empty key mean the unspecified
// distribution.
func ParseDistribution(s string) (Distribution, bool) {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" || s == "any" {
return DistributionAny, true
}
if d := Distribution(s); slices.Contains(Distributions, d) {
return d, true
}
return DistributionAny, false
}
// Package javaruntime decides which Java runtime a server runs on and how
// that runtime misses the requirement of the locked server. Every miss is a
// warning: Lucy never refuses to run a server because of its Java runtime.
package javaruntime
import (
"fmt"
"slices"
"strconv"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/java"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/version"
)
// dependencyID is the dependency name that package descriptors use for the
// Java runtime.
const dependencyID = "java"
// newestJava bounds the search for a major version that meets every
// constraint.
const newestJava = 99
type constraintKind int
const (
constraintAdvisory constraintKind = iota
constraintPin
constraintPackage
constraintIncompatible
)
// Constraint is one condition on the Java major version.
type Constraint struct {
// Source names who sets the condition, for example "Minecraft 1.20.1" or
// "carpet 1.4.112".
Source string `json:"source"`
// Expression is the condition as its source writes it. For a package that
// declares an incompatibility, it is the range the package rejects.
Expression string `json:"expression"`
kind constraintKind
accepts func(major int) bool
}
// Accepts reports whether Java major meets c.
func (c Constraint) Accepts(major int) bool {
return c.accepts(major)
}
// miss describes how Java major fails c.
func (c Constraint) miss(major int) string {
switch c.kind {
case constraintAdvisory:
return fmt.Sprintf(
"Java %d is older than the Java version that Mojang recommends for %s (%s)",
major,
c.Source,
c.Expression,
)
case constraintPin:
return fmt.Sprintf("Java %d is not Java %s, which %s pins", major, c.Expression, c.Source)
case constraintIncompatible:
return fmt.Sprintf("%s is incompatible with Java %s", c.Source, c.Expression)
default:
return fmt.Sprintf("%s requires Java %s", c.Source, c.Expression)
}
}
// Requirement is the Java runtime that a locked server asks for.
type Requirement struct {
// Advisory is the major version that Mojang recommends.
Advisory int `json:"advisory"`
// Version is the major version that the manifest pins; zero follows the
// constraints.
Version int `json:"version,omitempty"`
// Distribution is the distribution that the manifest pins; empty accepts
// every build.
Distribution java.Distribution `json:"distribution,omitempty"`
Constraints []Constraint `json:"constraints"`
}
// RequirementOf combines the Java inputs that lock records: the Mojang
// advisory, the manifest pin, and the Java requirements of the enabled
// packages.
func RequirementOf(lock *document.Lock, logger *log.Logger) Requirement {
settings := lock.Server.Java
r := Requirement{
Advisory: settings.Advisory,
Version: settings.Version,
Distribution: settings.Distribution,
}
advisory := settings.Advisory
r.Constraints = append(r.Constraints, Constraint{
Source: "Minecraft " + lock.Server.Minecraft.String(),
Expression: fmt.Sprintf(">=%d", advisory),
kind: constraintAdvisory,
accepts: func(major int) bool { return major >= advisory },
})
if pinned := settings.Version; pinned != 0 {
r.Constraints = append(r.Constraints, Constraint{
Source: document.ManifestFilename,
Expression: strconv.Itoa(pinned),
kind: constraintPin,
accepts: func(major int) bool { return major == pinned },
})
}
for i := range lock.Packages {
p := &lock.Packages[i]
if !p.Enabled() {
continue
}
for _, m := range p.Modules {
for _, dep := range m.Dependencies {
if c, ok := packageConstraint(m, dep, advisory, logger); ok &&
!slices.ContainsFunc(r.Constraints, func(known Constraint) bool {
return known.Source == c.Source && known.Expression == c.Expression && known.kind == c.kind
}) {
r.Constraints = append(r.Constraints, c)
}
}
}
}
return r
}
func packageConstraint(
m catalog.DescriptorModule,
dep catalog.DescriptorDependency,
advisory int,
logger *log.Logger,
) (Constraint, bool) {
if dep.ID != dependencyID || dep.Constraint == "" {
return Constraint{}, false
}
kind := constraintPackage
switch dep.Kind {
case catalog.DependencyKindRequired:
case catalog.DependencyKindIncompatible:
kind = constraintIncompatible
default:
return Constraint{}, false
}
expression, dialect := dep.Constraint, m.VersionDialect
match := func(major int) (bool, error) {
return version.Match(expression, version.Version(strconv.Itoa(major)), dialect)
}
if _, err := match(advisory); err != nil {
logger.Debug(
"java requirement ignored",
"module", m.ID,
"constraint", expression,
"reason", err,
)
return Constraint{}, false
}
return Constraint{
Source: m.ID + " " + m.Version.String(),
Expression: expression,
kind: kind,
accepts: func(major int) bool {
matched, _ := match(major)
return matched != (kind == constraintIncompatible)
},
}, true
}
// Unmet returns the constraints that Java major fails.
func (r Requirement) Unmet(major int) []Constraint {
var unmet []Constraint
for _, c := range r.Constraints {
if !c.Accepts(major) {
unmet = append(unmet, c)
}
}
return unmet
}
// Lowest returns the oldest major version that meets every constraint, and
// false when no version does.
func (r Requirement) Lowest() (int, bool) {
for major := document.MinimumJava; major <= newestJava; major++ {
if len(r.Unmet(major)) == 0 {
return major, true
}
}
return 0, false
}
// Target returns the major version to install: the pin, else the oldest
// version that meets every constraint, else the advisory.
func (r Requirement) Target() int {
if r.Version != 0 {
return r.Version
}
if lowest, ok := r.Lowest(); ok {
return lowest
}
return r.Advisory
}
package javaruntime
import (
"cmp"
"context"
"fmt"
"slices"
"sort"
"strconv"
"strings"
"github.com/mclucy/lucy/config"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/toolchain"
"github.com/mclucy/lucy/java"
"github.com/mclucy/lucy/log"
)
// Source names how a Java runtime was selected.
type Source string
const (
// SourceConfigured means configuration selects the runtime.
SourceConfigured Source = "configured"
// SourceInstalled means Lucy picked the runtime among the installed ones.
SourceInstalled Source = "installed"
)
// Runtime is one installed Java runtime.
type Runtime struct {
Home string `json:"home"`
Executable string `json:"executable"`
Version string `json:"version"`
Major int `json:"major"`
Distribution java.Distribution `json:"distribution,omitempty"`
Implementor string `json:"implementor,omitempty"`
}
// Build names the build of r for people, for example "Eclipse Temurin" or
// "Homebrew".
func (r *Runtime) Build() string {
if r.Distribution != java.DistributionAny {
return r.Distribution.Title()
}
if r.Implementor != "" {
return r.Implementor
}
return "unbranded"
}
// Check reports the Java runtime that a server runs on and how the runtime
// misses the requirement of the server.
type Check struct {
// Runtime is nil when no usable runtime exists.
Runtime *Runtime `json:"runtime,omitempty"`
Source Source `json:"source,omitempty"`
// ConfiguredHome names the selected home, even when it is not usable.
ConfiguredHome string `json:"configured_home,omitempty"`
ConfigPath string `json:"config_path,omitempty"`
// Target is the major version that meets the requirement.
Target int `json:"target"`
Distribution java.Distribution `json:"distribution,omitempty"`
// Problems describe each way the selection misses the requirement.
Problems []string `json:"problems,omitempty"`
}
// Satisfied reports whether a runtime exists and meets the requirement.
func (c *Check) Satisfied() bool {
return c != nil && c.Runtime != nil && len(c.Problems) == 0
}
// Executable returns the java executable of the selected runtime, or "" when
// no runtime is usable.
func (c *Check) Executable() string {
if c == nil || c.Runtime == nil {
return ""
}
return c.Runtime.Executable
}
// Select honors a configured Java home without fallback. Otherwise it picks the
// installed runtime that misses the fewest constraints, preferring the oldest
// major version that meets the Mojang advisory.
func Select(ctx context.Context, root string, req Requirement, logger *log.Logger, additionalHomes ...string) (*Check, error) {
check := &Check{
Target: req.Target(),
Distribution: req.Distribution,
}
settings, err := config.New(root, logger)
if err != nil {
return nil, err
}
home, sourcePath, err := settings.JavaHome()
if err != nil {
return nil, err
}
if home != "" {
check.Source = SourceConfigured
check.ConfiguredHome = home
check.ConfigPath = sourcePath
installation, err := toolchain.ProbeJava(ctx, home)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
check.Problems = append(check.Problems, fmt.Sprintf(
"%s selects %s, which is not a usable Java runtime: %v",
sourcePath,
home,
err,
))
return check, nil
}
check.Runtime = runtimeOf(installation)
check.Problems = append(conflicts(req), req.Misses(check.Runtime)...)
logger.Debug(
"java selected",
"home", check.Runtime.Home,
"major", check.Runtime.Major,
"reason", "configuration selects it",
)
return check, nil
}
runtimes, err := Installed(ctx, logger, additionalHomes...)
if err != nil {
return nil, err
}
if len(runtimes) == 0 {
check.Problems = append(check.Problems, "no Java runtime is installed")
return check, nil
}
check.Source = SourceInstalled
check.Runtime = Choose(req, runtimes)
check.Problems = append(conflicts(req), req.Misses(check.Runtime)...)
logger.Debug(
"java selected",
"home", check.Runtime.Home,
"major", check.Runtime.Major,
"problems", len(check.Problems),
"reason", "closest installed runtime to the requirement",
)
return check, nil
}
// Installed includes explicitly supplied homes in ordinary machine discovery.
func Installed(ctx context.Context, logger *log.Logger, additionalHomes ...string) ([]Runtime, error) {
inventory, err := toolchain.DiscoverJava(ctx, additionalHomes...)
if err != nil {
return nil, err
}
for _, problem := range inventory.Problems {
logger.Debug("java candidate unusable", "reason", problem)
}
runtimes := make([]Runtime, 0, len(inventory.Java))
for _, installation := range inventory.Java {
runtimes = append(runtimes, *runtimeOf(installation))
}
return runtimes, nil
}
// Choose returns the runtime that misses the fewest parts of req. Among
// equal runtimes it prefers one that meets the Mojang advisory, then the
// oldest major version, then the newest update. runtimes must not be empty.
func Choose(req Requirement, runtimes []Runtime) *Runtime {
ranked := slices.Clone(runtimes)
sort.SliceStable(ranked, func(i, j int) bool {
a, b := &ranked[i], &ranked[j]
return cmp.Or(
cmp.Compare(len(req.Misses(a)), len(req.Misses(b))),
compareBool(a.Major < req.Advisory, b.Major < req.Advisory),
cmp.Compare(a.Major, b.Major),
compareVersions(b.Version, a.Version),
cmp.Compare(a.Home, b.Home),
) < 0
})
return &ranked[0]
}
// conflicts reports a requirement that no Java version meets.
func conflicts(req Requirement) []string {
if _, ok := req.Lowest(); ok {
return nil
}
sources := make([]string, len(req.Constraints))
for i, c := range req.Constraints {
sources[i] = c.Source + " (" + c.Expression + ")"
}
return []string{"no Java version meets every requirement: " + strings.Join(sources, ", ")}
}
// Misses describes each way runtime misses r. An empty result means runtime
// meets r.
func (r Requirement) Misses(runtime *Runtime) []string {
var found []string
for _, c := range r.Unmet(runtime.Major) {
found = append(found, c.miss(runtime.Major))
}
if !r.Distribution.Accepts(runtime.Distribution) {
found = append(found, fmt.Sprintf(
"the Java runtime at %s is a %s build, not %s, which %s pins",
runtime.Home,
runtime.Build(),
r.Distribution.Title(),
document.ManifestFilename,
))
}
return found
}
func runtimeOf(installation toolchain.JavaInstallation) *Runtime {
return &Runtime{
Home: installation.Home,
Executable: installation.Java,
Version: installation.Version,
Major: installation.Major,
Distribution: installation.Distribution,
Implementor: installation.Implementor,
}
}
func compareBool(a, b bool) int {
switch {
case a == b:
return 0
case a:
return 1
default:
return -1
}
}
// compareVersions orders Java version strings such as "21.0.5" and "21.0.13"
// by their numeric parts.
func compareVersions(a, b string) int {
split := func(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool { return r < '0' || r > '9' })
}
left, right := split(a), split(b)
for i := range min(len(left), len(right)) {
l, _ := strconv.Atoi(left[i])
r, _ := strconv.Atoi(right[i])
if c := cmp.Compare(l, r); c != 0 {
return c
}
}
return cmp.Compare(len(left), len(right))
}
// Package log records operational diagnostics independently of user reports.
package log
import (
"fmt"
"io"
"os"
"sync"
"sync/atomic"
"time"
charm "charm.land/log/v2"
"github.com/charmbracelet/colorprofile"
)
// Logger owns one diagnostic destination and its optional terminal mirror.
// A nil Logger records nothing.
type Logger struct {
mu sync.RWMutex
file *os.File
path string
diagnostic *charm.Logger
mirror *charm.Logger
capture bool
stages []string
captureWait atomic.Bool
waitMu sync.Mutex
waitHTTP time.Duration
waitLock time.Duration
waitHTTPSampled bool
waitLockSampled bool
}
// New records all diagnostic levels in path. The level selects which records
// reach mirror; a nil mirror leaves diagnostics in the file only.
func New(path, level string, mirror io.Writer) (*Logger, error) {
threshold, err := charm.ParseLevel(level)
if err != nil {
return nil, fmt.Errorf("log level: %w", err)
}
if path == "" {
path = DefaultFile()
}
file, err := openLogFile(path)
if err != nil {
return nil, err
}
logger := &Logger{
file: file,
path: path,
diagnostic: newLogger(file, charm.DebugLevel),
}
if mirror != nil {
logger.mirror = newLogger(mirror, threshold)
}
return logger, nil
}
func newLogger(destination io.Writer, level charm.Level) *charm.Logger {
logger := charm.NewWithOptions(destination, charm.Options{
ReportTimestamp: true,
TimeFormat: "2006-01-02 15:04:05",
Level: level,
Formatter: charm.TextFormatter,
})
logger.SetColorProfile(colorprofile.NoTTY)
return logger
}
func (l *Logger) Info(content any, fields ...any) {
l.write(charm.InfoLevel, content, fields...)
}
func (l *Logger) Debug(content any, fields ...any) {
l.write(charm.DebugLevel, content, fields...)
}
func (l *Logger) Warn(err error) {
if err != nil {
l.write(charm.WarnLevel, err)
}
}
func (l *Logger) Error(err error) {
if err != nil {
l.write(charm.ErrorLevel, err)
}
}
func (l *Logger) write(level charm.Level, content any, fields ...any) {
if l == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
if l.capture && len(l.stages) < 128 {
if message, ok := content.(string); ok && diagnosticStage(message) {
l.stages = append(l.stages, message)
}
}
l.diagnostic.Log(level, content, fields...)
if l.mirror != nil {
l.mirror.Log(level, content, fields...)
}
}
// CaptureStages enables the bounded, allowlisted diagnostic record for this
// invocation. Arbitrary messages and fields remain in the local log only.
func (l *Logger) CaptureStages() {
if l == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
l.capture = true
l.captureWait.Store(true)
}
// Stages returns the captured messages without exposing log fields.
func (l *Logger) Stages() []string {
if l == nil {
return nil
}
l.mu.RLock()
defer l.mu.RUnlock()
return append([]string(nil), l.stages...)
}
func diagnosticStage(message string) bool {
switch message {
case "action invoked", "action completed",
"resolving installation", "installation decision",
"installation already current", "installation not current",
"installation current", "staging installation", "packages staged",
"installation transaction journaled", "installation committed",
"lock resolution reused current lock", "core pin not reusable",
"installing java", "java installed", "java repository added",
"upgrade: candidate combination failed":
return true
default:
return false
}
}
func (l *Logger) FilePath() string {
if l == nil {
return ""
}
return l.path
}
func (l *Logger) Close() error {
if l == nil {
return nil
}
l.mu.Lock()
defer l.mu.Unlock()
if l.file == nil {
return nil
}
l.diagnostic.SetOutput(io.Discard)
if l.mirror != nil {
l.mirror.SetOutput(io.Discard)
}
err := l.file.Close()
l.file = nil
if err != nil {
return fmt.Errorf("close log file %q: %w", l.path, err)
}
return nil
}
package log
import (
"fmt"
"os"
"path/filepath"
"runtime"
)
// DefaultDirectory names the per-user directory that holds Lucy's diagnostic
// records. Every retained diagnostic file derives from it, so their
// locations stay consistent.
func DefaultDirectory() string {
switch runtime.GOOS {
case "windows":
return filepath.Join(os.Getenv("APPDATA"), "lucy", "logs")
case "darwin":
return filepath.Join(os.Getenv("HOME"), "Library", "Logs", "lucy")
case "linux":
return filepath.Join(os.Getenv("HOME"), ".local", "share", "lucy", "logs")
default:
return "logs"
}
}
func DefaultFile() string {
return filepath.Join(DefaultDirectory(), "lucy.log")
}
func openLogFile(path string) (*os.File, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, fmt.Errorf("create log directory: %w", err)
}
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return nil, fmt.Errorf("open log file %q: %w", path, err)
}
return file, nil
}
package log
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
)
// maxSpoolBytes bounds one retained process log. A subprocess that prints more
// keeps its start; the spool records the truncation instead of filling the
// user's disk.
const maxSpoolBytes = 64 << 20
// truncationMarker ends a file that omitted output. Room for it is reserved
// from maxSpoolBytes, so the file stays within the bound.
const truncationMarker = "\n[process output truncated]\n"
// contentLimit bounds headers and subprocess output, leaving the marker its
// space inside maxSpoolBytes.
const contentLimit int64 = maxSpoolBytes - int64(len(truncationMarker))
// ProcessLog reports what became of a retained process log. Observed counts
// every byte the subprocesses printed; Stored counts the bytes the file
// holds, including command headers. Truncated reports that the file is
// incomplete because the size bound was reached or a write failed.
type ProcessLog struct {
Path string
Observed int64
Stored int64
Truncated bool
}
// ProcessSpool retains the combined output of the subprocesses one command
// runs. The file appears in the platform log directory under "installer" when
// the first subprocess is about to start, because its command header is
// written before the child runs. The command boundary retains the file when a
// step fails and discards it when the command succeeds, so a surviving file is
// always failure evidence. Writes are safe from concurrent copy goroutines,
// which the process package starts for stdout and stderr separately.
type ProcessSpool struct {
mu sync.Mutex
prefix string
logger *Logger
file *os.File
path string
written int64
seen int64
capped bool
createErr bool
writeErr bool
retained bool
retainedLog ProcessLog
closed bool
}
// NewProcessSpool prepares a spool that names its file after prefix. A nil
// logger records no diagnostics of the spool itself.
func NewProcessSpool(prefix string, logger *Logger) *ProcessSpool {
return &ProcessSpool{prefix: prefix, logger: logger}
}
// Write counts every byte and stores what the size bound allows. It always
// reports the full input length: the copy goroutines of the process package
// read a short write as a broken pipe and would fail the command over its
// diagnostic record. A spool that cannot create or write its file keeps
// counting and lets the command proceed; the retained log then reports how
// much evidence was lost. Output that arrives after Retain or Discard is
// accepted and dropped, so the retained file stays the evidence it named.
func (s *ProcessSpool) Write(data []byte) (int, error) {
total := len(data)
s.mu.Lock()
defer s.mu.Unlock()
if s.retained || s.closed {
return total, nil
}
s.seen += int64(total)
if s.writeErr || !s.ensure() {
return total, nil
}
s.append(data)
return total, nil
}
// Section introduces one subprocess run in the retained file. It stores the
// label only; the live output writer already narrates to the terminal.
func (s *ProcessSpool) Section(label string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.retained || s.closed || s.writeErr || !s.ensure() {
return
}
separator := ""
if s.written > 0 {
separator = "\n"
}
s.append([]byte(fmt.Sprintf("%s=== %s\n", separator, label)))
}
// Retain closes the file and reports where the evidence survives. Retention is
// terminal: a repeated call reports the same log, and no later write reopens
// the file. It reports no log when no file was created, so a failure without
// a subprocess run names no file.
func (s *ProcessSpool) Retain() (ProcessLog, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if s.retained {
return s.retainedLog, s.retainedLog.Path != ""
}
s.retained = true
if s.file == nil {
return ProcessLog{}, false
}
err := s.file.Close()
s.file = nil
if err != nil {
s.warnOnce(fmt.Errorf("close process log %q: %w", s.path, err))
}
s.retainedLog = ProcessLog{
Path: s.path,
Observed: s.seen,
Stored: s.written,
Truncated: s.capped || s.writeErr || err != nil,
}
return s.retainedLog, true
}
// Discard deletes the unretained file and ends the spool, so no later write
// leaves a file the command boundary does not own.
func (s *ProcessSpool) Discard() {
s.mu.Lock()
defer s.mu.Unlock()
if s.retained || s.closed {
return
}
s.closed = true
if s.file == nil {
return
}
err := errors.Join(s.file.Close(), os.Remove(s.path))
s.file = nil
if err != nil {
s.warnOnce(fmt.Errorf("discard process log %q: %w", s.path, err))
}
}
// append stores what fits of data and, when it must drop bytes, ends the file
// with the truncation marker. Headers and subprocess output share the bound,
// so neither can push the file past it.
func (s *ProcessSpool) append(data []byte) {
if s.capped || s.writeErr {
return
}
room := contentLimit - s.written
if room < 0 {
room = 0
}
if int64(len(data)) <= room {
s.store(data)
return
}
if room > 0 {
s.store(data[:room])
}
s.capped = true
s.store([]byte(truncationMarker))
}
// store writes what the file accepts and counts it. The spool is a diagnostic
// record; a file that stopped accepting writes must never fail or spam over
// the command it records.
func (s *ProcessSpool) store(data []byte) {
if len(data) == 0 {
return
}
written, err := s.file.Write(data)
s.written += int64(written)
if err != nil {
s.writeErr = true
s.warnOnce(fmt.Errorf("write process log %q: %w", s.path, err))
}
}
// ensure creates the file on first use. It reports whether writes may
// continue; a creation failure is permanent for this spool so a repeated
// warning leaves the output it reports intact.
func (s *ProcessSpool) ensure() bool {
if s.file != nil {
return true
}
if s.createErr {
return false
}
directory := filepath.Join(DefaultDirectory(), "installer")
stamp := time.Now().Format("20060102-150405")
name := fmt.Sprintf("%s-%s-%d.log", s.prefix, stamp, os.Getpid())
path := filepath.Join(directory, name)
if err := os.MkdirAll(directory, 0o755); err != nil {
s.warnOnce(fmt.Errorf("create process log directory: %w", err))
s.createErr = true
return false
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if errors.Is(err, fs.ErrExist) {
// Another spool of the same second took the timestamped name,
// so the random suffix keeps this run's evidence.
file, err = os.CreateTemp(directory, s.prefix+"-"+stamp+"-*.log")
}
if err != nil {
s.warnOnce(fmt.Errorf("open process log %q: %w", path, err))
s.createErr = true
return false
}
s.file = file
s.path = file.Name()
return true
}
func (s *ProcessSpool) warnOnce(err error) {
if s.logger != nil {
s.logger.Warn(err)
}
}
package log
import "time"
// WaitKind names one class of time a command spends waiting rather than
// computing.
type WaitKind int
const (
// WaitHTTP covers one request from send through the response headers.
WaitHTTP WaitKind = iota + 1
// WaitFileLock covers observed file-lock acquisition. Cache index locks
// block, while the workspace writer's nonblocking try contributes only
// the measured attempt.
WaitFileLock
)
// maxObservedWait bounds one wait sample and the cumulative total so a
// suspended machine or a clock jump cannot distort an event.
const maxObservedWait = 7 * 24 * time.Hour
// WaitStart marks the start of a wait when this logger captures telemetry.
// It returns the zero time otherwise, and WaitDone ignores a zero start.
// Calling it costs a time sample only; no timers or allocations are made.
func (l *Logger) WaitStart() time.Time {
if l == nil || !l.captureWait.Load() {
return time.Time{}
}
return time.Now()
}
// WaitDone records the elapsed time since start for kind. Multiple samples of
// the same kind accumulate; different kinds stay separate. Samples may span
// overlapping work, so their totals are observed waits, not exclusive stages.
func (l *Logger) WaitDone(kind WaitKind, start time.Time) {
if l == nil || start.IsZero() || !l.captureWait.Load() {
return
}
elapsed := time.Since(start)
if elapsed < 0 {
return
}
elapsed = min(elapsed, maxObservedWait)
l.waitMu.Lock()
defer l.waitMu.Unlock()
switch kind {
case WaitHTTP:
l.waitHTTP = min(l.waitHTTP+elapsed, maxObservedWait)
l.waitHTTPSampled = true
case WaitFileLock:
l.waitLock = min(l.waitLock+elapsed, maxObservedWait)
l.waitLockSampled = true
}
}
// WaitTimings returns the observed HTTP and workspace lock waits. A nil
// result means the kind was never sampled, which is distinct from a measured
// zero wait.
func (l *Logger) WaitTimings() (http, lock *time.Duration) {
if l == nil {
return nil, nil
}
l.waitMu.Lock()
defer l.waitMu.Unlock()
if l.waitHTTPSampled {
value := l.waitHTTP
http = &value
}
if l.waitLockSampled {
value := l.waitLock
lock = &value
}
return http, lock
}
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"github.com/mclucy/lucy/cmd"
"github.com/mclucy/lucy/internal/cli"
)
func main() {
ctx, stop := signalContext()
directory, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "determine invocation directory: %v\n", err)
stop()
os.Exit(1)
}
code := run(ctx, os.Args[1:], directory, os.Stdin, os.Stdout, os.Stderr)
stop()
os.Exit(code)
}
// signalCancelCause marks a cancellation that came from the operating system.
// It implements Is(context.Canceled) so existing exit handling is unchanged,
// and SignalCancellation lets command telemetry distinguish an actual signal
// from generic internal cancellation while keeping its description private.
type signalCancelCause struct{}
func (signalCancelCause) Error() string {
return "signal received"
}
func (signalCancelCause) Is(target error) bool {
return target == context.Canceled
}
func (signalCancelCause) SignalCancellation() {}
// signalContext owns signal handling at the process boundary. The returned
// context carries a typed cause so telemetry can attribute an interruption to
// an actual signal.
func signalContext() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(context.Background())
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
go func() {
select {
case <-signals:
cancel(signalCancelCause{})
case <-ctx.Done():
}
}()
return ctx, func() {
signal.Stop(signals)
cancel(nil)
}
}
func run(ctx context.Context, args []string, directory string, stdin io.Reader, stdout, stderr io.Writer) (exitCode int) {
runner := cmd.NewRunner(args, cmd.RunnerOptions{
Directory: directory,
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
})
executeErr := runner.Execute(ctx)
closeErr := runner.Close()
if executeErr == nil && closeErr == nil {
executeErr = runner.FlushOutput()
}
var exitErr *cli.ExitError
if errors.As(executeErr, &exitErr) {
if closeErr != nil {
if runner.JSONSelected() {
runner.WriteError(errors.Join(exitErr.Err, closeErr))
} else {
runner.WriteError(closeErr)
}
return 1
}
if exitErr.Silent {
if flushErr := runner.FlushOutput(); flushErr != nil {
runner.WriteError(flushErr)
return 2
}
return exitErr.Code
}
if runner.JSONSelected() {
runner.WriteError(exitErr.Err)
}
return exitErr.Code
}
switch {
case runner.JSONSelected():
// A close failure joins the action failure so stderr carries one document
// and the error survives.
if err := errors.Join(executeErr, closeErr); err != nil {
runner.WriteError(err)
}
case closeErr != nil:
runner.WriteError(closeErr)
}
switch {
case executeErr == nil && closeErr == nil:
return 0
case errors.Is(executeErr, context.Canceled):
return 130
default:
return 1
}
}
package operation
import (
"context"
"errors"
"fmt"
"maps"
"os"
"slices"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
// InitOptions describes adoption of the server already present in a
// directory.
type InitOptions struct {
Name string
MCDRVersion string
Force bool
NoComments bool
// Expectation narrows the observed installations by product and version
// for this initialization only; it is never persisted.
Expectation *discovery.Expectation
// PromptRuntime asks which installation to use when observation finds
// several equally valid runtimes. Nil keeps the strict failure.
PromptRuntime func(discovery.Result) (*discovery.Installation, error)
// Trace receives progress for the lock resolution initialization runs.
Trace *install.Trace
// Materialize supplies artifact bytes for adoption planning. Nil uses the
// configured cache and network.
Materialize artifact.Materializer
}
// InitResult is the structured outcome of one initialization. The document
// is the written manifest; warnings and discovery carry the observations
// that the command boundary presents.
type InitResult struct {
Document *documentpkg.Manifest
Lock *documentpkg.Lock
PublishedLock bool
PublishedConfig bool
Warnings []error
Discovery discovery.Result
}
func commandDocuments(root string, logger *log.Logger) (document *documentpkg.Manifest, locked *documentpkg.Lock, resultErr error) {
writer, err := workspacewrite.Lock(root, logger)
if err != nil {
return nil, nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, logger); err != nil {
return nil, nil, err
}
d, err := documentpkg.ManifestFile(root).Read()
if err != nil {
return nil, nil, err
}
old, err := documentpkg.LockFile(root).Read()
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, nil, err
}
return d, old, nil
}
// pinWorkspaceDocuments fills the state an operation selected from when the
// caller did not already pin it. The installation re-locks the workspace, so a
// recovery or concurrent edit in between fails instead of being overwritten.
func pinWorkspaceDocuments(opts *install.Options, d *documentpkg.Manifest, old *documentpkg.Lock) error {
if d != nil && opts.ExpectedManifest == "" {
fingerprint, err := d.Fingerprint()
if err != nil {
return err
}
opts.ExpectedManifest = fingerprint
}
if old == nil || opts.ExpectedLock != "" {
return nil
}
fingerprint, err := old.Fingerprint()
if err != nil {
return err
}
opts.ExpectedLock = fingerprint
return nil
}
func selectedEcosystem(d *documentpkg.Manifest, requested catalog.Ecosystem) catalog.Ecosystem {
if requested != catalog.EcosystemUnspecified {
return requested
}
target := resolve.Target{Product: d.Server.Core.Product}
if runtime, ok := target.PackageRuntime(); ok {
return runtime
}
if d.Server.Core.Repository != "" {
return catalog.EcosystemPaper
}
if d.MCDR != nil {
return catalog.EcosystemMCDR
}
return catalog.EcosystemUnspecified
}
// servedEcosystemSet returns the package ecosystems that the declared server
// can load. A probed runtime also reports bridged ecosystems, such as Fabric
// through Sinytra Connector. Only ecosystems the declared product loads enter
// the set. Without a probe, the declared product decides.
func servedEcosystemSet(d *documentpkg.Manifest, observed *workspace.Workspace) map[catalog.Ecosystem]struct{} {
target := resolve.Target{Product: d.Server.Core.Product}
served := map[catalog.Ecosystem]struct{}{}
if observed != nil {
for _, offer := range observed.ServedEcosystems() {
if resolve.SupportsPackages(target, offer.Ecosystem) {
served[offer.Ecosystem] = struct{}{}
}
}
}
if len(served) == 0 {
if ecosystem := selectedEcosystem(d, catalog.EcosystemUnspecified); ecosystem != catalog.EcosystemUnspecified {
served[ecosystem] = struct{}{}
}
}
return served
}
// servedEcosystemForFile reports the served loader whose descriptor reader
// recognizes the file. Each reader applies its loader's descriptor precedence,
// so a returned module proves that loader loads the file.
func servedEcosystemForFile(
ctx context.Context,
analysis *artifact.Analysis,
served map[catalog.Ecosystem]struct{},
minecraft string,
) (catalog.Ecosystem, bool) {
for _, ecosystem := range slices.Sorted(maps.Keys(served)) {
if ecosystem == catalog.EcosystemMCDR {
continue
}
view, err := analysis.Descriptor(ctx, ecosystem, minecraft)
if err != nil {
continue
}
if len(view.Modules) > 0 {
return ecosystem, true
}
}
return catalog.EcosystemUnspecified, false
}
func commandReference(d *documentpkg.Manifest, old *documentpkg.Lock, raw string, ecosystem catalog.Ecosystem) (string, version.Version, error) {
request, err := input.Parse(raw)
if err != nil {
return "", "", err
}
provider, name := request.Provider, string(request.Name)
if provider == catalog.ProviderUnspecified {
if old != nil {
ref, err := old.LookupReference(name)
if err != nil {
return "", "", err
}
if ref != "" {
provider, name, err = documentpkg.ParseReference(ref)
if err != nil {
return "", "", err
}
}
}
if provider == catalog.ProviderUnspecified {
provider = catalog.ProviderModrinth
if ecosystem == catalog.EcosystemMCDR {
provider = catalog.ProviderMCDR
}
}
}
ref := provider.String() + ":" + name
if _, _, err := documentpkg.ParseReference(ref); err != nil {
return "", "", err
}
return ref, request.Version, nil
}
func (s *Service) Add(ctx context.Context, root string, args []string, ecosystem catalog.Ecosystem, opts install.Options) (*install.Result, error) {
d, old, err := commandDocuments(root, s.logger)
if err != nil {
return nil, err
}
if err := pinWorkspaceDocuments(&opts, d, old); err != nil {
return nil, err
}
opts.RequirementChange = true
ecosystem = selectedEcosystem(d, ecosystem)
if ecosystem == catalog.EcosystemUnspecified {
return nil, fmt.Errorf("specify a package ecosystem supported by the declared server")
}
for _, raw := range args {
ref, selector, err := commandReference(d, old, raw, ecosystem)
if err != nil {
return nil, err
}
provider, _, err := documentpkg.ParseReference(ref)
if err != nil {
return nil, err
}
// The manifest stores MCDR packages in a separate block. A package
// provider that does not serve the selected environment would be
// written where resolution can never select it.
if (provider == catalog.ProviderMCDR) != (ecosystem == catalog.EcosystemMCDR) {
return nil, fmt.Errorf(
"provider %s cannot supply %s packages",
provider,
ecosystem,
)
}
packages := d.Server.Packages[ecosystem]
if ecosystem == catalog.EcosystemMCDR {
if d.MCDR == nil {
return nil, fmt.Errorf("manifest has no MCDR runtime")
}
packages = d.MCDR.Packages
}
if existing, ok := packages[ref]; ok {
// A bare add enables an existing declaration without discarding
// its version pin or file pattern. Explicit selectors still edit it.
explicit := strings.Contains(raw, "@")
if existing.IsEnabled() && (!explicit || selector == existing.Selector) {
continue
}
if explicit {
existing.Selector = selector
}
existing.Enabled = new(true)
packages[ref] = existing
} else {
if packages == nil {
packages = make(map[string]documentpkg.Requirement)
if ecosystem == catalog.EcosystemMCDR {
d.MCDR.Packages = packages
} else {
d.Server.Packages[ecosystem] = packages
}
}
packages[ref] = documentpkg.Requirement{Selector: selector, Enabled: new(true)}
}
opts.PublishManifest = true
}
return s.install.Sync(ctx, root, d, old, opts)
}
func (s *Service) Remove(ctx context.Context, root string, args []string, ecosystem catalog.Ecosystem, opts install.Options) (*install.Result, error) {
d, old, err := commandDocuments(root, s.logger)
if err != nil {
return nil, err
}
if err := pinWorkspaceDocuments(&opts, d, old); err != nil {
return nil, err
}
opts.RequirementChange = true
ecosystem = selectedEcosystem(d, ecosystem)
for _, raw := range args {
ref, _, err := commandReference(d, old, raw, ecosystem)
if err != nil {
return nil, err
}
packages := d.Server.Packages[ecosystem]
if ecosystem == catalog.EcosystemMCDR {
if d.MCDR == nil {
return nil, fmt.Errorf("manifest has no MCDR runtime")
}
packages = d.MCDR.Packages
}
if _, ok := packages[ref]; !ok {
return nil, fmt.Errorf("direct requirement %s not found in %s", ref, ecosystem)
}
delete(packages, ref)
}
opts.PublishManifest = true
return s.install.Sync(ctx, root, d, old, opts)
}
package operation
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/catalog"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
// CreateKind identifies the machine-readable document this operation emits.
const CreateKind = "create"
// CreateOptions describes a new workspace declaration and the installation
// that may follow it. Directory names the workspace root; the server occupies
// that directory directly.
type CreateOptions struct {
Directory string
Name string
Minecraft string
Product string
ProductVersion string
MCDRVersion string
Force bool
Install bool
InstallOptions install.Options
Trace *install.Trace
// Materialize supplies artifact bytes for planning and the optional
// installation. Nil uses the configured cache and network.
Materialize artifact.Materializer
}
// CreateTarget is the result of observing a directory before creation. It
// writes nothing.
type CreateTarget struct {
Path string
Exists bool
NonEmpty bool
ManifestExists bool
DeclaredPackages int
Entries []string
}
// CreateResult projects the resolution and optional installation into one
// document. The embedded result carries the shared operation facts; the
// surrounding fields describe the workspace itself.
type CreateResult struct {
install.Result
Workspace string `json:"workspace"`
NonEmpty bool `json:"non_empty"`
ReplacedManifest bool `json:"replaced_manifest,omitempty"`
Installed bool `json:"installed"`
Manifest *documentpkg.Manifest `json:"-"`
Lock *documentpkg.Lock `json:"-"`
}
// CreateResolveError reports a failure before any workspace document was
// written. Workspace may already exist because resolution needs its download
// store.
type CreateResolveError struct {
Workspace string
Product serverpkg.Product
Minecraft version.Version
Selector version.Version
Err error
}
func (e *CreateResolveError) Error() string { return e.Err.Error() }
func (e *CreateResolveError) Unwrap() error { return e.Err }
// CreatePublishError reports a failure while publishing the manifest and lock.
type CreatePublishError struct {
Workspace string
ManifestWritten bool
Err error
}
func (e *CreatePublishError) Error() string { return e.Err.Error() }
func (e *CreatePublishError) Unwrap() error { return e.Err }
// CreateRegistrationError reports that the manifest and lock were published
// but the workspace could not be recorded for the artifact store's retention
// sweep. The documents stay in place so a later attempt can register them.
type CreateRegistrationError struct {
Workspace string
Err error
}
func (e *CreateRegistrationError) Error() string { return e.Err.Error() }
func (e *CreateRegistrationError) Unwrap() error { return e.Err }
// CreateInstallError reports a failure after the workspace was published. The
// manifest and lock stay in place so the installation can be retried.
type CreateInstallError struct {
Workspace string
Err error
}
func (e *CreateInstallError) Error() string { return e.Err.Error() }
func (e *CreateInstallError) Unwrap() error { return e.Err }
// InspectCreateTarget observes path without creating it. Entries carries at
// most five names so a later warning can name what is already there.
func InspectCreateTarget(path string) (CreateTarget, error) {
absolute, err := createAbsolute(path)
if err != nil {
return CreateTarget{}, err
}
target := CreateTarget{Path: absolute}
info, err := os.Stat(absolute)
if errors.Is(err, os.ErrNotExist) {
return target, nil
}
if err != nil {
return target, err
}
if !info.IsDir() {
return target, fmt.Errorf("creation target is not a directory: %s", absolute)
}
target.Exists = true
directory, err := os.Open(absolute)
if err != nil {
return target, err
}
entries, readErr := directory.ReadDir(5)
closeErr := directory.Close()
if readErr != nil && !errors.Is(readErr, io.EOF) && !errors.Is(readErr, os.ErrNotExist) {
return target, errors.Join(readErr, closeErr)
}
if closeErr != nil {
return target, closeErr
}
target.NonEmpty = len(entries) > 0
for _, entry := range entries {
target.Entries = append(target.Entries, entry.Name())
}
_, err = os.Stat(filepath.Join(absolute, documentpkg.ManifestFilename))
switch {
case err == nil:
target.ManifestExists = true
if document, readErr := documentpkg.ManifestFile(absolute).Read(); readErr == nil {
target.DeclaredPackages = declaredPackageCount(document)
}
case errors.Is(err, os.ErrNotExist):
default:
return target, err
}
return target, nil
}
// Create writes a new manifest and lock in opts.Directory, then optionally
// installs the server. It does not prompt; the command boundary owns choices.
func (s *Service) Create(ctx context.Context, opts CreateOptions) (result *CreateResult, resultErr error) {
root, err := createAbsolute(opts.Directory)
if err != nil {
return nil, err
}
target, err := InspectCreateTarget(root)
if err != nil {
return nil, err
}
if target.ManifestExists && !opts.Force {
return nil, fmt.Errorf(
"lucy.yaml exists in %s; pass --force to replace declared intent",
target.Path,
)
}
if err := os.MkdirAll(root, 0o755); err != nil {
return nil, err
}
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
releaseWriter := func() error {
if writer == nil {
return nil
}
closeErr := writer.Close()
writer = nil
return closeErr
}
defer func() { resultErr = errors.Join(resultErr, releaseWriter()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
manifestExisted := false
switch _, err := os.Stat(filepath.Join(root, documentpkg.ManifestFilename)); {
case err == nil:
manifestExisted = true
if !opts.Force {
return nil, fmt.Errorf(
"lucy.yaml exists in %s; pass --force to replace declared intent",
root,
)
}
case errors.Is(err, os.ErrNotExist):
default:
return nil, err
}
var replaced *documentpkg.Manifest
if opts.Force && manifestExisted {
replaced, _ = documentpkg.ManifestFile(root).Read()
}
old, err := documentpkg.LockFile(root).Read()
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if errors.Is(err, os.ErrNotExist) {
old = nil
}
name := strings.TrimSpace(opts.Name)
if name == "" {
name = filepath.Base(root)
}
document := newCreateDocument(opts, name)
if err := document.Normalize(); err != nil {
return nil, newCreateResolveError(root, document, err)
}
resolved, resolution, err := s.install.Resolve(
ctx,
root,
document,
old,
install.Options{
AcceptBroken: false,
Trace: opts.Trace,
Materialize: opts.Materialize,
},
)
if err != nil {
return nil, newCreateResolveError(root, document, err)
}
manifestFile := documentpkg.ManifestFile(root)
if opts.Force {
manifestFile = manifestFile.WithoutMerge()
}
if err := manifestFile.Write(document); err != nil {
return nil, &CreatePublishError{Workspace: root, Err: err}
}
publishedLock := resolved != old
if publishedLock {
if err := documentpkg.LockFile(root).Write(resolved); err != nil {
return nil, &CreatePublishError{
Workspace: root,
ManifestWritten: true,
Err: err,
}
}
}
result = &CreateResult{
Workspace: root,
NonEmpty: target.NonEmpty,
ReplacedManifest: manifestExisted,
Manifest: document,
Lock: resolved,
}
if resolution != nil {
result.Result = *resolution
}
result.Schema = install.ResultSchema
result.Kind = CreateKind
if result.Mode == "" {
result.Mode = install.ModeResolve
}
if result.Mode == install.ModeResolve {
result.Reason = "new workspace"
}
result.Server = install.ServerChange{
Change: install.ChangeAdded,
Product: resolved.Server.Product,
Minecraft: resolved.Server.Minecraft,
Version: resolved.Server.CoreVersion,
}
result.TotalPackages = len(resolved.Packages)
result.PublishedManifest = true
result.PublishedLock = publishedLock
if replaced != nil {
if count := declaredPackageCount(replaced); count > 0 {
result.Warnings = append(result.Warnings, fmt.Errorf(
"replaced an existing manifest that declared %s",
packageCountLabel(count),
))
}
}
duplicates, err := s.registerWorkspace(root)
if err != nil {
result.finalizeWarnings()
return result, &CreateRegistrationError{
Workspace: root,
Err: fmt.Errorf("register server: %w", err),
}
}
for _, duplicate := range duplicates {
result.Warnings = append(result.Warnings, fmt.Errorf(
"server name %q is also registered at %s; --server cannot select an ambiguous name",
duplicate.Name,
duplicate.Path,
))
}
if opts.Install {
// Installation acquires the workspace writer lock itself.
if err := releaseWriter(); err != nil {
return result, err
}
installOptions := opts.InstallOptions
installOptions.Trace = opts.Trace
if opts.Materialize != nil {
installOptions.Materialize = opts.Materialize
}
if err := pinWorkspaceDocuments(&installOptions, document, resolved); err != nil {
return result, err
}
installed, installErr := s.install.Sync(
ctx,
root,
document,
resolved,
installOptions,
)
if installed != nil {
result.Files = installed.Files
result.Fetch.Cached += installed.Fetch.Cached
result.Fetch.Downloaded += installed.Fetch.Downloaded
result.Fetch.Bytes += installed.Fetch.Bytes
result.Phases = append(result.Phases, installed.Phases...)
result.Diagnostics = append(result.Diagnostics, installed.Diagnostics...)
result.Java = installed.Java
result.Packages = installed.Packages
result.Warnings = append(result.Warnings, installed.Warnings...)
result.PublishedManifest = result.PublishedManifest || installed.PublishedManifest
result.PublishedLock = result.PublishedLock || installed.PublishedLock
}
if installErr != nil {
if _, committed := errors.AsType[*install.CommittedError](installErr); committed {
result.Installed = true
}
result.finalizeWarnings()
return result, &CreateInstallError{Workspace: root, Err: installErr}
}
result.Installed = true
}
result.finalizeWarnings()
return result, nil
}
func (r *CreateResult) finalizeWarnings() {
seen := make(map[string]struct{}, len(r.Warnings))
unique := r.Warnings[:0]
for _, warning := range r.Warnings {
if _, duplicate := seen[warning.Error()]; duplicate {
continue
}
seen[warning.Error()] = struct{}{}
unique = append(unique, warning)
}
r.Warnings = unique
r.WarningMessages = warningStrings(r.Warnings)
if r.NonEmpty {
r.WarningMessages = append(
r.WarningMessages,
"the target directory was not empty; existing files are left in place",
)
}
}
func newCreateResolveError(
root string,
document *documentpkg.Manifest,
err error,
) *CreateResolveError {
return &CreateResolveError{
Workspace: root,
Product: document.Server.Core.Product,
Minecraft: document.Server.Minecraft,
Selector: document.Server.Core.ProductVersion,
Err: err,
}
}
func newCreateDocument(opts CreateOptions, name string) *documentpkg.Manifest {
product := serverpkg.ProductMinecraft
if productName := strings.TrimSpace(opts.Product); productName != "" {
if parsed, known := serverpkg.ParseProduct(productName); known {
product = parsed
} else {
product = serverpkg.Product(strings.ToLower(productName))
}
}
document := &documentpkg.Manifest{
SchemaVersion: documentpkg.ManifestSchemaVersion,
Name: name,
Server: documentpkg.ManifestServer{
Minecraft: version.Version(strings.TrimSpace(opts.Minecraft)),
Directory: ".",
Core: documentpkg.ManifestCore{
Product: product,
ProductVersion: version.Version(strings.TrimSpace(opts.ProductVersion)),
},
Packages: map[catalog.Ecosystem]map[string]documentpkg.Requirement{},
},
}
if opts.MCDRVersion != "" {
document.MCDR = &documentpkg.ManifestMCDR{
Directory: ".",
Version: version.Version(strings.TrimSpace(opts.MCDRVersion)),
Packages: map[string]documentpkg.Requirement{},
}
}
return document
}
func declaredPackageCount(document *documentpkg.Manifest) int {
if document == nil {
return 0
}
count := 0
for _, packages := range document.Server.Packages {
count += len(packages)
}
if document.MCDR != nil {
count += len(document.MCDR.Packages)
}
return count
}
func warningStrings(warnings []error) []string {
messages := make([]string, 0, len(warnings))
for _, warning := range warnings {
if warning != nil {
messages = append(messages, warning.Error())
}
}
return messages
}
func packageCountLabel(count int) string {
if count == 1 {
return "1 package"
}
return fmt.Sprintf("%d packages", count)
}
// createAbsolute expands a leading home marker before resolving a creation
// path. The interactive form cannot rely on a shell to do it.
func createAbsolute(path string) (string, error) {
path = strings.TrimSpace(path)
if path == "~" || strings.HasPrefix(path, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
if path == "~" {
path = home
} else {
path = filepath.Join(home, strings.TrimPrefix(path, "~/"))
}
}
return filepath.Abs(path)
}
package operation
import (
"crypto/rand"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/workspacewrite"
)
// DeinitResult reports the Lucy state that deinitialization removed. Paths are
// relative to the server root and listed in removal order. Displaced names the
// directory that keeps the files earlier installations displaced, or is empty
// when there were none.
type DeinitResult struct {
Removed []string
Displaced string
Warnings []error
}
// Deinitialize removes every path that marks root as a Lucy workspace and
// leaves the server it describes in place. Installed server content, worlds,
// and configuration stay untouched. Files that installations displaced move
// out of the state directory first, because Lucy never deletes them. An
// interrupted installation or file transaction is recovered before state is
// removed, and the writer lock keeps another Lucy process from writing while
// the state disappears.
func (s *Service) Deinitialize(root string) (result *DeinitResult, resultErr error) {
root, err := filepath.Abs(root)
if err != nil {
return nil, err
}
present, err := presentWorkspacePaths(root)
if err != nil {
return nil, err
}
if len(present) == 0 {
return nil, fmt.Errorf("no lucy workspace found in %s", root)
}
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
// Recovery can publish declarations that an interrupted transaction
// restored, so observe the workspace again before removing anything.
present, err = presentWorkspacePaths(root)
if err != nil {
return nil, err
}
result = &DeinitResult{}
displaced, err := keepDisplacedFiles(root)
if err != nil {
return result, err
}
result.Displaced = displaced
for _, name := range []string{
document.ManifestFilename,
document.LockFilename,
} {
if !slices.Contains(present, name) {
continue
}
if err := os.Remove(filepath.Join(root, name)); err != nil {
return result, err
}
result.Removed = append(result.Removed, name)
s.logger.Debug("workspace state removed", "path", name)
}
if s.registry == nil {
result.Warnings = append(
result.Warnings,
errors.New(
"server unregistration unavailable: no server registry was supplied; registered entries for this workspace may remain",
),
)
} else if err := s.registry.Unregister(root); err != nil {
result.Warnings = append(result.Warnings, fmt.Errorf("server unregistration failed: %w", err))
}
detached, err := detachWorkspaceState(root)
if err != nil {
return result, err
}
if err := writer.Close(); err != nil {
return result, err
}
if err := removeDetachedState(root, detached); err != nil {
return result, err
}
result.Removed = append(result.Removed, fsutil.WorkspaceMarker)
s.logger.Info("workspace deinitialized", "root", root, "removed", len(result.Removed))
return result, nil
}
// workspaceStatePaths names every top-level path that marks a Lucy workspace.
func workspaceStatePaths() []string {
return []string{
document.ManifestFilename,
document.LockFilename,
fsutil.WorkspaceMarker,
}
}
// presentWorkspacePaths returns the state paths that exist in root. Symlinks
// and wrong file kinds fail instead of being removed, so a link cannot redirect
// deletion outside the workspace.
func presentWorkspacePaths(root string) ([]string, error) {
present := make([]string, 0, len(workspaceStatePaths()))
for _, name := range workspaceStatePaths() {
if err := workspacewrite.SafePath(root, name); err != nil {
return nil, err
}
info, err := os.Lstat(filepath.Join(root, name))
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
if name == fsutil.WorkspaceMarker {
if !info.IsDir() {
return nil, fmt.Errorf("%s must be a directory", name)
}
} else if !info.Mode().IsRegular() {
return nil, fmt.Errorf("%s must be a regular file", name)
}
present = append(present, name)
}
return present, nil
}
// detachWorkspaceState moves the state directory aside while the writer lock
// is held. A writer that acquires the lock after this rename creates a new
// directory and a new lock file, so removing the detached one cannot pull the
// inode out from under it.
func detachWorkspaceState(root string) (string, error) {
detached := fsutil.WorkspaceMarker + "-removed-" + rand.Text()
if err := os.Rename(
filepath.Join(root, fsutil.WorkspaceMarker),
filepath.Join(root, detached),
); err != nil {
return "", err
}
return detached, nil
}
// removeDetachedState deletes the detached state directory after the writer
// lock is released. Root-confined removal keeps a symlink inside it from
// redirecting the deletion.
func removeDetachedState(root, detached string) (resultErr error) {
files, err := os.OpenRoot(root)
if err != nil {
return err
}
defer func() { resultErr = errors.Join(resultErr, files.Close()) }()
return files.RemoveAll(detached)
}
// keepDisplacedFiles moves the displaced-file directory to the server root and
// returns its new name, or an empty name when no installation displaced a
// file. A free name is chosen, so an earlier kept directory stays intact.
func keepDisplacedFiles(root string) (string, error) {
source := filepath.Join(root, filepath.FromSlash(workspacewrite.DisplacedRoot))
if err := workspacewrite.SafePath(root, workspacewrite.DisplacedRoot); err != nil {
return "", err
}
info, err := os.Lstat(source)
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", err
}
if !info.IsDir() {
return "", fmt.Errorf("%s must be a directory", workspacewrite.DisplacedRoot)
}
name := "lucy-displaced"
if _, err := os.Lstat(filepath.Join(root, name)); err == nil {
name += "-" + rand.Text()
} else if !errors.Is(err, os.ErrNotExist) {
return "", err
}
files, err := os.OpenRoot(root)
if err != nil {
return "", err
}
renameErr := fsutil.RenameDirRoot(files, filepath.FromSlash(workspacewrite.DisplacedRoot), name)
if err := errors.Join(renameErr, files.Close()); err != nil {
return "", fmt.Errorf("keep displaced files: %w", err)
}
return name, nil
}
package operation
import (
"context"
"errors"
"fmt"
"path/filepath"
"slices"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/resolve"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream/routing"
)
// DowngradeOptions selects an older published version for direct manifest
// roots. Every target moves by the same number of eligible versions.
type DowngradeOptions struct {
// Steps counts eligible older versions to move: one selects the version
// immediately older than the lock, two the next one, and so on. Zero means
// one; negative values are invalid.
Steps int
// AcceptPackageConflicts reports package module and metadata conflicts as
// warnings. Runtime-provided requirements and acquisition failures stay
// fatal.
AcceptPackageConflicts bool
// Install carries the shared installation options. Locked and Offline are
// rejected because a downgrade must resolve candidate history.
Install install.Options
}
// Downgrade moves each requested direct root to an older published version,
// then resolves and installs the whole graph as one transaction. The runtime
// and the packages nobody requested stay at their locked versions where the
// dependency graph allows it.
func (s *Service) Downgrade(
ctx context.Context,
root string,
args []string,
ecosystem catalog.Ecosystem,
opts DowngradeOptions,
) (result *install.Result, resultErr error) {
steps := opts.Steps
switch {
case steps < 0:
return nil, fmt.Errorf("downgrade steps must not be negative")
case steps == 0:
steps = 1
}
if len(args) == 0 {
return nil, fmt.Errorf("downgrade requires at least one direct package")
}
if opts.Install.Locked {
return nil, fmt.Errorf("downgrade cannot run with --locked; it must resolve an older version")
}
if opts.Install.Offline {
return nil, fmt.Errorf("downgrade cannot run with --offline; candidate history requires network access")
}
absolute, err := filepath.Abs(root)
if err != nil {
return nil, err
}
root = absolute
d, old, err := commandDocuments(root, s.logger)
if err != nil {
return nil, err
}
if old == nil {
return nil, fmt.Errorf("lucy-lock.yaml is required; run lucy install first")
}
baseManifest, err := d.Fingerprint()
if err != nil {
return nil, err
}
if old.ManifestFingerprint != baseManifest {
return nil, fmt.Errorf("manifest changed since the lock; run lucy install first")
}
baseLock, err := old.Fingerprint()
if err != nil {
return nil, err
}
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
// Recovery may have replaced documents, so capture their exact state now:
// this is the base the plan answers, and ApplyPlan may write nothing else.
baseDocuments, err := install.CaptureWorkspaceDocuments(root)
if err != nil {
return nil, err
}
if err := verifyRecoveredBase(
baseDocuments,
baseManifest,
d.Name,
baseLock,
"downgrade",
); err != nil {
return nil, err
}
targets, err := s.selectDowngradeTargets(ctx, d, old, args, ecosystem, steps)
if err != nil {
return nil, err
}
materialize, fetch := s.install.Materializer(opts.Install)
// The lock's core modules describe the frozen runtime. A lock that
// predates recording them needs the artifact, and failing to read it
// would make the resolution answer a different runtime.
coreModules, err := routing.CoreModules(
ctx,
old.Server.Product,
old.Server.Artifact,
materialize,
)
if err != nil {
return nil, fmt.Errorf("read server core modules: %w", err)
}
nextManifest, err := cloneManifest(d)
if err != nil {
return nil, err
}
var manifestChanges []install.ManifestChange
for _, target := range targets {
if err := setDowngradeSelector(nextManifest, target, target.Version); err != nil {
return nil, err
}
if target.Requirement.Selector == target.Version {
continue
}
manifestChanges = append(manifestChanges, install.ManifestChange{
Reference: target.Reference,
PreviousSelector: target.Requirement.Selector,
Selector: target.Version,
})
}
candidates, err := downgradeCandidateSource(s.source.Candidates, targets)
if err != nil {
return nil, err
}
lockTarget := upgradeTarget(old, coreModules)
packages, warnings, err := resolve.Packages(resolve.PackagesRequest{
Context: ctx,
Manifest: nextManifest,
Previous: old.Packages,
PreviousTarget: lockTarget,
Target: lockTarget,
Candidates: candidates,
Materialize: materialize,
WithOptional: opts.Install.WithOptional,
AcceptPackageConflicts: opts.AcceptPackageConflicts,
ExpandDependencies: true,
Cache: resolve.NewAnalysisCache(),
Logger: s.logger,
Trace: upgradeResolveTrace(opts.Install.Trace),
})
if err != nil {
return nil, err
}
if err := verifyDowngradeSelection(packages, targets); err != nil {
return nil, err
}
if opts.Install.WithOptional {
if err := recordResolvedRequirements(nextManifest, packages); err != nil {
return nil, err
}
}
if err := nextManifest.Normalize(); err != nil {
return nil, err
}
requirements := rootRequirements(nextManifest)
for i := range packages {
for j := range packages[i].Requirements {
binding := &packages[i].Requirements[j]
requirement, ok := requirements[binding.Reference]
if !ok {
continue
}
binding.Selector = requirement.Selector
binding.FilePattern = requirement.FilePattern
binding.Enabled = requirement.IsEnabled()
}
}
nextFingerprint, err := nextManifest.Fingerprint()
if err != nil {
return nil, err
}
resolved := &document.Lock{
SchemaVersion: document.LockSchemaVersion,
ManifestFingerprint: nextFingerprint,
Server: old.Server,
MCDR: old.MCDR,
Packages: packages,
Files: slices.Clone(nextManifest.Files),
}
if err := resolved.Validate(); err != nil {
return nil, err
}
publishManifest := true
plan, err := install.PlanFromResolution(
baseDocuments,
nextManifest,
old,
resolved,
publishManifest,
)
if err != nil {
return nil, err
}
plan.Result.Kind = install.ResultKind
plan.Result.Reason = "package downgrade"
plan.Result.ManifestChanges = manifestChanges
plan.Result.Warnings = warnings
plan.Result.Fetch = *fetch
// ApplyPlan takes the writer lock itself and rechecks the fingerprints
// this plan recorded, so the planning lock must be released first.
if err := writer.Close(); err != nil {
return nil, err
}
applyOpts := opts.Install
applyOpts.Locked = false
applyOpts.Offline = false
applyOpts.AcceptBroken = false
applyOpts.Overwrite = false
applyOpts.ForceResolve = false
applyOpts.RequirementChange = false
applyOpts.PublishManifest = publishManifest
return s.install.ApplyPlan(ctx, root, plan, applyOpts)
}
// recordResolvedRequirements adds optional dependencies without replacing
// selectors, file patterns, or enabled state already declared in the manifest.
func recordResolvedRequirements(d *document.Manifest, packages []document.Package) error {
for i := range packages {
p := &packages[i]
for _, requirement := range p.Requirements {
if _, _, declared := downgradeRootRequirement(d, p.Ecosystem, requirement.Reference); declared {
continue
}
recorded := document.Requirement{
Selector: requirement.Selector,
FilePattern: requirement.FilePattern,
Enabled: new(requirement.Enabled),
}
if p.Environment == serverpkg.EnvironmentMCDR {
if d.MCDR == nil {
return fmt.Errorf("resolution selected MCDR package %s but the manifest has no MCDR runtime", p.ProjectID)
}
d.MCDR.Packages[requirement.Reference] = recorded
continue
}
if d.Server.Packages[p.Ecosystem] == nil {
d.Server.Packages[p.Ecosystem] = map[string]document.Requirement{}
}
d.Server.Packages[p.Ecosystem][requirement.Reference] = recorded
}
}
return nil
}
package operation
import (
"context"
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/resolve"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
// downgradeTarget is one direct manifest root pinned to a chosen older build.
type downgradeTarget struct {
Environment serverpkg.Environment
Ecosystem catalog.Ecosystem
Reference string
Requirement document.Requirement
Provider catalog.Provider
Project string
Previous *document.Package
Version versionpkg.Version
Candidate upstream.Candidate
}
// downgradePreviousKey identifies one locked upstream package. Two manifest
// references that share it name the same package and cannot be downgraded
// separately.
type downgradePreviousKey struct {
Provider catalog.Provider
Project string
Environment serverpkg.Environment
Ecosystem catalog.Ecosystem
}
// selectDowngradeTargets resolves each argument to an enabled direct manifest
// root and picks the older build the requested step count names.
func (s *Service) selectDowngradeTargets(
ctx context.Context,
d *document.Manifest,
old *document.Lock,
args []string,
ecosystem catalog.Ecosystem,
steps int,
) ([]downgradeTarget, error) {
ecosystem = selectedEcosystem(d, ecosystem)
if ecosystem == catalog.EcosystemUnspecified {
return nil, fmt.Errorf("specify a package ecosystem supported by the declared server")
}
targets := make([]downgradeTarget, 0, len(args))
seen := map[string]bool{}
seenPrevious := map[downgradePreviousKey]string{}
for _, raw := range args {
if err := ctx.Err(); err != nil {
return nil, err
}
request, err := input.Parse(raw)
if err != nil {
return nil, err
}
if strings.Contains(raw, "@") ||
(request.Version != "" && request.Version != versionpkg.Any) {
return nil, fmt.Errorf("downgrade targets name packages, not versions: %s", raw)
}
ref, _, err := commandReference(d, old, raw, ecosystem)
if err != nil {
return nil, err
}
if seen[ref] {
return nil, fmt.Errorf("package %s is named more than once", ref)
}
seen[ref] = true
environment, requirement, declared := downgradeRootRequirement(d, ecosystem, ref)
if !declared {
return nil, fmt.Errorf(
"package %s is not a direct requirement of ecosystem %s; only direct manifest packages can be downgraded",
ref,
ecosystem,
)
}
if !requirement.IsEnabled() {
return nil, fmt.Errorf("package %s is disabled in the manifest; enable it before downgrading", ref)
}
previous := downgradePreviousPackage(old, environment, ecosystem, ref)
if previous == nil {
return nil, fmt.Errorf("lock has no package for manifest root %s; run lucy install first", ref)
}
identity := downgradePreviousKey{
Provider: previous.Provider,
Project: previous.ProjectID,
Environment: previous.Environment,
Ecosystem: previous.Ecosystem,
}
if prior, exists := seenPrevious[identity]; exists {
return nil, fmt.Errorf(
"packages %s and %s are the same locked upstream package %s:%s; downgrade it once",
prior,
ref,
previous.Provider,
previous.ProjectID,
)
}
seenPrevious[identity] = ref
provider, project, err := document.ParseReference(ref)
if err != nil {
return nil, err
}
version, candidate, err := s.selectDowngradeVersion(
ctx,
old,
ref,
ecosystem,
requirement,
previous,
steps,
)
if err != nil {
return nil, err
}
targets = append(targets, downgradeTarget{
Environment: environment,
Ecosystem: ecosystem,
Reference: ref,
Requirement: requirement,
Provider: provider,
Project: project,
Previous: previous,
Version: version,
Candidate: candidate,
})
}
return targets, nil
}
func downgradeRootRequirement(
d *document.Manifest,
ecosystem catalog.Ecosystem,
ref string,
) (serverpkg.Environment, document.Requirement, bool) {
if ecosystem == catalog.EcosystemMCDR {
if d.MCDR == nil {
return serverpkg.EnvironmentMCDR, document.Requirement{}, false
}
requirement, ok := d.MCDR.Packages[ref]
return serverpkg.EnvironmentMCDR, requirement, ok
}
requirement, ok := d.Server.Packages[ecosystem][ref]
return serverpkg.EnvironmentServer, requirement, ok
}
func downgradePreviousPackage(
old *document.Lock,
environment serverpkg.Environment,
ecosystem catalog.Ecosystem,
ref string,
) *document.Package {
for i := range old.Packages {
p := &old.Packages[i]
if p.Environment != environment || p.Ecosystem != ecosystem {
continue
}
for _, binding := range p.Requirements {
if binding.Reference == ref {
return p
}
}
}
return nil
}
// selectDowngradeVersion picks the older version label at the requested step
// and one deterministic build inside that label. The locked version is the
// baseline; upstream ordering only decides which older labels exist.
func (s *Service) selectDowngradeVersion(
ctx context.Context,
old *document.Lock,
ref string,
ecosystem catalog.Ecosystem,
requirement document.Requirement,
previous *document.Package,
steps int,
) (versionpkg.Version, upstream.Candidate, error) {
dialect := upgradeArtifactDialect(ecosystem)
if !dialect.Valid() || dialect == versionpkg.DialectOpaque {
return "", upstream.Candidate{}, fmt.Errorf(
"%s package versions have no ordering; cannot downgrade %s",
ecosystem,
ref,
)
}
locked, err := versionpkg.ParseVersion(previous.Version, dialect)
if err != nil {
return "", upstream.Candidate{}, fmt.Errorf(
"locked version %s of %s is not a comparable %s version: %w",
previous.Version,
ref,
dialect,
err,
)
}
provider, project, err := document.ParseReference(ref)
if err != nil {
return "", upstream.Candidate{}, err
}
registry, ok := provider.Registry()
if !ok {
return "", upstream.Candidate{}, fmt.Errorf("provider %s has no package catalogue", provider)
}
list, err := s.source.Candidates(
ctx,
registry,
project,
string(old.Server.Minecraft),
ecosystem,
)
if err != nil {
return "", upstream.Candidate{}, fmt.Errorf("list %s builds: %w", ref, err)
}
records := map[versionpkg.Version]downgradeVersionRecord{}
for _, candidate := range list {
if requirement.FilePattern != "" {
match, err := filepath.Match(requirement.FilePattern, candidate.Filename)
if err != nil {
return "", upstream.Candidate{}, fmt.Errorf(
"invalid file pattern %q for %s: %w",
requirement.FilePattern,
ref,
err,
)
}
if !match {
continue
}
} else if !candidate.PrimaryFile {
continue
}
if record, seen := records[candidate.Version]; seen {
if betterDowngradeCandidate(candidate, record.best) {
record.best = candidate
records[candidate.Version] = record
}
continue
}
candidateVersion, err := versionpkg.ParseVersion(candidate.Version, dialect)
if err != nil {
s.logger.Debug(
"downgrade: candidate version is not comparable",
"package", ref,
"version", candidate.Version,
"error", err,
)
continue
}
comparison, comparable := versionpkg.Compare(candidateVersion, locked)
if !comparable || comparison >= 0 {
continue
}
records[candidate.Version] = downgradeVersionRecord{
parsed: candidateVersion,
best: candidate,
}
}
labels := make([]versionpkg.Version, 0, len(records))
for label := range records {
labels = append(labels, label)
}
slices.SortFunc(labels, func(a, b versionpkg.Version) int {
comparison, comparable := versionpkg.Compare(
records[a].parsed,
records[b].parsed,
)
if comparable && comparison != 0 {
return -comparison
}
return strings.Compare(string(a), string(b))
})
if steps > len(labels) {
return "", upstream.Candidate{}, fmt.Errorf(
"cannot downgrade %s from %s by %d step(s): only %d older version(s) available for Minecraft %s",
ref,
previous.Version,
steps,
len(labels),
old.Server.Minecraft,
)
}
selected := labels[steps-1]
return selected, records[selected].best, nil
}
type downgradeVersionRecord struct {
parsed versionpkg.ResolvableVersion
best upstream.Candidate
}
// betterDowngradeCandidate reports whether a wins over b for the same version
// label: the newest artifact, then stable lexical identity as a tie breaker.
func betterDowngradeCandidate(a, b upstream.Candidate) bool {
if n := a.PublishedAt.Compare(b.PublishedAt); n != 0 {
return n > 0
}
if n := strings.Compare(a.ReleaseID, b.ReleaseID); n != 0 {
return n < 0
}
if n := strings.Compare(a.FileID, b.FileID); n != 0 {
return n < 0
}
return a.Filename < b.Filename
}
type downgradeCandidateKey struct {
Registry catalog.Registry
Ecosystem catalog.Ecosystem
Project string
}
type downgradeCandidateChoice struct {
Candidate upstream.Candidate
Reference string
}
// downgradeCandidateSource restricts each target project to its chosen build,
// under both the manifest slug and the canonical upstream identity. Another
// version of the same project can never answer the downgrade request.
func downgradeCandidateSource(
next resolve.CandidateSource,
targets []downgradeTarget,
) (resolve.CandidateSource, error) {
chosen := map[downgradeCandidateKey]downgradeCandidateChoice{}
for _, target := range targets {
registry, ok := target.Provider.Registry()
if !ok {
return nil, fmt.Errorf("provider %s has no package catalogue", target.Provider)
}
var keys []downgradeCandidateKey
if target.Candidate.ProjectID != "" {
keys = append(keys, downgradeCandidateKey{
Registry: registry,
Ecosystem: target.Ecosystem,
Project: target.Candidate.ProjectID,
})
}
if target.Project != "" && target.Project != target.Candidate.ProjectID {
keys = append(keys, downgradeCandidateKey{
Registry: registry,
Ecosystem: target.Ecosystem,
Project: target.Project,
})
}
if target.Previous != nil &&
target.Previous.ProjectID != "" &&
target.Previous.ProjectID != target.Candidate.ProjectID &&
target.Previous.ProjectID != target.Project {
keys = append(keys, downgradeCandidateKey{
Registry: registry,
Ecosystem: target.Ecosystem,
Project: target.Previous.ProjectID,
})
}
for _, key := range keys {
if prior, exists := chosen[key]; exists && !sameDowngradeCandidate(prior.Candidate, target.Candidate) {
return nil, fmt.Errorf(
"packages %s and %s resolve to the same upstream project with different builds",
prior.Reference,
target.Reference,
)
}
chosen[key] = downgradeCandidateChoice{
Candidate: target.Candidate,
Reference: target.Reference,
}
}
}
return func(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
ecosystem catalog.Ecosystem,
) ([]upstream.Candidate, error) {
if choice, ok := chosen[downgradeCandidateKey{
Registry: registry,
Ecosystem: ecosystem,
Project: project,
}]; ok {
return []upstream.Candidate{choice.Candidate}, nil
}
return next(ctx, registry, project, minecraft, ecosystem)
}, nil
}
func sameDowngradeCandidate(a, b upstream.Candidate) bool {
return a.Provider == b.Provider &&
a.ProjectID == b.ProjectID &&
a.ReleaseID == b.ReleaseID &&
a.FileID == b.FileID &&
a.Version == b.Version &&
a.Filename == b.Filename
}
// verifyDowngradeSelection ensures resolution committed exactly the build the
// selection chose, not merely another build carrying the same version label.
func verifyDowngradeSelection(packages []document.Package, targets []downgradeTarget) error {
for _, target := range targets {
selected := downgradeSelectedPackage(packages, target)
if selected == nil {
return fmt.Errorf("resolution did not select %s", target.Reference)
}
candidate := target.Candidate
if selected.Version != candidate.Version ||
selected.Provider != candidate.Provider ||
selected.ProjectID != candidate.ProjectID ||
selected.ReleaseID != candidate.ReleaseID ||
selected.FileID != candidate.FileID {
return fmt.Errorf(
"resolution selected %s %s (%s:%s/%s) instead of requested %s (%s:%s/%s)",
target.Reference,
selected.Version,
selected.Provider,
selected.ReleaseID,
selected.FileID,
candidate.Version,
candidate.Provider,
candidate.ReleaseID,
candidate.FileID,
)
}
}
return nil
}
func downgradeSelectedPackage(packages []document.Package, target downgradeTarget) *document.Package {
for i := range packages {
p := &packages[i]
if p.Environment != target.Environment || p.Ecosystem != target.Ecosystem {
continue
}
for _, binding := range p.Requirements {
if binding.Reference == target.Reference {
return p
}
}
}
return nil
}
func setDowngradeSelector(
d *document.Manifest,
target downgradeTarget,
selector versionpkg.Version,
) error {
return setRootSelector(d, upgradeRoot{
Environment: target.Environment,
Ecosystem: target.Ecosystem,
Reference: target.Reference,
}, selector)
}
package operation
import (
"bufio"
"bytes"
"context"
"encoding/json/v2"
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/bootstrap"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/importpack"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/receipt"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
// Import stage names the command renders. A remote reference and a direct URL
// both fetch an archive, but only a remote reference is a modpack; a local
// source starts directly with writing files.
const (
importDownloadPackPhase = "download pack"
importDownloadArchivePhase = "download archive"
importFilesPhase = "files"
importClassificationPhase = "classification"
importLoaderPhase = "loader preparation"
)
// importWarningCause groups file warnings that share one cause so the import
// report can summarize repeats. The per-file warning stays a distinct error
// until ImportResult finalizes its messages.
type importWarningCause uint8
const (
importWarningLoaderMismatch importWarningCause = iota + 1
importWarningRemoteSide
importWarningNoProvider
importWarningNoServerModule
)
// importWarning is one file-level import warning with the cause that lets the
// report summarize several files into one line.
type importWarning struct {
cause importWarningCause
path string
message string
}
func (w *importWarning) Error() string {
return w.message
}
// newImportWarning records a warning whose path is already relative to the
// workspace.
func newImportWarning(
cause importWarningCause,
path, message string,
) *importWarning {
return &importWarning{cause: cause, path: path, message: message}
}
// groupImportWarnings replaces repeated per-file warnings with one line per
// cause. A single warning keeps its exact message so its file-specific detail
// stays visible.
func groupImportWarnings(warnings []error) []error {
groups := map[importWarningCause][]*importWarning{}
for _, warning := range warnings {
var grouped *importWarning
if errors.As(warning, &grouped) {
groups[grouped.cause] = append(groups[grouped.cause], grouped)
}
}
if len(groups) == 0 {
return warnings
}
grouped := make([]error, 0, len(warnings))
emitted := map[importWarningCause]bool{}
for _, warning := range warnings {
var fileWarning *importWarning
if !errors.As(warning, &fileWarning) {
grouped = append(grouped, warning)
continue
}
if len(groups[fileWarning.cause]) <= 1 {
grouped = append(grouped, warning)
continue
}
if emitted[fileWarning.cause] {
continue
}
emitted[fileWarning.cause] = true
grouped = append(grouped, errors.New(summarizeImportWarnings(
fileWarning.cause,
groups[fileWarning.cause],
)))
}
return grouped
}
// summarizeImportWarnings names one repeated cause, its count, and up to three
// example paths.
func summarizeImportWarnings(
cause importWarningCause,
warnings []*importWarning,
) string {
paths := make([]string, 0, len(warnings))
for _, warning := range warnings {
if warning.path == "" || slices.Contains(paths, warning.path) {
continue
}
paths = append(paths, warning.path)
}
count := len(paths)
if count == 0 {
count = len(warnings)
}
examples := firstExamples(paths, 3)
var subject string
switch cause {
case importWarningLoaderMismatch:
subject = "matched releases that target another loader"
case importWarningRemoteSide:
subject = "matched releases that exclude a dedicated server"
case importWarningNoProvider:
subject = "have no configured provider identity"
case importWarningNoServerModule:
subject = "have descriptors that declare no server-side module"
default:
subject = "were reported"
}
message := fmt.Sprintf("%s %s", packageCountLabel(count), subject)
if len(examples) > 0 {
message += " (examples: " + strings.Join(examples, ", ") + ")"
}
return message
}
// finalizeImportResult groups repeated warning causes and renders the strings
// the JSON result and CLI report expose.
func finalizeImportResult(result *ImportResult) {
if result == nil {
return
}
result.Warnings = groupImportWarnings(result.Warnings)
result.WarningMessages = warningStrings(result.Warnings)
}
// importDownloadPhase names the stage that fetches the source, or "" when the
// source is already local.
func importDownloadPhase(source string) string {
if _, remote, err := ParseRemoteImportSource(source); remote && err == nil {
return importDownloadPackPhase
}
if strings.Contains(source, "://") {
return importDownloadArchivePhase
}
return ""
}
// importProgress adapts the operation trace to importpack's download hooks. A
// nil trace reports nothing.
func importProgress(trace *install.Trace) importpack.Progress {
if trace == nil {
return importpack.Progress{}
}
return importpack.Progress{
FileStarted: trace.ReportFetchStarted,
FileProgress: trace.ReportFetchProgress,
FileDone: trace.ReportFetchDone,
}
}
// errImportNotInitialized reports an imported tree with no runtime. The tree
// stays extracted in the target, and the operator initializes it once the
// modpack is set up.
var errImportNotInitialized = errors.New(
"no server detected; the archive was extracted as-is. " +
"Run `lucy init` once the modpack is set up.",
)
// importSource adopts an external server archive as a new workspace. The
// archive is materialized and initialized in a private staging directory
// beside the target, so the target is untouched until every check that can
// fail has passed.
func (s *Service) importSource(
ctx context.Context,
opts ImportOptions,
network *cache.Client,
) (result *ImportResult, resultErr error) {
target, err := importTargetPath(opts.Directory)
if err != nil {
return nil, err
}
if s.registry == nil {
return nil, errors.New(
"server registry is unavailable; cannot record the imported workspace",
)
}
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() {
closeErr := lease.Close()
if closeErr == nil {
return
}
if resultErr == nil && result != nil {
result.Warnings = append(result.Warnings, fmt.Errorf(
"release import operation lease: %w", closeErr,
))
finalizeImportResult(result)
return
}
resultErr = errors.Join(resultErr, closeErr)
}()
downloadPhase := importDownloadPhase(opts.Source)
downloadStarted := time.Now()
if downloadPhase != "" {
opts.Trace.ReportPhaseStarted(downloadPhase)
}
progress := importProgress(opts.Trace)
sourcePath, source, releaseSource, err := s.resolveImportSource(
ctx,
opts.Source,
opts.SHA256,
network,
progress,
)
if err != nil {
return nil, err
}
defer releaseSource()
if downloadPhase != "" {
opts.Trace.ReportPhase(install.PhaseInfo{
Name: downloadPhase,
Elapsed: time.Since(downloadStarted),
})
}
name := opts.Name
if name == "" {
name = filepath.Base(target)
}
parent := filepath.Dir(target)
rollbackParents, err := createImportParents(parent)
if err != nil {
return nil, err
}
stage := ""
stageRegistered := false
published := false
defer func() {
if published {
return
}
if stageRegistered {
resultErr = errors.Join(resultErr, s.unregisterWorkspace(stage))
}
if stage != "" {
resultErr = errors.Join(resultErr, os.RemoveAll(stage))
}
rollbackParents()
}()
stage, err = os.MkdirTemp(parent, ".lucy-import-*")
if err != nil {
return nil, fmt.Errorf("create import staging directory: %w", err)
}
if err := os.Chmod(stage, 0o755); err != nil {
return nil, fmt.Errorf("prepare import staging directory: %w", err)
}
filesStarted := time.Now()
opts.Trace.ReportPhaseStarted(importFilesPhase)
materialized, err := importpack.Materialize(
ctx,
sourcePath,
stage,
network,
progress,
)
if err != nil {
return nil, err
}
filesElapsed := time.Since(filesStarted)
analyses := new(artifact.Analyses)
var matches map[string]upstream.ArtifactReleaseResolution
var removalWarnings []error
if materialized.Format == importpack.FormatMrpack {
// A client modpack marks its client-only files server-required, so the
// env declaration alone cannot exclude them from a server.
classificationStarted := time.Now()
opts.Trace.ReportPhaseStarted(importClassificationPhase)
removed, warnings, classified, releases, err := s.removeClientOnlyMods(
ctx,
stage,
materialized.Product,
materialized.Minecraft,
analyses,
opts.Trace,
)
if err != nil {
return nil, err
}
removalWarnings = warnings
matches = releases
materialized.RecordClientOnlyRemoval(removed)
opts.Trace.ReportPhase(install.PhaseInfo{
Name: importClassificationPhase,
Elapsed: time.Since(classificationStarted),
Count: classified - len(removed),
Total: classified,
})
}
opts.Trace.ReportPhase(install.PhaseInfo{
Name: importFilesPhase,
Elapsed: filesElapsed,
Count: materialized.ServerFiles,
})
var loaderWarnings []error
force := false
if materialized.Format == importpack.FormatMrpack {
loaderStarted := time.Now()
opts.Trace.ReportPhaseStarted(importLoaderPhase)
if err := s.installDeclaredLoader(ctx, stage, name, materialized, opts.Trace); err != nil {
return nil, err
}
opts.Trace.ReportPhase(install.PhaseInfo{
Name: importLoaderPhase,
Elapsed: time.Since(loaderStarted),
})
force = true
} else {
loaderWarnings, err = s.runTreeInstaller(ctx, stage, opts.Trace)
if err != nil {
return nil, err
}
}
stageRegistered = true
initResult, initErr := s.initialize(ctx, stage, InitOptions{
Name: name,
MCDRVersion: opts.MCDRVersion,
Force: force,
NoComments: opts.NoComments,
Expectation: opts.Expectation,
PromptRuntime: opts.PromptRuntime,
Trace: opts.Trace,
}, analyses, matches)
uninitialized := errors.Is(initErr, errNoServerDetected)
if initErr != nil && !uninitialized {
return nil, initErr
}
if uninitialized {
// applyRuntimeIdentity refuses before registration and document
// publication, so the stage was never registered.
stageRegistered = false
result, err = publishUninitializedImport(
stage,
target,
name,
source,
materialized.Format,
materialized,
loaderWarnings,
initResult,
analyses,
)
if err != nil {
return nil, err
}
published = true
return result, nil
}
manifest := initResult.Document
lock := initResult.Lock
observed := workspace.ObserveWithAnalyses(stage, discovery.Request{}, analyses)
unmanaged, err := unmanagedImportFiles(stage, observed)
if err != nil {
return nil, err
}
review := importReview(filepath.Join(stage, filepath.FromSlash(manifest.Server.Directory)))
// Hold the stage's writer lock across publication and registration. The
// rename moves the lock into the target, so another operation cannot enter
// between the workspace becoming visible and its registration.
writer, err := workspacewrite.Lock(stage, s.logger)
if err != nil {
return nil, err
}
writerHeld := true
defer func() {
if writerHeld {
resultErr = errors.Join(resultErr, writer.Close())
}
}()
publication, err := publishImportStage(stage, target)
if err != nil {
return nil, err
}
published = true
result = &ImportResult{
Workspace: target,
Initialized: true,
Source: source,
Format: string(materialized.Format),
Name: manifest.Name,
Minecraft: string(manifest.Server.Minecraft),
Product: string(manifest.Server.Core.Product),
CoreVersion: string(manifest.Server.Core.ProductVersion),
ServerFiles: materialized.ServerFiles,
SkippedClient: materialized.SkippedClient,
Overrides: materialized.Overrides,
Skipped: materialized.Skipped,
Unmanaged: unmanaged,
Review: review,
Manifest: manifest,
Lock: lock,
Warnings: append(
append(
append([]error(nil), initResult.Warnings...),
removalWarnings...,
),
loaderWarnings...,
),
Discovery: initResult.Discovery.RebasePaths(stage, target),
}
if lock != nil {
result.ManagedPackages = len(lock.Packages)
}
duplicates, regErr := s.registerWorkspace(target)
if regErr != nil {
rollbackErr := publication.rollback()
closeErr := writer.Close()
writerHeld = false
if rollbackErr != nil {
return result, errors.Join(
fmt.Errorf("register imported workspace: %w", regErr),
fmt.Errorf("rollback published workspace: %w", rollbackErr),
)
}
published = false
return result, errors.Join(
fmt.Errorf("register imported workspace: %w", regErr),
closeErr,
)
}
closeErr := writer.Close()
writerHeld = false
if closeErr != nil {
return result, fmt.Errorf("release imported workspace lock: %w", closeErr)
}
if err := s.unregisterWorkspace(stage); err != nil {
result.Warnings = append(result.Warnings, fmt.Errorf(
"remove import staging registration: %w", err,
))
}
stageRegistered = false
if err := os.RemoveAll(stage); err != nil {
result.Warnings = append(result.Warnings, fmt.Errorf(
"remove import staging directory: %w", err,
))
}
for _, duplicate := range duplicates {
result.Warnings = append(result.Warnings, fmt.Errorf(
"server name %q is also registered at %s; --server cannot select an ambiguous name",
duplicate.Name,
duplicate.Path,
))
}
finalizeImportResult(result)
return result, nil
}
// publishUninitializedImport publishes the stage of a source that declares no
// loader and ships no usable installer. The tree has no runtime, so it is
// extracted as-is: generated workspace documents are removed, nothing is
// registered, and the result carries a warning to initialize once the modpack
// is set up. The stage is private and unpublished, so no writer lock is
// required.
func publishUninitializedImport(
stage, target, name, source string,
format importpack.Format,
materialized *importpack.Result,
loaderWarnings []error,
initResult *InitResult,
analyses *artifact.Analyses,
) (*ImportResult, error) {
observed := workspace.ObserveWithAnalyses(stage, discovery.Request{}, analyses)
unmanaged, err := unmanagedImportFilePaths(stage, observed)
if err != nil {
return nil, err
}
review := importReview(stage)
if err := removeGeneratedImportArtifacts(stage); err != nil {
return nil, err
}
if _, err := publishImportStage(stage, target); err != nil {
return nil, err
}
result := &ImportResult{
Workspace: target,
Initialized: false,
Source: source,
Format: string(format),
Name: name,
ServerFiles: materialized.ServerFiles,
SkippedClient: materialized.SkippedClient,
Overrides: materialized.Overrides,
Skipped: materialized.Skipped,
Unmanaged: unmanaged,
Review: review,
Warnings: append(loaderWarnings, errImportNotInitialized),
}
if initResult != nil {
result.Discovery = initResult.Discovery.RebasePaths(stage, target)
}
result.WarningMessages = warningStrings(result.Warnings)
return result, nil
}
// removeGeneratedImportArtifacts deletes the workspace documents that
// initialization created in the stage. importpack rejects archive entries with
// these names, so only generated artifacts can exist.
func removeGeneratedImportArtifacts(stage string) error {
for _, name := range []string{
document.ManifestFilename,
document.LockFilename,
} {
if err := os.Remove(filepath.Join(stage, name)); err != nil &&
!errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove generated %s: %w", name, err)
}
}
if err := os.RemoveAll(filepath.Join(stage, ".lucy")); err != nil {
return fmt.Errorf("remove generated workspace state: %w", err)
}
return nil
}
// runTreeInstaller runs the loader installer that a source shipping its own
// tree carries. It returns the warnings that leave the extracted files
// uninstalled; any other failure aborts the import.
func (s *Service) runTreeInstaller(
ctx context.Context,
stage string,
trace *install.Trace,
) ([]error, error) {
installers, err := s.findImportInstallers(ctx, stage)
if err != nil {
return nil, err
}
switch len(installers) {
case 0:
return nil, nil
case 1:
default:
return []error{
errors.New("multiple loader installers found; none was run"),
}, nil
}
installer := installers[0]
if !bootstrap.InstallerSupported(installer.Kind) {
// An unsupported installer is never executed, so importing it must
// not require a Java runtime.
return []error{unsupportedInstallerWarning(installer.Kind)}, nil
}
advisory := bootstrap.InstallerJavaAdvisory(installer)
lock := &document.Lock{Server: document.LockedServer{
Minecraft: installer.Minecraft,
Java: document.NewLockedJava(advisory, nil),
}}
check, err := s.install.CheckJava(ctx, stage, lock)
if err != nil {
return nil, err
}
if !check.Satisfied() {
return nil, fmt.Errorf(
"run the %s installer: %s",
installer.Kind,
strings.Join(check.Problems, "; "),
)
}
const phase = "loader installer"
root := importServerRoot(stage)
if err := os.MkdirAll(root, 0o755); err != nil {
return nil, fmt.Errorf(
"create the installer working directory %s: %w",
root,
err,
)
}
started := time.Now()
trace.ReportPhaseStarted(phase)
err = bootstrap.RunInstaller(
ctx,
root,
installer,
check.Executable(),
importProcessOutput(trace),
)
trace.ReportPhase(install.PhaseInfo{
Name: phase,
Elapsed: time.Since(started),
})
if err != nil {
if errors.Is(err, bootstrap.ErrInstallerUnsupported) {
return []error{unsupportedInstallerWarning(installer.Kind)}, nil
}
return nil, err
}
return nil, nil
}
// unsupportedInstallerWarning reports an installer that was found but cannot
// be executed yet. Its extracted files remain untouched.
func unsupportedInstallerWarning(kind artifact.InstallerKind) error {
return fmt.Errorf(
"%s was found but is not supported yet; "+
"its files were extracted without running it",
kind,
)
}
// importServerRoot returns the directory a bundled installer must provision.
// MCDR moves the server into its configured working directory, and
// initialization observes only that directory. A working directory outside the
// staging tree is not trusted, so the stage root answers instead.
func importServerRoot(stage string) string {
root := workspace.ServerDirectory(stage)
relative, err := filepath.Rel(stage, root)
if err != nil || relative == ".." ||
strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return stage
}
return root
}
// findImportInstallers lists the loader installers a tree ships. A pack may
// nest an installer under any directory. A non-archive and an archive without
// installer metadata are not errors, so a failed read is reported at debug
// and does not fail the import.
func (s *Service) findImportInstallers(
ctx context.Context,
stage string,
) ([]artifact.Installer, error) {
var installers []artifact.Installer
err := filepath.WalkDir(
stage,
func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if err := ctx.Err(); err != nil {
return err
}
if !entry.Type().IsRegular() {
return nil
}
installer, found, err := artifact.ReadInstaller(path)
if err != nil {
s.logger.Debug(
"read loader installer",
"path", path,
"error", err,
)
return nil
}
if found {
installers = append(installers, installer)
}
return nil
},
)
if err != nil {
return nil, err
}
return installers, nil
}
// importProcessOutput returns the writer that receives installer output. A nil
// trace has none.
func importProcessOutput(trace *install.Trace) io.Writer {
if trace == nil {
return nil
}
return trace.ProcessOutput
}
// unmanagedImportFilePaths lists every observed package file without asking the
// committed receipt. A tree that is not initialized has no receipt, so all of
// its package files are unmanaged.
func unmanagedImportFilePaths(
root string,
observed *workspace.Workspace,
) ([]string, error) {
paths := make(
[]string,
0,
len(observed.Packages)+len(observed.UnidentifiedPackageFiles),
)
for _, pkg := range observed.Packages {
if pkg.Path != "" {
paths = append(paths, pkg.Path)
}
}
paths = append(paths, observed.UnidentifiedPackageFiles...)
relative, err := relativeImportPaths(root, paths)
if err != nil {
return nil, err
}
slices.Sort(relative)
return slices.Compact(relative), nil
}
// installDeclaredLoader installs the loader an mrpack declares into the
// private stage. The temporary manifest exists only in the stage; Initialize
// replaces it with the adopted manifest.
func (s *Service) installDeclaredLoader(
ctx context.Context,
stage, name string,
source *importpack.Result,
trace *install.Trace,
) error {
manifest := &document.Manifest{
SchemaVersion: document.ManifestSchemaVersion,
Name: name,
Server: document.ManifestServer{
Minecraft: version.Version(source.Minecraft),
Core: document.ManifestCore{
Product: source.Product,
ProductVersion: version.Version(source.CoreVersion),
},
Packages: map[catalog.Ecosystem]map[string]document.Requirement{},
},
}
if err := manifest.Normalize(); err != nil {
return err
}
_, err := s.install.Sync(ctx, stage, manifest, nil, install.Options{
PublishManifest: true,
SkipRegistration: true,
Trace: trace,
})
return err
}
// unregisterWorkspace removes the registry entry for root under the
// workspace's writer lock, as the registry requires.
func (s *Service) unregisterWorkspace(root string) error {
lock, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return err
}
return errors.Join(s.registry.Unregister(root), lock.Close())
}
// importTargetPath validates the requested target. The target must be an
// absolute path that is absent or an empty directory.
func importTargetPath(directory string) (string, error) {
if !filepath.IsAbs(directory) {
return "", fmt.Errorf("import target must be an absolute directory path: %q", directory)
}
target := filepath.Clean(directory)
info, err := os.Lstat(target)
if errors.Is(err, os.ErrNotExist) {
return target, nil
}
if err != nil {
return "", err
}
if !info.IsDir() {
return "", fmt.Errorf("import target is not a directory: %s", target)
}
entries, err := os.ReadDir(target)
if err != nil {
return "", err
}
if len(entries) > 0 {
return "", fmt.Errorf("import target is not empty: %s", target)
}
return target, nil
}
// acquireImportSource returns a local path for the archive, the source as it
// should be reported, and a release function for any temporary download.
func acquireImportSource(
ctx context.Context,
source, sha256 string,
network *cache.Client,
progress importpack.Progress,
) (string, string, func(), error) {
if strings.Contains(source, "://") {
return downloadImportSource(ctx, source, sha256, network, progress)
}
local, err := filepath.Abs(source)
if err != nil {
return "", "", nil, err
}
info, err := os.Stat(local)
if err != nil {
return "", "", nil, fmt.Errorf("import source: %w", err)
}
if !info.Mode().IsRegular() {
return "", "", nil, fmt.Errorf("import source is not a regular file: %s", local)
}
if err := verifyImportSHA256(local, sha256); err != nil {
return "", "", nil, err
}
return local, local, func() {}, nil
}
// downloadImportSource fetches an http(s) archive into a private temporary
// directory. The expected SHA-256 is checked on the downloaded bytes because
// the cache does not verify SHA-256 expectations itself.
func downloadImportSource(
ctx context.Context,
source, sha256 string,
network *cache.Client,
progress importpack.Progress,
) (string, string, func(), error) {
parsed, err := url.Parse(source)
if err != nil {
return "", "", nil, fmt.Errorf("parse import URL: %w", err)
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return "", "", nil, fmt.Errorf(
"unsupported import source scheme %q: use a local file or an http(s) URL",
parsed.Scheme,
)
}
if parsed.Host == "" {
return "", "", nil, fmt.Errorf("import URL has no host: %s", source)
}
if network == nil {
return "", "", nil, errors.New("import URL requires a network client")
}
dir, err := os.MkdirTemp("", "lucy-import-source-*")
if err != nil {
return "", "", nil, fmt.Errorf("create import download directory: %w", err)
}
release := func() { _ = os.RemoveAll(dir) }
filename := path.Base(parsed.Path)
if filename == "" || filename == "." || filename == "/" {
filename = "import-source"
}
download, err := network.CachedDownload(ctx, source, dir, cache.DownloadOptions{
Kind: cache.KindArtifact,
Filename: filename,
FileMode: 0o600,
MaxBytes: importpack.MaxSourceBytes,
WrapReader: func(r io.Reader, size int64) io.Reader {
progress.ReportStarted(filename, size)
return cache.ProgressReader(r, size, func(read, total int64) {
progress.ReportProgress(filename, read, total)
})
},
})
if err != nil {
release()
return "", "", nil, err
}
file := download.File.Name()
if err := download.File.Close(); err != nil {
release()
return "", "", nil, err
}
if err := verifyImportSHA256(file, sha256); err != nil {
release()
return "", "", nil, err
}
progress.ReportDone(filename, download.CacheHit)
return file, source, release, nil
}
func verifyImportSHA256(file, expected string) error {
if expected == "" {
return nil
}
_, err := install.DigestFile(file, map[string]string{
"sha256": strings.ToLower(expected),
})
return err
}
// createImportParents creates parent and returns a rollback that removes only
// the directories it created, deepest first.
func createImportParents(parent string) (func(), error) {
var missing []string
for dir := parent; ; {
info, err := os.Lstat(dir)
if err == nil {
if !info.IsDir() {
return nil, fmt.Errorf("import parent is not a directory: %s", dir)
}
break
}
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
missing = append(missing, dir)
next := filepath.Dir(dir)
if next == dir {
break
}
dir = next
}
var created []string
rollback := func() {
for i := len(created) - 1; i >= 0; i-- {
_ = os.Remove(created[i])
}
}
for i := len(missing) - 1; i >= 0; i-- {
if err := os.Mkdir(missing[i], 0o755); err != nil {
rollback()
return nil, err
}
created = append(created, missing[i])
}
return rollback, nil
}
// importPublication records how publishImportStage moved the staged tree into
// the target, so rollback can put it back. The caller holds the stage's writer
// lock, which travels with the moved entries, so a published workspace stays
// exclusively owned until registration finishes.
type importPublication struct {
stage string
target string
// inPlace records that target was an existing empty directory. Publication
// moved the stage's top-level entries into it, so rollback moves them back
// and leaves the directory itself, and its inode, in place.
inPlace bool
// moved lists the top-level entry names moved into target, in move order.
moved []string
}
func (p *importPublication) rollback() error {
if p == nil {
return nil
}
if !p.inPlace {
return os.Rename(p.target, p.stage)
}
var errs []error
for i := len(p.moved) - 1; i >= 0; i-- {
name := p.moved[i]
if err := os.Rename(filepath.Join(p.target, name), filepath.Join(p.stage, name)); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
// publishImportStage publishes a staged tree into target. An absent target is
// created by renaming the stage into place. An existing empty directory is kept
// and receives the stage's top-level entries, so its inode and the invoking
// shell's working directory remain valid. The target must be absent or an empty
// directory, rechecked after staging. The caller must hold the stage's writer
// lock.
func publishImportStage(stage, target string) (*importPublication, error) {
publication := &importPublication{stage: stage, target: target}
info, err := os.Lstat(target)
switch {
case errors.Is(err, os.ErrNotExist):
if err := os.Rename(stage, target); err != nil {
return nil, fmt.Errorf("publish import stage: %w", err)
}
return publication, nil
case err != nil:
return nil, fmt.Errorf("inspect import target: %w", err)
case !info.IsDir():
return nil, fmt.Errorf("import target is not a directory: %s", target)
}
entries, err := os.ReadDir(target)
if err != nil {
return nil, fmt.Errorf("inspect import target: %w", err)
}
if len(entries) > 0 {
return nil, fmt.Errorf("import target is not empty: %s", target)
}
staged, err := os.ReadDir(stage)
if err != nil {
return nil, fmt.Errorf("read import stage: %w", err)
}
publication.inPlace = true
for _, entry := range staged {
name := entry.Name()
dst := filepath.Join(target, name)
if _, err := os.Lstat(dst); err == nil {
return nil, errors.Join(fmt.Errorf("import target gained entry: %s", dst), publication.rollback())
} else if !errors.Is(err, os.ErrNotExist) {
return nil, errors.Join(fmt.Errorf("inspect import target: %w", err), publication.rollback())
}
if err := os.Rename(filepath.Join(stage, name), dst); err != nil {
return nil, errors.Join(fmt.Errorf("publish import stage: %w", err), publication.rollback())
}
publication.moved = append(publication.moved, name)
}
return publication, nil
}
// removeClientOnlyMods deletes mod jars only when their own descriptor says a
// dedicated server cannot load them. Provider labels are reported for review
// but never decide deletion, because a remote label is not evidence about the
// installed bytes. A client-only candidate stays when a kept package needs one
// of its modules or projects.
func (s *Service) removeClientOnlyMods(
ctx context.Context,
stage string,
product serverpkg.Product,
minecraft string,
analyses *artifact.Analyses,
trace *install.Trace,
) ([]string, []error, int, map[string]upstream.ArtifactReleaseResolution, error) {
modsDir := filepath.Join(stage, "mods")
entries, err := os.ReadDir(modsDir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil, 0, nil, nil
}
if err != nil {
return nil, nil, 0, nil, fmt.Errorf("read imported mod directory: %w", err)
}
ecosystem := catalog.Ecosystem(product)
mappers, mapperErr := s.packageMappers()
if mapperErr != nil {
s.logger.Debug(
"package mappers unavailable during import",
"error", mapperErr,
)
}
var paths []string
for _, entry := range entries {
if entry.IsDir() ||
!strings.EqualFold(filepath.Ext(entry.Name()), ".jar") {
continue
}
paths = append(paths, filepath.Join(modsDir, entry.Name()))
}
files := make([]importModFile, len(paths))
resolutions := s.importReleaseResolutions(ctx, paths, mappers, analyses)
var progress sync.Mutex
completed := 0
parallelPackageProbes(ctx, len(paths), func(i int) {
path := paths[i]
files[i] = s.classifyImportMod(ctx, path, analyses.File(path), ecosystem, minecraft, mappers, resolutions[i])
progress.Lock()
completed++
trace.ReportPhaseProgress(importClassificationPhase, completed, len(paths))
progress.Unlock()
})
if err := ctx.Err(); err != nil {
return nil, nil, 0, nil, err
}
keepRequiredMods(files)
var removed []string
var warnings []error
matches := make(map[string]upstream.ArtifactReleaseResolution, len(paths))
for i, file := range files {
relative, err := filepath.Rel(stage, file.path)
if err != nil {
return removed, warnings, len(paths), nil, fmt.Errorf(
"relativize imported mod %s: %w",
file.path,
err,
)
}
relative = filepath.ToSlash(relative)
if file.remote {
message := fmt.Sprintf(
"package %s: its %s; keeping the installed file",
relative,
file.reason,
)
if file.provider != "" {
message = fmt.Sprintf(
"package %s matched %s but its %s; keeping the installed file",
relative,
file.provider,
file.reason,
)
}
warnings = append(warnings, newImportWarning(
importWarningRemoteSide,
relative,
message,
))
}
if file.kept {
resolution := resolutions[i]
if !resolution.Matched || resolution.Release.Ref.Name != "" {
matches[file.path] = resolution
}
continue
}
if err := os.Remove(file.path); err != nil {
return removed, warnings, len(paths), nil, fmt.Errorf(
"remove client-only mod %s: %w",
file.path,
err,
)
}
s.logger.Debug(
"removed client-only mod",
"path", relative,
"reason", file.reason,
)
removed = append(removed, relative)
}
return removed, warnings, len(paths), matches, nil
}
// classifyImportMod reads one archive and decides whether a dedicated server
// can use it. Classification runs concurrently across files, so the helper
// reads no shared mutable state.
func (s *Service) classifyImportMod(
ctx context.Context,
path string,
analysis *artifact.Analysis,
ecosystem catalog.Ecosystem,
minecraft string,
mappers []upstream.ArtifactReleaseMapper,
resolution upstream.ArtifactReleaseResolution,
) importModFile {
infos, _ := analysis.Info()
loaders := descriptorLoaders(infos, ecosystem)
modules := importModules(ctx, analysis, loaders, minecraft)
if len(modules) == 0 {
// A descriptor that is client-only is filtered from the server view,
// but its identity still proves a kept file depends on it.
modules = importDescriptorIdentities(infos)
}
file := importModFile{
path: path,
modules: modules,
kept: true,
}
matched := resolution.Matched
if matched {
release := resolution.Release
if release.Candidate.Provider == "" {
release.Candidate.Provider = resolution.Provider
}
file.project = projectKey(
release.Candidate.Provider,
release.Candidate.ProjectID,
)
file.dependencies = release.Candidate.Dependencies
file.provider = release.Candidate.Provider
switch {
case release.ServerSide == upstream.ServerSideUnsupported:
file.reason = "release does not support a dedicated server"
file.remote = true
case release.ClientOnly():
file.reason = "release declares client-only support"
file.remote = true
}
}
reason, clientOnly := clientOnlyDescriptor(
ctx,
analysis,
loaders,
minecraft,
)
if clientOnly {
// Local descriptor evidence is the only reason a dedicated server may
// delete a jar.
file.reason = reason
file.remote = false
file.kept = false
} else if !matched {
if project, found := s.catalogProjectSide(
ctx,
infos,
mappers,
); found {
switch {
case project.ServerSide == upstream.ServerSideUnsupported:
file.reason = "release does not support a dedicated server"
file.remote = true
case project.IsClientOnly():
file.reason = "release declares client-only support"
file.remote = true
}
}
}
return file
}
// importDescriptorIdentities reads the package identities a client-only
// descriptor still declares, so a kept file can be matched to its module.
func importDescriptorIdentities(infos []artifact.PackageInfo) []catalog.DescriptorModule {
modules := make([]catalog.DescriptorModule, 0, len(infos))
for _, info := range infos {
if info.Ref.Name == "" {
continue
}
modules = append(modules, catalog.DescriptorModule{
ID: string(info.Ref.Name),
Ecosystem: info.Ref.Ecosystem,
})
}
return modules
}
// importModFile is one imported mod archive and its classification.
type importModFile struct {
path string
// project is the provider-qualified project the file was published as.
project string
// dependencies lists the project relationships the release declares.
dependencies []upstream.ProjectDependency
modules []catalog.DescriptorModule
// provider names the release mapper that identified the file.
provider catalog.Provider
// reason explains a deletion candidate or a review warning.
reason string
// remote marks a provider label that excludes a dedicated server. It is a
// review warning, never a deletion decision.
remote bool
kept bool
}
// keepRequiredMods keeps candidates a server package depends on, whether the
// dependency comes from a descriptor module or the provider's release
// metadata. A promoted candidate can itself require another candidate, so the
// pass repeats until nothing changes.
func keepRequiredMods(files []importModFile) {
for {
requiredModules := requiredModuleIDs(files)
requiredProjectKeys := requiredProjectIDs(files)
changed := false
for i := range files {
if files[i].kept {
continue
}
if modulesProvide(files[i].modules, requiredModules) ||
(files[i].project != "" && requiredProjectKeys[files[i].project]) {
files[i].kept = true
changed = true
}
}
if !changed {
return
}
}
}
// requiredModuleIDs lists every dependency a kept archive declares.
func requiredModuleIDs(files []importModFile) map[string]bool {
required := make(map[string]bool)
for _, file := range files {
if !file.kept {
continue
}
for _, module := range file.modules {
for _, dependency := range module.Dependencies {
addDependencyIDs(required, dependency)
}
}
}
return required
}
// requiredProjectIDs lists the provider projects that kept files require.
func requiredProjectIDs(files []importModFile) map[string]bool {
required := make(map[string]bool)
for _, file := range files {
if !file.kept {
continue
}
for _, dependency := range file.dependencies {
if dependency.Kind != catalog.DependencyKindRequired {
continue
}
if key := projectKey(dependency.Provider, dependency.ProjectID); key != "" {
required[key] = true
}
}
}
return required
}
func addDependencyIDs(ids map[string]bool, dependency catalog.DescriptorDependency) {
if dependency.Kind != catalog.DependencyKindRequired {
return
}
if dependency.ID != "" {
ids[dependency.ID] = true
}
for _, alternative := range dependency.AnyOf {
addDependencyIDs(ids, alternative)
}
for _, condition := range dependency.AllOf {
addDependencyIDs(ids, condition)
}
}
// modulesProvide reports whether any module or provided identity satisfies one
// of the required IDs.
func modulesProvide(
modules []catalog.DescriptorModule,
required map[string]bool,
) bool {
for _, module := range modules {
if required[module.ID] {
return true
}
if module.Group != "" && required[module.Group+":"+module.ID] {
return true
}
for _, provided := range module.Provides {
if required[provided] {
return true
}
}
}
return false
}
// descriptorLoaders lists the loaders whose descriptor the file carries,
// starting with the server loader. A file with no readable descriptor answers
// only the server loader.
func descriptorLoaders(infos []artifact.PackageInfo, loader catalog.Ecosystem) []catalog.Ecosystem {
loaders := []catalog.Ecosystem{loader}
for _, info := range infos {
ecosystem := info.Ref.Ecosystem
if ecosystem == catalog.EcosystemUnspecified ||
slices.Contains(loaders, ecosystem) {
continue
}
loaders = append(loaders, ecosystem)
}
return loaders
}
// importModules reads the modules that describe a file. The server loader's
// descriptor answers first; a file it has no descriptor for (a Fabric jar
// bridged by Connector) contributes the modules of the descriptor it carries,
// so the dependencies that keep server-optional libraries stay visible.
func importModules(
ctx context.Context,
analysis *artifact.Analysis,
loaders []catalog.Ecosystem,
minecraft string,
) []catalog.DescriptorModule {
for _, candidate := range loaders {
view, err := analysis.Descriptor(ctx, candidate, minecraft)
if err == nil && len(view.Modules) > 0 {
return view.Modules
}
}
return nil
}
// clientOnlyDescriptor reports which descriptor makes the file client-only.
// The server loader is tried first because its view decides whether the file
// can load at all. A file whose descriptor belongs to another ecosystem (a
// Fabric jar bridged by Connector) is checked with that descriptor's loader.
func clientOnlyDescriptor(
ctx context.Context,
analysis *artifact.Analysis,
loaders []catalog.Ecosystem,
minecraft string,
) (string, bool) {
for i, candidate := range loaders {
view, err := analysis.Descriptor(ctx, candidate, minecraft)
if err != nil || !view.Known {
continue
}
if view.ClientOnly {
return "client-only " + string(candidate), true
}
if i == 0 {
// The server loader accepts the file, so another loader's
// client-only descriptor cannot remove it.
return "", false
}
}
return "", false
}
// catalogProjectSide asks a provider that publishes side labels for the
// file's project. The descriptor title and project name select the project; a
// provider title must agree with the descriptor title, so a same-named but
// different project cannot classify the file.
func (s *Service) catalogProjectSide(
ctx context.Context,
infos []artifact.PackageInfo,
mappers []upstream.ArtifactReleaseMapper,
) (upstream.ProjectServerSide, bool) {
for _, info := range infos {
names := projectNameCandidates(info)
if len(names) == 0 {
continue
}
for _, mapper := range mappers {
resolver, ok := mapper.(upstream.ServerSideResolver)
if !ok {
continue
}
for _, candidate := range names {
project, found, err := resolver.ServerSideByName(
ctx,
candidate,
)
if err != nil {
s.logger.Debug(
"project side lookup failed",
"name", candidate,
"provider", mapper.Provider(),
"error", err,
)
continue
}
if !found {
continue
}
if info.Metadata.Title == "" ||
!sameProjectTitle(info.Metadata.Title, project.Title) {
break
}
return project, true
}
}
}
return upstream.ProjectServerSide{}, false
}
// projectNameCandidates lists the names a provider may use for the project:
// the descriptor title as a slug, then the module name.
func projectNameCandidates(info artifact.PackageInfo) []string {
var candidates []string
add := func(name string) {
if name == "" || slices.Contains(candidates, name) {
return
}
candidates = append(candidates, name)
}
add(slugify(info.Metadata.Title))
add(string(info.Ref.Name))
return candidates
}
// slugify lowercases a project title and joins its words with hyphens.
func slugify(raw string) string {
var b strings.Builder
pending := false
for _, r := range strings.ToLower(raw) {
alphanumeric := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')
if !alphanumeric {
pending = true
continue
}
if pending && b.Len() > 0 {
b.WriteByte('-')
}
pending = false
b.WriteRune(r)
}
return b.String()
}
// sameProjectTitle reports whether two titles name the same project. An empty
// title on either side gives the slug lookup the benefit of the doubt.
func sameProjectTitle(left, right string) bool {
a, b := slugify(left), slugify(right)
if a == "" || b == "" {
return true
}
return a == b
}
// importReleaseResolutions asks the release mappers once for every imported
// file. Mappers run in trial order: the first provider that identifies a file
// supplies its side labels, project identity, and declared dependencies, and a
// failed lookup leaves the file to the next provider.
func (s *Service) importReleaseResolutions(
ctx context.Context,
paths []string,
mappers []upstream.ArtifactReleaseMapper,
analyses *artifact.Analyses,
) []upstream.ArtifactReleaseResolution {
resolutions := make([]upstream.ArtifactReleaseResolution, len(paths))
if len(paths) == 0 || len(mappers) == 0 {
return resolutions
}
fingerprints := make([]upstream.ArtifactFingerprint, len(paths))
for i, path := range paths {
fingerprints[i] = analyses.File(path)
}
found := upstream.LookupArtifactReleases(ctx, fingerprints, mappers, nil)
for i := 0; i < len(resolutions) && i < len(found); i++ {
resolutions[i] = found[i]
for _, providerErr := range found[i].Errors {
s.logger.Debug(
"artifact hash lookup failed",
"path", paths[i],
"provider", providerErr.Provider,
"error", providerErr.Err,
)
}
}
return resolutions
}
// projectKey identifies one provider project across the files of an import.
// An empty provider or project has no identity to match.
func projectKey(provider catalog.Provider, projectID string) string {
if provider == "" || projectID == "" {
return ""
}
return string(provider) + ":" + projectID
}
// relativeImportPaths reports files relative to root, slash-separated, so no
// staging path leaks into the result.
func relativeImportPaths(root string, files []string) ([]string, error) {
var relative []string
for _, file := range files {
rel := file
if filepath.IsAbs(file) {
var err error
rel, err = filepath.Rel(root, file)
if err != nil {
return nil, fmt.Errorf("relativize %s: %w", file, err)
}
}
relative = append(relative, filepath.ToSlash(rel))
}
return relative, nil
}
// unmanagedImportFiles lists observed package files that the committed receipt
// does not own. A readable descriptor alone does not make a file managed:
// adoption leaves packages without a matching release unmanaged.
func unmanagedImportFiles(
root string,
observed *workspace.Workspace,
) ([]string, error) {
committed, err := receipt.Read(root)
if err != nil {
return nil, fmt.Errorf("read imported installation receipt: %w", err)
}
owned := make(map[string]struct{}, len(committed.Entries))
for _, entry := range committed.Entries {
owned[entry.Path] = struct{}{}
}
paths := make(
[]string,
0,
len(observed.Packages)+len(observed.UnidentifiedPackageFiles),
)
for _, pkg := range observed.Packages {
if pkg.Path != "" {
paths = append(paths, pkg.Path)
}
}
paths = append(paths, observed.UnidentifiedPackageFiles...)
relative, err := relativeImportPaths(root, paths)
if err != nil {
return nil, err
}
unmanaged := make([]string, 0, len(relative))
for _, file := range relative {
if _, ok := owned[file]; ok {
continue
}
unmanaged = append(unmanaged, file)
}
slices.Sort(unmanaged)
return slices.Compact(unmanaged), nil
}
// importReview reports server settings and grants that the operator should
// check before the imported server is run. A metadata file that cannot be read
// within importMetadataMaxBytes is reported as unreadable instead of failing
// the import.
func importReview(serverDir string) []string {
var review []string
props, err := importPropertyValues(
filepath.Join(serverDir, "server.properties"),
"online-mode",
"enable-rcon",
)
if err != nil {
review = append(review, "server.properties: unreadable metadata")
}
if strings.EqualFold(props["online-mode"], "false") {
review = append(review, "server.properties: online-mode=false; players are not authenticated with Mojang")
}
if strings.EqualFold(props["enable-rcon"], "true") {
review = append(review, "server.properties: enable-rcon=true; remote console access is enabled")
}
eula, err := importPropertyValues(filepath.Join(serverDir, "eula.txt"), "eula")
if err != nil {
review = append(review, "eula.txt: unreadable metadata")
}
if strings.EqualFold(eula["eula"], "true") {
review = append(review, "eula.txt: eula=true; the Minecraft EULA was accepted in the source")
}
ops, err := importOperatorCount(filepath.Join(serverDir, "ops.json"))
if err != nil {
review = append(review, "ops.json: unreadable operator list")
} else if ops > 0 {
review = append(review, fmt.Sprintf("ops.json: %d operator(s) granted", ops))
}
return review
}
// errImportMetadataTooLarge reports a metadata file larger than
// importMetadataMaxBytes.
var errImportMetadataTooLarge = errors.New("import metadata exceeds size limit")
// importPropertyValues returns the last value of each requested key in a
// key=value file. Keys absent from the file are absent from the result, and a
// missing file is not an error. The file is streamed line by line through a
// reader capped at importMetadataMaxBytes, so a larger file fails with
// errImportMetadataTooLarge without its contents being loaded.
func importPropertyValues(file string, keys ...string) (map[string]string, error) {
values := make(map[string]string, len(keys))
f, err := os.Open(file)
if errors.Is(err, os.ErrNotExist) {
return values, nil
}
if err != nil {
return nil, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, err
}
if info.Size() > importMetadataMaxBytes {
return nil, importMetadataTooLarge(file)
}
// One byte past the cap lets a file that grows after Stat be detected
// below instead of being read to its end.
limited := &io.LimitedReader{R: f, N: importMetadataMaxBytes + 1}
scanner := bufio.NewScanner(limited)
scanner.Buffer(make([]byte, 0, 4096), importMetadataMaxBytes+1)
for scanner.Scan() {
line := bytes.TrimSpace(scanner.Bytes())
if len(line) == 0 || line[0] == '#' || line[0] == '!' {
continue
}
k, v, ok := bytes.Cut(line, []byte("="))
if !ok {
continue
}
name := bytes.TrimSpace(k)
for _, key := range keys {
if string(name) == key {
values[key] = string(bytes.TrimSpace(v))
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if limited.N <= 0 {
return nil, importMetadataTooLarge(file)
}
return values, nil
}
// importMetadataTooLarge describes a metadata file over importMetadataMaxBytes.
func importMetadataTooLarge(file string) error {
return fmt.Errorf("%s exceeds %d bytes: %w", file, importMetadataMaxBytes, errImportMetadataTooLarge)
}
// importMetadataMaxBytes caps the review metadata Lucy reads from a server
// directory. Operator lists are small; a larger file is reported as unreadable
// instead of being loaded.
const importMetadataMaxBytes = 1 << 20
// importOperatorCount counts entries in ops.json. A missing file has none. A
// file larger than importMetadataMaxBytes is an error.
func importOperatorCount(file string) (int, error) {
f, err := os.Open(file)
if errors.Is(err, os.ErrNotExist) {
return 0, nil
}
if err != nil {
return 0, err
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, importMetadataMaxBytes+1))
if err != nil {
return 0, err
}
if len(data) > importMetadataMaxBytes {
return 0, importMetadataTooLarge(file)
}
var ops []any
if err := json.Unmarshal(data, &ops); err != nil {
return 0, err
}
return len(ops), nil
}
package operation
import (
"context"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/workspace/discovery"
)
// ImportOptions describes one external server source and its target workspace.
// Directory must be an absolute path that is absent or empty.
type ImportOptions struct {
Source string
Directory string
Name string
MCDRVersion string
NoComments bool
SHA256 string
Expectation *discovery.Expectation
PromptRuntime func(discovery.Result) (*discovery.Installation, error)
Trace *install.Trace
}
// ImportResult reports the materialized source and the adopted workspace.
type ImportResult struct {
Workspace string `json:"workspace"`
Initialized bool `json:"initialized"`
Source string `json:"source"`
Format string `json:"format"`
Name string `json:"name"`
Minecraft string `json:"minecraft"`
Product string `json:"product"`
CoreVersion string `json:"core_version"`
ServerFiles int `json:"server_files"`
SkippedClient int `json:"skipped_client"`
Overrides int `json:"overrides"`
ManagedPackages int `json:"managed_packages"`
Skipped []string `json:"skipped,omitempty"`
Unmanaged []string `json:"unmanaged,omitempty"`
Review []string `json:"review,omitempty"`
WarningMessages []string `json:"warnings,omitempty"`
Manifest *document.Manifest `json:"-"`
Lock *document.Lock `json:"-"`
Warnings []error `json:"-"`
Discovery discovery.Result `json:"-"`
}
// Import materializes source and publishes the workspace at Directory. A
// source that declares a loader or ships an installer in its tree gets that
// installer run in the stage. When a runtime is detected the imported tree is
// initialized; otherwise the tree is extracted as-is and a warning asks the
// operator to run `lucy init` once the modpack is set up.
func (s *Service) Import(
ctx context.Context,
opts ImportOptions,
network *cache.Client,
) (*ImportResult, error) {
return s.importSource(ctx, opts, network)
}
package operation
import (
"context"
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"unicode"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/importpack"
"github.com/mclucy/lucy/upstream"
)
// importPackResolver is the optional capability a Source provides to turn a
// remote modpack reference into the pack file its provider publishes. A Source
// without it cannot import remote modpacks.
type importPackResolver interface {
ResolveImportPack(
ctx context.Context,
provider catalog.Provider,
project, version string,
) (upstream.ImportPack, error)
}
// RemoteImportSource names a modpack on a provider. Project is a slug or, for
// CurseForge, a numeric id. Version is empty when the source does not pin a
// version or file, so the resolver chooses the provider's latest pack.
type RemoteImportSource struct {
Provider catalog.Provider
Project string
Version string
}
const (
modrinthIdentifierPrefix = "modrinth:"
curseforgeIdentifierPrefix = "curseforge:"
)
// ParseRemoteImportSource recognizes provider identifiers and modpack project
// pages. ok is false for every other source, which keeps local paths and direct
// archive URLs on their existing path. A source that is recognized but
// malformed reports ok with an error, so it fails before any file is touched.
func ParseRemoteImportSource(source string) (RemoteImportSource, bool, error) {
lower := strings.ToLower(source)
switch {
case strings.HasPrefix(lower, modrinthIdentifierPrefix):
return parseModrinthIdentifier(source[len(modrinthIdentifierPrefix):])
case strings.HasPrefix(lower, curseforgeIdentifierPrefix):
return parseCurseForgeIdentifier(source[len(curseforgeIdentifierPrefix):])
}
parsed, err := url.Parse(source)
if err != nil || parsed.Scheme != "https" {
return RemoteImportSource{}, false, nil
}
segments := strings.FieldsFunc(parsed.Path, func(r rune) bool { return r == '/' })
switch strings.TrimPrefix(strings.ToLower(parsed.Hostname()), "www.") {
case "modrinth.com":
if len(segments) == 0 || segments[0] != "modpack" {
return RemoteImportSource{}, false, nil
}
ref, err := parseModrinthPage(source, segments[1:])
return ref, true, err
case "curseforge.com":
if len(segments) < 2 || segments[0] != "minecraft" || segments[1] != "modpacks" {
return RemoteImportSource{}, false, nil
}
ref, err := parseCurseForgePage(source, segments[2:])
return ref, true, err
}
return RemoteImportSource{}, false, nil
}
// parseModrinthIdentifier reads the body of modrinth:<slug>[@<version>].
func parseModrinthIdentifier(body string) (RemoteImportSource, bool, error) {
project, version, pinned := strings.Cut(body, "@")
if !validRemoteName(project) || (pinned && !validRemoteName(version)) {
return RemoteImportSource{}, true, fmt.Errorf(
"invalid Modrinth source %q: want modrinth:<slug>[@<version>]",
modrinthIdentifierPrefix+body,
)
}
return RemoteImportSource{
Provider: catalog.ProviderModrinth,
Project: project,
Version: version,
}, true, nil
}
// parseCurseForgeIdentifier reads the body of curseforge:<slug-or-id>[@<file-id>].
func parseCurseForgeIdentifier(body string) (RemoteImportSource, bool, error) {
project, file, pinned := strings.Cut(body, "@")
if !validRemoteName(project) || (pinned && !isDecimal(file)) {
return RemoteImportSource{}, true, fmt.Errorf(
"invalid CurseForge source %q: want curseforge:<slug-or-id>[@<file-id>] with a numeric file id",
curseforgeIdentifierPrefix+body,
)
}
return RemoteImportSource{
Provider: catalog.ProviderCurseForge,
Project: project,
Version: file,
}, true, nil
}
// parseModrinthPage reads the path after /modpack/.
func parseModrinthPage(source string, rest []string) (RemoteImportSource, error) {
switch {
case len(rest) == 1 && validRemoteName(rest[0]):
return RemoteImportSource{Provider: catalog.ProviderModrinth, Project: rest[0]}, nil
case len(rest) == 3 && rest[1] == "version" &&
validRemoteName(rest[0]) && validRemoteName(rest[2]):
return RemoteImportSource{
Provider: catalog.ProviderModrinth,
Project: rest[0],
Version: rest[2],
}, nil
}
return RemoteImportSource{}, fmt.Errorf(
"unsupported Modrinth modpack URL %q: want https://modrinth.com/modpack/<slug>[/version/<version>]",
source,
)
}
// parseCurseForgePage reads the path after /minecraft/modpacks/.
func parseCurseForgePage(source string, rest []string) (RemoteImportSource, error) {
switch {
case len(rest) == 1 && validRemoteName(rest[0]):
return RemoteImportSource{Provider: catalog.ProviderCurseForge, Project: rest[0]}, nil
case len(rest) == 3 && rest[1] == "files" &&
validRemoteName(rest[0]) && isDecimal(rest[2]):
return RemoteImportSource{
Provider: catalog.ProviderCurseForge,
Project: rest[0],
Version: rest[2],
}, nil
}
return RemoteImportSource{}, fmt.Errorf(
"unsupported CurseForge modpack URL %q: want https://www.curseforge.com/minecraft/modpacks/<slug>[/files/<file-id>]",
source,
)
}
// validRemoteName reports whether name can be a slug, id or version segment
// without separators, spaces or query characters.
func validRemoteName(name string) bool {
return name != "" && !strings.ContainsFunc(name, func(r rune) bool {
return unicode.IsSpace(r) || unicode.IsControl(r) || strings.ContainsRune(`/\@?#`, r)
})
}
func isDecimal(value string) bool {
if value == "" {
return false
}
for _, r := range value {
if r < '0' || r > '9' {
return false
}
}
return true
}
// resolveImportSource returns the local archive path for source. Remote modpack
// references are resolved and downloaded; every other source keeps the
// local-path and direct-URL handling of acquireImportSource.
func (s *Service) resolveImportSource(
ctx context.Context,
source, sha256 string,
network *cache.Client,
progress importpack.Progress,
) (string, string, func(), error) {
ref, ok, err := ParseRemoteImportSource(source)
if err != nil {
return "", "", nil, err
}
if !ok {
return acquireImportSource(ctx, source, sha256, network, progress)
}
return s.acquireRemoteImportSource(ctx, source, ref, sha256, network, progress)
}
// acquireRemoteImportSource asks the configured resolver for the pack a remote
// reference names and downloads it. The returned label is the user's source.
func (s *Service) acquireRemoteImportSource(
ctx context.Context,
source string,
ref RemoteImportSource,
sha256 string,
network *cache.Client,
progress importpack.Progress,
) (string, string, func(), error) {
resolver, ok := s.source.(importPackResolver)
if !ok {
return "", "", nil, fmt.Errorf(
"import source %q: no %s pack resolver is configured",
source,
ref.Provider,
)
}
if network == nil {
return "", "", nil, fmt.Errorf("import source %q requires a network client", source)
}
pack, err := resolver.ResolveImportPack(ctx, ref.Provider, ref.Project, ref.Version)
if err != nil {
return "", "", nil, fmt.Errorf("resolve import source %q: %w", source, err)
}
return downloadImportPack(ctx, source, pack, sha256, network, progress)
}
// downloadImportPack fetches a resolved pack into a private temporary directory
// through the bounded source download. The provider's digest, preferring SHA-512
// over SHA-1, is checked on the materialized file, including cache hits that the
// cache serves without verifying. --sha256 is checked on the same bytes.
func downloadImportPack(
ctx context.Context,
source string,
pack upstream.ImportPack,
sha256 string,
network *cache.Client,
progress importpack.Progress,
) (string, string, func(), error) {
rawURL := strings.TrimSpace(pack.URL)
if rawURL == "" {
return "", "", nil, fmt.Errorf("import source %q: resolved pack has no download URL", source)
}
parsed, err := url.Parse(rawURL)
if err != nil {
return "", "", nil, fmt.Errorf("import source %q: parse resolved pack URL: %w", source, err)
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return "", "", nil, fmt.Errorf(
"import source %q: resolved pack URL scheme %q is not http or https",
source,
parsed.Scheme,
)
}
if parsed.Host == "" {
return "", "", nil, fmt.Errorf("import source %q: resolved pack URL has no host", source)
}
name := strings.TrimSpace(pack.Filename)
if name == "" {
return "", "", nil, fmt.Errorf("import source %q: resolved pack has no filename", source)
}
name = path.Base(name)
if name == "." || name == ".." || name == "/" {
return "", "", nil, fmt.Errorf(
"import source %q: resolved pack filename %q is not a file name",
source,
pack.Filename,
)
}
algorithm, digest := importPackDigest(pack.Hashes)
if digest == "" && strings.TrimSpace(sha256) == "" {
return "", "", nil, fmt.Errorf(
"import source %q: resolved pack publishes no checksum; pass --sha256 with the expected digest to verify the download",
source,
)
}
dir, err := os.MkdirTemp("", "lucy-import-pack-*")
if err != nil {
return "", "", nil, fmt.Errorf("create import download directory: %w", err)
}
release := func() { _ = os.RemoveAll(dir) }
download, err := network.CachedDownload(ctx, rawURL, dir, cache.DownloadOptions{
Kind: cache.KindArtifact,
ExpectedHash: digest,
HashAlgorithm: algorithm,
Filename: name,
FileMode: 0o600,
MaxBytes: importpack.MaxSourceBytes,
WrapReader: func(r io.Reader, size int64) io.Reader {
progress.ReportStarted(name, size)
return cache.ProgressReader(r, size, func(read, total int64) {
progress.ReportProgress(name, read, total)
})
},
})
if err != nil {
release()
return "", "", nil, fmt.Errorf("download resolved pack for %q: %w", source, err)
}
file := download.File.Name()
if err := download.File.Close(); err != nil {
release()
return "", "", nil, err
}
if err := verifyImportPackDigest(file, algorithm, digest); err != nil {
release()
return "", "", nil, fmt.Errorf("verify resolved pack for %q: %w", source, err)
}
if err := verifyImportSHA256(file, sha256); err != nil {
release()
return "", "", nil, err
}
progress.ReportDone(name, download.CacheHit)
return file, source, release, nil
}
// importPackDigest selects the strongest digest a pack publishes. An absent
// digest yields HashNone, which the cache treats as no expectation.
func importPackDigest(hashes map[string]string) (cache.HashAlgorithm, string) {
candidates := []struct {
name string
algorithm cache.HashAlgorithm
}{
{name: "sha512", algorithm: cache.HashSHA512},
{name: "sha1", algorithm: cache.HashSHA1},
}
for _, candidate := range candidates {
if digest := strings.ToLower(strings.TrimSpace(hashes[candidate.name])); digest != "" {
return candidate.algorithm, digest
}
}
return cache.HashNone, ""
}
// verifyImportPackDigest checks the materialized pack against the digest the
// provider published. It runs for cache hits as well, because the cache does not
// verify bytes it serves. An empty digest means the provider published none.
func verifyImportPackDigest(file string, algorithm cache.HashAlgorithm, digest string) error {
if digest == "" {
return nil
}
_, err := install.DigestFile(file, map[string]string{algorithm.String(): digest})
return err
}
package operation
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/config"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/resolve"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
"github.com/mclucy/lucy/workspace/identify"
)
// Initialize adopts the server already present in root: it observes the
// runtime and packages, resolves the lock, and publishes the manifest, lock,
// and installation receipt as one workspace transaction.
func (s *Service) Initialize(ctx context.Context, root string, opts InitOptions) (result *InitResult, resultErr error) {
return s.initialize(ctx, root, opts, new(artifact.Analyses), nil)
}
func (s *Service) initialize(ctx context.Context, root string, opts InitOptions, analyses *artifact.Analyses, known map[string]upstream.ArtifactReleaseResolution) (result *InitResult, resultErr error) {
root, err := filepath.Abs(root)
if err != nil {
return nil, err
}
if err := os.MkdirAll(root, 0o755); err != nil {
return nil, err
}
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
// Pin the recovered documents before resolution reads the workspace.
// Adoption publishes the manifest, lock, and receipt as one transaction
// and refuses to overwrite bytes that changed in between.
documents, err := install.CaptureWorkspaceDocuments(root)
if err != nil {
return nil, err
}
manifest, err := initialManifest(root, opts)
if err != nil {
return nil, err
}
// Runtime discovery, selection, and identity form one reported phase.
// Any error or prompt cancellation returns before completion, so the
// trace keeps the phase active instead of inventing an elapsed time.
opts.Trace.ReportPhaseStarted("identification")
identificationStarted := time.Now()
observed := workspace.ObserveWithAnalyses(root, discovery.Request{Expectation: opts.Expectation}, analyses)
if err := promptRuntime(opts, observed); err != nil {
return initResult(observed), err
}
// Adoption checks the bytes and mode captured before resolution, so a
// replacement does not inherit the ownership of an observed file.
var runtimeInstallation *discovery.Installation
if selection := observed.Runtime(); selection != nil {
runtimeInstallation = selection.Installation
}
runtimeObserved, err := captureRuntimeObservation(runtimeInstallation)
if err != nil {
return initResult(observed), err
}
if err := s.applyRuntimeIdentity(ctx, root, manifest, observed); err != nil {
return initResult(observed), err
}
if err := verifyCoreVersionExpectation(opts.Expectation, manifest); err != nil {
return initResult(observed), err
}
opts.Trace.ReportPhase(install.PhaseInfo{
Name: "identification",
Elapsed: time.Since(identificationStarted),
})
adoptionStarted := time.Now()
opts.Trace.ReportPhaseStarted("adoption")
if known == nil && len(observed.UnidentifiedPackageFiles) > 0 {
known = make(map[string]upstream.ArtifactReleaseResolution, len(observed.UnidentifiedPackageFiles))
}
identificationErrors := identify.Packages(
ctx,
observed,
s.source.ResolveArtifactsByHash,
known,
)
if err := ctx.Err(); err != nil {
return initResult(observed), err
}
fatalIdentification, identificationWarnings := identificationOutcome(
identificationErrors,
)
if fatalIdentification != nil {
return initResult(observed), fatalIdentification
}
// Keep per-attempt details at debug level. Adoption reports incomplete
// lookups when they prevent identification.
for _, warning := range identificationWarnings {
s.logger.Debug("package identification failed", "error", warning)
}
if err := s.applyDetectedVersions(manifest, opts, observed); err != nil {
return initResult(observed), err
}
if err := manifest.Normalize(); err != nil {
return initResult(observed), err
}
adoptedPackages, adoptedReleases, reportedMissing, inspected, err := s.adoptInstalledPackages(
ctx,
root,
manifest,
observed,
known,
)
if err != nil {
return initResult(observed), err
}
opts.Trace.ReportPhase(install.PhaseInfo{
Name: "adoption",
Elapsed: time.Since(adoptionStarted),
Count: len(adoptedPackages),
Total: inspected,
})
old, err := documents.DecodeLock()
if err != nil {
return initResult(observed), err
}
resolved, err := s.resolveAdoptedLock(
ctx,
root,
manifest,
old,
opts,
observed,
runtimeObserved,
adoptedReleases,
reportedMissing,
)
if err != nil {
return initResult(observed), err
}
return s.publishInitialization(
ctx,
root,
manifest,
old,
resolved,
adoptedPackages,
runtimeObserved,
observed,
opts,
documents,
)
}
// verifyCoreVersionExpectation confirms that the version identity assigned
// after selection answers an exact core version filter. Selection accepts an
// installation whose observed version is unknown; identification can then
// reveal a different build, which must fail the invocation instead of
// publishing a server the caller did not request.
func verifyCoreVersionExpectation(
expectation *discovery.Expectation,
manifest *documentpkg.Manifest,
) error {
if expectation == nil || !concreteVersion(expectation.CoreVersion) {
return nil
}
identified := manifest.Server.Core.ProductVersion
if identified == expectation.CoreVersion {
return nil
}
if !concreteVersion(identified) {
return fmt.Errorf(
"cannot identify the installed %s version, which the invocation requires to be %s",
manifest.Server.Core.Product,
expectation.CoreVersion,
)
}
return fmt.Errorf(
"installed %s version %s does not match the requested %s",
manifest.Server.Core.Product,
identified,
expectation.CoreVersion,
)
}
// initialManifest builds the declaration initialization will write, keeping
// the name an existing declaration already chose when --force replaces it.
func initialManifest(root string, opts InitOptions) (*documentpkg.Manifest, error) {
if _, err := os.Stat(filepath.Join(root, documentpkg.ManifestFilename)); err == nil &&
!opts.Force {
return nil, fmt.Errorf("lucy.yaml exists; use --force to replace declared intent")
}
name := strings.TrimSpace(opts.Name)
if name == "" && opts.Force {
// Replacing a declaration keeps the name the user already chose; an
// unreadable or nameless manifest falls back to the directory name.
if existing, err := documentpkg.ManifestFile(root).Read(); err == nil {
name = existing.Name
}
}
if name == "" {
name = filepath.Base(root)
}
return &documentpkg.Manifest{
SchemaVersion: documentpkg.ManifestSchemaVersion,
Name: name,
Server: documentpkg.ManifestServer{
Packages: map[catalog.Ecosystem]map[string]documentpkg.Requirement{},
},
}, nil
}
// promptRuntime asks the caller to disambiguate several equally valid
// runtimes and applies the selection to observed.
func promptRuntime(opts InitOptions, observed *workspace.Workspace) error {
if opts.Expectation != nil || observed.Runtime() != nil || opts.PromptRuntime == nil {
return nil
}
var selectionErr *discovery.SelectionError
if !errors.As(observed.SelectionError(), &selectionErr) ||
selectionErr.State != discovery.SelectionAmbiguous {
return nil
}
installation, err := opts.PromptRuntime(observed.Discovery)
if err != nil {
return err
}
if installation == nil {
return nil
}
return observed.Select(discovery.Request{Installation: installation})
}
// errNoServerDetected reports an adopted tree that holds no runtime. Import
// extracts such a tree instead of failing.
var errNoServerDetected = errors.New("no server detected")
// applyRuntimeIdentity records the observed server's product, versions, and
// directory in the manifest.
func (s *Service) applyRuntimeIdentity(
ctx context.Context,
root string,
manifest *documentpkg.Manifest,
observed *workspace.Workspace,
) error {
selection := observed.Runtime()
if selection == nil {
if selectionErr := observed.SelectionError(); selectionErr != nil {
var typed *discovery.SelectionError
noServer := errors.As(selectionErr, &typed) &&
typed.State == discovery.SelectionNone
if !noServer {
return selectionErr
}
}
return fmt.Errorf(
"%w; use `lucy create` to generate a new server",
errNoServerDetected,
)
}
identity := selection.Installation.Identity
manifest.Server.Minecraft = selection.MinecraftVersion()
if detected := selection.Product(); detected != serverpkg.ProductUnknown {
manifest.Server.Core.Product = detected
} else {
manifest.Server.Core.Product = serverpkg.Product(
identity.Primary.Name.String(),
)
}
if identity.Primary.Version != "" &&
!identity.Primary.Version.IsInvalid() &&
!identity.Primary.Version.CanInfer() {
manifest.Server.Core.ProductVersion = identity.Primary.Version
}
if paperLineageProduct(manifest.Server.Core.Product) &&
!concreteVersion(manifest.Server.Core.ProductVersion) {
build, found, err := s.identifyInstalledCoreBuild(
ctx,
root,
selection.Installation,
manifest.Server.Core.Product,
)
if err != nil {
return err
}
if !found {
return fmt.Errorf(
"cannot identify the installed %s build; restore the "+
"published %s-<minecraft>-<build>.jar name or pin "+
"the core version in lucy.yaml",
manifest.Server.Core.Product,
manifest.Server.Core.Product,
)
}
manifest.Server.Core.ProductVersion = build
}
if observed.ServerDir == "" {
manifest.Server.Directory = "."
} else {
relative, err := filepath.Rel(root, observed.ServerDir)
if err != nil {
return err
}
manifest.Server.Directory = filepath.ToSlash(relative)
}
s.logger.Debug(
"detected server runtime",
"minecraft", manifest.Server.Minecraft,
"product", manifest.Server.Core.Product,
"core-version", manifest.Server.Core.ProductVersion,
"directory", manifest.Server.Directory,
)
return nil
}
// identificationOutcome separates a cancellation, which aborts
// initialization, from identification failures. A failure leaves the file
// unidentified and adoption reports it when no provider identifies it.
func identificationOutcome(errs []error) (error, []error) {
var fatal error
warnings := make([]error, 0, len(errs))
for _, err := range errs {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
fatal = err
continue
}
warnings = append(warnings, err)
}
return fatal, warnings
}
// applyDetectedVersions completes the server declaration from observation:
// a concrete Minecraft version, the default product, and the MCDR runtime.
func (s *Service) applyDetectedVersions(
manifest *documentpkg.Manifest,
opts InitOptions,
observed *workspace.Workspace,
) error {
if manifest.Server.Minecraft == "" || manifest.Server.Minecraft.IsInvalid() {
return fmt.Errorf(
"the detected server has no concrete Minecraft version",
)
}
if manifest.Server.Core.Product == serverpkg.ProductUnknown {
manifest.Server.Core.Product = serverpkg.ProductMinecraft
s.logger.Debug(
"core product defaulted",
"product", manifest.Server.Core.Product,
)
}
mcdrVersion := version.Version(opts.MCDRVersion)
detectedMCDR := observed != nil && observed.Wrappers.MCDR != nil
if mcdrVersion == "" && detectedMCDR {
observedVersion := observed.Wrappers.MCDR.Version
if observedVersion.IsInvalid() || observedVersion.CanInfer() {
// The lock needs a concrete version, so resolution records the
// latest published release. The warning keeps this substitution
// visible to the user.
observed.Warnings = append(observed.Warnings, fmt.Errorf("failed to detect the system's MCDReforged version"))
} else {
mcdrVersion = observedVersion
s.logger.Debug(
"MCDR version from workspace detection",
"version", mcdrVersion,
)
}
}
if mcdrVersion != "" || detectedMCDR {
if mcdrVersion == "" {
mcdrVersion = version.Any
}
manifest.MCDR = &documentpkg.ManifestMCDR{
Directory: ".",
Version: mcdrVersion,
Packages: map[string]documentpkg.Requirement{},
}
}
return nil
}
// resolveAdoptedLock resolves the observed declaration. Module requirements
// the installed jars report but the catalogue metadata cannot satisfy become
// warnings instead of a refusal, because adoption records the set the server
// already runs. A missing module the adoption report already named with its
// files does not warn again. The selected runtime's observed files are offered
// to resolution, so verified local bytes are imported instead of downloaded.
func (s *Service) resolveAdoptedLock(
ctx context.Context,
root string,
manifest *documentpkg.Manifest,
old *documentpkg.Lock,
opts InitOptions,
observed *workspace.Workspace,
runtimeObserved *runtimeObservation,
releases []install.AdoptedRelease,
reportedMissing map[string]struct{},
) (*documentpkg.Lock, error) {
var localRuntime []install.AdoptedRuntimeFile
if runtimeObserved != nil {
localRuntime = runtimeObserved.files
}
resolved, resolution, err := s.install.Resolve(
ctx,
root,
manifest,
old,
install.Options{
AcceptBroken: true,
Trace: opts.Trace,
Materialize: opts.Materialize,
Adopted: releases,
LocalRuntime: localRuntime,
},
)
if observed != nil && resolution != nil {
warnings := resolution.Warnings
if len(reportedMissing) > 0 {
warnings = dropReportedMissingModules(warnings, reportedMissing)
}
observed.Warnings = append(observed.Warnings, warnings...)
}
if err != nil {
return nil, err
}
return resolved, nil
}
// dropReportedMissingModules drops resolution warnings for absent modules the
// adoption report already named. Every other warning stays.
func dropReportedMissingModules(
warnings []error,
reported map[string]struct{},
) []error {
kept := warnings[:0]
for _, warning := range warnings {
var missing *resolve.MissingModuleError
if errors.As(warning, &missing) {
if _, ok := reported[missing.Required]; ok {
continue
}
}
kept = append(kept, warning)
}
return kept
}
// publishInitialization commits the manifest, lock, and receipt together,
// then registers the workspace and publishes the user configuration.
func (s *Service) publishInitialization(
ctx context.Context,
root string,
manifest *documentpkg.Manifest,
old *documentpkg.Lock,
resolved *documentpkg.Lock,
adoptedPackages []install.AdoptedPackage,
runtimeObserved *runtimeObservation,
observed *workspace.Workspace,
opts InitOptions,
documents install.WorkspaceDocuments,
) (*InitResult, error) {
configurationPath := filepath.Join(root, filepath.FromSlash(config.WorkspaceFilename))
if err := workspacewrite.SafePath(root, config.WorkspaceFilename); err != nil {
return initResult(observed), err
}
_, configErr := os.Lstat(configurationPath)
publishedConfig := errors.Is(configErr, os.ErrNotExist)
if configErr != nil && !publishedConfig {
return initResult(observed), configErr
}
if err := ctx.Err(); err != nil {
return initResult(observed), err
}
const imagePhase = "runtime image"
opts.Trace.ReportPhaseStarted(imagePhase)
imageStarted := time.Now()
image, err := s.install.RuntimeImage(ctx, root, resolved, install.Options{
Trace: opts.Trace,
Materialize: opts.Materialize,
})
if errors.Is(err, install.ErrRuntimeImageUnavailable) {
observed.Warnings = append(observed.Warnings, fmt.Errorf(
"%w; the next lucy install verifies and owns the remaining runtime files",
err,
))
} else if err != nil {
return initResult(observed), err
}
opts.Trace.ReportPhase(install.PhaseInfo{
Name: imagePhase,
Elapsed: time.Since(imageStarted),
Count: len(image),
})
var runtimeFiles []install.AdoptedRuntimeFile
if runtimeObserved != nil {
// Re-discover from disk instead of trusting the in-memory selection
// that may predate the ambiguity prompt or network identification.
// Installation membership binds the same observed runtime without
// turning a member path into a selection key.
fresh := workspace.ObserveRuntime(root, discovery.Request{})
freshInstallation := fresh.Discovery.FindInstallation(runtimeObserved.members)
if err := runtimeObserved.verify(freshInstallation); err != nil {
return initResult(observed), err
}
runtimeFiles = runtimeObserved.files
}
manifestFile := documentpkg.ManifestFile(root)
if opts.Force {
manifestFile = manifestFile.WithoutMerge()
}
if opts.NoComments {
manifestFile = manifestFile.WithEncoder(
(*documentpkg.Manifest).PlainBytes,
)
}
var manifestMerge func([]byte) ([]byte, error)
if !opts.Force && !opts.NoComments {
manifestMerge = manifest.MergeBytes
}
publishLock := resolved != old
// Adoption publishes the manifest, lock, and receipt as one workspace
// transaction. Registration runs only after that commit because the
// registry reads the manifest, and no document is written ahead of the
// transaction. The operation lease stays held until registration
// completes: the artifact store's sweep cannot reclaim the bytes
// resolution materialized while the workspace still had no visible lock.
var committedErr *install.CommittedError
adoptWarnings, adoptErr := install.AdoptExistingWorkspace(root, install.AdoptOptions{
Manifest: manifest,
Lock: resolved,
Image: image,
RuntimeFiles: runtimeFiles,
Packages: adoptedPackages,
Logger: s.logger,
PublishLock: publishLock,
ManifestSnapshot: func() ([]byte, error) {
return manifestFile.Snapshot(manifest)
},
ManifestMerge: manifestMerge,
Preconditions: documents,
})
if adoptErr != nil && !errors.As(adoptErr, &committedErr) {
return initResult(observed), adoptErr
}
result := &InitResult{
Document: manifest,
Lock: resolved,
PublishedLock: publishLock,
}
if observed != nil {
result.Warnings = observed.Warnings
result.Discovery = observed.Discovery
}
result.Warnings = append(result.Warnings, adoptWarnings...)
// Registration is required even when the transaction committed but its
// cleanup or post-commit verification failed: the published lock must stay
// traceable by the artifact store's sweep. The original committed error is
// returned after registration, never replaced by it.
duplicates, regErr := s.registerWorkspace(root)
if regErr != nil {
regErr = fmt.Errorf("register server: %w", regErr)
if adoptErr != nil {
return result, errors.Join(adoptErr, regErr)
}
return result, regErr
}
for _, duplicate := range duplicates {
result.Warnings = append(result.Warnings, fmt.Errorf(
"server name %q is also registered at %s; --server cannot select an ambiguous name",
duplicate.Name,
duplicate.Path,
))
}
if adoptErr != nil {
// The manifest, lock, and receipt reached the commit point. Do not
// publish user configuration past a failed transaction completion.
return result, adoptErr
}
if publishedConfig {
created, err := config.CreateWorkspace(root, opts.NoComments)
if err != nil {
return result, err
}
publishedConfig = created
}
result.PublishedConfig = publishedConfig
return result, nil
}
package operation
import (
"context"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
documentpkg "github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/resolve"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/workspace"
)
// packageAdopter recognizes installed packages against the servers and
// ecosystems this workspace already loads. The file is the ownership unit:
// observation reports one entry per descriptor, so several entries can name
// one file, and adoption claims that path once. A manifest requirement names
// one project, so two different files that identify the same project cannot
// both be managed: the key would record only the last file while the receipt
// and fingerprint claim both. Conflicting projects stay unmanaged.
type packageAdopter struct {
service *Service
root string
manifest *documentpkg.Manifest
observed *workspace.Workspace
served map[catalog.Ecosystem]struct{}
mappers []upstream.ArtifactReleaseMapper
accepted []acceptedPackage
index map[string]int
conflicts map[string]bool
target resolve.Target
moduleClaims map[resolve.ModuleIdentity]moduleClaim
}
// acceptedPackage is one installed file adoption manages. The embedded
// release is the resolver input; PackageID and Mode complete the receipt
// entry. A conflict invalidates this record so the file contributes neither
// a receipt entry nor a resolver candidate. The record keeps its index while
// invalid, so the module claims of accepted files stay addressable.
type acceptedPackage struct {
install.AdoptedRelease
PackageID string
Mode uint32
valid bool
}
// moduleClaim names the recorded package that answers one module identity.
type moduleClaim struct {
index int
module catalog.DescriptorModule
}
// moduleCollision pairs a proposed module with a claim on one of its
// identities.
type moduleCollision struct {
identity resolve.ModuleIdentity
module catalog.DescriptorModule
prior moduleClaim
}
// adoptionProposal is one file's probe result. Probing reads the file and its
// upstream identity without mutating the adopter, so probes can run in
// parallel and apply in a deterministic order.
type adoptionProposal struct {
pkg workspace.DiscoveredPackage
analysis *artifact.Analysis
ecosystem catalog.Ecosystem
key string
reference string
packageID string
sha256 string
mode uint32
candidate upstream.Candidate
matched bool
modules []catalog.DescriptorModule
fatal error
warnings []error
// mapped marks a file whose local evidence is collected and which joins
// the shared hash lookup.
mapped bool
}
// adoptInstalledPackages adds requirements for the packages discovery
// identified and returns the ownership claims installation must record,
// together with the releases resolution selects for them and the absent
// modules the adoption report already named. known holds the resolutions an
// earlier identification pass obtained for these paths, so adoption never
// resends them to the provider chain.
func (s *Service) adoptInstalledPackages(
ctx context.Context,
root string,
manifest *documentpkg.Manifest,
observed *workspace.Workspace,
known map[string]upstream.ArtifactReleaseResolution,
) (
packages []install.AdoptedPackage,
releases []install.AdoptedRelease,
reportedMissing map[string]struct{},
inspected int,
err error,
) {
mappers, err := s.packageMappers()
if err != nil {
return nil, nil, nil, 0, err
}
mcdrVersion := ""
if manifest.MCDR != nil {
mcdrVersion = string(manifest.MCDR.Version)
}
adopter := &packageAdopter{
service: s,
root: root,
manifest: manifest,
observed: observed,
served: servedEcosystemSet(manifest, observed),
mappers: mappers,
index: map[string]int{},
conflicts: map[string]bool{},
target: resolve.Target{
Product: manifest.Server.Core.Product,
Minecraft: manifest.Server.Minecraft,
CoreVersion: manifest.Server.Core.ProductVersion,
MCDRVersion: mcdrVersion,
},
moduleClaims: map[resolve.ModuleIdentity]moduleClaim{},
}
var discovered []workspace.DiscoveredPackage
if observed != nil {
discovered = observed.Packages
}
unique := uniquePackages(discovered, adopter.served)
proposals := make([]adoptionProposal, len(unique))
parallelPackageProbes(ctx, len(unique), func(i int) {
proposals[i] = adopter.prepare(unique[i])
})
if err := ctx.Err(); err != nil {
return nil, nil, nil, 0, err
}
// Unreadable local evidence invalidates the whole adoption, so this
// check precedes every provider lookup.
for _, proposal := range proposals {
if proposal.fatal != nil {
return nil, nil, nil, 0, proposal.fatal
}
}
resolutions := adopter.lookupReleases(ctx, proposals, known)
if err := ctx.Err(); err != nil {
return nil, nil, nil, 0, err
}
parallelPackageProbes(ctx, len(proposals), func(i int) {
adopter.complete(ctx, &proposals[i], resolutions[i])
})
if err := ctx.Err(); err != nil {
return nil, nil, nil, 0, err
}
for i := range proposals {
if err := proposals[i].fatal; err != nil {
return nil, nil, nil, 0, err
}
}
for _, proposal := range proposals {
adopter.apply(proposal)
}
if observed != nil {
for _, path := range observed.UnidentifiedPackageFiles {
if lookupErrors := known[path].Errors; len(lookupErrors) != 0 {
adopter.warn("%v", incompleteHashLookupWarning("package", path, lookupErrors))
}
}
}
reportedMissing = adopter.reportMissingModules(proposals)
// Derive the receipt entries and the resolver input from the accepted
// records in one pass; an invalidated record contributes to neither.
packages = make([]install.AdoptedPackage, 0, len(adopter.accepted))
releases = make([]install.AdoptedRelease, 0, len(adopter.accepted))
for _, accepted := range adopter.accepted {
if !accepted.valid {
continue
}
packages = append(packages, install.AdoptedPackage{
Path: accepted.Path,
PackageID: accepted.PackageID,
ExpectedSHA256: accepted.SHA256,
ExpectedMode: accepted.Mode,
})
releases = append(releases, accepted.AdoptedRelease)
}
s.logger.Debug(
"recognized existing packages",
"count", len(packages),
"present", len(discovered),
)
return packages, releases, reportedMissing, len(unique), nil
}
// uniquePackages keeps one entry per file, preferring an ecosystem the server
// serves. Observation reports one entry per descriptor, so a jar carrying
// descriptors for several loaders would otherwise be claimed several times.
func uniquePackages(
discovered []workspace.DiscoveredPackage,
served map[catalog.Ecosystem]struct{},
) []workspace.DiscoveredPackage {
positions := make(map[string]int, len(discovered))
unique := make([]workspace.DiscoveredPackage, 0, len(discovered))
for _, p := range discovered {
if p.Path == "" || !artifact.SupportsPath(p.Path) {
continue
}
path := filepath.Clean(p.Path)
position, seen := positions[path]
if !seen {
positions[path] = len(unique)
unique = append(unique, p)
continue
}
if _, current := served[unique[position].ID.Ecosystem]; current {
continue
}
if _, replacement := served[p.ID.Ecosystem]; replacement {
unique[position] = p
}
}
return unique
}
// packageMapperProviders are the hash mappers that identify installed
// packages, in trial order. A file that Modrinth identifies is managed under
// Modrinth even when CurseForge also matches it.
var packageMapperProviders = []catalog.Provider{
catalog.ProviderModrinth,
catalog.ProviderCurseForge,
}
// packageProbeLimit bounds concurrent package I/O during initialization and
// import. Probes read local descriptors and collect digests; one shared lookup
// then batches provider requests, so an unbounded fan-out over a large modpack
// cannot rate-limit them.
const packageProbeLimit = 8
func parallelPackageProbes(ctx context.Context, count int, run func(int)) {
var next atomic.Int64
var wg sync.WaitGroup
for range min(count, packageProbeLimit) {
wg.Go(func() {
for ctx.Err() == nil {
i := int(next.Add(1) - 1)
if i >= count {
return
}
run(i)
}
})
}
wg.Wait()
}
// packageMappers returns the configured release mappers in trial order. A
// provider without a configured mapper is skipped, not an error.
func (s *Service) packageMappers() ([]upstream.ArtifactReleaseMapper, error) {
var mappers []upstream.ArtifactReleaseMapper
for _, provider := range packageMapperProviders {
release, ok, err := s.source.GetArtifactReleaseMapper(provider)
if err != nil {
return nil, err
}
if !ok {
continue
}
mappers = append(mappers, release)
}
return mappers, nil
}
// prepare collects the local evidence a hash lookup needs. A file whose digest
// or metadata cannot be read fails adoption before any provider is queried, and
// a file MCDR owns or no mapper covers is never sent to the mappers.
func (a *packageAdopter) prepare(
p workspace.DiscoveredPackage,
) adoptionProposal {
proposal := adoptionProposal{pkg: p, analysis: a.observed.PackageAnalysis(p.Path)}
if p.ID.Ecosystem == catalog.EcosystemMCDR || len(a.mappers) == 0 {
return proposal
}
sha256, err := proposal.analysis.SHA256()
if err != nil {
proposal.fatal = fmt.Errorf("digest package %s: %w", p.Path, err)
return proposal
}
info, err := os.Lstat(p.Path)
if err != nil {
proposal.fatal = fmt.Errorf("inspect package %s: %w", p.Path, err)
return proposal
}
proposal.mapped = true
proposal.sha256 = sha256
proposal.mode = uint32(info.Mode().Perm())
return proposal
}
// lookupReleases resolves the prepared files identification has not already
// resolved. A path an earlier pass resolved, including a clean miss or a
// provider failure, is reused as is, so each file enters the provider chain at
// most once. The remaining files share one batched lookup. A provider
// identifies a package only by a named release, so a mapper that matched
// without a project name leaves the file to the next provider.
func (a *packageAdopter) lookupReleases(
ctx context.Context,
proposals []adoptionProposal,
known map[string]upstream.ArtifactReleaseResolution,
) []upstream.ArtifactReleaseResolution {
resolutions := make([]upstream.ArtifactReleaseResolution, len(proposals))
fingerprints := make([]upstream.ArtifactFingerprint, 0, len(proposals))
positions := make([]int, 0, len(proposals))
for i := range proposals {
if !proposals[i].mapped {
// MCDR uses its own catalogue to match releases, but can retain
// diagnostics from an earlier lookup without querying mappers.
resolutions[i].Errors = known[proposals[i].pkg.Path].Errors
continue
}
if resolution, ok := known[proposals[i].pkg.Path]; ok {
resolutions[i] = resolution
continue
}
positions = append(positions, i)
fingerprints = append(fingerprints, proposals[i].analysis)
}
if len(fingerprints) == 0 {
return resolutions
}
found := upstream.LookupArtifactReleases(
ctx,
fingerprints,
a.mappers,
func(release upstream.Release) bool { return release.Ref.Name != "" },
)
for j, position := range positions {
resolutions[position] = found[j]
}
return resolutions
}
// complete turns one resolution into either an adopted release or the
// descriptor report that explains why the file stays unmanaged. A provider
// failure never excludes the file: another provider may still identify it, and
// otherwise the file is reported once.
func (a *packageAdopter) complete(
ctx context.Context,
proposal *adoptionProposal,
resolution upstream.ArtifactReleaseResolution,
) {
for _, providerErr := range resolution.Errors {
a.service.logger.Debug(
"artifact hash lookup failed",
"path", proposal.pkg.Path,
"provider", providerErr.Provider,
"error", providerErr.Err,
)
}
if resolution.Matched {
// A provider that identifies the file already answers its project,
// version, and release, so descriptor inspection cannot add ownership.
a.adoptMapped(ctx, proposal, resolution)
return
}
a.probeDescriptor(ctx, proposal, resolution.Errors)
}
// probeDescriptor classifies a file no provider identified. Adoption needs a
// release, so this path only explains why the file stays unmanaged.
func (a *packageAdopter) probeDescriptor(
ctx context.Context,
proposal *adoptionProposal,
lookupErrors []upstream.ProviderError,
) {
p := proposal.pkg
ecosystem := p.ID.Ecosystem
if ecosystem != catalog.EcosystemMCDR {
if _, ok := a.served[ecosystem]; !ok {
var adopted bool
ecosystem, adopted = servedEcosystemForFile(
ctx,
proposal.analysis,
a.served,
string(a.manifest.Server.Minecraft),
)
if !adopted {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: the server does not load %s",
p.Path,
p.ID.Ecosystem,
))
return
}
}
}
proposal.ecosystem = ecosystem
view, err := proposal.analysis.Descriptor(ctx, ecosystem, string(a.manifest.Server.Minecraft))
if err != nil {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: read descriptor: %w",
p.Path,
err,
))
return
}
if view.ClientOnly {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: client-only %s",
p.Path,
ecosystem,
))
return
}
modules := view.Modules
if len(modules) == 0 {
proposal.warnings = append(proposal.warnings, a.importWarning(
importWarningNoServerModule,
p.Path,
"package %s left unmanaged: its descriptor declares no server-side module",
p.Path,
))
return
}
proposal.modules = modules
if ecosystem == catalog.EcosystemMCDR {
a.probeMCDR(ctx, proposal, lookupErrors)
return
}
if len(lookupErrors) != 0 {
proposal.warnings = append(proposal.warnings, incompleteHashLookupWarning("package", p.Path, lookupErrors))
return
}
proposal.warnings = append(proposal.warnings, a.importWarning(
importWarningNoProvider,
p.Path,
"package %s left unmanaged: no configured provider identifies its hash",
p.Path,
))
}
func (a *packageAdopter) probeMCDR(
ctx context.Context,
proposal *adoptionProposal,
lookupErrors []upstream.ProviderError,
) {
p := proposal.pkg
moduleID := proposal.modules[0].ID
if a.manifest.MCDR == nil {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"plugin %s left unmanaged: MCDReforged is not configured",
p.Path,
))
return
}
pluginDirectory := filepath.Join(
a.root,
a.manifest.MCDR.Directory,
"plugins",
)
if filepath.Clean(filepath.Dir(p.Path)) != filepath.Clean(pluginDirectory) {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"plugin %s left unmanaged: MCDReforged loads it outside the default plugins directory",
filepath.Base(p.Path),
))
return
}
candidates, err := a.service.source.Candidates(
ctx,
catalog.RegistryMCDR,
moduleID,
string(a.manifest.Server.Minecraft),
catalog.EcosystemMCDR,
)
if err != nil {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"plugin %s left unmanaged: MCDReforged catalogue lookup failed: %w",
p.Path,
err,
))
return
}
sha256, err := proposal.analysis.SHA256()
if err != nil {
proposal.fatal = fmt.Errorf("digest package %s: %w", p.Path, err)
return
}
for _, candidate := range candidates {
if !strings.EqualFold(candidate.Hashes["sha256"], sha256) {
continue
}
info, err := os.Lstat(p.Path)
if err != nil {
proposal.fatal = fmt.Errorf("inspect package %s: %w", p.Path, err)
return
}
packageID := "mcdr:" + candidate.ProjectID
proposal.key = packageKey(catalog.EcosystemMCDR, packageID)
proposal.packageID = packageID
proposal.reference = packageID
proposal.sha256 = sha256
proposal.mode = uint32(info.Mode().Perm())
proposal.candidate = candidate
proposal.matched = true
return
}
if len(lookupErrors) != 0 {
proposal.warnings = append(proposal.warnings, incompleteHashLookupWarning("plugin", p.Path, lookupErrors))
return
}
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"plugin %s left unmanaged: no listed release matches its bytes",
p.Path,
))
}
func incompleteHashLookupWarning(kind, path string, failures []upstream.ProviderError) error {
reasons := make([]string, len(failures))
for i, failure := range failures {
reasons[i] = failure.Error()
}
return fmt.Errorf("%s %s left unmanaged: provider hash lookup incomplete: %s", kind, path, strings.Join(reasons, "; "))
}
// adoptMapped records an installed package a provider identified by content
// hash. The file's own descriptor decides whether a dedicated server can load
// it; the release only supplies identity, a download URL, and advisory labels,
// so a remote side label never excludes an installed file the descriptor
// accepts. A loader mismatch is reported but does not by itself prevent
// adoption.
func (a *packageAdopter) adoptMapped(
ctx context.Context,
proposal *adoptionProposal,
resolution upstream.ArtifactReleaseResolution,
) {
p := proposal.pkg
release := resolution.Release
provider := resolution.Provider
ecosystem, local := a.descriptorEcosystem(ctx, p, proposal.analysis)
if !local {
served, ok := a.releaseEcosystem(p, release)
if !ok {
a.warnLoaderMismatch(
proposal,
provider,
release,
a.serverEcosystem(),
)
return
}
ecosystem = served
}
clientOnly, known, sideEcosystem, sideErr := a.descriptorSide(
ctx,
proposal.analysis,
ecosystem,
p.ID.Ecosystem,
)
loaderMismatch := !release.SupportsLoader(ecosystem)
if sideErr != nil {
if loaderMismatch {
a.warnLoaderMismatch(proposal, provider, release, ecosystem)
} else {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: read descriptor: %w",
p.Path,
sideErr,
))
}
return
}
if known && clientOnly {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: client-only %s",
p.Path,
sideEcosystem,
))
return
}
if loaderMismatch {
a.warnLoaderMismatch(proposal, provider, release, ecosystem)
if !known {
return
}
}
// A mapped release becomes a locked requirement, so its descriptor
// must be readable and declare a server-visible module. A library
// archive is loaded by the loader but is not a package Lucy can
// resolve, so it stays unmanaged.
view, readErr := proposal.analysis.Descriptor(ctx, ecosystem, string(a.manifest.Server.Minecraft))
if readErr != nil {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: read descriptor: %w",
p.Path,
readErr,
))
return
}
modules := view.Modules
if len(modules) == 0 {
// A descriptor without a server module is not evidence the server
// can load the file; resolution cannot satisfy the locked build.
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s left unmanaged: its descriptor declares no server-side module",
p.Path,
))
return
}
proposal.modules = modules
if !known {
switch {
case release.ServerSide == upstream.ServerSideUnsupported:
proposal.warnings = append(proposal.warnings, a.importWarning(
importWarningRemoteSide,
p.Path,
"package %s left unmanaged: its release does not support a dedicated server",
p.Path,
))
return
case release.ClientOnly():
proposal.warnings = append(proposal.warnings, a.importWarning(
importWarningRemoteSide,
p.Path,
"package %s left unmanaged: its release declares client-only support",
p.Path,
))
return
}
}
if release.Candidate.ProjectID == "" {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s matched %s but its release has no project ID",
p.Path,
provider,
))
return
}
if release.Candidate.URL == "" {
// A lock needs a source for replay when its store object is missing.
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s matched %s but its release has no download URL",
p.Path,
provider,
))
return
}
candidate := release.Candidate
if !release.Supports(
string(a.manifest.Server.Minecraft),
ecosystem,
) {
if !loaderMismatch {
proposal.warnings = append(proposal.warnings, fmt.Errorf(
"package %s: %s lists release %s for another server; adopting the installed file",
p.Path,
provider,
release.Ref.Version,
))
}
candidate.CompatibilityUnknown = true
}
providerName := string(provider)
proposal.ecosystem = ecosystem
proposal.reference = providerName + ":" + release.Ref.Name.String()
proposal.packageID = providerName + ":" + candidate.ProjectID
proposal.key = packageKey(ecosystem, proposal.packageID)
proposal.candidate = candidate
proposal.matched = true
}
// descriptorSide reads the file's side evidence. The served loader decides
// first; a file it has no descriptor for (a Fabric jar bridged by Connector)
// is checked with the descriptor the file carries, so a client-only bridge
// cannot slip onto the server.
func (a *packageAdopter) descriptorSide(
ctx context.Context,
analysis *artifact.Analysis,
ecosystem catalog.Ecosystem,
fileEcosystem catalog.Ecosystem,
) (clientOnly, known bool, sideEcosystem catalog.Ecosystem, err error) {
minecraft := string(a.manifest.Server.Minecraft)
view, err := analysis.Descriptor(ctx, ecosystem, minecraft)
clientOnly, known = view.ClientOnly, view.Known
if err != nil || known || fileEcosystem == ecosystem ||
fileEcosystem == catalog.EcosystemUnspecified ||
fileEcosystem == catalog.EcosystemMCDR {
return clientOnly, known, ecosystem, err
}
if _, served := a.served[fileEcosystem]; !served {
return clientOnly, known, ecosystem, err
}
bridged, bridgedErr := analysis.Descriptor(ctx, fileEcosystem, minecraft)
if bridgedErr == nil && bridged.Known {
return bridged.ClientOnly, true, fileEcosystem, nil
}
return clientOnly, known, ecosystem, err
}
// descriptorEcosystem reports the served loader whose descriptor the file
// carries. The file's own descriptor ecosystem wins; a file the server has no
// descriptor for (a bridged Fabric jar) is tried with each served loader.
func (a *packageAdopter) descriptorEcosystem(
ctx context.Context,
p workspace.DiscoveredPackage,
analysis *artifact.Analysis,
) (catalog.Ecosystem, bool) {
if _, served := a.served[p.ID.Ecosystem]; served &&
p.ID.Ecosystem != catalog.EcosystemMCDR {
return p.ID.Ecosystem, true
}
return servedEcosystemForFile(
ctx,
analysis,
a.served,
string(a.manifest.Server.Minecraft),
)
}
// serverEcosystem names the loader a warning should attribute the server to.
func (a *packageAdopter) serverEcosystem() catalog.Ecosystem {
product := catalog.Ecosystem(a.manifest.Server.Core.Product)
if product != catalog.EcosystemUnspecified &&
product != catalog.EcosystemMinecraft {
return product
}
for _, ecosystem := range slices.Sorted(maps.Keys(a.served)) {
if ecosystem != catalog.EcosystemMCDR {
return ecosystem
}
}
if product != catalog.EcosystemUnspecified {
return product
}
return catalog.EcosystemMinecraft
}
// warnLoaderMismatch reports a release whose loader labels do not include the
// loader the server runs. The message is reporting only: a local descriptor
// that proves the file loads still lets adoption manage it.
func (a *packageAdopter) warnLoaderMismatch(
proposal *adoptionProposal,
provider catalog.Provider,
release upstream.Release,
ecosystem catalog.Ecosystem,
) {
proposal.warnings = append(proposal.warnings, a.importWarning(
importWarningLoaderMismatch,
proposal.pkg.Path,
"package %s matched %s but its release targets %s while the server runs %s",
proposal.pkg.Path,
provider,
strings.Join(release.Loaders, ", "),
ecosystem,
))
}
// releaseEcosystem selects the served ecosystem a release belongs to. The
// file's descriptor ecosystem wins when the server serves it; otherwise the
// release's loader labels decide. A release with no recognized loader labels
// belongs to any served ecosystem.
func (a *packageAdopter) releaseEcosystem(
p workspace.DiscoveredPackage,
release upstream.Release,
) (catalog.Ecosystem, bool) {
if _, served := a.served[p.ID.Ecosystem]; served &&
release.SupportsLoader(p.ID.Ecosystem) {
return p.ID.Ecosystem, true
}
for _, ecosystem := range slices.Sorted(maps.Keys(a.served)) {
if ecosystem == catalog.EcosystemMCDR {
continue
}
if release.SupportsLoader(ecosystem) {
return ecosystem, true
}
}
return catalog.EcosystemUnspecified, false
}
func (a *packageAdopter) apply(proposal adoptionProposal) {
for _, warning := range proposal.warnings {
var importWarn *importWarning
if errors.As(warning, &importWarn) {
if a.observed != nil {
a.observed.Warnings = append(a.observed.Warnings, importWarn)
}
continue
}
a.warn("%v", warning)
}
if !proposal.matched {
return
}
if a.conflicts[proposal.key] {
a.warn(
"package %s left unmanaged: several installed files identify the same project",
proposal.pkg.Path,
)
return
}
if _, exists := a.index[proposal.key]; exists {
prior := a.markConflict(proposal.key)
a.warn(
"package %s left unmanaged: installed jars %s and %s identify the same project",
proposal.reference, prior, proposal.pkg.Path,
)
return
}
if len(proposal.modules) > 0 && a.resolveModuleCollisions(proposal) {
return
}
requirement := documentpkg.Requirement{
Selector: proposal.candidate.Version,
}
if proposal.ecosystem == catalog.EcosystemMCDR {
a.manifest.MCDR.Packages[proposal.reference] = requirement
} else {
a.requirePackageMap(proposal.ecosystem)[proposal.reference] = requirement
}
a.record(proposal)
}
// proposalEnvironment scopes a proposal's module identities like the
// resolver's packages.
func proposalEnvironment(proposal adoptionProposal) serverpkg.Environment {
if proposal.ecosystem == catalog.EcosystemMCDR {
return serverpkg.EnvironmentMCDR
}
return serverpkg.EnvironmentServer
}
// nativeModule reports whether the artifact itself declares the module. A
// bundled module is a loader-selected library; several packages may ship the
// same one, and resolution picks the version. It is not a file conflict.
func nativeModule(module catalog.DescriptorModule) bool {
return module.NestedPath == ""
}
// moduleCollisions lists the proposal's module identities another recorded
// file already provides.
func (a *packageAdopter) moduleCollisions(
proposal adoptionProposal,
) []moduleCollision {
var collisions []moduleCollision
for _, module := range proposal.modules {
if !nativeModule(module) {
continue
}
for _, identity := range a.target.ModuleIdentityKeys(
proposalEnvironment(proposal),
module.Ecosystem,
module,
) {
prior, claimed := a.moduleClaims[identity]
if !claimed {
continue
}
collisions = append(collisions, moduleCollision{
identity: identity,
module: module,
prior: prior,
})
}
}
return collisions
}
// resolveModuleCollisions keeps one file for each module identity. It reports
// whether the proposal loses an identity and must stay unmanaged.
func (a *packageAdopter) resolveModuleCollisions(
proposal adoptionProposal,
) bool {
collisions := a.moduleCollisions(proposal)
if len(collisions) == 0 {
return false
}
for _, collision := range collisions {
if resolve.ModuleOrder(collision.prior.module, collision.module) >= 0 {
a.warnModuleCollision(
proposal.pkg.Path,
a.accepted[collision.prior.index].Path,
collision.identity,
proposal.ecosystem,
)
return true
}
}
var displaced []moduleCollision
for _, collision := range collisions {
if slices.ContainsFunc(displaced, func(prior moduleCollision) bool {
return prior.prior.index == collision.prior.index
}) {
continue
}
displaced = append(displaced, collision)
}
paths := make([]string, len(displaced))
for i, collision := range displaced {
paths[i] = a.accepted[collision.prior.index].Path
}
for _, collision := range displaced {
a.unclaim(collision.prior.index)
}
for i, collision := range displaced {
a.warnModuleCollision(
paths[i],
proposal.pkg.Path,
collision.identity,
proposal.ecosystem,
)
}
return false
}
// warnModuleCollision reports one file left unmanaged because another file
// provides the same module identity.
func (a *packageAdopter) warnModuleCollision(
loserPath string,
winnerPath string,
identity resolve.ModuleIdentity,
ecosystem catalog.Ecosystem,
) {
impact := fmt.Sprintf("%s rejects duplicate module IDs", ecosystem)
if ecosystem == catalog.EcosystemMCDR {
impact = "MCDReforged loads both plugins under the same ID"
}
a.warn(
"package %s left unmanaged: it declares %s module %q, which %s already provides; %s. To keep it instead, remove %s and run `lucy add <file>`.",
loserPath,
ecosystem,
identity.ID,
winnerPath,
impact,
winnerPath,
)
}
// unclaim invalidates a recorded package and removes its project index,
// module claims, and requirement.
func (a *packageAdopter) unclaim(index int) {
if index < 0 || index >= len(a.accepted) {
return
}
accepted := &a.accepted[index]
if !accepted.valid {
return
}
accepted.valid = false
delete(a.index, packageKey(accepted.Ecosystem, accepted.PackageID))
if accepted.Ecosystem == catalog.EcosystemMCDR {
delete(a.manifest.MCDR.Packages, accepted.Reference)
} else {
delete(a.manifest.Server.Packages[accepted.Ecosystem], accepted.Reference)
}
a.dropModuleClaims(index)
}
// dropModuleClaims deletes the module claims recorded for one package.
func (a *packageAdopter) dropModuleClaims(index int) {
for identity, claim := range a.moduleClaims {
if claim.index == index {
delete(a.moduleClaims, identity)
}
}
}
// markConflict invalidates a project key, removes its earlier claim, and
// returns the path that claim had recorded.
func (a *packageAdopter) markConflict(key string) string {
a.conflicts[key] = true
index, exists := a.index[key]
if !exists {
return ""
}
prior := a.accepted[index].Path
a.unclaim(index)
return prior
}
func (a *packageAdopter) record(proposal adoptionProposal) {
index := len(a.accepted)
a.index[proposal.key] = index
a.accepted = append(a.accepted, acceptedPackage{
AdoptedRelease: install.AdoptedRelease{
Reference: proposal.reference,
Ecosystem: proposal.ecosystem,
Candidate: proposal.candidate,
Path: proposal.pkg.Path,
SHA256: proposal.sha256,
Analysis: proposal.analysis,
},
PackageID: proposal.packageID,
Mode: proposal.mode,
valid: true,
})
for _, module := range proposal.modules {
if !nativeModule(module) {
continue
}
for _, identity := range a.target.ModuleIdentityKeys(
proposalEnvironment(proposal),
module.Ecosystem,
module,
) {
a.moduleClaims[identity] = moduleClaim{index: index, module: module}
}
}
}
func (a *packageAdopter) requirePackageMap(
ecosystem catalog.Ecosystem,
) map[string]documentpkg.Requirement {
if a.manifest.Server.Packages[ecosystem] == nil {
a.manifest.Server.Packages[ecosystem] = map[string]documentpkg.Requirement{}
}
return a.manifest.Server.Packages[ecosystem]
}
func packageKey(ecosystem catalog.Ecosystem, packageID string) string {
return string(ecosystem) + "\x00" + packageID
}
// reportMissingModules warns about required descriptor modules that no
// installed file provides and returns the identities it reported. It reads only
// the descriptors the probes already parsed, so it adds no provider lookups.
func (a *packageAdopter) reportMissingModules(
proposals []adoptionProposal,
) map[string]struct{} {
if a.observed == nil {
return nil
}
provided := map[string]struct{}{}
clientOnly := map[string]struct{}{}
for _, proposal := range proposals {
for _, module := range proposal.modules {
addProvidedIdentity(provided, module)
for _, id := range module.ClientOnly {
clientOnly[id] = struct{}{}
}
}
}
required := map[string][]string{}
for _, proposal := range proposals {
path := a.displayPath(proposal.pkg.Path)
for _, module := range proposal.modules {
for _, dependency := range module.Dependencies {
if dependency.Kind != catalog.DependencyKindRequired {
continue
}
id := dependency.ID
if id == "" || runtimeModuleIdentity(id) {
continue
}
if _, skip := clientOnly[id]; skip {
continue
}
if _, ok := provided[id]; ok {
continue
}
required[id] = appendUniqueString(required[id], path)
}
}
}
reported := make(map[string]struct{}, len(required))
for _, id := range slices.Sorted(maps.Keys(required)) {
paths := required[id]
reported[id] = struct{}{}
a.warn(
"module %s is required by %d installed files but no installed file provides it (%s)",
id,
len(paths),
strings.Join(firstExamples(paths, 3), ", "),
)
}
return reported
}
// addProvidedIdentity records every module identity an installed file
// provides to the server.
func addProvidedIdentity(
provided map[string]struct{},
module catalog.DescriptorModule,
) {
add := func(id string) {
if id != "" {
provided[id] = struct{}{}
}
}
add(module.ID)
if module.Group != "" {
add(module.Group + ":" + module.ID)
}
for _, id := range module.Provides {
add(id)
if module.Group != "" {
add(module.Group + ":" + id)
}
}
}
// runtimeModuleIdentity reports a module the server loader itself provides, so
// an installed file is not expected to ship it.
func runtimeModuleIdentity(id string) bool {
switch strings.ToLower(id) {
case "minecraft",
"java",
"forge",
"neoforge",
"fml",
"fabric",
"fabricloader",
"fabric-loader",
"quilt",
"quilt_loader",
"quilt-loader",
"bukkit",
"paper",
"spigot",
"bungeecord",
"velocity",
"sponge",
"mcdr":
return true
default:
return false
}
}
func appendUniqueString(values []string, value string) []string {
if slices.Contains(values, value) {
return values
}
return append(values, value)
}
// firstExamples keeps at most limit distinct paths for a summarized warning.
func firstExamples(paths []string, limit int) []string {
examples := make([]string, 0, limit)
for _, path := range paths {
if slices.Contains(examples, path) {
continue
}
if len(examples) == limit {
break
}
examples = append(examples, path)
}
return examples
}
// displayPath reports a path relative to the workspace, so warnings never leak
// the staging directory.
func (a *packageAdopter) displayPath(path string) string {
if path == "" {
return ""
}
relative, err := filepath.Rel(a.root, path)
if err != nil {
return filepath.ToSlash(path)
}
return filepath.ToSlash(relative)
}
// importWarning builds a warning whose message and example path are relative
// to the workspace.
func (a *packageAdopter) importWarning(
cause importWarningCause,
path, format string,
args ...any,
) *importWarning {
message := fmt.Sprintf(format, args...)
if a.root != "" {
message = strings.ReplaceAll(
message,
a.root+string(filepath.Separator),
"",
)
}
return &importWarning{
cause: cause,
path: a.displayPath(path),
message: message,
}
}
func (a *packageAdopter) warn(format string, args ...any) {
if a.observed == nil {
return
}
message := fmt.Sprintf(format, args...)
message = strings.ReplaceAll(message, a.root+string(filepath.Separator), "")
a.observed.Warnings = append(a.observed.Warnings, errors.New(message))
}
package operation
import (
"context"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"os"
"path/filepath"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
"github.com/mclucy/lucy/workspace/discovery"
)
// runtimeObservation binds the selected runtime identity, membership, and
// regular-file bytes observed before identification performs network work.
// Adoption may only publish these bytes.
type runtimeObservation struct {
product serverpkg.Product
minecraft version.Version
coreVersion version.Version
members map[string]discovery.FileRole
files []install.AdoptedRuntimeFile
}
func captureRuntimeObservation(
installation *discovery.Installation,
) (*runtimeObservation, error) {
if installation == nil {
return nil, nil
}
files, err := adoptedRuntimeFiles(installation)
if err != nil {
return nil, err
}
members := make(map[string]discovery.FileRole, len(installation.Files))
for _, file := range installation.Files {
members[file.Path] = file.Role
}
return &runtimeObservation{
product: installation.Identity.Product(),
minecraft: installation.Identity.MinecraftVersion(),
coreVersion: installation.Identity.Primary.Version,
members: members,
files: files,
}, nil
}
// verify rejects a change to the selected runtime's identity or membership.
func (o *runtimeObservation) verify(installation *discovery.Installation) error {
if o == nil {
if installation != nil {
return errors.New("a runtime appeared after observation; rerun lucy init")
}
return nil
}
if installation == nil {
return errors.New("the observed runtime disappeared during initialization")
}
if installation.Identity.Product() != o.product ||
installation.Identity.MinecraftVersion() != o.minecraft ||
installation.Identity.Primary.Version != o.coreVersion {
return errors.New("the observed runtime identity changed during initialization")
}
if !o.sameMembership(installation.Files) {
return errors.New("the observed runtime membership changed during initialization")
}
return nil
}
func (o *runtimeObservation) sameMembership(files []discovery.File) bool {
if len(files) != len(o.members) {
return false
}
for _, file := range files {
role, ok := o.members[file.Path]
if !ok || role != file.Role {
return false
}
}
return true
}
func adoptedRuntimeFiles(
installation *discovery.Installation,
) ([]install.AdoptedRuntimeFile, error) {
if installation == nil {
return nil, nil
}
files := make([]install.AdoptedRuntimeFile, 0, len(installation.Files))
for _, f := range installation.Files {
info, err := os.Lstat(f.Path)
if err != nil {
return nil, fmt.Errorf("inspect runtime file %s: %w", f.Path, err)
}
if !info.Mode().IsRegular() {
if info.Mode()&os.ModeSymlink != 0 {
// A launcher alias stays unowned; discovery selects the
// canonical target when one exists.
continue
}
return nil, fmt.Errorf("runtime file %s is not a regular file", f.Path)
}
hashes, err := install.DigestFile(f.Path, map[string]string{"sha1": ""})
if err != nil {
return nil, fmt.Errorf("digest runtime file %s: %w", f.Path, err)
}
files = append(files, install.AdoptedRuntimeFile{
Path: f.Path,
Role: f.Role,
ExpectedSHA256: hashes["sha256"],
ExpectedHashes: hashes,
ExpectedMode: workspacewrite.EffectiveInstallMode(info.Mode().Perm()),
})
}
return files, nil
}
// initResult carries the observations of a failed initialization so the
// command boundary can present them alongside the failure.
func initResult(observed *workspace.Workspace) *InitResult {
if observed == nil {
return nil
}
return &InitResult{
Warnings: observed.Warnings,
Discovery: observed.Discovery,
}
}
func concreteVersion(v version.Version) bool {
return v != "" && !v.IsInvalid() && !v.CanInfer()
}
func paperLineageProduct(product serverpkg.Product) bool {
switch product {
case serverpkg.ProductPaper, serverpkg.ProductPurpur, serverpkg.ProductFolia:
return true
default:
return false
}
}
// identifyInstalledCoreBuild asks the source which build the installed Paper
// or Purpur jar is, using the digest that source identifies builds by.
func (s *Service) identifyInstalledCoreBuild(
ctx context.Context,
root string,
installation *discovery.Installation,
product serverpkg.Product,
) (version.Version, bool, error) {
if installation == nil || installation.CorePath == "" {
return "", false, nil
}
hasher, flavor, err := buildDigest(product)
if err != nil {
return "", false, err
}
path := installation.CorePath
if !filepath.IsAbs(path) {
path = filepath.Join(root, path)
}
digest, err := digestFile(hasher, path)
if err != nil {
return "", false, fmt.Errorf("read %s jar: %w", product, err)
}
var build version.Version
var found bool
if product == serverpkg.ProductPurpur {
build, found, err = s.source.IdentifyPurpurBuild(
ctx,
installation.Identity.MinecraftVersion(),
digest,
)
} else {
build, found, err = s.source.IdentifyFillBuild(
ctx,
flavor,
installation.Identity.MinecraftVersion(),
digest,
)
}
if err != nil {
return "", false, fmt.Errorf("identify installed %s build: %w", product, err)
}
return build, found, nil
}
// buildDigest selects the digest algorithm and Fill flavor that identify one
// paper-lineage product.
func buildDigest(product serverpkg.Product) (hash.Hash, string, error) {
switch product {
case serverpkg.ProductPaper:
return sha256.New(), "paper", nil
case serverpkg.ProductFolia:
return sha256.New(), "folia", nil
case serverpkg.ProductPurpur:
return md5.New(), "", nil
default:
return nil, "", fmt.Errorf("product %s has no build digest", product)
}
}
func digestFile(hasher hash.Hash, path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
_, copyErr := io.Copy(hasher, file)
if err := errors.Join(copyErr, file.Close()); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
package operation
import (
"context"
"errors"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/java"
)
// JavaChange edits declared Java requirements. A nil field stays unchanged.
type JavaChange struct {
// Version is the major version that lucy.yaml pins; zero returns it to
// auto.
Version *int
// Distribution is the distribution that lucy.yaml pins; the unspecified
// distribution returns it to auto.
Distribution *java.Distribution
}
// JavaChangeResult reports the declared Java requirements after a change.
type JavaChangeResult struct {
// Java is the override in lucy.yaml; nil means auto.
Java *document.ManifestJava `json:"java,omitempty"`
PublishedManifest bool `json:"published_manifest"`
}
// SetJava changes only the manifest. Installation reconciles the lock.
func (s *Service) SetJava(ctx context.Context, root string, change JavaChange) (result *JavaChangeResult, resultErr error) {
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
d, err := document.ManifestFile(root).Read()
if err != nil {
return nil, err
}
result = &JavaChangeResult{}
if change.Version != nil || change.Distribution != nil {
if err := s.setJavaOverride(root, d, change, result); err != nil {
return nil, err
}
}
result.Java = d.Server.Java
return result, nil
}
func (s *Service) setJavaOverride(root string, d *document.Manifest, change JavaChange, result *JavaChangeResult) error {
before, err := d.Fingerprint()
if err != nil {
return err
}
override := document.ManifestJava{}
if d.Server.Java != nil {
override = *d.Server.Java
}
if change.Version != nil {
override.Version = *change.Version
}
if change.Distribution != nil {
override.Distribution = *change.Distribution
}
d.Server.Java = &override
after, err := d.Fingerprint()
if err != nil {
return err
}
if after == before {
s.logger.Debug("java override unchanged", "reason", "lucy.yaml already declares it")
return nil
}
if err := document.ManifestFile(root).Write(d); err != nil {
return err
}
result.PublishedManifest = true
s.logger.Info(
"java override changed",
"version", override.Version,
"distribution", override.Distribution.String(),
)
return nil
}
package operation
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/internal/workspacewrite"
)
// RenameServer changes only the manifest name of the workspace rooted at root.
// It returns the name the manifest carried before the change. Every other
// declaration, the lockfile, and installed server content stay untouched, so
// no dependency or runtime work follows a rename.
func (s *Service) RenameServer(root string, name string) (previous string, resultErr error) {
root, err := filepath.Abs(root)
if err != nil {
return "", err
}
name, err = document.NormalizeName(name)
if err != nil {
return "", err
}
if err := workspacewrite.SafePath(root, document.ManifestFilename); err != nil {
return "", err
}
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return "", err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return "", err
}
manifest, err := document.ManifestFile(root).Read()
if errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("no lucy workspace found in %s", root)
}
if err != nil {
return "", err
}
previous = manifest.Name
if previous == name {
s.logger.Debug("server name unchanged", "root", root, "name", name)
return previous, nil
}
manifest.Name = name
if err := document.ManifestFile(root).Write(manifest); err != nil {
return "", err
}
s.logger.Info("server renamed", "root", root, "previous", previous, "name", name)
return previous, nil
}
package operation
import (
"context"
"errors"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/serverregistry"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
// Source is the configured routing capability that workspace operations
// consume: catalogue builds, artifact release identification, and build
// identification.
type Source interface {
Candidates(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
ecosystem catalog.Ecosystem,
) ([]upstream.Candidate, error)
GetArtifactReleaseMapper(provider catalog.Provider) (upstream.ArtifactReleaseMapper, bool, error)
IdentifyFillBuild(
ctx context.Context,
project string,
minecraft version.Version,
sha256 string,
) (version.Version, bool, error)
IdentifyPurpurBuild(
ctx context.Context,
minecraft version.Version,
md5 string,
) (version.Version, bool, error)
ResolveArtifactsByHash(
ctx context.Context,
artifacts []upstream.ArtifactFingerprint,
) []upstream.ArtifactReleaseResolution
}
// Service executes workspace operations with dependencies supplied by its
// caller: installation, routing, registry, and diagnostics.
type Service struct {
install *install.Service
source Source
registry *serverregistry.Registry
logger *log.Logger
}
// NewService constructs the operation service. registry may be nil when the
// machine has no registry location; operations report that only when they
// actually need registration state.
func NewService(
installer *install.Service,
source Source,
registry *serverregistry.Registry,
logger *log.Logger,
) *Service {
return &Service{
install: installer,
source: source,
registry: registry,
logger: logger,
}
}
// registerWorkspace records root for the artifact store's retention sweep.
// Operations that publish a lock must not report success when the entry is
// missing, because the sweep could otherwise reclaim that lock's artifacts.
func (s *Service) registerWorkspace(root string) ([]serverregistry.Entry, error) {
if s.registry == nil {
return nil, errors.New("server registry is unavailable; cannot record this workspace for artifact retention")
}
return s.registry.Register(root)
}
package operation
import (
"context"
"errors"
"os"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
)
// Sync converges the workspace to its manifest and lock. A missing manifest or
// lock is allowed only when the other document can drive the operation.
func (s *Service) Sync(ctx context.Context, root string, opts install.Options) (*install.Result, error) {
d, old, err := s.syncDocuments(root)
if err != nil {
return nil, err
}
if err := pinWorkspaceDocuments(&opts, d, old); err != nil {
return nil, err
}
return s.install.Sync(ctx, root, d, old, opts)
}
// syncDocuments reads the documents a converge operation starts from. It takes
// the writer lock and replays interrupted journals first, so the installation
// that re-locks the workspace never plans from pre-recovery state.
func (s *Service) syncDocuments(root string) (manifest *document.Manifest, locked *document.Lock, resultErr error) {
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, nil, err
}
manifest, err = document.ManifestFile(root).Read()
if errors.Is(err, os.ErrNotExist) {
manifest, err = nil, nil
}
if err != nil {
return nil, nil, err
}
locked, err = document.LockFile(root).Read()
if errors.Is(err, os.ErrNotExist) {
locked, err = nil, nil
}
if err != nil {
return nil, nil, err
}
return manifest, locked, nil
}
package operation
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/artifactstore"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/filetrack"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/internal/workspacewrite"
"github.com/mclucy/lucy/resolve"
)
const (
defaultUpgradeCombinations = 32
defaultUpgradeVersions = 6
maxUpgradeFailures = 5
)
// UpgradeOptions selects the manifest roots an upgrade may advance. An empty
// Targets upgrades every enabled root.
type UpgradeOptions struct {
Targets []string
// Offline disallows network acquisition. Upgrade cannot discover newer
// versions offline, so this is only useful when it fails early.
Offline bool
Trace *install.Trace
// Materialize supplies artifact bytes for frontier planning. Nil uses the
// configured cache and network.
Materialize artifact.Materializer
// MaxCombinations and MaxVersions bound the frontier search. Zero uses
// the package defaults.
MaxCombinations int
MaxVersions int
}
// UpgradeMetrics scores one frontier point. UpgradedRoots counts manifest
// roots whose selected build differs from the lock. VersionBumps sums the
// number of newer eligible versions skipped for roots whose version changed.
type UpgradeMetrics struct {
UpgradedRoots int `json:"upgraded_roots"`
VersionBumps int `json:"version_bumps"`
}
// UpgradeOption is one resolved plan and its policy metrics.
type UpgradeOption struct {
Hash string `json:"hash"`
Metrics UpgradeMetrics `json:"metrics"`
Plan *install.Plan `json:"-"`
}
// UpgradeResult carries the bounded Pareto frontier and non-fatal findings.
type UpgradeResult struct {
BaseManifestFingerprint string
BaseLockFingerprint string
Options []UpgradeOption
Warnings []error
}
func (s *Service) PlanUpgrade(
ctx context.Context,
root string,
opts UpgradeOptions,
) (result *UpgradeResult, resultErr error) {
absolute, err := filepath.Abs(root)
if err != nil {
return nil, err
}
root = absolute
d, err := document.ManifestFile(root).Read()
if err != nil {
return nil, err
}
old, err := document.LockFile(root).Read()
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("lucy-lock.yaml is required; run lucy install first")
}
return nil, err
}
baseManifest, err := d.Fingerprint()
if err != nil {
return nil, err
}
if old.ManifestFingerprint != baseManifest {
return nil, fmt.Errorf("manifest changed since the lock; run lucy install first")
}
if err := s.upgradePreflight(ctx, root, d, old); err != nil {
return nil, err
}
baseLock, err := old.Fingerprint()
if err != nil {
return nil, err
}
lease, err := artifactstore.AcquireOperation()
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, lease.Close()) }()
writer, err := workspacewrite.Lock(root, s.logger)
if err != nil {
return nil, err
}
defer func() { resultErr = errors.Join(resultErr, writer.Close()) }()
if err := filetrack.RecoverLocked(root, s.logger); err != nil {
return nil, err
}
// Recovery may have replaced documents, so capture their exact state now:
// this is the base every plan answers, and ApplyPlan may write nothing else.
baseDocuments, err := install.CaptureWorkspaceDocuments(root)
if err != nil {
return nil, err
}
if err := verifyRecoveredBase(
baseDocuments,
baseManifest,
d.Name,
baseLock,
"upgrade",
); err != nil {
return nil, err
}
roots, err := upgradeRoots(d, old)
if err != nil {
return nil, err
}
targets, err := upgradeTargets(roots, opts)
if err != nil {
return nil, err
}
warnings := []error{}
materialize, fetch := s.install.Materializer(install.Options{
Offline: opts.Offline,
Trace: opts.Trace,
Materialize: opts.Materialize,
})
cache := resolve.NewAnalysisCache()
listings := resolve.NewCandidateCache()
maxVersions := opts.MaxVersions
if maxVersions <= 0 {
maxVersions = defaultUpgradeVersions
}
active := make([]int, 0, len(roots))
for i := range roots {
if err := ctx.Err(); err != nil {
return nil, err
}
if !targets[roots[i].Reference] {
continue
}
versions, lockedIndex, lockedRank, upgradable, err := s.upgradeVersions(ctx, roots[i], old, maxVersions)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
if len(opts.Targets) == 0 {
warnings = append(warnings, fmt.Errorf(
"keep %s at %s: %w",
roots[i].Reference,
roots[i].Previous.Version,
err,
))
continue
}
return nil, err
}
roots[i].Versions = versions
roots[i].LockedIndex = lockedIndex
roots[i].LockedRank = lockedRank
// A root is active only when a retained build is newer than its lock.
// A missing locked build ranks below every retained build, so the scan
// reports that case as upgradable directly.
if upgradable {
active = append(active, i)
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(active) == 0 {
option, err := noopUpgradeOption(baseDocuments, d, old, baseManifest, baseLock)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
return &UpgradeResult{
BaseManifestFingerprint: baseManifest,
BaseLockFingerprint: baseLock,
Options: []UpgradeOption{option},
Warnings: warnings,
}, nil
}
maxCombinations := opts.MaxCombinations
if maxCombinations <= 0 {
maxCombinations = defaultUpgradeCombinations
}
combos := upgradeCombinations(roots, active, maxCombinations)
seen := map[string]UpgradeOption{}
failures := []error{}
for _, combo := range combos {
if err := ctx.Err(); err != nil {
return nil, err
}
option, err := s.resolveUpgradeOption(
ctx,
root,
baseDocuments,
d,
old,
baseManifest,
baseLock,
roots,
active,
combo,
materialize,
cache,
listings,
opts.Trace,
)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
s.logger.Debug("upgrade: candidate combination failed", "error", err)
if len(failures) < maxUpgradeFailures {
failures = append(failures, err)
}
continue
}
seen[option.Hash] = option
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(seen) == 0 {
if len(failures) == 0 {
return nil, fmt.Errorf("no eligible upgrade found")
}
return nil, fmt.Errorf("no valid upgrade option: %w", errors.Join(failures...))
}
options := make([]UpgradeOption, 0, len(seen))
for _, option := range seen {
if option.Plan != nil && option.Plan.Result != nil {
option.Plan.Result.Fetch = *fetch
}
options = append(options, option)
}
if len(failures) > 0 {
warnings = append(warnings, fmt.Errorf(
"%d candidate combinations failed; showing the resolvable frontier",
len(failures),
))
}
if err := ctx.Err(); err != nil {
return nil, err
}
return &UpgradeResult{
BaseManifestFingerprint: baseManifest,
BaseLockFingerprint: baseLock,
Options: paretoFrontier(options),
Warnings: warnings,
}, nil
}
// ApplyUpgrade applies one selected option through the install transaction.
func (s *Service) ApplyUpgrade(
ctx context.Context,
root string,
option UpgradeOption,
policy string,
opts install.Options,
) (*install.Result, error) {
if option.Plan == nil {
return nil, fmt.Errorf("upgrade option has no plan")
}
option.Plan.Result.Policy = policy
option.Plan.Result.PlanHash = option.Hash
return s.install.ApplyPlan(ctx, root, option.Plan, opts)
}
// SelectUpgradeOption picks a frontier point for a policy value. A policy that
// is not more/later/options is treated as a plan hash.
func SelectUpgradeOption(result *UpgradeResult, policy string) (*UpgradeOption, error) {
if result == nil || len(result.Options) == 0 {
return nil, fmt.Errorf("no upgrade options")
}
switch policy {
case "", "more", "later":
case "options":
return nil, fmt.Errorf("policy options has no single selection")
default:
for i := range result.Options {
if result.Options[i].Hash == policy {
return &result.Options[i], nil
}
}
return nil, fmt.Errorf("plan hash %q was not found; rerun with --dry-run or --policy options", policy)
}
best := &result.Options[0]
for i := range result.Options[1:] {
candidate := &result.Options[i+1]
switch policy {
case "later":
if candidate.Metrics.VersionBumps > best.Metrics.VersionBumps ||
(candidate.Metrics.VersionBumps == best.Metrics.VersionBumps &&
candidate.Metrics.UpgradedRoots > best.Metrics.UpgradedRoots) {
best = candidate
}
default:
if candidate.Metrics.UpgradedRoots > best.Metrics.UpgradedRoots ||
(candidate.Metrics.UpgradedRoots == best.Metrics.UpgradedRoots &&
candidate.Metrics.VersionBumps > best.Metrics.VersionBumps) {
best = candidate
}
}
}
return best, nil
}
// ListUpgradeRoots returns the enabled manifest roots a user can select.
func ListUpgradeRoots(root string) ([]string, error) {
d, err := document.ManifestFile(root).Read()
if err != nil {
return nil, err
}
var refs []string
for _, ecosystem := range sortedEcosystems(d.Server.Packages) {
for ref, requirement := range d.Server.Packages[ecosystem] {
if requirement.IsEnabled() {
refs = append(refs, ref)
}
}
}
if d.MCDR != nil {
for ref, requirement := range d.MCDR.Packages {
if requirement.IsEnabled() {
refs = append(refs, ref)
}
}
}
slices.Sort(refs)
return refs, nil
}
func (s *Service) upgradePreflight(
ctx context.Context,
root string,
d *document.Manifest,
old *document.Lock,
) error {
if d.Server.Minecraft != old.Server.Minecraft {
return fmt.Errorf("Minecraft %s differs from locked %s; run lucy migrate", d.Server.Minecraft, old.Server.Minecraft)
}
if d.Server.Core.Product != old.Server.Product {
return fmt.Errorf("server product %s differs from locked %s; run lucy migrate", d.Server.Core.Product, old.Server.Product)
}
if !upgradeFloating(d.Server.Core.ProductVersion) && d.Server.Core.ProductVersion != old.Server.CoreVersion {
return fmt.Errorf("server core %s differs from locked %s; run lucy migrate", d.Server.Core.ProductVersion, old.Server.CoreVersion)
}
switch {
case d.MCDR == nil && old.MCDR != nil:
return fmt.Errorf("manifest removed MCDR; run lucy install or lucy migrate")
case d.MCDR != nil && old.MCDR == nil:
return fmt.Errorf("manifest added MCDR; run lucy install or lucy migrate")
case d.MCDR != nil && old.MCDR != nil &&
!upgradeFloating(d.MCDR.Version) && d.MCDR.Version != old.MCDR.Version:
return fmt.Errorf("MCDR %s differs from locked %s; run lucy migrate", d.MCDR.Version, old.MCDR.Version)
}
check, err := s.install.CheckJava(ctx, root, old)
if err != nil {
return err
}
if !check.Satisfied() {
if len(check.Problems) > 0 {
return fmt.Errorf("Java runtime does not satisfy the lock: %s", strings.Join(check.Problems, "; "))
}
return fmt.Errorf("Java %d is required; run lucy install --java", check.Target)
}
return nil
}
package operation
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/install"
"github.com/mclucy/lucy/resolve"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/routing"
versionpkg "github.com/mclucy/lucy/version"
)
func (s *Service) resolveUpgradeOption(
ctx context.Context,
root string,
baseDocuments install.WorkspaceDocuments,
d *document.Manifest,
old *document.Lock,
baseManifest string,
baseLock string,
roots []upgradeRoot,
active []int,
combo []int,
materialize artifact.Materializer,
cache *resolve.AnalysisCache,
listings *resolve.CandidateCache,
trace *install.Trace,
) (UpgradeOption, error) {
resolutionManifest, err := cloneManifest(d)
if err != nil {
return UpgradeOption{}, err
}
pinCoreAndMCDR(resolutionManifest, old)
choices := map[string]versionpkg.Version{}
for i, rootIndex := range active {
root := roots[rootIndex]
choices[root.Reference] = root.Versions[combo[i]].Version
}
for _, root := range roots {
selector := root.Requirement.Selector
if choice, ok := choices[root.Reference]; ok {
selector = choice
} else if root.Previous != nil {
selector = upgradeBuildSelector(upstream.Candidate{Artifact: root.Previous.Artifact})
}
if err := setRootSelector(resolutionManifest, root, selector); err != nil {
return UpgradeOption{}, err
}
}
if err := resolutionManifest.Normalize(); err != nil {
return UpgradeOption{}, err
}
coreModules, moduleErr := routing.CoreModules(
ctx,
old.Server.Product,
old.Server.Artifact,
materialize,
)
if moduleErr != nil {
s.logger.Warn(fmt.Errorf("read server core modules: %w", moduleErr))
}
lockTarget := upgradeTarget(old, coreModules)
packages, resolutionWarnings, err := resolve.Packages(resolve.PackagesRequest{
Context: ctx,
Manifest: resolutionManifest,
Previous: old.Packages,
PreviousTarget: lockTarget,
Target: lockTarget,
Candidates: s.source.Candidates,
Materialize: materialize,
ExpandDependencies: true,
Cache: cache,
Listings: listings,
Logger: s.logger,
Trace: upgradeResolveTrace(trace),
})
if err != nil {
return UpgradeOption{}, err
}
finalManifest, err := cloneManifest(d)
if err != nil {
return UpgradeOption{}, err
}
var manifestChanges []install.ManifestChange
for _, rootIndex := range active {
root := roots[rootIndex]
selected := selectedRootPackage(packages, root)
if selected == nil {
return UpgradeOption{}, fmt.Errorf("resolution did not select %s", root.Reference)
}
if atLeast, comparable := upgradeVersionAtLeast(
selected.Version,
root.Previous.Version,
upgradeArtifactDialect(root.Ecosystem),
); comparable && !atLeast {
return UpgradeOption{}, fmt.Errorf(
"selected %s %s downgrades locked %s",
root.Reference,
selected.Version,
root.Previous.Version,
)
}
if root.Requirement.Selector.CanInfer() || root.Requirement.Selector == "" {
continue
}
if selected.Version == root.Requirement.Selector {
continue
}
if err := setRootSelector(finalManifest, root, selected.Version); err != nil {
return UpgradeOption{}, err
}
manifestChanges = append(manifestChanges, install.ManifestChange{
Reference: root.Reference,
PreviousSelector: root.Requirement.Selector,
Selector: selected.Version,
})
}
if err := finalManifest.Normalize(); err != nil {
return UpgradeOption{}, err
}
requirements := rootRequirements(finalManifest)
for i := range packages {
for j := range packages[i].Requirements {
if requirement, ok := requirements[packages[i].Requirements[j].Reference]; ok {
packages[i].Requirements[j].Selector = requirement.Selector
packages[i].Requirements[j].FilePattern = requirement.FilePattern
packages[i].Requirements[j].Enabled = requirement.IsEnabled()
}
}
}
finalFingerprint, err := finalManifest.Fingerprint()
if err != nil {
return UpgradeOption{}, err
}
resolved := &document.Lock{
SchemaVersion: document.LockSchemaVersion,
ManifestFingerprint: finalFingerprint,
Server: old.Server,
MCDR: old.MCDR,
Packages: packages,
Files: slices.Clone(finalManifest.Files),
}
if err := resolved.Validate(); err != nil {
return UpgradeOption{}, err
}
if fingerprint, err := resolved.Fingerprint(); err == nil && fingerprint == baseLock {
resolved = old
}
metrics := UpgradeMetrics{}
for _, rootIndex := range active {
root := roots[rootIndex]
selected := selectedRootPackage(resolved.Packages, root)
if selected == nil {
continue
}
changed := selected.Version != root.Previous.Version ||
selected.ReleaseID != root.Previous.ReleaseID ||
selected.FileID != root.Previous.FileID
if changed {
metrics.UpgradedRoots++
}
for _, version := range root.Versions {
if version.Version == selected.Version {
if version.Rank < root.LockedRank {
metrics.VersionBumps += root.LockedRank - version.Rank
}
break
}
}
}
publishManifest := finalFingerprint != baseManifest
plan, err := install.PlanFromResolution(baseDocuments, finalManifest, old, resolved, publishManifest)
if err != nil {
return UpgradeOption{}, err
}
plan.Result.ManifestChanges = manifestChanges
plan.Result.Warnings = append(plan.Result.Warnings, resolutionWarnings...)
hash := upgradePlanHash(baseManifest, baseLock, finalFingerprint, resolved.Packages)
plan.Result.PlanHash = hash
return UpgradeOption{
Hash: hash,
Metrics: metrics,
Plan: plan,
}, nil
}
func upgradeBuildSelector(candidate upstream.Candidate) versionpkg.Version {
if candidate.ReleaseID != "" {
return versionpkg.Version(candidate.ReleaseID)
}
return candidate.Version
}
func upgradeResolveTrace(trace *install.Trace) resolve.Trace {
if trace == nil {
return resolve.Trace{}
}
return trace.Resolve
}
func selectedRootPackage(packages []document.Package, root upgradeRoot) *document.Package {
for i := range packages {
p := &packages[i]
if p.Environment != root.Environment || p.Ecosystem != root.Ecosystem {
continue
}
for _, binding := range p.Requirements {
if binding.Reference == root.Reference {
return p
}
}
}
return nil
}
// verifyRecoveredBase fails when journal recovery left different documents
// than the early manifest and lock the caller selected its roots from.
func verifyRecoveredBase(
baseDocuments install.WorkspaceDocuments,
manifestFingerprint string,
manifestName string,
lockFingerprint string,
action string,
) error {
recoveredManifest, recoveredLock, err := baseDocuments.Decode()
if err != nil {
return err
}
recoveredManifestFingerprint, recoveredLockFingerprint := "", ""
if recoveredManifest != nil {
if recoveredManifestFingerprint, err = recoveredManifest.Fingerprint(); err != nil {
return err
}
if recoveredManifest.Name != manifestName {
return fmt.Errorf("manifest name changed during %s planning; retry", action)
}
}
if recoveredLock != nil {
if recoveredLockFingerprint, err = recoveredLock.Fingerprint(); err != nil {
return err
}
}
if recoveredManifestFingerprint != manifestFingerprint {
return fmt.Errorf("manifest changed during %s planning; retry", action)
}
if recoveredLockFingerprint != lockFingerprint {
return fmt.Errorf("lock changed during %s planning; retry", action)
}
return nil
}
func noopUpgradeOption(
baseDocuments install.WorkspaceDocuments,
d *document.Manifest,
old *document.Lock,
baseManifest string,
baseLock string,
) (UpgradeOption, error) {
plan, err := install.PlanFromResolution(baseDocuments, d, old, old, false)
if err != nil {
return UpgradeOption{}, err
}
hash := upgradePlanHash(baseManifest, baseLock, old.ManifestFingerprint, old.Packages)
plan.Result.PlanHash = hash
return UpgradeOption{
Hash: hash,
Plan: plan,
}, nil
}
func upgradePlanHash(
baseManifest string,
baseLock string,
finalManifest string,
packages []document.Package,
) string {
lines := []string{
"v1",
"base-manifest:" + baseManifest,
"base-lock:" + baseLock,
"final-manifest:" + finalManifest,
}
sorted := slices.Clone(packages)
sort.Slice(sorted, func(i, j int) bool {
a, b := &sorted[i], &sorted[j]
if n := strings.Compare(string(a.Environment), string(b.Environment)); n != 0 {
return n < 0
}
if n := strings.Compare(string(a.Ecosystem), string(b.Ecosystem)); n != 0 {
return n < 0
}
if n := strings.Compare(string(a.Provider), string(b.Provider)); n != 0 {
return n < 0
}
return strings.Compare(a.ProjectID, b.ProjectID) < 0
})
for _, p := range sorted {
lines = append(lines, strings.Join([]string{
"pkg",
string(p.Environment),
string(p.Ecosystem),
string(p.Provider),
p.ProjectID,
string(p.Version),
p.ReleaseID,
p.FileID,
}, "|"))
}
sum := sha256.Sum256([]byte(strings.Join(lines, "\n")))
return "sha256:" + hex.EncodeToString(sum[:])
}
func paretoFrontier(options []UpgradeOption) []UpgradeOption {
sort.Slice(options, func(i, j int) bool {
a, b := &options[i], &options[j]
if a.Metrics.UpgradedRoots != b.Metrics.UpgradedRoots {
return b.Metrics.UpgradedRoots < a.Metrics.UpgradedRoots
}
if a.Metrics.VersionBumps != b.Metrics.VersionBumps {
return b.Metrics.VersionBumps < a.Metrics.VersionBumps
}
return strings.Compare(a.Hash, b.Hash) < 0
})
frontier := make([]UpgradeOption, 0, len(options))
maxBumps := -1
for _, option := range options {
if option.Metrics.VersionBumps <= maxBumps {
continue
}
frontier = append(frontier, option)
maxBumps = option.Metrics.VersionBumps
}
return frontier
}
package operation
import (
"bytes"
"fmt"
"slices"
"sort"
"strings"
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/resolve"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
type upgradeRoot struct {
Environment serverpkg.Environment
Ecosystem catalog.Ecosystem
Reference string
Requirement document.Requirement
Provider catalog.Provider
Project string
Previous *document.Package
Versions []upgradeVersion
// LockedIndex is the highest selectable index in Versions. It is the
// locked build's index when that build is listed, or the oldest listed
// index when the locked build is missing from a mutable location.
LockedIndex int
// LockedRank is the locked build's rank, or len(Versions) when the locked
// build is missing and ranks below every listed build.
LockedRank int
}
type upgradeVersion struct {
Version versionpkg.Version
Builds []upstream.Candidate
Rank int
PublishedAt time.Time
}
// PlanUpgrade resolves candidate frontiers without staging or committing.
func upgradeFloating(v versionpkg.Version) bool {
switch v {
case "", versionpkg.Any, versionpkg.Beta, versionpkg.Stable, "latest":
return true
default:
return false
}
}
func upgradeRoots(d *document.Manifest, old *document.Lock) ([]upgradeRoot, error) {
var roots []upgradeRoot
for _, ecosystem := range sortedEcosystems(d.Server.Packages) {
for ref, requirement := range d.Server.Packages[ecosystem] {
if !requirement.IsEnabled() {
continue
}
root, err := newUpgradeRoot(serverpkg.EnvironmentServer, ecosystem, ref, requirement, old)
if err != nil {
return nil, err
}
roots = append(roots, root)
}
}
if d.MCDR != nil {
for ref, requirement := range d.MCDR.Packages {
if !requirement.IsEnabled() {
continue
}
root, err := newUpgradeRoot(serverpkg.EnvironmentMCDR, catalog.EcosystemMCDR, ref, requirement, old)
if err != nil {
return nil, err
}
roots = append(roots, root)
}
}
sort.Slice(roots, func(i, j int) bool {
if n := strings.Compare(string(roots[i].Environment), string(roots[j].Environment)); n != 0 {
return n < 0
}
if n := strings.Compare(string(roots[i].Ecosystem), string(roots[j].Ecosystem)); n != 0 {
return n < 0
}
return roots[i].Reference < roots[j].Reference
})
return roots, nil
}
func newUpgradeRoot(
environment serverpkg.Environment,
ecosystem catalog.Ecosystem,
ref string,
requirement document.Requirement,
old *document.Lock,
) (upgradeRoot, error) {
provider, project, err := document.ParseReference(ref)
if err != nil {
return upgradeRoot{}, err
}
previous := previousRootPackage(old, environment, ecosystem, ref, provider, project)
if previous == nil {
return upgradeRoot{}, fmt.Errorf("lock has no package for manifest root %s; run lucy install first", ref)
}
return upgradeRoot{
Environment: environment,
Ecosystem: ecosystem,
Reference: ref,
Requirement: requirement,
Provider: provider,
Project: project,
Previous: previous,
}, nil
}
func previousRootPackage(
old *document.Lock,
environment serverpkg.Environment,
ecosystem catalog.Ecosystem,
ref string,
provider catalog.Provider,
project string,
) *document.Package {
for i := range old.Packages {
p := &old.Packages[i]
if p.Environment != environment || p.Ecosystem != ecosystem {
continue
}
for _, binding := range p.Requirements {
if binding.Reference == ref {
return p
}
}
}
for i := range old.Packages {
p := &old.Packages[i]
if p.Environment == environment && p.Ecosystem == ecosystem &&
p.Provider == provider && p.ProjectID == project {
return p
}
}
return nil
}
func upgradeTargets(roots []upgradeRoot, opts UpgradeOptions) (map[string]bool, error) {
if len(opts.Targets) == 0 {
targets := make(map[string]bool, len(roots))
for _, root := range roots {
targets[root.Reference] = true
}
return targets, nil
}
targets := map[string]bool{}
for _, raw := range opts.Targets {
request, err := input.Parse(raw)
if err != nil {
return nil, err
}
if request.Version != "" && request.Version != versionpkg.Any {
return nil, fmt.Errorf("upgrade targets name packages, not versions: %s", raw)
}
var matched []string
for _, root := range roots {
if request.Provider != catalog.ProviderUnspecified && request.Provider != root.Provider {
continue
}
if !strings.EqualFold(string(request.Name), root.Project) {
continue
}
matched = append(matched, root.Reference)
}
switch len(matched) {
case 0:
return nil, fmt.Errorf("package %s is not an enabled manifest root", raw)
case 1:
targets[matched[0]] = true
default:
return nil, fmt.Errorf("package %s is ambiguous: %s", raw, strings.Join(matched, ", "))
}
}
return targets, nil
}
func pinCoreAndMCDR(d *document.Manifest, old *document.Lock) {
d.Server.Minecraft = old.Server.Minecraft
d.Server.Core.Product = old.Server.Product
d.Server.Core.ProductVersion = old.Server.CoreVersion
if d.MCDR != nil && old.MCDR != nil {
d.MCDR.Version = old.MCDR.Version
}
}
func upgradeTarget(old *document.Lock, coreModules []catalog.DescriptorModule) resolve.Target {
mcdrVersion := ""
if old.MCDR != nil {
mcdrVersion = string(old.MCDR.Version)
}
return resolve.Target{
Product: old.Server.Product,
Minecraft: old.Server.Minecraft,
CoreVersion: old.Server.CoreVersion,
MCDRVersion: mcdrVersion,
CoreModules: coreModules,
}
}
func rootRequirements(d *document.Manifest) map[string]document.Requirement {
requirements := map[string]document.Requirement{}
for _, ecosystem := range sortedEcosystems(d.Server.Packages) {
for ref, requirement := range d.Server.Packages[ecosystem] {
requirements[ref] = requirement
}
}
if d.MCDR != nil {
for ref, requirement := range d.MCDR.Packages {
requirements[ref] = requirement
}
}
return requirements
}
func setRootSelector(d *document.Manifest, root upgradeRoot, selector versionpkg.Version) error {
if root.Environment == serverpkg.EnvironmentMCDR {
if d.MCDR == nil {
return fmt.Errorf("manifest has no MCDR runtime")
}
requirement, ok := d.MCDR.Packages[root.Reference]
if !ok {
return fmt.Errorf("manifest root %s is missing", root.Reference)
}
requirement.Selector = selector
d.MCDR.Packages[root.Reference] = requirement
return nil
}
packages, ok := d.Server.Packages[root.Ecosystem]
if !ok {
return fmt.Errorf("manifest ecosystem %s is missing", root.Ecosystem)
}
requirement, ok := packages[root.Reference]
if !ok {
return fmt.Errorf("manifest root %s is missing", root.Reference)
}
requirement.Selector = selector
packages[root.Reference] = requirement
return nil
}
func cloneManifest(d *document.Manifest) (*document.Manifest, error) {
data, err := d.CanonicalBytes()
if err != nil {
return nil, err
}
return document.DecodeManifest(bytes.NewReader(data))
}
func sortedEcosystems(packages map[catalog.Ecosystem]map[string]document.Requirement) []catalog.Ecosystem {
ecosystems := make([]catalog.Ecosystem, 0, len(packages))
for ecosystem := range packages {
ecosystems = append(ecosystems, ecosystem)
}
slices.Sort(ecosystems)
return ecosystems
}
package operation
import (
"context"
"fmt"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
func (s *Service) upgradeVersions(
ctx context.Context,
root upgradeRoot,
old *document.Lock,
maxVersions int,
) ([]upgradeVersion, int, int, bool, error) {
registry, ok := root.Provider.Registry()
if !ok {
return nil, 0, 0, false, fmt.Errorf("provider %s has no package catalogue", root.Provider)
}
list, err := s.source.Candidates(
ctx,
registry,
root.Project,
string(old.Server.Minecraft),
root.Ecosystem,
)
if err != nil {
return nil, 0, 0, false, err
}
selector := root.Requirement.Selector
artifactEligible := make([]upstream.Candidate, 0, len(list))
for _, candidate := range list {
if upgradeLockedBuild(candidate, root.Previous) {
artifactEligible = append(artifactEligible, candidate)
continue
}
if root.Requirement.FilePattern != "" {
match, err := filepath.Match(root.Requirement.FilePattern, candidate.Filename)
if err != nil {
return nil, 0, 0, false, err
}
if !match {
continue
}
} else if !candidate.PrimaryFile {
continue
}
artifactEligible = append(artifactEligible, candidate)
}
var lockedCandidate *upstream.Candidate
for i := range artifactEligible {
if upgradeLockedBuild(artifactEligible[i], root.Previous) {
lockedCandidate = &artifactEligible[i]
break
}
}
lockedMissing := lockedCandidate == nil
if lockedMissing {
// The catalogue no longer serves the locked build. A mutable upstream
// location can still be upgraded safely: its URL now resolves to a
// different release, so the lock's bytes are gone rather than the
// build being quietly re-served under its old identity. Only builds
// that location currently serves may replace it; unrelated historical
// builds are never upgrade targets, and any other absence has no safe
// replacement, so keep failing.
artifactEligible = upgradeLockedLocationCandidates(root.Previous, artifactEligible)
if len(artifactEligible) == 0 {
return nil, 0, 0, false, fmt.Errorf("locked version %s is no longer listed", root.Previous.Version)
}
lockedCandidate = upgradeLockedBaseline(root.Previous)
}
dialect := upgradeArtifactDialect(root.Ecosystem)
withoutDowngrades := make([]upstream.Candidate, 0, len(artifactEligible))
for _, candidate := range artifactEligible {
if upgradeLockedBuild(candidate, root.Previous) {
withoutDowngrades = append(withoutDowngrades, candidate)
continue
}
if atLeast, comparable := upgradeVersionAtLeast(candidate.Version, lockedCandidate.Version, dialect); comparable {
if !atLeast {
continue
}
} else if !candidate.PublishedAt.IsZero() && !lockedCandidate.PublishedAt.IsZero() &&
candidate.PublishedAt.Before(lockedCandidate.PublishedAt) {
continue
}
withoutDowngrades = append(withoutDowngrades, candidate)
}
hasRelease := false
for _, candidate := range withoutDowngrades {
if candidate.Channel == upstream.ReleaseChannelRelease {
hasRelease = true
break
}
}
eligible := make([]upstream.Candidate, 0, len(withoutDowngrades))
for _, candidate := range withoutDowngrades {
locked := upgradeLockedBuild(candidate, root.Previous)
if !locked && selector == versionpkg.Stable && candidate.Channel != upstream.ReleaseChannelRelease {
continue
}
if !locked &&
(selector == versionpkg.Any || selector == "" || !selector.CanInfer()) &&
hasRelease && candidate.Channel != upstream.ReleaseChannelRelease {
continue
}
eligible = append(eligible, candidate)
}
if len(eligible) == 0 {
return nil, 0, 0, false, fmt.Errorf("no eligible builds for Minecraft %s", old.Server.Minecraft)
}
byVersion := map[versionpkg.Version][]upstream.Candidate{}
for _, candidate := range eligible {
byVersion[candidate.Version] = append(byVersion[candidate.Version], candidate)
}
versions := make([]upgradeVersion, 0, len(byVersion))
for version, builds := range byVersion {
sort.SliceStable(builds, func(i, j int) bool {
a, b := &builds[i], &builds[j]
if n := b.PublishedAt.Compare(a.PublishedAt); n != 0 {
return n < 0
}
if n := strings.Compare(a.ReleaseID, b.ReleaseID); n != 0 {
return n < 0
}
return a.FileID < b.FileID
})
versions = append(versions, upgradeVersion{
Version: version,
Builds: builds,
PublishedAt: builds[0].PublishedAt,
})
}
sort.Slice(versions, func(i, j int) bool {
a, b := &versions[i], &versions[j]
if n := b.PublishedAt.Compare(a.PublishedAt); n != 0 {
return n < 0
}
return string(b.Version) < string(a.Version)
})
lockedRank := -1
for i := range versions {
versions[i].Rank = i
if lockedMissing {
continue
}
if versions[i].Version == root.Previous.Version {
lockedRank = i
continue
}
for _, build := range versions[i].Builds {
if build.ReleaseID == root.Previous.ReleaseID && build.FileID == root.Previous.FileID {
lockedRank = i
}
}
}
if lockedRank < 0 {
if !lockedMissing {
return nil, 0, 0, false, fmt.Errorf("locked version %s is no longer listed", root.Previous.Version)
}
// The locked build sits below every listed build: all of them are
// candidates to move forward to, never a downgrade target.
lockedRank = len(versions)
}
trimmed := versions
lockedIndex := lockedRank
if lockedMissing {
if len(versions) > maxVersions {
trimmed = versions[:maxVersions]
}
lockedIndex = len(trimmed) - 1
lockedRank = len(trimmed)
return trimmed, lockedIndex, lockedRank, true, nil
}
if len(versions) > maxVersions {
if lockedRank < maxVersions {
trimmed = versions[:maxVersions]
lockedIndex = lockedRank
} else {
trimmed = append([]upgradeVersion{}, versions[:maxVersions-1]...)
trimmed = append(trimmed, versions[lockedRank])
lockedIndex = len(trimmed) - 1
}
}
return trimmed, lockedIndex, lockedRank, lockedIndex > 0, nil
}
func upgradeCombinations(roots []upgradeRoot, active []int, limit int) [][]int {
locked := make([]int, len(active))
for i, rootIndex := range active {
locked[i] = roots[rootIndex].LockedIndex
}
seeds := []int{}
for range active {
seeds = append(seeds, 0)
}
queue := [][]int{seeds, locked}
seen := map[string]bool{}
var combos [][]int
for len(queue) > 0 && len(combos) < limit {
combo := queue[0]
queue = queue[1:]
key := fmt.Sprint(combo)
if seen[key] {
continue
}
seen[key] = true
combos = append(combos, combo)
for i, rootIndex := range active {
if combo[i]+1 > roots[rootIndex].LockedIndex {
continue
}
next := slices.Clone(combo)
next[i]++
queue = append(queue, next)
}
}
slices.SortFunc(combos, func(a, b []int) int {
sumA, sumB := 0, 0
for i := range a {
sumA += a[i]
sumB += b[i]
}
if sumA != sumB {
return sumA - sumB
}
for i := range a {
if a[i] != b[i] {
return a[i] - b[i]
}
}
return 0
})
return combos
}
func upgradeLockedBuild(candidate upstream.Candidate, previous *document.Package) bool {
if previous == nil {
return false
}
if previous.ReleaseID != "" || previous.FileID != "" {
return candidate.ReleaseID == previous.ReleaseID && candidate.FileID == previous.FileID
}
return candidate.Version == previous.Version
}
// upgradeLockedLocationCandidates keeps only candidates served from the locked
// artifact's URL. That URL is a mutable upstream location when it resolves to a
// different release: the locked build's bytes are no longer retrievable under
// their pinned identity, while the location's current builds are. A build that
// simply vanished from an immutable catalogue leaves no candidates.
func upgradeLockedLocationCandidates(
previous *document.Package,
candidates []upstream.Candidate,
) []upstream.Candidate {
if previous == nil || previous.URL == "" {
return nil
}
kept := make([]upstream.Candidate, 0, len(candidates))
for _, candidate := range candidates {
if candidate.URL == previous.URL {
kept = append(kept, candidate)
}
}
return kept
}
// upgradeLockedBaseline reconstructs the locked build from the validated lock
// for comparison and ranking only. It deliberately carries no URL, filename,
// hashes, or primary-file claim: the catalogue no longer serves this build, so
// it must never be selected, materialized, or presented as a retrievable
// historical artifact.
func upgradeLockedBaseline(previous *document.Package) *upstream.Candidate {
return &upstream.Candidate{
Artifact: catalog.Artifact{
Provider: previous.Provider,
ProjectID: previous.ProjectID,
ReleaseID: previous.ReleaseID,
FileID: previous.FileID,
Version: previous.Version,
},
}
}
func upgradeArtifactDialect(ecosystem catalog.Ecosystem) versionpkg.Dialect {
switch ecosystem {
case catalog.EcosystemBukkit, catalog.EcosystemPaper:
return versionpkg.DialectOpaque
default:
return versionpkg.DialectMaven
}
}
func upgradeVersionAtLeast(
candidate, locked versionpkg.Version,
dialect versionpkg.Dialect,
) (bool, bool) {
if !dialect.Valid() || dialect == versionpkg.DialectOpaque {
return false, false
}
parsedCandidate, err := versionpkg.ParseVersion(candidate, dialect)
if err != nil {
return false, false
}
parsedLocked, err := versionpkg.ParseVersion(locked, dialect)
if err != nil {
return false, false
}
comparison, comparable := versionpkg.Compare(parsedCandidate, parsedLocked)
if !comparable {
return false, false
}
return comparison >= 0, true
}
// Package receipt owns the workspace installation receipt: the authoritative
// ledger of committed runtime outputs and the resolutions that produced them.
package receipt
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/workspacewrite"
"go.yaml.in/yaml/v4"
)
const (
// Filename is the receipt's path inside a workspace.
Filename = ".lucy/install.yaml"
// Version is the schema version this build reads and writes.
Version = 1
// OriginBootstrap identifies outputs produced by server bootstrap.
OriginBootstrap = "bootstrap"
// OriginPackage identifies outputs installed from packages.
OriginPackage = "package"
// OriginMCDR identifies outputs produced by the MCDReforged wrapper
// runtime, which is reconciled independently of the server bootstrap.
OriginMCDR = "mcdr"
)
// ErrLegacyReceipt is returned when a receipt was written by an older version of Lucy
// that lacks provenance origin attribution.
type ErrLegacyReceipt struct {
Receipt *Receipt
}
func (e *ErrLegacyReceipt) Error() string {
return fmt.Sprintf("legacy installation receipt in %s requires explicit adoption; run 'lucy init' (or 'lucy init --force') to adopt existing files safely", Filename)
}
// Receipt records the outputs an installation committed. It is an authoritative
// local ledger of committed paths Lucy owns, their origins, and update policies.
// It is not a second lock: paths and digests describe local state, and the
// fingerprints name the resolution that produced it.
type Receipt struct {
Version int `yaml:"version"`
BootstrapFingerprint string `yaml:"bootstrap_fingerprint,omitempty"`
// SeedPaths names the seed outputs the recorded bootstrap produced. Seeds
// stay user-owned, so the receipt records only their presence.
SeedPaths []string `yaml:"seed_paths,omitempty"`
PackageFingerprint string `yaml:"package_fingerprint,omitempty"`
LockFingerprint string `yaml:"lock_fingerprint,omitempty"`
Entries []Entry `yaml:"entries"`
}
// Entry records one committed managed output.
type Entry struct {
Path string `yaml:"path"`
SHA256 string `yaml:"sha256"`
Mode uint32 `yaml:"mode"`
Origin string `yaml:"origin"`
Package string `yaml:"package,omitempty"`
}
// New returns an empty receipt for the current schema.
func New() Receipt {
return Receipt{Version: Version, Entries: []Entry{}}
}
// Validate verifies receipt structural invariants: valid schema version,
// safe relative clean paths, origin attribution, valid SHA256 hex digests,
// non-reserved paths, and absence of duplicate or colliding entries.
// Ambiguous legacy receipts (such as those with lock_fingerprint or missing
// origins) return ErrLegacyReceipt.
func (r *Receipt) Validate() error {
if r.Version != Version {
return fmt.Errorf("unsupported receipt version %d", r.Version)
}
isLegacy := r.LockFingerprint != ""
seen := make(map[string]string, len(r.Entries))
seeds := make(map[string]string, len(r.SeedPaths))
for i := range r.Entries {
entry := &r.Entries[i]
if entry.Path == "" {
return errors.New("receipt entry has empty path")
}
switch entry.Origin {
case OriginBootstrap, OriginMCDR:
if entry.Package != "" {
return fmt.Errorf("receipt entry %s has origin %s but non-empty package %q", entry.Path, entry.Origin, entry.Package)
}
case OriginPackage:
if entry.Package == "" {
return fmt.Errorf("receipt entry %s has origin %s but empty package identity", entry.Path, OriginPackage)
}
case "":
isLegacy = true
default:
return fmt.Errorf("receipt entry %s has unsupported origin %q; expected %q, %q or %q", entry.Path, entry.Origin, OriginBootstrap, OriginPackage, OriginMCDR)
}
clean, err := validateReceiptPath("path", entry.Path)
if err != nil {
return err
}
lower := strings.ToLower(clean)
if len(entry.SHA256) != 64 {
return fmt.Errorf("receipt entry %s has invalid sha256 digest %q", entry.Path, entry.SHA256)
}
for _, c := range entry.SHA256 {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
return fmt.Errorf("receipt entry %s has non-hex sha256 digest %q", entry.Path, entry.SHA256)
}
}
r.Entries[i].SHA256 = strings.ToLower(entry.SHA256)
if prior, exists := seen[lower]; exists {
return fmt.Errorf("receipt path collision: %s and %s", prior, entry.Path)
}
seen[lower] = clean
}
for _, seed := range r.SeedPaths {
clean, err := validateReceiptPath("seed path", seed)
if err != nil {
return err
}
lower := strings.ToLower(clean)
if prior, exists := seen[lower]; exists {
return fmt.Errorf("receipt seed path %s collides with managed output %s", seed, prior)
}
if prior, exists := seeds[lower]; exists {
return fmt.Errorf("receipt seed path collision: %s and %s", prior, seed)
}
seeds[lower] = clean
}
if isLegacy {
return &ErrLegacyReceipt{Receipt: r}
}
return nil
}
// validateReceiptPath rejects a path that could escape the workspace, is not
// canonical, or names a file the workspace reserves. label names the path
// class in errors.
func validateReceiptPath(label, path string) (string, error) {
clean := filepath.ToSlash(filepath.Clean(filepath.FromSlash(path)))
if clean != path || filepath.IsAbs(path) || strings.HasPrefix(clean, "../") {
return "", fmt.Errorf("unsafe or unnormalized receipt %s: %s", label, path)
}
if err := document.SafeRelativePath(clean); err != nil {
return "", fmt.Errorf("unsafe receipt %s %s: %w", label, path, err)
}
lower := strings.ToLower(clean)
if lower == ".lucy" || strings.HasPrefix(lower, ".lucy/") ||
lower == strings.ToLower(document.LockFilename) ||
lower == strings.ToLower(document.ManifestFilename) {
return "", fmt.Errorf("receipt %s %s is reserved", label, path)
}
return clean, nil
}
// Decode parses receipt bytes strictly and verifies schema version and entry validity.
// If the receipt contains legacy fields or entries lacking origin attribution,
// Decode returns the parsed receipt alongside an *ErrLegacyReceipt error so adoption
// callers can preserve baselines.
func Decode(reader io.Reader) (*Receipt, error) {
raw, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
var result Receipt
dec := yaml.NewDecoder(bytes.NewReader(raw))
dec.KnownFields(true)
if err := dec.Decode(&result); err != nil {
return nil, fmt.Errorf("decode receipt YAML: %w", err)
}
for i := range result.Entries {
result.Entries[i].SHA256 = strings.ToLower(result.Entries[i].SHA256)
}
var trailing any
if err := dec.Decode(&trailing); err == nil {
return nil, errors.New("receipt contains unexpected trailing documents")
} else if !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("check trailing receipt documents: %w", err)
}
if err := result.Validate(); err != nil {
var legacyErr *ErrLegacyReceipt
if errors.As(err, &legacyErr) {
return &result, err
}
return nil, err
}
return &result, nil
}
// ReadAt reads the receipt at path. A missing file returns an error that
// matches os.ErrNotExist.
func ReadAt(path string) (*Receipt, error) {
info, err := os.Lstat(path)
if err != nil {
return nil, err
}
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
return nil, fmt.Errorf("refuse symlinked or non-regular receipt %s", path)
}
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return Decode(bytes.NewReader(raw))
}
// Read reads the receipt of the workspace at root after validating confinement.
func Read(root string) (*Receipt, error) {
if err := workspacewrite.SafePath(root, Filename); err != nil {
return nil, err
}
return ReadAt(filepath.Join(root, Filename))
}
// Snapshot returns the receipt bytes without writing them.
func (r *Receipt) Snapshot() ([]byte, error) {
if err := r.Validate(); err != nil {
return nil, err
}
result := *r
result.LockFingerprint = ""
result.SeedPaths = slices.Clone(r.SeedPaths)
slices.Sort(result.SeedPaths)
if result.Entries == nil {
result.Entries = []Entry{}
} else {
result.Entries = slices.Clone(r.Entries)
slices.SortFunc(result.Entries, func(a, b Entry) int {
return strings.Compare(a.Path, b.Path)
})
}
return yaml.Marshal(result)
}
package receipt
import (
"crypto/sha256"
"encoding/hex"
"github.com/mclucy/lucy/bootstrap/snapshot"
"github.com/mclucy/lucy/document"
"go.yaml.in/yaml/v4"
)
// BootstrapFingerprint returns the bootstrap installation key of a lock: the
// snapshot recipe key plus the server directory. The recipe key names a
// shareable output tree; the directory is where this workspace installs it, so
// moving the server restages the runtime. A new Lucy build changes the recipe
// key, so the next install restages. Packages, tracked files, MCDR, Java
// requirements, URLs, and filenames cannot invalidate an unchanged bootstrap.
func BootstrapFingerprint(l *document.Lock) (string, error) {
if l == nil {
return "", nil
}
recipe, err := snapshot.Key(l.Server)
if err != nil {
return "", err
}
data, err := yaml.Marshal(struct {
Recipe string `yaml:"recipe"`
Directory string `yaml:"directory"`
}{recipe.String(), l.Server.Directory})
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]), nil
}
// PackageFingerprint digests the package pins and wrapper runtime in the lock:
// package identities, artifacts, requirement bindings, and MCDR directory.
func PackageFingerprint(l *document.Lock) (string, error) {
if l == nil {
return "", nil
}
data, err := yaml.Marshal(struct {
MCDR *document.LockedMCDR `yaml:"mcdr,omitempty"`
Packages []document.Package `yaml:"packages"`
}{l.MCDR, l.Packages})
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]), nil
}
package resolve
import (
"fmt"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
// candidateDecision records the first reason a candidate cannot answer a
// request. A later rule may also fail; the first failure is the one reported.
type candidateDecision struct {
eligible bool
kind RejectionKind
detail string
reason string
}
// decideCandidate applies the request's hard filters to one candidate.
func decideCandidate(
candidate upstream.Candidate,
request projectRequest,
) (candidateDecision, error) {
decision := candidateDecision{eligible: true}
reject := func(kind RejectionKind, detail string) {
decision.eligible = false
if decision.reason == "" {
decision.reason = describeRejection(kind, detail)
decision.kind = kind
decision.detail = detail
}
}
// Remote release hints are advisory. They order candidates, but a build
// the dependent did not name can still satisfy the dependency.
constrained := false
for _, requirement := range request.requirements {
if !requirement.Enabled {
continue
}
constrained = true
switch requirement.Selector {
case versionpkg.Stable:
if candidate.Channel != upstream.ReleaseChannelRelease {
reject(RejectionChannel, "requested a release build")
}
case versionpkg.Any, versionpkg.Beta, "":
default:
if candidate.Version != requirement.Selector &&
candidate.ReleaseID != string(requirement.Selector) &&
candidate.FileID != string(requirement.Selector) &&
candidate.Filename != string(requirement.Selector) {
reject(RejectionVersionMismatch, string(requirement.Selector))
}
}
if requirement.FilePattern != "" {
match, err := filepath.Match(requirement.FilePattern, candidate.Filename)
if err != nil {
return decision, err
}
if !match {
reject(RejectionFilePattern, requirement.FilePattern)
}
} else if !candidate.PrimaryFile && !keepsLockedFile(request, candidate) {
// Only the primary file answers an unconstrained requirement. The
// lock records the file an earlier resolution or adoption chose,
// and that variant must stay eligible so a later resolution does
// not silently swap in the release's primary file.
reject(RejectionPrimaryFile, "")
}
}
// A dependency request carries no requirement of its own, so no enabled
// binding rejects the extra files a release publishes: the sources and dev
// jars carry a readable descriptor and would otherwise win the version race
// on publication date alone.
if !constrained && !candidate.PrimaryFile {
reject(RejectionPrimaryFile, "")
}
return decision, nil
}
// keepsLockedFile reports whether the candidate is the file the lock selected
// for the request's project. Providers without file identities answer false.
func keepsLockedFile(
request projectRequest,
candidate upstream.Candidate,
) bool {
return request.previousFileID != "" &&
candidate.FileID == request.previousFileID
}
// orderCandidates applies the cache order: newest publication first, then the
// previously locked build. The release-channel preference depends on each
// request's selectors, so the caller applies it after reading the cache.
func orderCandidates(
list []upstream.Candidate,
pin *document.Package,
) []upstream.Candidate {
ordered := slices.Clone(list)
sort.SliceStable(ordered, func(i, j int) bool {
return ordered[i].PublishedAt.After(ordered[j].PublishedAt)
})
if pin != nil {
for i, candidate := range ordered {
if candidate.ReleaseID == pin.ReleaseID && candidate.FileID == pin.FileID {
copy(ordered[1:i+1], ordered[:i])
ordered[0] = candidate
break
}
}
}
return ordered
}
// preferReleaseBuilds applies the default selector's preference: `any` takes
// the newest build but prefers a release over a prerelease when both exist.
// `beta` keeps publication order because it accepts prereleases outright, and
// `stable` rejects prereleases in the candidate loop.
func preferReleaseBuilds(
list []upstream.Candidate,
requirements []document.RequirementBinding,
) []upstream.Candidate {
if len(list) < 2 {
return list
}
prefer := false
for _, requirement := range requirements {
if !requirement.Enabled {
continue
}
if requirement.Selector == versionpkg.Any || requirement.Selector == "" {
prefer = true
}
}
if !prefer {
return list
}
ordered := make([]upstream.Candidate, 0, len(list))
for _, candidate := range list {
if candidate.Channel == upstream.ReleaseChannelRelease {
ordered = append(ordered, candidate)
}
}
for _, candidate := range list {
if candidate.Channel != upstream.ReleaseChannelRelease {
ordered = append(ordered, candidate)
}
}
return ordered
}
// preferReleaseHints moves candidates named by remote dependency metadata to
// the front of the candidate list. The hints are advisory: a different build
// can still satisfy the dependency.
func preferReleaseHints(
list []upstream.Candidate,
hints []releaseHint,
) []upstream.Candidate {
hinted := map[string]bool{}
for _, hint := range hints {
if hint.releaseID != "" {
hinted[hint.releaseID] = true
}
}
if len(hinted) == 0 {
return list
}
ordered := make([]upstream.Candidate, 0, len(list))
for _, candidate := range list {
if hinted[candidate.ReleaseID] {
ordered = append(ordered, candidate)
}
}
for _, candidate := range list {
if !hinted[candidate.ReleaseID] {
ordered = append(ordered, candidate)
}
}
return ordered
}
// candidateProvenance records the metadata a provider could not establish for
// one candidate. It follows the selected artifact so resolution can report the
// gap instead of letting missing metadata read as a negative answer.
type candidateProvenance struct {
dependenciesUnknown bool
compatibilityUnknown bool
}
// provenanceKey is the persisted candidate identity. URL is deliberately
// excluded: merging selections keeps the artifact identity, not any mirror
// the provider happened to return.
func provenanceKey(
provider catalog.Provider,
ecosystem catalog.Ecosystem,
projectID, releaseID, fileID string,
) string {
return provider.String() + "|" + ecosystem.String() + "|" +
projectID + "|" + releaseID + "|" + fileID
}
func packageProvenanceKey(p document.Package) string {
return provenanceKey(p.Provider, p.Ecosystem, p.ProjectID, p.ReleaseID, p.FileID)
}
// packageReference prefers the declared reference, which keeps a provider's
// canonical project ID from replacing the identity the user wrote.
func packageReference(p document.Package) string {
for _, requirement := range p.Requirements {
if requirement.Reference != "" {
return requirement.Reference
}
}
return p.Provider.String() + ":" + p.ProjectID
}
// provenanceWarnings reports the metadata gaps of the selected builds. A
// provider that cannot answer must be distinguishable from one that answered
// "none".
func provenanceWarnings(
packages []document.Package,
provenance map[string]candidateProvenance,
target Target,
expandDependencies bool,
) []error {
var warnings []error
for _, p := range packages {
entry, known := provenance[packageProvenanceKey(p)]
if !known {
continue
}
reference := packageReference(p)
if entry.dependenciesUnknown && expandDependencies {
warnings = append(warnings, fmt.Errorf(
"%s %s: %s does not report dependency metadata for this build; upstream dependencies were not expanded",
reference,
p.Version,
p.Provider.Title(),
))
}
if entry.compatibilityUnknown {
warnings = append(warnings, fmt.Errorf(
"%s %s: %s cannot verify compatibility with Minecraft %s (%s); resolution selected it anyway",
reference,
p.Version,
p.Provider.Title(),
target.Minecraft,
p.Ecosystem,
))
}
}
return warnings
}
// conflictDependencies returns the candidate's incompatibility declarations.
func conflictDependencies(candidate upstream.Candidate) []upstream.ProjectDependency {
var out []upstream.ProjectDependency
for _, dep := range candidate.Dependencies {
switch dep.Kind {
case catalog.DependencyKindIncompatible, catalog.DependencyKindConflict:
out = append(out, dep)
}
}
return out
}
// metadataConflict reports the first metadata-declared incompatibility between
// candidate and the selected packages. It checks both directions so a one-sided
// declaration behaves the same in either selection order.
func metadataConflict(
candidate upstream.Candidate,
request projectRequest,
chosen map[projectKey]document.Package,
conflicts map[projectKey][]upstream.ProjectDependency,
) (string, bool) {
best := ""
note := func(detail string) {
if best == "" || strings.Compare(detail, best) < 0 {
best = detail
}
}
for _, dep := range conflictDependencies(candidate) {
if dep.Provider == candidate.Provider && dep.ProjectID == candidate.ProjectID {
continue
}
for key, selected := range chosen {
if key.environment != request.key.environment || key.ecosystem != request.key.ecosystem {
continue
}
if selected.Artifact.Filename == "" ||
selected.Provider != dep.Provider ||
selected.ProjectID != dep.ProjectID {
continue
}
if dep.ReleaseID != "" && selected.ReleaseID != dep.ReleaseID {
continue
}
note(conflictDetail(dep))
}
}
for key, selectedConflicts := range conflicts {
if key.environment != request.key.environment || key.ecosystem != request.key.ecosystem {
continue
}
for _, dep := range selectedConflicts {
if dep.Provider != candidate.Provider || dep.ProjectID != candidate.ProjectID {
continue
}
if dep.ReleaseID != "" && candidate.ReleaseID != dep.ReleaseID {
continue
}
note(conflictDetail(dep))
}
}
return best, best != ""
}
func conflictDetail(dep upstream.ProjectDependency) string {
detail := dep.Provider.String() + ":" + dep.ProjectID
if dep.ReleaseID != "" {
detail += "@" + dep.ReleaseID
}
return detail
}
// packageConflictWarnings reports the metadata-declared incompatibilities
// among the packages a resolution finally selected. It scans every selected
// package's declarations against every other selection, so a conflict declared
// by either side is reported whichever package the search selected first.
// Findings are deduplicated as unordered pairs and sorted, so repeated
// resolutions report the same warnings in the same order.
func packageConflictWarnings(
packages []document.Package,
declared map[projectKey][]upstream.ProjectDependency,
) []error {
selected := make(map[projectKey]document.Package, len(packages))
for _, p := range packages {
selected[projectKey{p.Environment, p.Ecosystem, p.Provider, p.ProjectID}] = p
}
seen := make(map[string]struct{})
var details []string
for key, conflicts := range declared {
owner, ok := selected[key]
if !ok || owner.Artifact.Filename == "" {
continue
}
ownerRef := owner.Provider.String() + ":" + owner.ProjectID
for _, dep := range conflicts {
if dep.Provider == owner.Provider && dep.ProjectID == owner.ProjectID {
continue
}
target, ok := selected[projectKey{key.environment, key.ecosystem, dep.Provider, dep.ProjectID}]
if !ok || target.Artifact.Filename == "" {
continue
}
if dep.ReleaseID != "" && target.ReleaseID != dep.ReleaseID {
continue
}
left, right := ownerRef, conflictDetail(dep)
if strings.Compare(left, right) > 0 {
left, right = right, left
}
pair := left + "\x00" + right
if _, ok := seen[pair]; ok {
continue
}
seen[pair] = struct{}{}
details = append(details, left+" conflicts with "+right)
}
}
slices.Sort(details)
warnings := make([]error, 0, len(details))
for _, detail := range details {
warnings = append(warnings, fmt.Errorf("package conflict: %s", detail))
}
return warnings
}
type analysisEntry struct {
modules []catalog.DescriptorModule
hashes map[string]string
}
// AnalysisCache reuses artifact analysis within one resolution session. The
// cache is safe for concurrent use, because speculative analysis runs beside
// the search that may consume it.
type AnalysisCache struct {
mu sync.Mutex
entries map[analysisKey]analysisEntry
content map[analysisContentKey]analysisEntry
}
func NewAnalysisCache() *AnalysisCache {
return &AnalysisCache{
entries: make(map[analysisKey]analysisEntry),
content: make(map[analysisContentKey]analysisEntry),
}
}
// has reports whether the cache holds analysis for key. It copies nothing.
func (c *AnalysisCache) has(key analysisKey, expected map[string]string) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, hit := c.lookupLocked(key, expected)
return hit
}
// RecordVerified records descriptor modules of an artifact whose bytes the
// caller already verified and made available for replay.
func (c *AnalysisCache) RecordVerified(candidate upstream.Candidate, target Target, ecosystem catalog.Ecosystem, modules []catalog.DescriptorModule, hashes map[string]string) {
key := analysisKeyFor(candidate, target.DescriptorLoader(ecosystem), target.Minecraft)
c.put(key, analysisEntry{modules: modules, hashes: hashes})
}
// SeedPrevious records the analysis a lock already carries. A locked package
// names its artifact and hashes, so a pinned candidate whose lock recorded its
// modules needs no materialization or reopen. Packages without recorded
// modules are skipped: an absent module list does not prove the artifact has
// none. Packages whose modules finalization trimmed are skipped too, because
// the trimmed list omits descriptors that a different selection may need. A
// descriptor reader selects its files by loader and Minecraft version, so a
// package resolved for previousTarget is seeded only when both match target.
func (c *AnalysisCache) SeedPrevious(previous []document.Package, previousTarget, target Target) {
if previousTarget.Minecraft == "" || previousTarget.Minecraft != target.Minecraft {
return
}
c.mu.Lock()
defer c.mu.Unlock()
for i := range previous {
p := &previous[i]
if p.Artifact.Filename == "" || len(p.Artifact.Modules) == 0 || p.ModulesSuperseded {
continue
}
loader := target.DescriptorLoader(p.Ecosystem)
if previousTarget.DescriptorLoader(p.Ecosystem) != loader {
continue
}
candidate := upstream.Candidate{Artifact: p.Artifact}
key := analysisKeyFor(candidate, loader, target.Minecraft)
// A shared cache may seed the same lock again for another search.
if _, hit := c.lookupLocked(key, p.Artifact.Hashes); hit {
continue
}
c.putLocked(key, analysisEntry{
modules: p.Artifact.Modules,
hashes: p.Artifact.Hashes,
})
}
}
func (c *AnalysisCache) get(key analysisKey, expected map[string]string) (analysisEntry, bool) {
c.mu.Lock()
defer c.mu.Unlock()
entry, hit := c.lookupLocked(key, expected)
if !hit {
return analysisEntry{}, false
}
entry.modules = cloneModules(entry.modules)
return entry, true
}
// lookupLocked resolves an entry without copying its modules. The caller
// holds the cache mutex.
func (c *AnalysisCache) lookupLocked(key analysisKey, expected map[string]string) (analysisEntry, bool) {
entry, hit := c.entries[key]
if hit && matchesAnalysisHashes(entry.hashes, expected) {
return analysisEntry{modules: entry.modules, hashes: entry.hashes}, true
}
if expected["sha256"] == "" {
return analysisEntry{}, false
}
entry, hit = c.content[key.contentKey(expected["sha256"])]
if !hit || !matchesAnalysisHashes(entry.hashes, expected) {
return analysisEntry{}, false
}
hashes := make(map[string]string, len(expected))
for algorithm := range expected {
hashes[algorithm] = entry.hashes[algorithm]
}
return analysisEntry{modules: entry.modules, hashes: hashes}, true
}
func matchesAnalysisHashes(actual, expected map[string]string) bool {
for algorithm, digest := range expected {
if value, found := actual[algorithm]; !found || digest != "" && !strings.EqualFold(value, digest) {
return false
}
}
return true
}
func (c *AnalysisCache) put(key analysisKey, entry analysisEntry) {
c.mu.Lock()
defer c.mu.Unlock()
c.putLocked(key, entry)
}
// putLocked stores an entry. The caller holds the cache mutex.
func (c *AnalysisCache) putLocked(key analysisKey, entry analysisEntry) {
entry.modules = cloneModules(entry.modules)
c.entries[key] = entry
if digest := entry.hashes["sha256"]; digest != "" {
c.content[key.contentKey(digest)] = entry
}
}
type analysisKey struct {
provider catalog.Provider
project, release, file, url, filename string
loader catalog.Ecosystem
minecraft versionpkg.Version
}
type analysisContentKey struct {
digest, extension string
loader catalog.Ecosystem
minecraft versionpkg.Version
}
func (key analysisKey) contentKey(digest string) analysisContentKey {
return analysisContentKey{
digest: strings.ToLower(digest),
extension: strings.ToLower(filepath.Ext(key.filename)),
loader: key.loader,
minecraft: key.minecraft,
}
}
func analysisKeyFor(c upstream.Candidate, loader catalog.Ecosystem, minecraft versionpkg.Version) analysisKey {
return analysisKey{c.Provider, c.ProjectID, c.ReleaseID, c.FileID, c.URL, c.Filename, loader, minecraft}
}
func cloneModules(modules []catalog.DescriptorModule) []catalog.DescriptorModule {
if len(modules) == 0 {
return nil
}
out := make([]catalog.DescriptorModule, len(modules))
for i, module := range modules {
out[i] = module
out[i].Provides = slices.Clone(module.Provides)
out[i].Dependencies = slices.Clone(module.Dependencies)
}
return out
}
package resolve
import (
"fmt"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// ModuleProblem names the module requirement that a candidate cannot satisfy,
// together with the package that ships the module. The owner lets the failure
// ledger attribute the problem to the package that caused it instead of the
// last package that happened to be selected.
type ModuleProblem struct {
Environment server.Environment
Ecosystem catalog.Ecosystem
Provider catalog.Provider
ProjectID string
// RequiredBy names the module that states the requirement, Dependency the
// module it requires, and Constraint the range that Selected fails.
RequiredBy string
Dependency string
Constraint string
Selected string
// Server marks a requirement the server itself answers. No candidate can
// change it, so it explains the failure better than any package rejection.
Server bool
Message string
// cause keeps the typed cause, so callers can tell an absent module from
// a version mismatch without reading Message.
cause error
}
func (p ModuleProblem) Error() string { return p.Message }
// Unwrap exposes the typed cause of the problem.
func (p ModuleProblem) Unwrap() error { return p.cause }
func moduleProblem(
owner *document.Package,
requiredBy string,
dependency catalog.DescriptorDependency,
selected string,
serverProvided bool,
message string,
) ModuleProblem {
return ModuleProblem{
Environment: owner.Environment,
Ecosystem: owner.Ecosystem,
Provider: owner.Provider,
ProjectID: owner.ProjectID,
RequiredBy: requiredBy,
Dependency: dependency.ID,
Constraint: dependency.Constraint,
Selected: selected,
Server: serverProvided,
Message: message,
}
}
// SearchLimitError reports that resolution stopped before it settled a graph.
// The failure it produces keeps the rejection ledger for the command layer.
type SearchLimitError struct {
Attempts int
}
func (e *SearchLimitError) Error() string {
return fmt.Sprintf(
"package resolution exhausted its budget of %d speculative retries",
e.Attempts,
)
}
// RejectionKind names why one candidate was discarded.
type RejectionKind string
const (
RejectionVersionMismatch RejectionKind = "version-mismatch"
RejectionReleaseMismatch RejectionKind = "release-mismatch"
RejectionFilePattern RejectionKind = "file-pattern"
RejectionPrimaryFile RejectionKind = "not-primary-file"
RejectionChannel RejectionKind = "not-a-release"
RejectionModules RejectionKind = "modules"
// RejectionServer is a module requirement the server itself answers, such
// as the loader version. No candidate choice can satisfy it.
RejectionServer RejectionKind = "server"
RejectionMetadataConflict RejectionKind = "metadata-conflict"
RejectionNested RejectionKind = "nested"
RejectionEmpty RejectionKind = "empty"
)
// RejectionGroup aggregates identical rejections of one project's candidates.
type RejectionGroup struct {
Kind RejectionKind
Detail string
Count int
FirstVersion string
LastVersion string
// Module facts describe a requirement that rejected the builds. They are
// populated only for module-related rejection kinds.
RequiredBy string
Dependency string
Constraint string
Selected string
}
// Failure explains why a project could not be resolved: which project, how
// many builds were considered, and why each group was rejected. The command
// layer renders it; this type only carries facts.
type Failure struct {
Project string
Provider catalog.Provider
ProjectID string
Minecraft versionpkg.Version
Ecosystem catalog.Ecosystem
Candidates int
Groups []RejectionGroup
Cause error
// Aborted marks a search that stopped before it settled a graph. Project
// and Groups describe the candidate it rejected most often; Cause names
// the stop.
Aborted bool
}
// Error reports the failure on one line. It is the fallback for surfaces that
// do not render the grouped detail.
func (f *Failure) Error() string {
if f == nil {
return ""
}
if f.Aborted {
if f.Cause != nil {
return f.Cause.Error()
}
return "package resolution stopped before it settled"
}
if len(f.Groups) > 0 && f.Groups[0].Kind == RejectionServer {
group := f.Groups[0]
return fmt.Sprintf(
"%s requires %s %s, but this server runs %s",
group.RequiredBy,
group.Dependency,
group.Constraint,
group.Selected,
)
}
var parts []string
for _, group := range f.Groups {
text := group.Detail
if group.Count > 1 {
text = fmt.Sprintf("%s (%d builds)", text, group.Count)
}
parts = append(parts, text)
}
message := fmt.Sprintf("no build of %s works on this server", f.Project)
if len(parts) > 0 {
message += ": " + strings.Join(parts, "; ")
}
return message
}
func (f *Failure) Unwrap() error { return f.Cause }
type rejectionKey struct {
kind RejectionKind
detail string
}
type rejectionGroup struct {
kind RejectionKind
detail string
count int
versions map[string]struct{}
firstVersion string
lastVersion string
requiredBy string
dependency string
constraint string
selected string
}
type projectLedger struct {
display string
provider catalog.Provider
projectID string
candidates int
groups map[rejectionKey]*rejectionGroup
order []rejectionKey
}
// rejectionLedger records why candidates were discarded, grouped by project.
// It keeps one entry per distinct reason so the failure summary can report
// "47 builds, all for the same reason" instead of the last error alone.
type rejectionLedger struct {
projects map[projectKey]*projectLedger
order []projectKey
displays map[projectKey]string
// failed holds the projects whose resolution gave up. Projects that only
// rejected builds on the way to a selection are not failures.
failed map[projectKey]bool
}
func newRejectionLedger() *rejectionLedger {
return &rejectionLedger{
projects: map[projectKey]*projectLedger{},
displays: map[projectKey]string{},
failed: map[projectKey]bool{},
}
}
func (l *rejectionLedger) reset() {
l.projects = map[projectKey]*projectLedger{}
l.order = nil
l.displays = map[projectKey]string{}
l.failed = map[projectKey]bool{}
}
func (l *rejectionLedger) markFailed(key projectKey) { l.failed[key] = true }
func (l *rejectionLedger) noteDisplay(key projectKey, display string) {
if display != "" {
l.displays[key] = display
}
}
func (l *rejectionLedger) displayFor(key projectKey) string {
return l.displays[key]
}
func (l *rejectionLedger) project(key projectKey, display string) *projectLedger {
entry, ok := l.projects[key]
if !ok {
entry = &projectLedger{
display: display,
provider: key.provider,
projectID: key.project,
groups: map[rejectionKey]*rejectionGroup{},
}
l.projects[key] = entry
l.order = append(l.order, key)
}
if display != "" {
entry.display = display
}
return entry
}
func (l *rejectionLedger) setCandidates(key projectKey, display string, count int) {
entry := l.project(key, display)
if count > entry.candidates {
entry.candidates = count
}
}
func (l *rejectionLedger) record(
key projectKey,
display string,
version, detail string,
kind RejectionKind,
) {
l.add(l.project(key, display), version, rejectionKey{kind: kind, detail: detail})
}
// recordModule records a module requirement rejection. A requirement the
// server answers becomes a server rejection, which the summary prefers over
// every package-level reason.
func (l *rejectionLedger) recordModule(
key projectKey,
display string,
version string,
problem ModuleProblem,
) {
kind := RejectionModules
if problem.Server {
kind = RejectionServer
}
group := l.add(
l.project(key, display),
version,
rejectionKey{kind: kind, detail: problem.Message},
)
group.requiredBy = problem.RequiredBy
group.dependency = problem.Dependency
group.constraint = problem.Constraint
group.selected = problem.Selected
}
func (l *rejectionLedger) add(
entry *projectLedger,
version string,
groupKey rejectionKey,
) *rejectionGroup {
group, ok := entry.groups[groupKey]
if !ok {
group = &rejectionGroup{kind: groupKey.kind, detail: groupKey.detail}
entry.groups[groupKey] = group
entry.order = append(entry.order, groupKey)
}
group.count++
if version != "" {
if group.versions == nil {
group.versions = map[string]struct{}{}
}
group.versions[version] = struct{}{}
if group.firstVersion == "" {
group.firstVersion = version
}
group.lastVersion = version
}
return group
}
// A conflict on a build that passed its selector explains more than conflicts
// on versions the selector excluded.
func rejectionPriority(kind RejectionKind) int {
switch kind {
case RejectionServer:
return 3
case RejectionModules, RejectionMetadataConflict, RejectionEmpty:
return 2
case RejectionNested:
return 0
default:
return 1
}
}
// summary picks the project whose rejection explains the failure best: a
// requirement the server cannot satisfy first, then the most specific reasons,
// ahead of the request that happened to be processed first. Nested failures
// back up a deeper cause, so ties between projects with direct evidence favor
// the rejections the report will show; build drops their nested counts.
func (l *rejectionLedger) summary(minecraft versionpkg.Version, cause error) *Failure {
var bestKey projectKey
var bestEntry *projectLedger
bestPriority := -1
bestScore := -1
bestDirect := -1
for _, key := range l.order {
if !l.failed[key] {
continue
}
entry := l.projects[key]
priority := -1
score := 0
direct := 0
for _, group := range entry.groups {
if group.kind != RejectionNested {
direct += group.count
}
rank := rejectionPriority(group.kind)
if rank > priority {
priority, score = rank, 0
}
if rank == priority {
score += group.count
}
}
if priority < 0 {
continue
}
if priority > bestPriority ||
(priority == bestPriority && (score > bestScore || score == bestScore && direct > bestDirect)) {
bestKey, bestEntry = key, entry
bestPriority, bestScore, bestDirect = priority, score, direct
}
}
if bestEntry == nil {
return nil
}
return l.build(bestKey, bestEntry, minecraft, cause)
}
func (l *rejectionLedger) build(
key projectKey,
entry *projectLedger,
minecraft versionpkg.Version,
cause error,
) *Failure {
groups := make([]RejectionGroup, 0, len(entry.order))
for _, groupKey := range entry.order {
group := entry.groups[groupKey]
count := group.count
if len(group.versions) > 0 {
count = len(group.versions)
}
groups = append(groups, RejectionGroup{
Kind: group.kind,
Detail: group.detail,
Count: count,
FirstVersion: group.firstVersion,
LastVersion: group.lastVersion,
RequiredBy: group.requiredBy,
Dependency: group.dependency,
Constraint: group.constraint,
Selected: group.selected,
})
}
// A nested failure is the parent's summary of a deeper cause. When the
// parent also records a reason of its own, the summary adds nothing.
if len(groups) > 1 {
groups = slices.DeleteFunc(groups, func(group RejectionGroup) bool {
return group.Kind == RejectionNested
})
}
// Report the strongest evidence before incidental filter rejections.
sort.SliceStable(groups, func(i, j int) bool {
left := rejectionPriority(groups[i].Kind)
right := rejectionPriority(groups[j].Kind)
if left != right {
return left > right
}
if groups[i].Count != groups[j].Count {
return groups[i].Count > groups[j].Count
}
return groups[i].Detail < groups[j].Detail
})
display := entry.display
if display == "" {
display = l.displays[key]
}
if display == "" {
display = entry.projectID
}
return &Failure{
Project: display,
Provider: entry.provider,
ProjectID: entry.projectID,
Minecraft: minecraft,
Ecosystem: key.ecosystem,
Candidates: entry.candidates,
Groups: groups,
Cause: cause,
}
}
func problemErrors(problems []ModuleProblem) []error {
errs := make([]error, 0, len(problems))
for _, problem := range problems {
errs = append(errs, problem)
}
return errs
}
// resolutionFailure prefers the structured explanation over the last error,
// which only names the request that happened to fail last.
func resolutionFailure(failure *Failure, cause error) error {
if failure != nil {
return failure
}
return cause
}
func describeRejection(kind RejectionKind, detail string) string {
switch kind {
case RejectionVersionMismatch:
return "does not match " + detail
case RejectionReleaseMismatch:
return "release " + detail + " expected"
case RejectionFilePattern:
return "filename does not match " + detail
case RejectionPrimaryFile:
return "not the primary file"
case RejectionChannel:
return "not a release build"
case RejectionMetadataConflict:
return "conflicts with " + detail
default:
return detail
}
}
package resolve
import (
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
func fmlLoader(target Target) bool {
return target.Product == serverpkg.ProductForge ||
target.Product == serverpkg.ProductNeoForge
}
func matchesLoaderCompatibility(
raw string,
module string,
target Target,
dialect versionpkg.Dialect,
) (bool, error) {
for _, compatible := range loaderCompatibilityVersions(module, target) {
matched, err := versionpkg.Match(raw, compatible, dialect)
if err != nil {
return false, err
}
if matched {
return true, nil
}
}
return false, nil
}
// loaderCompatibilityVersions mirrors the built-in version support matrices of
// Forge and NeoForge. A loader accepts a dependency when either the selected
// version or one of the module's compatibility versions satisfies the range.
// The entries and their exact Minecraft gates come from the FMLLoader classes
// shipped with the loader:
//
// - NeoForge FML 1.0.16: 1.19.2 -> javafml 42, minecraft 1.19.1, forge 42.0.9
// - NeoForge FML 4.0.x: 1.21.1 -> minecraft 1.21, neoforge 21.0.166
// - NeoForge FML 11.0.16: no entries; 11.0.23 and 12.x cover 1.21.8
// -> minecraft 1.21.7, neoforge 21.7.26-beta
// - Forge FML 43.x: 1.19.2 -> javafml 42, minecraft 1.19.1, forge 42.0.9
// - Forge FML 47.4.x: 1.20.1 -> forge 47.1.79
// - Forge FML 52.x: 1.21.1 -> javafml 51, minecraft 1.21, forge 51.0.33
// - Forge FML 54.x and 61.x keep the 1.21.1 gate, so they have no entries
// on their own Minecraft version.
//
// A compatibility entry can satisfy a dependency even when no selected package
// provides the module, because the loader's matrix substitutes a version for
// modules such as languageloader.javafml.
func loaderCompatibilityVersions(
module string,
target Target,
) []versionpkg.Version {
switch target.Product {
case serverpkg.ProductNeoForge:
switch target.Minecraft {
case "1.19.2":
switch module {
case "languageloader.javafml":
return []versionpkg.Version{"42"}
case "minecraft":
return []versionpkg.Version{"1.19.1"}
case "forge":
return []versionpkg.Version{"42.0.9"}
}
case "1.21.1":
switch module {
case "minecraft":
return []versionpkg.Version{"1.21"}
case "neoforge":
return []versionpkg.Version{"21.0.166"}
}
case "1.21.8":
switch module {
case "minecraft":
return []versionpkg.Version{"1.21.7"}
case "neoforge":
return []versionpkg.Version{"21.7.26-beta"}
}
}
case serverpkg.ProductForge:
switch target.Minecraft {
case "1.19.2":
switch module {
case "languageloader.javafml":
return []versionpkg.Version{"42"}
case "minecraft":
return []versionpkg.Version{"1.19.1"}
case "forge":
return []versionpkg.Version{"42.0.9"}
}
case "1.20.1":
if module == "forge" {
return []versionpkg.Version{"47.1.79"}
}
case "1.21.1":
switch module {
case "languageloader.javafml":
return []versionpkg.Version{"51"}
case "minecraft":
return []versionpkg.Version{"1.21"}
case "forge":
return []versionpkg.Version{"51.0.33"}
}
}
}
return nil
}
package resolve
import (
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
)
// lockedEdges restores only the relationships the lock selected from those
// published upstream. In particular, an imported pack can use a different
// provider or omit a client-only dependency. Only an additive change can
// reuse that graph. Changed or removed bindings require fresh expansion.
func (l lockIndex) lockedEdges(requests []projectRequest, packages []document.Package) map[projectKey][]projectRequest {
matched := 0
for _, r := range requests {
binding := r.requirements[0]
key := r.key
key.project = binding.Reference
if p := l.byReference[key]; p != nil {
if !slices.Contains(p.Requirements, binding) {
return nil
}
matched++
}
}
if matched != len(l.byReference) {
return nil
}
// DependencyOf does not carry the parent's ecosystem. If two parent
// selections have the same reference, reconstruct neither by guessing.
parents := make(map[projectKey]projectKey, len(packages))
for key := range l.byProject {
ref := key
ref.ecosystem = catalog.EcosystemUnspecified
if _, exists := parents[ref]; exists {
return nil
}
parents[ref] = key
}
edges := make(map[projectKey][]projectRequest)
for i := range packages {
p := &packages[i]
for _, ref := range p.DependencyOf {
parent, ok := parents[projectKey{p.Environment, catalog.EcosystemUnspecified, ref.Provider, string(ref.Name)}]
if !ok {
return nil
}
child := projectRequest{
key: projectKey{p.Environment, p.Ecosystem, p.Provider, p.ProjectID},
origin: originDependency,
dependencyOf: ref,
}
if p.ReleaseID != "" {
child.releaseHints = []releaseHint{{releaseID: p.ReleaseID}}
}
edges[parent] = append(edges[parent], child)
}
}
return edges
}
package resolve
import (
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// clientOnlyIdentities collects module identities that only client-only
// declarations answer. A loader filters those candidates out of a dedicated
// server, so requirements they alone would answer are not failures. Each
// identity is scoped like module resolution, by the environment of the
// declaring package and the target's module namespace, so it exempts only
// requirements in that namespace.
func clientOnlyIdentities(
packages []document.Package,
target Target,
) map[moduleKey]struct{} {
identities := map[moduleKey]struct{}{}
add := func(
environment serverpkg.Environment,
module catalog.DescriptorModule,
) {
for _, name := range module.ClientOnly {
id := normalizeModuleID(module.Ecosystem, name)
if id != "" {
identities[moduleKey{
environment,
target.moduleNamespace(module.Ecosystem),
id,
}] = struct{}{}
}
}
}
for pi := range packages {
p := &packages[pi]
if !p.Enabled() {
continue
}
for _, module := range p.Modules {
add(p.Environment, module)
}
}
for _, module := range target.CoreModules {
add(serverpkg.EnvironmentServer, module)
}
return identities
}
// moduleKey scopes a module identity so identically named modules in
// different environments or module namespaces stay distinct.
type moduleKey struct {
environment serverpkg.Environment
ecosystem catalog.Ecosystem
id string
}
// moduleSource names the artifact a module came from. The offsets identify the
// declaration inside its package; runtime modules have no package.
type moduleSource struct {
packageIndex int
moduleIndex int
}
func (s moduleSource) owns(packageIndex, moduleIndex int) bool {
return s.packageIndex == packageIndex && s.moduleIndex == moduleIndex
}
func (s moduleSource) runtime() bool {
return s.packageIndex < 0
}
// moduleProvider is the module that answers one identity, together with the
// coordinates a dependency binds to.
type moduleProvider struct {
source moduleSource
module catalog.DescriptorModule
provider catalog.Provider
projectID string
}
// finalizeModules checks module requirements against the target and drops
// modules that lose to another selected module with the same identity. It
// returns the problems it found; only an unparsable or ambiguous module
// identity is an error.
func finalizeModules(packages []document.Package, target Target) ([]ModuleProblem, error) {
runtime := runtimeModules(target)
clientOnly := clientOnlyIdentities(packages, target)
index, err := buildModuleIndex(packages, target, runtime)
if err != nil {
return nil, err
}
var problems []ModuleProblem
surviving := make([][]catalog.DescriptorModule, len(packages))
for pi := range packages {
p := &packages[pi]
if !p.Enabled() {
continue
}
for mi := range p.Modules {
m := p.Modules[mi]
key := moduleKey{
p.Environment,
target.moduleNamespace(m.Ecosystem),
normalizeModuleID(m.Ecosystem, m.ID),
}
if owner, ok := index[key]; !ok || !owner.source.owns(pi, mi) {
continue
}
problems = append(
problems,
checkModuleDependencies(p, m, moduleScope{
target: target,
environment: p.Environment,
ecosystem: m.Ecosystem,
dialect: m.VersionDialect,
runtime: runtime,
index: index,
clientOnly: clientOnly,
})...,
)
surviving[pi] = append(surviving[pi], m)
}
}
// Assignment happens only after every package has been checked, so a
// lookup never observes a compacted module list.
for pi := range packages {
if !packages[pi].Enabled() {
continue
}
dropped := len(surviving[pi]) < len(packages[pi].Modules)
packages[pi].ModulesSuperseded = packages[pi].ModulesSuperseded || dropped
packages[pi].Modules = surviving[pi]
}
return problems, nil
}
// moduleIdentities lists every identity a module answers: its ID, the
// identities it provides, and its group-qualified ID.
func moduleIdentities(m catalog.DescriptorModule) []string {
names := make([]string, 0, len(m.Provides)+2)
names = append(names, m.ID)
names = append(names, m.Provides...)
if m.Group != "" {
names = append(names, m.Group+":"+m.ID)
}
return names
}
// ModuleIdentityKeys returns every scoped identity a module answers.
func (t Target) ModuleIdentityKeys(
environment serverpkg.Environment,
ecosystem catalog.Ecosystem,
m catalog.DescriptorModule,
) []ModuleIdentity {
names := moduleIdentities(m)
identities := make([]ModuleIdentity, 0, len(names))
namespace := t.moduleNamespace(ecosystem)
for _, name := range names {
identities = append(identities, ModuleIdentity{
Environment: environment,
Namespace: namespace,
ID: normalizeModuleID(ecosystem, name),
})
}
return identities
}
// ModuleOrder compares two modules that answer one identity. A native module
// outranks a nested one; otherwise the higher version wins. It returns 0 when
// the versions are equal or unparseable.
func ModuleOrder(a, b catalog.DescriptorModule) int {
aNative := a.NestedPath == ""
bNative := b.NestedPath == ""
if aNative != bNative {
if aNative {
return 1
}
return -1
}
aVersion, err := versionpkg.ParseVersion(a.Version, a.VersionDialect)
if err != nil {
return 0
}
bVersion, err := versionpkg.ParseVersion(b.Version, b.VersionDialect)
if err != nil {
return 0
}
comparison, comparable := versionpkg.Compare(aVersion, bVersion)
if !comparable {
return 0
}
return comparison
}
// buildModuleIndex resolves every module identity to the declaration that
// answers it. A native module outranks a bundled copy of the same identity.
// Bundled copies from different packages compare versions; bundled copies from
// the same package are loader-selected variants, so the one whose requirements
// the server satisfies wins first. Two native modules in different packages are
// ambiguous.
func buildModuleIndex(
packages []document.Package,
target Target,
runtime map[string]catalog.DescriptorModule,
) (map[moduleKey]moduleProvider, error) {
index := map[moduleKey]moduleProvider{}
for pi := range packages {
p := &packages[pi]
if !p.Enabled() {
continue
}
for mi, m := range p.Modules {
for _, name := range moduleIdentities(m) {
module := m
if name != m.ID {
module.Version = m.ProvidedVersion(name)
}
candidate := moduleProvider{
source: moduleSource{
packageIndex: pi,
moduleIndex: mi,
},
module: module,
provider: p.Provider,
projectID: p.ProjectID,
}
key := moduleKey{
p.Environment,
target.moduleNamespace(m.Ecosystem),
normalizeModuleID(m.Ecosystem, name),
}
previous, ok := index[key]
if !ok {
index[key] = candidate
continue
}
keep, err := moduleWins(
previous,
candidate,
packages[previous.source.packageIndex].Filename,
p.Filename,
name,
target,
runtime,
)
if err != nil {
return nil, err
}
if !keep {
index[key] = candidate
}
}
}
}
return index, nil
}
type nativeOwner struct {
project projectKey
file string
}
// claimNativeModules reserves identities for a direct requirement only after
// every identity is free. Several declarations within one artifact may share
// an identity. The caller releases the returned keys on backtrack.
func claimNativeModules(owners map[moduleKey]nativeOwner, owner projectKey, p document.Package, target Target) ([]moduleKey, projectKey, error) {
var keys []moduleKey
for _, module := range p.Modules {
if module.NestedPath != "" {
continue
}
namespace := target.moduleNamespace(module.Ecosystem)
for _, name := range moduleIdentities(module) {
key := moduleKey{p.Environment, namespace, normalizeModuleID(module.Ecosystem, name)}
if other, ok := owners[key]; ok {
return nil, other.project, duplicateNativeModule(name, p.Filename, other.file)
}
keys = append(keys, key)
}
}
for _, key := range keys {
owners[key] = nativeOwner{owner, p.Filename}
}
return keys, projectKey{}, nil
}
func duplicateNativeModule(name, candidate, previous string) error {
return fmt.Errorf("duplicate native module %s in %s and %s", name, candidate, previous)
}
// moduleWins reports whether the module already indexed keeps the identity.
func moduleWins(
previous moduleProvider,
candidate moduleProvider,
previousFile string,
candidateFile string,
name string,
target Target,
runtime map[string]catalog.DescriptorModule,
) (bool, error) {
previousNative := previous.module.NestedPath == ""
candidateNative := candidate.module.NestedPath == ""
if previousNative && candidateNative {
if previous.source.packageIndex == candidate.source.packageIndex {
return true, nil
}
return false, duplicateNativeModule(name, candidateFile, previousFile)
}
if previousNative {
return true, nil
}
if candidateNative {
return false, nil
}
if previous.source.packageIndex == candidate.source.packageIndex {
previousServes, previousKnown := servesTarget(previous.module, target, runtime)
candidateServes, candidateKnown := servesTarget(candidate.module, target, runtime)
if previousKnown && candidateKnown && previousServes != candidateServes {
return previousServes, nil
}
}
a, err := versionpkg.ParseVersion(
previous.module.Version,
previous.module.VersionDialect,
)
if err != nil {
return false, err
}
b, err := versionpkg.ParseVersion(
candidate.module.Version,
candidate.module.VersionDialect,
)
if err != nil {
return false, err
}
comparison, comparable := versionpkg.Compare(a, b)
if !comparable {
return false, fmt.Errorf(
"incomparable nested module versions %s and %s",
previous.module.Version,
candidate.module.Version,
)
}
return comparison >= 0, nil
}
// servesTarget reports whether the requirements a module places on the modules
// the server itself provides hold for target. A wrapper that bundles one nested
// jar per Minecraft line publishes every variant under one identity with
// disjoint requirements, and the loader loads the variant the running version
// satisfies. Requirements that another package answers are not part of that
// decision, because they do not vary with the server.
//
// The second result is false when a requirement cannot be evaluated, so the
// caller keeps its version order instead of guessing.
func servesTarget(
m catalog.DescriptorModule,
target Target,
runtime map[string]catalog.DescriptorModule,
) (bool, bool) {
scope := moduleScope{
target: target,
ecosystem: m.Ecosystem,
dialect: m.VersionDialect,
runtime: runtime,
}
for di := range m.Dependencies {
dep := &m.Dependencies[di]
if dep.Kind != catalog.DependencyKindRequired || dep.ID == "java" {
continue
}
outcome, err := scope.evaluate(dep, false)
if err != nil {
return false, false
}
if outcome.present && !outcome.matched {
return false, true
}
}
return true, true
}
// runtimeModules reports the modules the runtime itself provides. They answer
// requirements before any package does, the same way a loader resolves its own
// modules before the package graph.
func runtimeModules(target Target) map[string]catalog.DescriptorModule {
modules := map[string]catalog.DescriptorModule{}
add := func(module catalog.DescriptorModule) {
id := normalizeModuleID(module.Ecosystem, module.ID)
if id != "" {
if _, ok := modules[id]; !ok {
modules[id] = module
}
}
if module.Group != "" && id != "" {
groupID := module.Group + ":" + id
if _, ok := modules[groupID]; !ok {
alias := module
alias.ID = groupID
alias.Provides = nil
alias.ProvidedVersions = nil
modules[groupID] = alias
}
}
for _, name := range module.Provides {
key := normalizeModuleID(module.Ecosystem, name)
if key == "" {
continue
}
if _, ok := modules[key]; ok {
continue
}
alias := module
alias.ID = name
alias.Version = module.ProvidedVersion(name)
alias.Group = ""
alias.Provides = nil
alias.ProvidedVersions = nil
alias.Dependencies = nil
modules[key] = alias
}
}
add(catalog.DescriptorModule{
ID: "minecraft",
Version: target.Minecraft,
Ecosystem: catalog.EcosystemMinecraft,
})
switch target.Product {
case serverpkg.ProductFabric:
add(catalog.DescriptorModule{
ID: "fabricloader",
Version: target.CoreVersion,
Ecosystem: catalog.EcosystemFabric,
})
case serverpkg.ProductQuilt:
add(catalog.DescriptorModule{
ID: "quilt_loader",
Version: target.CoreVersion,
Ecosystem: catalog.EcosystemQuilt,
})
case serverpkg.ProductForge:
add(catalog.DescriptorModule{
ID: "forge",
Version: target.CoreVersion,
Ecosystem: catalog.EcosystemForge,
})
case serverpkg.ProductNeoForge:
add(catalog.DescriptorModule{
ID: "neoforge",
Version: target.CoreVersion,
Ecosystem: catalog.EcosystemNeoForge,
})
}
if target.MCDRVersion != "" {
add(catalog.DescriptorModule{
ID: "mcdreforged",
Version: versionpkg.Version(target.MCDRVersion),
Ecosystem: catalog.EcosystemMCDR,
})
}
for _, module := range target.CoreModules {
add(module)
}
return modules
}
func normalizeModuleID(ecosystem catalog.Ecosystem, id string) string {
if ecosystem == catalog.EcosystemBukkit || ecosystem == catalog.EcosystemPaper {
return strings.ToLower(id)
}
return id
}
package resolve
import (
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// moduleScope evaluates the dependency tree of one module against the modules
// a graph selects. Identities are scoped by the environment of the declaring
// package and by the target's module namespace for the module's ecosystem.
type moduleScope struct {
target Target
environment serverpkg.Environment
ecosystem catalog.Ecosystem
dialect versionpkg.Dialect
runtime map[string]catalog.DescriptorModule
// index is nil when only the modules of the server runtime count.
index map[moduleKey]moduleProvider
clientOnly map[moduleKey]struct{}
}
// requirementOutcome is the state of the selected graph that one dependency
// node observes.
type requirementOutcome struct {
// present reports that a module answers an identity the node names.
present bool
// matched reports that the node holds.
matched bool
// waived reports a node that holds without a module to bind: an unless
// condition holds, an any-of group has an absent optional alternative, or
// the only candidate is client-only.
waived bool
value string
owner *moduleProvider
matchedID string
}
func (s moduleScope) key(id string) moduleKey {
return moduleKey{
s.environment,
s.target.moduleNamespace(s.ecosystem),
normalizeModuleID(s.ecosystem, id),
}
}
// lookup returns the selected version of an identity and the package module
// that answers it. A runtime module answers before any package and has no
// owner.
func (s moduleScope) lookup(id string) (string, *moduleProvider) {
if module, ok := s.runtime[normalizeModuleID(s.ecosystem, id)]; ok {
return string(module.Version), nil
}
if provider, ok := s.index[s.key(id)]; ok {
return string(provider.module.Version), &provider
}
return "", nil
}
// evaluate decides one dependency node. A node holds when its own identity or
// one of its AnyOf alternatives holds, and every AllOf node holds too. A
// holding Unless condition waives the node; a waived break does not apply.
// grouped marks a node that is an alternative of an any-of group.
func (s moduleScope) evaluate(
dep *catalog.DescriptorDependency,
grouped bool,
) (requirementOutcome, error) {
exempt, err := s.exempted(dep)
if err != nil {
return requirementOutcome{}, err
}
if exempt {
holds := dep.Kind != catalog.DependencyKindIncompatible
return requirementOutcome{matched: holds, waived: holds}, nil
}
outcome, err := s.leaf(dep, grouped || len(dep.AnyOf) > 0)
if err != nil {
return outcome, err
}
for i := 0; !outcome.matched && i < len(dep.AnyOf); i++ {
alternative, err := s.evaluate(&dep.AnyOf[i], true)
if err != nil {
return outcome, err
}
if alternative.matched {
alternative.present = alternative.present || outcome.present
outcome = alternative
} else if !outcome.present && alternative.present {
outcome.present = true
outcome.value = alternative.value
}
}
if !outcome.matched || outcome.waived {
return outcome, nil
}
for i := range dep.AllOf {
condition, err := s.evaluate(&dep.AllOf[i], false)
if err != nil {
return outcome, err
}
if !condition.matched {
outcome.matched = false
return outcome, nil
}
}
return outcome, nil
}
// leaf decides the identity a node names, without its alternatives.
func (s moduleScope) leaf(
dep *catalog.DescriptorDependency,
grouped bool,
) (requirementOutcome, error) {
value, owner := s.lookup(dep.ID)
outcome := requirementOutcome{
present: value != "",
value: value,
owner: owner,
}
var err error
switch {
case value != "":
outcome.matched, err = matchModuleConstraint(dep, value, s.target, s.dialect)
case dep.Constraint != "":
// A loader support matrix can answer a module no package selects.
outcome.matched, err = matchesLoaderCompatibility(
dep.Constraint,
dep.ID,
s.target,
s.dialect,
)
}
if err != nil {
return outcome, err
}
if outcome.matched {
outcome.matchedID = dep.ID
return outcome, nil
}
if value != "" || dep.Kind == catalog.DependencyKindIncompatible {
return outcome, nil
}
if _, clientOnly := s.clientOnly[s.key(dep.ID)]; clientOnly ||
(grouped && dep.Kind == catalog.DependencyKindOptional) {
// The loader filters a client-only candidate out of a dedicated
// server, and an absent optional alternative satisfies its group.
return requirementOutcome{matched: true, waived: true}, nil
}
return outcome, nil
}
// exempted reports whether an Unless condition of dep holds. A condition
// holds only when a selected module answers it.
func (s moduleScope) exempted(dep *catalog.DescriptorDependency) (bool, error) {
for i := range dep.Unless {
condition, err := s.evaluate(&dep.Unless[i], false)
if err != nil {
return false, err
}
if condition.present && condition.matched {
return true, nil
}
}
return false, nil
}
// matchModuleConstraint applies one dependency constraint to a selected
// version, including the loader support matrices that substitute versions for
// modules the loader knows about.
func matchModuleConstraint(
dep *catalog.DescriptorDependency,
value string,
target Target,
dialect versionpkg.Dialect,
) (bool, error) {
if fmlLoader(target) && value == "0.0NONE" {
// FMLLoader treats the 0.0NONE sentinel as satisfying every range.
return true, nil
}
if dep.Constraint == "" {
return true, nil
}
matched, err := versionpkg.Match(
dep.Constraint,
versionpkg.Version(value),
dialect,
)
if err != nil || matched {
return matched, err
}
return matchesLoaderCompatibility(dep.Constraint, dep.ID, target, dialect)
}
// checkModuleDependencies reports the problems of one module's dependencies
// and binds each holding dependency to the package module that answers it.
func checkModuleDependencies(
p *document.Package,
m catalog.DescriptorModule,
scope moduleScope,
) []ModuleProblem {
var problems []ModuleProblem
for di := range m.Dependencies {
dep := &m.Dependencies[di]
// A Java requirement is checked against the Java runtime that runs
// the server, and only warns.
if dep.Kind == catalog.DependencyKindPython || dep.ID == "java" {
continue
}
outcome, err := scope.evaluate(dep, false)
if err != nil {
problems = append(problems, moduleProblem(
p,
m.ID,
*dep,
outcome.value,
false,
fmt.Sprintf("module %s requires %s: %v", m.ID, dep.ID, err),
))
continue
}
if problem := dependencyProblem(m.ID, dep, outcome); problem != nil {
entry := moduleProblem(
p,
m.ID,
*dep,
outcome.value,
outcome.owner == nil && outcome.value != "",
problem.Error(),
)
entry.cause = problem
problems = append(problems, entry)
}
if !outcome.matched || outcome.waived {
continue
}
switch {
case outcome.owner != nil && !outcome.owner.source.runtime():
dep.Provider = outcome.owner.provider
dep.ProjectID = outcome.owner.projectID
dep.ModuleID = outcome.owner.module.ID
case outcome.matchedID != "":
dep.ModuleID = outcome.matchedID
default:
dep.ModuleID = dep.ID
}
}
return problems
}
// MissingModuleError reports a module requirement that no selected package
// provides. Required names the module identity alone, without its constraint,
// so callers can compare it with the modules adoption reports.
type MissingModuleError struct {
Requiring string
Required string
// requirement is the text shown for the requirement: the identity with its
// constraint, or the alternatives of an any-of group.
requirement string
}
func (e *MissingModuleError) Error() string {
requirement := e.requirement
if requirement == "" {
requirement = e.Required
}
return fmt.Sprintf(
"module %s requires %s, which no selected package provides",
e.Requiring,
requirement,
)
}
// dependencyProblem describes the problem an evaluated dependency causes, or
// returns nil when it causes none. An optional dependency outside an any-of
// group is checked only when a module answers it.
func dependencyProblem(
requiredBy string,
dep *catalog.DescriptorDependency,
outcome requirementOutcome,
) error {
requirement := dependencyRequirementText(dep)
switch {
case dep.Kind == catalog.DependencyKindIncompatible:
if outcome.matched {
breaks := dep.ID
if outcome.matchedID != "" {
breaks = outcome.matchedID
}
return fmt.Errorf(
"module %s breaks %s %s",
requiredBy,
breaks,
outcome.value,
)
}
case dep.Kind == catalog.DependencyKindRequired ||
(dep.Kind == catalog.DependencyKindOptional && len(dep.AnyOf) > 0):
if outcome.matched {
return nil
}
if outcome.value == "" {
return &MissingModuleError{
Requiring: requiredBy,
Required: dep.ID,
requirement: requirement,
}
}
return fmt.Errorf(
"module %s requires %s (selected %s)",
requiredBy,
requirement,
outcome.value,
)
case dep.Kind == catalog.DependencyKindOptional:
if outcome.present && !outcome.matched {
return fmt.Errorf(
"module %s optionally requires %s (selected %s)",
requiredBy,
requirement,
outcome.value,
)
}
}
return nil
}
func dependencyRequirementText(dep *catalog.DescriptorDependency) string {
parts := make([]string, 0, 1+len(dep.AnyOf))
parts = append(parts, strings.TrimSpace(dep.ID+" "+dep.Constraint))
for i := range dep.AnyOf {
alternative := &dep.AnyOf[i]
parts = append(
parts,
strings.TrimSpace(alternative.ID+" "+alternative.Constraint),
)
}
if len(parts) == 1 {
return parts[0]
}
return "one of " + strings.Join(parts, ", ")
}
package resolve
import (
"cmp"
"context"
"errors"
"fmt"
"maps"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/upstream"
serverpkg "github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// Limit failed speculative selections while leaving successful visits and
// merges unbounded.
const backtrackLimit = 10000
// catalogueRegistry names the registry that serves a package provider. Only a
// provider backing a registry can answer catalogue queries.
func catalogueRegistry(provider catalog.Provider) catalog.Registry {
registry, ok := provider.Registry()
if !ok {
return catalog.RegistryUnspecified
}
return registry
}
// selectionState owns the branch-local graph of the package search: the
// chosen packages, the incompatibilities their metadata declares, and the
// packages an exact release demand pins. An artifact and its declarations
// form one selection, so the maps change together. Canonical identities,
// candidate lists, and artifact analysis are session-scoped caches and
// deliberately live outside this state.
type selectionState struct {
chosen map[projectKey]document.Package
conflicts map[projectKey][]upstream.ProjectDependency
pinned map[projectKey]bool
}
// searchOutcome reports how exploring one branch of the search ended. A
// failure only this branch reaches leaves the enclosing requests free to try
// another candidate; a failure that holds in every branch stops the search.
type searchOutcome uint8
const (
// branchFailed means the explored branch cannot settle. The enclosing
// request may still try its next candidate.
branchFailed searchOutcome = iota
// graphSettled means the explored branch produced a complete selection.
graphSettled
// searchStopped means the search ended before it settled. Backtracking
// would only repeat work no candidate choice changes.
searchStopped
)
// selectionBranch records the entry one change replaced, so restore can put
// it back.
type selectionBranch struct {
key projectKey
previous document.Package
hadPrevious bool
conflicts []upstream.ProjectDependency
hadConflicts bool
pinned bool
}
func newSelectionState() selectionState {
return selectionState{
chosen: map[projectKey]document.Package{},
conflicts: map[projectKey][]upstream.ProjectDependency{},
pinned: map[projectKey]bool{},
}
}
func (s *selectionState) reset() {
clear(s.chosen)
clear(s.conflicts)
clear(s.pinned)
}
func (s *selectionState) selection(key projectKey) (document.Package, bool) {
p, ok := s.chosen[key]
return p, ok
}
// extend merges a demand into a selected package. The selection keeps its
// conflicts and pins; an incoming exact-release demand adds a pin.
func (s *selectionState) extend(
key projectKey,
p document.Package,
pin bool,
) selectionBranch {
return s.install(key, p, s.conflicts[key], s.pinned[key] || pin)
}
func (s *selectionState) install(
key projectKey,
p document.Package,
declared []upstream.ProjectDependency,
pinned bool,
) selectionBranch {
branch := s.snapshot(key)
s.chosen[key] = p
if len(declared) > 0 {
s.conflicts[key] = declared
} else {
delete(s.conflicts, key)
}
if pinned {
s.pinned[key] = true
} else {
delete(s.pinned, key)
}
return branch
}
func (s *selectionState) remove(key projectKey) selectionBranch {
branch := s.snapshot(key)
delete(s.chosen, key)
delete(s.conflicts, key)
delete(s.pinned, key)
return branch
}
func (s *selectionState) snapshot(key projectKey) selectionBranch {
previous, hadPrevious := s.chosen[key]
conflicts, hadConflicts := s.conflicts[key]
return selectionBranch{
key: key,
previous: previous,
hadPrevious: hadPrevious,
conflicts: conflicts,
hadConflicts: hadConflicts,
pinned: s.pinned[key],
}
}
func (s *selectionState) restore(branch selectionBranch) {
if branch.hadPrevious {
s.chosen[branch.key] = branch.previous
} else {
delete(s.chosen, branch.key)
}
if branch.hadConflicts {
s.conflicts[branch.key] = branch.conflicts
} else {
delete(s.conflicts, branch.key)
}
if branch.pinned {
s.pinned[branch.key] = true
} else {
delete(s.pinned, branch.key)
}
}
// restoreAll undoes branches in reverse order of their changes.
func (s *selectionState) restoreAll(branches []selectionBranch) {
for i := len(branches) - 1; i >= 0; i-- {
s.restore(branches[i])
}
}
// Index both identities: manifest requests use references, dependencies use project IDs.
type lockIndex struct {
byProject map[projectKey]*document.Package
byReference map[projectKey]*document.Package
}
func indexLock(previous []document.Package) lockIndex {
index := lockIndex{
byProject: make(map[projectKey]*document.Package, len(previous)),
byReference: make(map[projectKey]*document.Package, len(previous)),
}
for i := range previous {
p := &previous[i]
key := projectKey{p.Environment, p.Ecosystem, p.Provider, p.ProjectID}
index.byProject[key] = p
for _, binding := range p.Requirements {
key.project = binding.Reference
index.byReference[key] = p
}
}
return index
}
// lockedCandidate rebuilds the candidate the lock accepted for this request.
// An adopted release can carry a compatibility exception that ordinary
// provider filtering drops, so the locked file stays selectable while its
// runtime target is unchanged. The candidate keeps the dependency metadata the
// lock recorded, because the catalogue no longer supplies it.
func lockedCandidate(p *document.Package) (upstream.Candidate, bool) {
if p == nil || p.Filename == "" {
return upstream.Candidate{}, false
}
return upstream.Candidate{
Artifact: p.Artifact,
PrimaryFile: true,
Channel: p.Channel,
Dependencies: candidateDependencies(p.Dependencies),
DependenciesUnknown: p.DependenciesUnknown,
}, true
}
// releaseDependencies records a candidate's declared project relationships in
// the lock.
func releaseDependencies(
deps []upstream.ProjectDependency,
) []document.PackageDependency {
if len(deps) == 0 {
return nil
}
out := make([]document.PackageDependency, len(deps))
for i, dep := range deps {
out[i] = document.PackageDependency{
Provider: dep.Provider,
ProjectID: dep.ProjectID,
ReleaseID: dep.ReleaseID,
Kind: dep.Kind,
}
}
return out
}
// candidateDependencies restores the relationships a lock recorded.
func candidateDependencies(
deps []document.PackageDependency,
) []upstream.ProjectDependency {
if len(deps) == 0 {
return nil
}
out := make([]upstream.ProjectDependency, len(deps))
for i, dep := range deps {
out[i] = upstream.ProjectDependency{
Provider: dep.Provider,
ProjectID: dep.ProjectID,
ReleaseID: dep.ReleaseID,
Kind: dep.Kind,
}
}
return out
}
func appendLockedCandidate(
list []upstream.Candidate,
pin *document.Package,
) []upstream.Candidate {
locked, ok := lockedCandidate(pin)
if !ok {
return list
}
locked.CompatibilityUnknown = true
if slices.ContainsFunc(list, func(candidate upstream.Candidate) bool {
if locked.FileID != "" && candidate.FileID != "" {
return candidate.FileID == locked.FileID
}
return candidate.Version == locked.Version &&
candidate.Filename == locked.Filename
}) {
return list
}
return append(list, locked)
}
func Packages(request PackagesRequest) ([]document.Package, []error, error) {
ctx := request.Context
logger := request.Logger
if ctx == nil {
ctx = context.Background()
}
d := request.Manifest
previous := indexLock(request.Previous)
preserveLocked := request.PreserveLocked
target := request.Target
withOptional := request.WithOptional
acceptBroken := request.AcceptBroken
acceptPackageConflicts := request.AcceptPackageConflicts
expandDependencies := request.ExpandDependencies
trace := request.Trace
var requests []projectRequest
appendRequest := func(environment serverpkg.Environment, ecosystem catalog.Ecosystem, ref string, r document.Requirement) error {
provider, project, err := document.ParseReference(ref)
if err != nil {
return err
}
// The slug the user wrote is the display name even when the lock lets
// resolution start from the project identity.
display := project
fileID := ""
if pin := previous.byReference[projectKey{environment, ecosystem, provider, ref}]; pin != nil {
project, fileID = pin.ProjectID, pin.FileID
}
requests = append(requests, projectRequest{
key: projectKey{
environment,
ecosystem,
provider,
project,
},
display: display,
origin: originManifest,
previousFileID: fileID,
requirements: []document.RequirementBinding{
{
Reference: ref,
Selector: r.Selector,
FilePattern: r.FilePattern,
Enabled: r.IsEnabled(),
},
},
})
return nil
}
var ecosystems []catalog.Ecosystem
for ecosystem := range d.Server.Packages {
ecosystems = append(ecosystems, ecosystem)
}
slices.Sort(ecosystems)
for _, ecosystem := range ecosystems {
var refs []string
for ref := range d.Server.Packages[ecosystem] {
refs = append(refs, ref)
}
slices.Sort(refs)
for _, ref := range refs {
if err := appendRequest(serverpkg.EnvironmentServer, ecosystem, ref, d.Server.Packages[ecosystem][ref]); err != nil {
return nil, nil, err
}
}
}
if d.MCDR != nil {
var refs []string
for ref := range d.MCDR.Packages {
refs = append(refs, ref)
}
slices.Sort(refs)
for _, ref := range refs {
if err := appendRequest(serverpkg.EnvironmentMCDR, catalog.EcosystemMCDR, ref, d.MCDR.Packages[ref]); err != nil {
return nil, nil, err
}
}
}
for _, r := range requests {
if r.key.environment == serverpkg.EnvironmentServer {
if !SupportsPackages(target, r.key.ecosystem) {
for _, req := range r.requirements {
if req.Enabled {
return nil, nil, fmt.Errorf("product %s cannot load %s packages", target.Product, r.key.ecosystem)
}
}
}
}
}
candidates := map[projectKey][]upstream.Candidate{}
provenance := map[string]candidateProvenance{}
canonical := map[projectKey]projectKey{}
state := newSelectionState()
cache := request.Cache
if cache == nil {
cache = NewAnalysisCache()
}
cache.SeedPrevious(request.Previous, request.PreviousTarget, target)
prefetch := newPrefetcher(ctx, request, cache, request.Listings)
defer prefetch.close()
attempts := 0
backtracks := 0
preferPins := preserveLocked && request.PreferLocked && !withOptional
var pinnedEdges map[projectKey][]projectRequest
if preferPins && expandDependencies {
pinnedEdges = previous.lockedEdges(requests, request.Previous)
}
// Start the listings every learned request needs before the search asks
// for the first one. The search still consumes them in its own order.
prefetch.prefetchRequests(requests, previous, preferPins)
usedPin := false
native := make(map[moduleKey]nativeOwner)
nonPrimary := make(map[projectKey]bool)
// Non-nil only when a direct requirement exhausted its candidates and
// the named prior decisions alone suffice to explain every rejection.
var blockers map[projectKey]bool
var settled []document.Package
var problems []ModuleProblem
strict := true
var lastErr error
ledger := newRejectionLedger()
logger.Info(
"resolve: resolving package requirements",
"requests", len(requests),
)
// operational marks a failure that no candidate rejection explains, such as
// a network or checksum error. It outranks the rejection summary.
operational := false
// hardFail records a failure scoped to the branch being explored. Another
// candidate of an enclosing request may still settle a graph.
hardFail := func(err error) searchOutcome {
lastErr = err
operational = true
return branchFailed
}
// stop ends the search because no remaining candidate reaches a different
// answer. Only a failure that holds in every branch qualifies: a cancelled
// context, an exhausted search budget, or a manifest requirement that no
// catalogue answer can satisfy. A dependency requirement exists only
// because one parent candidate selected it, and another candidate of that
// parent may not need the project at all, so its failures stay local.
stop := func(err error) searchOutcome {
lastErr = err
operational = true
return searchStopped
}
var backtrack func([]projectRequest) searchOutcome
backtrack = func(pending []projectRequest) searchOutcome {
if err := ctx.Err(); err != nil {
return stop(err)
}
attempts++
trace.state(len(state.chosen), len(pending))
if len(pending) == 0 {
all := make([]document.Package, 0, len(state.chosen))
for _, p := range state.chosen {
if p.Filename != "" {
all = append(all, p)
}
}
all = mergeArtifactSelections(all)
sortPackages(all)
var err error
problems, err = finalizeModules(all, target)
if err != nil {
logger.Debug(
"resolve: settled graph invalid",
"attempt", attempts,
"reason", err,
)
return hardFail(err)
}
if len(problems) > 0 && strict {
fatal := problems
if acceptPackageConflicts && !acceptBroken {
fatal = serverModuleProblems(problems)
}
if len(fatal) == 0 {
settled = all
return graphSettled
}
logger.Debug(
"resolve: settled graph rejected",
"attempt", attempts,
"reason", fatal[0],
)
lastErr = errors.Join(problemErrors(fatal)...)
for _, problem := range fatal {
key := projectKey{
problem.Environment,
problem.Ecosystem,
problem.Provider,
problem.ProjectID,
}
display := ledger.displayFor(key)
if display == "" {
display = problem.ProjectID
}
version := ""
if owner, ok := state.selection(key); ok {
version = string(owner.Version)
}
ledger.recordModule(
key,
display,
version,
problem,
)
ledger.markFailed(key)
}
return branchFailed
}
settled = all
return graphSettled
}
r := pending[0]
rest := pending[1:]
// giveUp records the request-level failure that explains why this
// branch cannot settle.
giveUp := func() {
if lastErr == nil {
lastErr = fmt.Errorf("no candidate satisfies %s:%s", r.key.provider, r.key.project)
}
ledger.markFailed(r.key)
}
if canonicalKey, ok := canonical[r.key]; ok {
r.key = canonicalKey
}
ledger.noteDisplay(r.key, r.display)
dependencyDemand := r.dependencyOf.Name != ""
active := len(r.requirements) == 0
for _, req := range r.requirements {
active = active || req.Enabled
}
// An artifact-less entry records only a disabled direct binding. When
// something else in the graph needs the package, that demand outranks
// the binding, so the artifact resolves instead of merging into a
// package that no file can satisfy.
if previous, ok := state.selection(r.key); ok &&
(!active || previous.Artifact.Filename != "") {
if active && len(r.requirements) != 0 {
selected := upstream.Candidate{
Artifact: previous.Artifact,
Channel: previous.Channel,
PrimaryFile: !nonPrimary[r.key],
}
decision, err := decideCandidate(selected, r)
if err != nil {
return hardFail(err)
}
if !decision.eligible {
ledger.record(r.key, r.display, string(previous.Version), decision.detail, decision.kind)
trace.rejected(r.display, string(previous.Version), decision.reason)
giveUp()
return branchFailed
}
}
previous.Requirements = append(previous.Requirements, r.requirements...)
previous.Dependency = previous.Dependency || dependencyDemand
if dependencyDemand && !slices.Contains(previous.DependencyOf, r.dependencyOf) {
previous.DependencyOf = append(previous.DependencyOf, r.dependencyOf)
}
branch := state.extend(
r.key,
previous,
len(r.releaseHints) > 0,
)
if outcome := backtrack(rest); outcome != branchFailed {
return outcome
}
state.restore(branch)
logger.Debug(
"resolve: backtracking requirement merge",
"provider", r.key.provider,
"project", r.key.project,
"reason", "remaining requests failed after merge",
)
return branchFailed
}
if !active {
p := document.Package{
Environment: r.key.environment,
Ecosystem: r.key.ecosystem,
Provider: r.key.provider,
ProjectID: r.key.project,
Requirements: r.requirements,
}
branch := state.install(r.key, p, nil, false)
if outcome := backtrack(rest); outcome != branchFailed {
return outcome
}
state.restore(branch)
return branchFailed
}
// A disabled direct binding may already hold an artifact-less entry
// here, because a real demand outranks it. Selecting a file replaces
// the entry, so the binding's requirements have to travel into the
// selection and back out again when the selection does not resolve.
var artifactless document.Package
replacingArtifactless := false
if prior, ok := state.selection(r.key); ok && prior.Artifact.Filename == "" {
artifactless, replacingArtifactless = prior, true
}
list, ok := candidates[r.key]
prior := previous.byProject[r.key]
replayEdges := false
if preferPins {
pin, found, err := pinAccepts(prior, r)
if err != nil {
return hardFail(err)
}
if found {
list, ok = []upstream.Candidate{pin}, true
usedPin = true
replayEdges = pinnedEdges != nil
ledger.setCandidates(r.key, r.display, 1)
}
}
if !ok {
if request.Candidates == nil {
return stop(errors.New("resolution requires a candidate source"))
}
var err error
list, err = prefetch.list(ctx, r.key)
if err != nil {
var locked upstream.Candidate
lockedOK := false
if preserveLocked {
locked, lockedOK = lockedCandidate(prior)
locked.CompatibilityUnknown = true
}
if !lockedOK {
// A manifest requirement holds in every branch, so a
// catalogue that cannot list it ends the search. A
// dependency requirement can still be avoided by another
// candidate of its parent.
if r.origin == originManifest {
return stop(err)
}
return hardFail(err)
}
logger.Debug(
"resolve: catalogue failed; keeping locked file",
"provider", r.key.provider,
"project", r.key.project,
"reason", err,
)
list = []upstream.Candidate{locked}
} else if preserveLocked {
list = appendLockedCandidate(list, prior)
}
list = orderCandidates(list, prior)
candidates[r.key] = list
ledger.setCandidates(r.key, r.display, len(list))
}
if len(list) > 0 {
// Direct requirements name a project by its catalogue slug, while
// catalogue metadata names the same project by identity. Resolve
// under the identity so the project enters the graph only once.
if project := list[0].ProjectID; project != "" && project != r.key.project {
canonicalKey := r.key
canonicalKey.project = project
canonical[r.key] = canonicalKey
if _, cached := candidates[canonicalKey]; !cached {
candidates[canonicalKey] = list
}
ledger.setCandidates(canonicalKey, r.display, len(list))
logger.Debug(
"resolve: project identity canonicalized",
"provider", r.key.provider,
"reference", r.key.project,
"project", project,
)
pending[0].key = canonicalKey
return backtrack(pending)
}
}
if len(list) == 0 {
ledger.record(r.key, r.display, "", "no published builds match this server", RejectionEmpty)
giveUp()
if r.origin == originManifest {
// Nothing this project published satisfies a requirement that
// holds in every branch.
return searchStopped
}
return branchFailed
}
list = preferReleaseBuilds(list, r.requirements)
list = preferReleaseHints(list, r.releaseHints)
eligible := false
explained := r.origin == originManifest
var causes map[projectKey]bool
triedBranch := false
descend := func(next []projectRequest) searchOutcome {
if triedBranch {
backtracks++
if backtracks > backtrackLimit {
return stop(&SearchLimitError{Attempts: backtrackLimit})
}
}
triedBranch = true
return backtrack(next)
}
for _, candidate := range list {
if err := ctx.Err(); err != nil {
return stop(err)
}
decision, err := decideCandidate(candidate, r)
if err != nil {
return hardFail(err)
}
if !decision.eligible {
ledger.record(r.key, r.display, string(candidate.Version), decision.detail, decision.kind)
trace.rejected(r.display, string(candidate.Version), decision.reason)
logger.Debug(
"resolve: candidate rejected",
"provider", r.key.provider,
"project", r.key.project,
"origin", r.origin.String(),
"candidate", candidate.Version,
"file", candidate.Filename,
"reason", decision.reason,
)
continue
}
eligible = true
if detail, conflicting := metadataConflict(candidate, r, state.chosen, state.conflicts); conflicting {
if !acceptPackageConflicts {
explained = false
reason := describeRejection(RejectionMetadataConflict, detail)
ledger.record(r.key, r.display, string(candidate.Version), detail, RejectionMetadataConflict)
trace.rejected(r.display, string(candidate.Version), reason)
logger.Debug(
"resolve: candidate rejected",
"provider", r.key.provider,
"project", r.key.project,
"origin", r.origin.String(),
"candidate", candidate.Version,
"file", candidate.Filename,
"reason", reason,
)
continue
}
logger.Debug(
"resolve: metadata conflict accepted",
"provider", r.key.provider,
"project", r.key.project,
"origin", r.origin.String(),
"candidate", candidate.Version,
"file", candidate.Filename,
"conflict", detail,
)
}
a := candidate.Artifact
if candidate.DependenciesUnknown || candidate.CompatibilityUnknown {
provenance[provenanceKey(
candidate.Provider,
r.key.ecosystem,
candidate.ProjectID,
candidate.ReleaseID,
candidate.FileID,
)] = candidateProvenance{
dependenciesUnknown: candidate.DependenciesUnknown,
compatibilityUnknown: candidate.CompatibilityUnknown,
}
}
var modules []catalog.DescriptorModule
descriptorLoader := target.DescriptorLoader(r.key.ecosystem)
analysis := prefetch.analyze(ctx, candidate, r.key.ecosystem)
if analysis.fatal != nil {
return hardFail(analysis.fatal)
}
a.Hashes = analysis.hashes
modules = analysis.modules
if analysis.descriptor != nil {
explained = false
// A descriptor the reader cannot interpret rejects this
// candidate. It is content evidence, not an operational
// failure of the whole search.
message := fmt.Sprintf(
"artifact %s has an unreadable %s descriptor: %v",
a.Filename,
descriptorLoader,
analysis.descriptor,
)
lastErr = analysis.descriptor
ledger.record(r.key, r.display, string(candidate.Version), message, RejectionModules)
trace.rejected(r.display, string(candidate.Version), message)
continue
}
if len(modules) == 0 {
message := fmt.Sprintf("artifact %s has no server-visible %s modules", a.Filename, descriptorLoader)
lastErr = errors.New(message)
ledger.record(r.key, r.display, string(candidate.Version), message, RejectionModules)
trace.rejected(r.display, string(candidate.Version), message)
continue
}
a.Modules = modules
requirements := r.requirements
if replacingArtifactless {
requirements = append(slices.Clone(artifactless.Requirements), r.requirements...)
}
var dependencyOf []catalog.Ref
if dependencyDemand {
dependencyOf = []catalog.Ref{r.dependencyOf}
}
pkg := document.Package{
Environment: r.key.environment,
Ecosystem: r.key.ecosystem,
Artifact: a,
Requirements: requirements,
Dependency: dependencyDemand,
DependencyOf: dependencyOf,
Dependencies: releaseDependencies(candidate.Dependencies),
DependenciesUnknown: candidate.DependenciesUnknown,
Channel: candidate.Channel,
}
// Direct selections cannot be superseded. A duplicate between
// two of them cannot be repaired by any remaining request.
var claims []moduleKey
if r.origin == originManifest {
var duplicate error
var other projectKey
claims, other, duplicate = claimNativeModules(native, r.key, pkg, target)
if duplicate != nil {
if causes == nil {
causes = make(map[projectKey]bool)
}
causes[other] = true
lastErr = duplicate
ledger.record(r.key, r.display, string(candidate.Version), duplicate.Error(), RejectionModules)
trace.rejected(r.display, string(candidate.Version), duplicate.Error())
logger.Debug("resolve: duplicate native module", "reason", duplicate)
continue
}
}
// A pure dependency demand binds to a selected package that
// answers every module identity of the candidate. The candidate
// installs only when that substitution leaves no settled graph.
if dependencyDemand && len(requirements) == 0 {
var providerKey projectKey
var ok bool
if r.key.environment == serverpkg.EnvironmentServer {
other := state.selectedRuntimeProject(target, r.key)
if other != r.key && coversModules(target, state.chosen[other], pkg, maps.Values(state.chosen)) {
providerKey, ok = other, true
}
}
if !ok && len(r.releaseHints) == 0 {
providerKey, ok = state.substitute(target, pkg)
}
if ok {
provider, _ := state.selection(providerKey)
branch := state.extend(
providerKey,
withDependents(provider, dependencyOf),
len(r.releaseHints) != 0,
)
logger.Debug(
"resolve: dependency answered by provider",
"provider", r.key.provider,
"project", r.key.project,
"answered-by", providerKey.project,
)
if outcome := descend(rest); outcome != branchFailed {
return outcome
}
state.restore(branch)
blockers = nil
explained = false
}
}
branches := []selectionBranch{
state.install(
r.key,
pkg,
conflictDependencies(candidate),
len(r.releaseHints) > 0,
),
}
branches = append(branches, state.supersede(target, r.key)...)
logger.Debug(
"resolve: candidate selected",
"provider", r.key.provider,
"project", r.key.project,
"candidate", candidate.Version,
"file", candidate.Filename,
"modules", len(modules),
)
trace.selected(r.display, string(candidate.Version))
next := rest
var learned []projectRequest
wasNonPrimary := nonPrimary[r.key]
if !candidate.PrimaryFile || wasNonPrimary {
nonPrimary[r.key] = !candidate.PrimaryFile
}
if replayEdges {
next = append(next, pinnedEdges[r.key]...)
learned = pinnedEdges[r.key]
} else if expandDependencies {
for _, dep := range candidate.Dependencies {
if dep.Kind == catalog.DependencyKindRequired || (withOptional && dep.Kind == catalog.DependencyKindOptional) {
var hints []releaseHint
if dep.ReleaseID != "" {
hints = append(hints, releaseHint{releaseID: dep.ReleaseID})
}
dependency := projectRequest{
key: projectKey{
r.key.environment,
r.key.ecosystem,
dep.Provider,
dep.ProjectID,
},
origin: originDependency,
releaseHints: hints,
}
if dep.Kind == catalog.DependencyKindRequired {
dependency.dependencyOf = catalog.Ref{
Provider: r.key.provider,
Name: catalog.Name(r.key.project),
}
}
if dep.Kind == catalog.DependencyKindOptional {
dependency.requirements = []document.RequirementBinding{
{
Reference: dep.Provider.String() + ":" + dep.ProjectID,
Selector: versionpkg.Stable,
Enabled: true,
},
}
}
next = append(next, dependency)
learned = append(learned, dependency)
}
}
}
prefetch.prefetchRequests(learned, previous, preferPins)
if outcome := descend(next); outcome != branchFailed {
return outcome
}
if wasNonPrimary {
nonPrimary[r.key] = true
} else {
delete(nonPrimary, r.key)
}
state.restoreAll(branches)
for _, key := range claims {
delete(native, key)
}
if blockers == nil {
explained = false
} else {
if !blockers[r.key] {
return branchFailed
}
delete(blockers, r.key)
if causes == nil {
causes = blockers
} else {
maps.Copy(causes, blockers)
}
blockers = nil
}
logger.Debug(
"resolve: backtracking candidate",
"provider", r.key.provider,
"project", r.key.project,
"candidate", candidate.Version,
"reason", "nested resolution failed",
)
ledger.record(
r.key,
r.display,
string(candidate.Version),
"a required dependency could not be resolved",
RejectionNested,
)
}
giveUp()
if !eligible && r.origin == originManifest {
return searchStopped
}
if explained && causes != nil {
blockers = causes
}
return branchFailed
}
search := func(allowBroken bool) searchOutcome {
state.reset()
attempts = 0
backtracks = 0
clear(native)
clear(nonPrimary)
blockers = nil
strict = !allowBroken
lastErr = nil
operational = false
ledger.reset()
return backtrack(requests)
}
finalFailure := func() error {
if err := ctx.Err(); err != nil {
return err
}
if operational {
var limit *SearchLimitError
if errors.As(lastErr, &limit) {
// The search stopped early, so keep the rejection ledger the
// command layer renders instead of the bare stop message.
summary := ledger.summary(target.Minecraft, limit)
if summary == nil {
summary = &Failure{Minecraft: target.Minecraft}
}
summary.Cause = limit
summary.Aborted = true
return summary
}
return lastErr
}
return resolutionFailure(ledger.summary(target.Minecraft, lastErr), lastErr)
}
// A stopped search cannot be relaxed: no candidate choice changes a
// cancelled context, an exhausted budget, or a missing catalogue answer.
outcome := search(false)
if outcome == branchFailed && usedPin {
logger.Debug("resolve: prior pins did not settle; considering catalogue alternatives", "reason", lastErr)
preferPins = false
// The retry needs every listing the lock pins made unnecessary.
prefetch.prefetchRequests(requests, previous, false)
outcome = search(false)
}
if outcome == branchFailed && acceptBroken {
logger.Debug(
"resolve: retrying with broken graphs",
"reason", lastErr,
)
outcome = search(true)
}
if outcome != graphSettled {
return nil, nil, finalFailure()
}
out := settled
for i := range out {
slices.SortFunc(out[i].DependencyOf, func(a, b catalog.Ref) int {
return cmp.Or(cmp.Compare(a.Provider, b.Provider), cmp.Compare(a.Name, b.Name))
})
}
var warnings []error
if acceptPackageConflicts {
warnings = append(warnings, packageConflictWarnings(out, state.conflicts)...)
}
if len(problems) > 0 {
if acceptBroken {
warnings = append(warnings, problemErrors(problems)...)
} else if acceptPackageConflicts {
// A requirement the server runtime answers is not something a
// package choice can change, so it stays fatal even when package
// conflicts are accepted.
if fatal := serverModuleProblems(problems); len(fatal) > 0 {
return nil, nil, errors.Join(problemErrors(fatal)...)
}
warnings = append(warnings, problemErrors(problems)...)
} else {
return nil, nil, errors.Join(problemErrors(problems)...)
}
}
warnings = append(warnings, provenanceWarnings(out, provenance, target, expandDependencies)...)
logger.Info(
"resolve: selected packages",
"packages", len(out),
)
return out, warnings, nil
}
// serverModuleProblems keeps the module problems the server runtime itself
// answers. Only that runtime can satisfy such a requirement, so these stay
// fatal when package conflicts are accepted.
func serverModuleProblems(problems []ModuleProblem) []ModuleProblem {
var fatal []ModuleProblem
for _, problem := range problems {
if problem.Server {
fatal = append(fatal, problem)
}
}
return fatal
}
func mergeArtifactSelections(packages []document.Package) []document.Package {
type key struct {
environment serverpkg.Environment
ecosystem catalog.Ecosystem
provider catalog.Provider
project, release, file string
}
index := map[key]int{}
out := make([]document.Package, 0, len(packages))
for _, p := range packages {
k := key{
p.Environment,
p.Ecosystem,
p.Provider,
p.ProjectID,
p.ReleaseID,
p.FileID,
}
if i, ok := index[k]; ok {
out[i].Requirements = append(out[i].Requirements, p.Requirements...)
out[i].Dependency = out[i].Dependency || p.Dependency
for _, source := range p.DependencyOf {
if !slices.Contains(out[i].DependencyOf, source) {
out[i].DependencyOf = append(out[i].DependencyOf, source)
}
}
continue
}
index[k] = len(out)
out = append(out, p)
}
return out
}
// sortPackages orders packages by their persisted identity so validation
// reports findings in a stable order.
func sortPackages(packages []document.Package) {
sort.Slice(packages, func(i, j int) bool {
a, b := &packages[i], &packages[j]
if n := strings.Compare(string(a.Environment), string(b.Environment)); n != 0 {
return n < 0
}
if n := strings.Compare(string(a.Ecosystem), string(b.Ecosystem)); n != 0 {
return n < 0
}
if n := strings.Compare(string(a.Provider), string(b.Provider)); n != 0 {
return n < 0
}
return strings.Compare(a.ProjectID, b.ProjectID) < 0
})
}
package resolve
import (
"cmp"
"iter"
"maps"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
versionpkg "github.com/mclucy/lucy/version"
)
// A runtime that loads several descriptor ecosystems resolves all their
// modules in one namespace. When a package of a preferred descriptor
// ecosystem answers every module identity of a package of a later one, such
// as Quilted Fabric API answering Fabric API on a Quilt server, the loader
// would see two native modules with one identity. The search therefore binds
// a pure dependency demand to the preferred package instead of installing
// both. Direct requirements and exact release demands are never substituted.
// substitute returns the selected package that can stand in for dependency.
// Among several, the first in key order wins.
func (s *selectionState) substitute(
target Target,
dependency document.Package,
) (projectKey, bool) {
if rank, ok := target.descriptorRank(dependency); !ok || rank == 0 {
return projectKey{}, false
}
for _, key := range s.keys() {
provider := s.chosen[key]
if provider.Artifact.Filename == "" {
continue
}
if providesFor(target, provider, dependency, maps.Values(s.chosen)) {
return key, true
}
}
return projectKey{}, false
}
// Upstream dependency edges name projects, not descriptor ecosystems. For
// example, a Quilt mod can depend on a Fabric project already loaded by Quilt.
// Direct manifest bindings keep their own ecosystem.
func (s *selectionState) selectedRuntimeProject(target Target, key projectKey) projectKey {
if p, found := s.chosen[key]; found && p.Filename != "" {
return key
}
runtime, ok := target.PackageRuntime()
if !ok {
return key
}
for _, ecosystem := range runtime.Loads() {
if ecosystem == key.ecosystem || target.moduleNamespace(ecosystem) != target.moduleNamespace(key.ecosystem) {
continue
}
other := key
other.ecosystem = ecosystem
if p, found := s.chosen[other]; found && p.Filename != "" {
return other
}
}
return key
}
// supersede removes every selected pure dependency package that the package at
// key stands in for, and moves their dependents onto it. It returns the
// branches that undo the change.
func (s *selectionState) supersede(
target Target,
key projectKey,
) []selectionBranch {
provider := s.chosen[key]
rank, ok := target.descriptorRank(provider)
runtime, _ := target.PackageRuntime()
if !ok || rank+1 == len(runtime.Loads()) {
return nil
}
var branches []selectionBranch
var dependents []catalog.Ref
for _, other := range s.keys() {
dependency := s.chosen[other]
if other == key ||
!dependency.Dependency ||
len(dependency.Requirements) > 0 ||
s.pinned[other] ||
dependency.Artifact.Filename == "" {
continue
}
if !providesFor(target, provider, dependency, maps.Values(s.chosen)) {
continue
}
branches = append(branches, s.remove(other))
dependents = append(dependents, dependency.DependencyOf...)
}
if len(branches) == 0 {
return nil
}
return append(
branches,
s.extend(key, withDependents(provider, dependents), false),
)
}
func (s *selectionState) keys() []projectKey {
keys := make([]projectKey, 0, len(s.chosen))
for key := range s.chosen {
keys = append(keys, key)
}
slices.SortFunc(keys, func(a, b projectKey) int {
return cmp.Or(
strings.Compare(string(a.environment), string(b.environment)),
strings.Compare(string(a.ecosystem), string(b.ecosystem)),
strings.Compare(string(a.provider), string(b.provider)),
strings.Compare(a.project, b.project),
)
})
return keys
}
// withDependents records dependents as packages that depend on p.
func withDependents(p document.Package, dependents []catalog.Ref) document.Package {
if len(dependents) == 0 {
return p
}
p.Dependency = true
p.DependencyOf = slices.Clone(p.DependencyOf)
for _, dependent := range dependents {
if !slices.Contains(p.DependencyOf, dependent) {
p.DependencyOf = append(p.DependencyOf, dependent)
}
}
return p
}
// providesFor reports whether provider can stand in for dependency on
// target. The provider must share the dependency's environment, come before
// it in the runtime's descriptor precedence, answer every module identity of
// the dependency, and expose versions that the constraints of the selected
// graph accept.
func providesFor(
target Target,
provider document.Package,
dependency document.Package,
selected iter.Seq[document.Package],
) bool {
if provider.Environment != dependency.Environment ||
samePackage(provider, dependency) {
return false
}
providerRank, ok := target.descriptorRank(provider)
if !ok {
return false
}
dependencyRank, ok := target.descriptorRank(dependency)
if !ok || providerRank >= dependencyRank {
return false
}
return coversModules(target, provider, dependency, selected)
}
func coversModules(
target Target,
provider, dependency document.Package,
selected iter.Seq[document.Package],
) bool {
provided := identityVersions(target, provider)
required := identityVersions(target, dependency)
if len(required) == 0 {
return false
}
for key := range required {
if _, ok := provided[key]; !ok {
return false
}
}
for p := range selected {
if samePackage(p, dependency) {
continue
}
if !acceptsVersions(target, p, provided) {
return false
}
}
return true
}
func samePackage(a, b document.Package) bool {
return a.Environment == b.Environment &&
a.Ecosystem == b.Ecosystem &&
a.Provider == b.Provider &&
a.ProjectID == b.ProjectID
}
// descriptorRank returns the position of a package's descriptor ecosystem in
// the precedence of the target runtime. Native modules decide it; a package
// without one is ranked by its bundled modules.
func (t Target) descriptorRank(p document.Package) (int, bool) {
runtime, ok := t.PackageRuntime()
if !ok {
return 0, false
}
loads := runtime.Loads()
rank := func(native bool) int {
best := len(loads)
for _, m := range p.Modules {
if native && m.NestedPath != "" {
continue
}
if i := slices.Index(loads, m.Ecosystem); i >= 0 && i < best {
best = i
}
}
return best
}
best := rank(true)
if best == len(loads) {
best = rank(false)
}
return best, best < len(loads)
}
// identityVersions maps every module identity of p, scoped like module
// resolution, to the version it exposes. The first declaration of an
// identity wins.
func identityVersions(
target Target,
p document.Package,
) map[moduleKey]versionpkg.Version {
versions := map[moduleKey]versionpkg.Version{}
for _, m := range p.Modules {
for _, name := range moduleIdentities(m) {
if name == "" {
continue
}
key := moduleKey{
p.Environment,
target.moduleNamespace(m.Ecosystem),
normalizeModuleID(m.Ecosystem, name),
}
if _, exists := versions[key]; !exists {
versions[key] = m.ProvidedVersion(name)
}
}
}
return versions
}
// acceptsVersions reports whether the plain version constraints that the
// modules of p place on provided identities accept the provided versions.
// Required and optional constraints must match, and a break must fail the
// match. Compound nodes are left to the final module check, which evaluates
// complete dependency trees.
func acceptsVersions(
target Target,
p document.Package,
provided map[moduleKey]versionpkg.Version,
) bool {
for _, m := range p.Modules {
for _, dep := range m.Dependencies {
if dep.Constraint == "" ||
len(dep.AnyOf) > 0 ||
len(dep.AllOf) > 0 ||
len(dep.Unless) > 0 {
continue
}
version, ok := provided[moduleKey{
p.Environment,
target.moduleNamespace(m.Ecosystem),
normalizeModuleID(m.Ecosystem, dep.ID),
}]
if !ok {
continue
}
matched, err := versionpkg.Match(dep.Constraint, version, m.VersionDialect)
if err != nil {
return false
}
switch dep.Kind {
case catalog.DependencyKindRequired, catalog.DependencyKindOptional:
if !matched {
return false
}
case catalog.DependencyKindIncompatible:
if matched {
return false
}
}
}
}
return true
}
package resolve
import (
"context"
"slices"
"sync"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/upstream"
)
// prefetchLimit bounds the candidate listings and artifact analyses that run
// beside the search. The search itself stays sequential, so this only decides
// how much upstream work may overlap.
const prefetchLimit = 8
// listingKey identifies one candidate listing. A listing answers the same
// builds whatever selectors a search applies, so it does not name them.
type listingKey struct {
registry catalog.Registry
project string
minecraft string
ecosystem catalog.Ecosystem
}
func listingKeyFor(key projectKey, minecraft string) listingKey {
return listingKey{
catalogueRegistry(key.provider),
key.project,
minecraft,
key.ecosystem,
}
}
// CandidateCache shares candidate listings across related searches. It only
// keeps listings that succeeded, because a failed listing may answer
// differently after a transient upstream error.
type CandidateCache struct {
mu sync.Mutex
entries map[listingKey][]upstream.Candidate
}
// NewCandidateCache constructs an empty listing cache.
func NewCandidateCache() *CandidateCache {
return &CandidateCache{
entries: make(map[listingKey][]upstream.Candidate),
}
}
func (c *CandidateCache) contains(key listingKey) bool {
if c == nil {
return false
}
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.entries[key]
return ok
}
func (c *CandidateCache) lookup(key listingKey) ([]upstream.Candidate, bool) {
if c == nil {
return nil, false
}
c.mu.Lock()
defer c.mu.Unlock()
list, ok := c.entries[key]
return slices.Clone(list), ok
}
func (c *CandidateCache) store(key listingKey, list []upstream.Candidate) {
if c == nil {
return
}
c.mu.Lock()
defer c.mu.Unlock()
c.entries[key] = slices.Clone(list)
}
// analysisResult is the outcome of one candidate analysis. A fatal error ends
// the enclosing branch; a descriptor error rejects only the candidate.
type analysisResult struct {
modules []catalog.DescriptorModule
hashes map[string]string
fatal error
descriptor error
}
type analysisFuture struct {
done chan struct{}
// started marks the owner that actually performs the read, so the search
// can take over a queued speculative read instead of waiting behind it.
started bool
result analysisResult
}
type listingFuture struct {
done chan struct{}
list []upstream.Candidate
err error
}
// prefetcher overlaps upstream work with the sequential search. It starts
// candidate listings and analyses in the background, and the search consumes
// them in its own deterministic order. Unused work is cancelled; an error of
// unused work is dropped, so attribution stays identical to a serial search.
type prefetcher struct {
ctx context.Context
cancel context.CancelFunc
source CandidateSource
materialize artifact.Materializer
cache *AnalysisCache
shared *CandidateCache
target Target
slots chan struct{}
mu sync.Mutex
listings map[listingKey]*listingFuture
analyses map[analysisKey]*analysisFuture
wg sync.WaitGroup
}
func newPrefetcher(
ctx context.Context,
request PackagesRequest,
cache *AnalysisCache,
shared *CandidateCache,
) *prefetcher {
ctx, cancel := context.WithCancel(ctx)
return &prefetcher{
ctx: ctx,
cancel: cancel,
source: request.Candidates,
materialize: request.Materialize,
cache: cache,
shared: shared,
target: request.Target,
slots: make(chan struct{}, prefetchLimit),
listings: make(map[listingKey]*listingFuture),
analyses: make(map[analysisKey]*analysisFuture),
}
}
func (p *prefetcher) close() {
p.cancel()
p.wg.Wait()
}
func (p *prefetcher) acquire() bool {
select {
case p.slots <- struct{}{}:
return true
case <-p.ctx.Done():
return false
}
}
func (p *prefetcher) release() {
<-p.slots
}
// prefetchRequests starts the listings and pinned analyses the search will
// need for requests it has just learned about. skipLocked reports requests a
// lock pin settles without listing alternatives.
func (p *prefetcher) prefetchRequests(
requests []projectRequest,
previous lockIndex,
pinsPreferred bool,
) {
for _, r := range requests {
if pinsPreferred {
prior := previous.byProject[r.key]
if pin, found, err := pinAccepts(prior, r); err == nil && found {
p.startAnalysis(pin, r.key.ecosystem)
continue
}
}
p.startListing(listingKeyFor(r.key, string(p.target.Minecraft)))
}
}
// startListing registers one listing before it starts, so the search can
// consume it whether it asks first or last.
func (p *prefetcher) startListing(key listingKey) {
if p.source == nil || p.shared.contains(key) {
return
}
p.mu.Lock()
if _, ok := p.listings[key]; ok {
p.mu.Unlock()
return
}
future := &listingFuture{done: make(chan struct{})}
p.listings[key] = future
p.mu.Unlock()
p.wg.Add(1)
go func() {
defer p.wg.Done()
if !p.acquire() {
future.err = p.ctx.Err()
close(future.done)
return
}
defer p.release()
list, err := p.source(
p.ctx,
key.registry,
key.project,
key.minecraft,
key.ecosystem,
)
future.list, future.err = list, err
if err == nil && len(list) > 0 {
p.shared.store(key, list)
// Register the analysis before the listing completes, so the
// search joins it instead of reading the artifact again.
p.startAnalysis(list[0], key.ecosystem)
}
close(future.done)
}()
}
// list returns the candidate listing for key, waiting for a speculative one
// when it is already running.
func (p *prefetcher) list(
ctx context.Context,
key projectKey,
) ([]upstream.Candidate, error) {
listing := listingKeyFor(key, string(p.target.Minecraft))
if list, ok := p.shared.lookup(listing); ok {
return list, nil
}
p.startListing(listing)
p.mu.Lock()
future := p.listings[listing]
p.mu.Unlock()
if future == nil {
// Another search published the listing between the two lookups.
if list, ok := p.shared.lookup(listing); ok {
return list, nil
}
return p.source(
ctx,
listing.registry,
listing.project,
listing.minecraft,
listing.ecosystem,
)
}
select {
case <-future.done:
case <-ctx.Done():
return nil, ctx.Err()
}
if future.err != nil {
return nil, future.err
}
return slices.Clone(future.list), nil
}
// startAnalysis registers one artifact analysis and runs it in the background.
// A cached entry needs no work, so a pinned candidate whose lock records its
// modules stays untouched.
func (p *prefetcher) startAnalysis(
candidate upstream.Candidate,
ecosystem catalog.Ecosystem,
) {
if p.materialize == nil || p.cache == nil {
return
}
loader := p.target.DescriptorLoader(ecosystem)
key := analysisKeyFor(candidate, loader, p.target.Minecraft)
if p.cache.has(key, candidate.Artifact.Hashes) {
return
}
p.mu.Lock()
if _, ok := p.analyses[key]; ok {
p.mu.Unlock()
return
}
future := &analysisFuture{done: make(chan struct{})}
p.analyses[key] = future
p.mu.Unlock()
p.wg.Add(1)
go func() {
defer p.wg.Done()
if !p.acquire() {
p.mu.Lock()
if !future.started {
future.started = true
future.result = analysisResult{fatal: p.ctx.Err()}
close(future.done)
}
p.mu.Unlock()
return
}
defer p.release()
p.mu.Lock()
if future.started {
// The search took the read over; it publishes the result.
p.mu.Unlock()
return
}
future.started = true
p.mu.Unlock()
result := p.analyzeSerial(p.ctx, candidate, loader, key)
p.mu.Lock()
future.result = result
close(future.done)
p.mu.Unlock()
}()
}
// analyze returns the analysis of one candidate. It joins a speculative read
// when one is running, and reads synchronously otherwise.
func (p *prefetcher) analyze(
ctx context.Context,
candidate upstream.Candidate,
ecosystem catalog.Ecosystem,
) analysisResult {
loader := p.target.DescriptorLoader(ecosystem)
key := analysisKeyFor(candidate, loader, p.target.Minecraft)
if entry, ok := p.cache.get(key, candidate.Artifact.Hashes); ok {
return analysisResult{modules: entry.modules, hashes: entry.hashes}
}
p.mu.Lock()
future := p.analyses[key]
if future != nil && !future.started {
// A queued speculative read has not started, so the search performs
// it now instead of waiting behind unrelated artifacts.
future.started = true
p.mu.Unlock()
result := p.analyzeSerial(ctx, candidate, loader, key)
p.mu.Lock()
future.result = result
close(future.done)
p.mu.Unlock()
return result
}
p.mu.Unlock()
if future == nil {
return p.analyzeSerial(ctx, candidate, loader, key)
}
select {
case <-future.done:
case <-ctx.Done():
return analysisResult{fatal: ctx.Err()}
}
result := future.result
if result.fatal == nil && result.descriptor == nil &&
!matchesAnalysisHashes(result.hashes, candidate.Artifact.Hashes) {
// The speculative read addressed bytes the caller did not ask for.
return p.analyzeSerial(ctx, candidate, loader, key)
}
return result
}
// analyzeSerial performs one candidate analysis: reuse verified bytes when the
// cache already holds them, otherwise materialize and read the descriptor.
func (p *prefetcher) analyzeSerial(
ctx context.Context,
candidate upstream.Candidate,
loader catalog.Ecosystem,
key analysisKey,
) analysisResult {
a := candidate.Artifact
if entry, ok := p.cache.get(key, a.Hashes); ok {
return analysisResult{modules: entry.modules, hashes: entry.hashes}
}
if err := ctx.Err(); err != nil {
return analysisResult{fatal: err}
}
materialized, err := p.materialize(ctx, &a)
if err != nil {
return analysisResult{fatal: err}
}
a.Hashes = materialized.Hashes
if entry, ok := p.cache.get(key, a.Hashes); ok {
return analysisResult{modules: entry.modules, hashes: entry.hashes}
}
modules, err := artifact.ReadModulesFor(
ctx,
materialized.Path,
loader,
string(p.target.Minecraft),
)
if err != nil {
return analysisResult{descriptor: err, hashes: a.Hashes}
}
p.cache.put(key, analysisEntry{modules: modules, hashes: a.Hashes})
return analysisResult{modules: modules, hashes: a.Hashes}
}
// pinAccepts reports whether the locked file answers the request without
// listing alternatives. The search and the prefetcher share this test, so the
// prefetcher never lists a project the search settles from the lock.
func pinAccepts(
prior *document.Package,
request projectRequest,
) (upstream.Candidate, bool, error) {
pin, found := lockedCandidate(prior)
if !found {
return upstream.Candidate{}, false, nil
}
decision, err := decideCandidate(pin, request)
if err != nil {
return upstream.Candidate{}, false, err
}
if !decision.eligible {
return upstream.Candidate{}, false, nil
}
if len(request.releaseHints) != 0 &&
request.releaseHints[0].releaseID != pin.ReleaseID {
return upstream.Candidate{}, false, nil
}
return pin, true, nil
}
package resolve
import (
"context"
"slices"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/log"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
type (
requestOrigin uint8
releaseHint struct {
releaseID string
}
projectKey struct {
environment serverpkg.Environment
ecosystem catalog.Ecosystem
provider catalog.Provider
project string
}
projectRequest struct {
key projectKey
display string
origin requestOrigin
requirements []document.RequirementBinding
dependencyOf catalog.Ref
// previousFileID is the file the lock selected for this project. A
// release may publish several files of one version, and only the
// primary one answers an unconstrained requirement, so the locked
// variant stays eligible.
previousFileID string
// releaseHints come from remote dependency metadata. They order
// candidates but do not by themselves reject another build.
releaseHints []releaseHint
}
)
const (
originManifest requestOrigin = iota
originDependency
)
func (o requestOrigin) String() string {
switch o {
case originManifest:
return "manifest"
case originDependency:
return "dependency"
default:
return "unknown"
}
}
// Target identifies the server runtime whose compatibility rules package
// resolution enforces.
type Target struct {
Product serverpkg.Product
Minecraft versionpkg.Version
CoreVersion versionpkg.Version
MCDRVersion string
// CoreModules are the descriptor modules the server core artifact ships.
// Fabric's loader bundles mods as nested jars, so these satisfy package
// requirements that no package provides.
CoreModules []catalog.DescriptorModule
}
// ModuleIdentity names one scoped module identity.
type ModuleIdentity struct {
Environment serverpkg.Environment
Namespace catalog.Ecosystem
ID string
}
// PackageRuntime returns the ecosystem whose loader loads server packages on
// target. Lucy resolves every Paper-family, Bukkit-family, or unlisted product
// as a Paperclip server, from a release API or a GitHub repository, so each of
// them runs Paper. The second result is false for a target that loads no
// server packages through Lucy.
func (t Target) PackageRuntime() (catalog.Ecosystem, bool) {
if t.Product == serverpkg.ProductUnknown {
return catalog.EcosystemUnspecified, false
}
if _, known := serverpkg.ParseProduct(t.Product.String()); !known {
return catalog.EcosystemPaper, true
}
switch ecosystem := t.Product.Ecosystem(); ecosystem {
case catalog.EcosystemFabric,
catalog.EcosystemQuilt,
catalog.EcosystemForge,
catalog.EcosystemNeoForge:
return ecosystem, true
case catalog.EcosystemPaper, catalog.EcosystemBukkit:
return catalog.EcosystemPaper, true
}
return catalog.EcosystemUnspecified, false
}
// SupportsPackages reports whether the target loads server packages from
// ecosystem.
func SupportsPackages(target Target, ecosystem catalog.Ecosystem) bool {
runtime, ok := target.PackageRuntime()
return ok && slices.Contains(runtime.Loads(), ecosystem)
}
// moduleNamespace returns the ecosystem that scopes module identities of
// descriptor ecosystem d on target.
func (t Target) moduleNamespace(d catalog.Ecosystem) catalog.Ecosystem {
runtime, _ := t.PackageRuntime()
return runtime.ModuleNamespace(d)
}
// ModuleNamespace returns the ecosystem that scopes module identities of
// descriptor ecosystem d on target.
func (t Target) ModuleNamespace(d catalog.Ecosystem) catalog.Ecosystem {
return t.moduleNamespace(d)
}
// DescriptorLoader returns the loader whose descriptor precedence reads an
// artifact of a package in ecosystem. A runtime that loads the ecosystem
// reads the artifact as its own loader would.
func (t Target) DescriptorLoader(ecosystem catalog.Ecosystem) catalog.Ecosystem {
if runtime, ok := t.PackageRuntime(); ok &&
slices.Contains(runtime.Loads(), ecosystem) {
return runtime
}
return ecosystem
}
// CandidateSource lists the published builds of one project. Callers inject
// the routing capability that serves their configured providers; resolution
// never selects a provider on its own.
type CandidateSource func(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
ecosystem catalog.Ecosystem,
) ([]upstream.Candidate, error)
// PackagesRequest describes one package resolution. Trace, Logger, and Context
// default to their zero values, which report nothing and never cancel. A
// resolution that needs candidates fails when Candidates is nil.
type PackagesRequest struct {
Context context.Context
Manifest *document.Manifest
Previous []document.Package
// PreviousTarget is the runtime Previous was resolved for. A zero value
// reuses no recorded analysis.
PreviousTarget Target
// PreserveLocked keeps the file recorded by Previous selectable when the
// catalogue no longer publishes it for the current labels. It applies only
// while the runtime target is unchanged.
PreserveLocked bool
// PreferLocked requires PreserveLocked. It tries compatible pins before
// listing alternatives unless WithOptional requires fresh dependency metadata.
PreferLocked bool
Target Target
// Candidates lists the builds a direct or dependency requirement may
// select. It is required for every non-empty resolution.
Candidates CandidateSource
// Materialize must leave its input unchanged and return verified local bytes.
Materialize artifact.Materializer
WithOptional bool
AcceptBroken bool
// AcceptPackageConflicts accepts a graph whose package metadata conflicts
// or whose package modules cannot satisfy each other, reporting them as
// warnings after the final selection. Requirements the server runtime
// itself answers stay fatal. It is separate from AcceptBroken, which
// relaxes every module check.
AcceptPackageConflicts bool
ExpandDependencies bool
// Cache shares artifact analysis across related searches. A nil cache
// limits reuse to this invocation.
Cache *AnalysisCache
// Listings shares candidate listings across related searches. A listing
// answers the same builds whatever selectors a search applies, so one
// command may reuse it for every resolution of the same project, runtime,
// and ecosystem. A nil Listings limits reuse to this invocation.
Listings *CandidateCache
// Logger records resolution diagnostics. A nil Logger records nothing.
Logger *log.Logger
Trace Trace
}
package resolve
// Trace receives facts about one resolution as they happen. Every field is
// optional: a nil field or a nil Trace reports nothing.
//
// Hooks run on the goroutine that searches, one call at a time. A caller that
// resolves concurrently must synchronize its own sink.
type Trace struct {
// State reports how many projects are chosen and how many requests remain.
State func(resolved, pending int)
// Selected reports the candidate that entered the graph.
Selected func(project, version string)
// Rejected reports a candidate that did not enter the graph. The reason is
// the same text the failure summary groups, without the package's name.
Rejected func(project, version, reason string)
}
func (t Trace) state(resolved, pending int) {
if t.State != nil {
t.State(resolved, pending)
}
}
func (t Trace) selected(project, version string) {
if t.Selected != nil {
t.Selected(project, version)
}
}
func (t Trace) rejected(project, version, reason string) {
if t.Rejected != nil {
t.Rejected(project, version, reason)
}
}
package server
import "fmt"
// BootstrapMethod identifies the algorithm that prepares a server tree from
// its locked core artifact and inputs. The values are persisted in
// lucy-lock.yaml.
type BootstrapMethod string
const (
// BootstrapMethodVanilla copies the core artifact as server.jar.
BootstrapMethodVanilla BootstrapMethod = "vanilla"
// BootstrapMethodPaperclip copies the core artifact and runs Paperclip in
// patch-only mode.
BootstrapMethodPaperclip BootstrapMethod = "paperclip"
// BootstrapMethodFabric places the loader in the library layout and
// generates launch files.
BootstrapMethodFabric BootstrapMethod = "fabric"
// BootstrapMethodQuilt places the Quilt loader in the library layout and
// generates the Quilt launcher JAR and its properties.
BootstrapMethodQuilt BootstrapMethod = "quilt"
// BootstrapMethodForge runs the processors of a pinned Forge or NeoForge
// installer profile. Both products share the installer profile format.
BootstrapMethodForge BootstrapMethod = "forge"
)
// Validate rejects a method that no build of Lucy implements.
func (m BootstrapMethod) Validate() error {
switch m {
case BootstrapMethodVanilla,
BootstrapMethodPaperclip,
BootstrapMethodFabric,
BootstrapMethodQuilt,
BootstrapMethodForge:
return nil
case "":
return fmt.Errorf("bootstrap method is required; resolve the server again")
default:
return fmt.Errorf("unsupported bootstrap method %q; resolve the server again", m)
}
}
package server
import (
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
)
// Product identifies the executable server product. It is the ground
// fact about what the server runs; an Ecosystem describes what it can serve.
type Product string
const (
ProductUnknown Product = ""
ProductMinecraft Product = "minecraft"
ProductFabric Product = "fabric"
ProductQuilt Product = "quilt"
ProductForge Product = "forge"
ProductNeoForge Product = "neoforge"
ProductMCDReforged Product = "mcdreforged"
ProductCraftBukkit Product = "craftbukkit"
ProductSpigot Product = "spigot"
ProductPaper Product = "paper"
ProductPurpur Product = "purpur"
ProductFolia Product = "folia"
ProductLeaves Product = "leaves"
ProductArclight Product = "arclight"
ProductArclightForge Product = "arclight-forge"
ProductArclightNeoForge Product = "arclight-neoforge"
ProductArclightFabric Product = "arclight-fabric"
ProductCatServer Product = "catserver"
ProductYouer Product = "youer"
ProductSpongeVanilla Product = "spongevanilla"
ProductSpongeForge Product = "spongeforge"
ProductSpongeNeo Product = "spongeneo"
ProductBungeeCord Product = "bungeecord"
ProductVelocity Product = "velocity"
ProductWaterfall Product = "waterfall"
)
func (p Product) String() string {
return string(p)
}
// Ecosystem returns the package ecosystem p natively serves, or
// catalog.EcosystemUnspecified when p serves none on its own.
func (p Product) Ecosystem() catalog.Ecosystem {
if definition, ok := productDefinitionOf(p); ok {
return definition.Ecosystem
}
return catalog.EcosystemUnspecified
}
// Title returns the presentation name of p.
func (p Product) Title() string {
if definition, ok := productDefinitionOf(p); ok {
return definition.Title
}
return "Unknown"
}
// LoaderComponent returns the runtime component name p reports as a mod
// loader, or an empty name when p is not a mod loader.
func (p Product) LoaderComponent() catalog.Name {
if definition, ok := productDefinitionOf(p); ok {
return definition.Loader.Component
}
return ""
}
// LoaderEcosystem returns the ecosystem of the mod loader that spelling
// names, or catalog.EcosystemUnspecified. Only loader component spellings
// match; product aliases such as "paper" do not.
func LoaderEcosystem(spelling string) catalog.Ecosystem {
name := catalog.Name(strings.ToLower(strings.TrimSpace(spelling)))
for _, definition := range productDefinitions {
if definition.Loader.recognizes(name) {
return definition.Ecosystem
}
}
return catalog.EcosystemUnspecified
}
// LoaderComponentName returns the component name that the mod loader of
// ecosystem reports for spelling. The second result reports whether spelling
// names that loader.
func LoaderComponentName(
ecosystem catalog.Ecosystem,
spelling string,
) (catalog.Name, bool) {
name := catalog.Name(strings.ToLower(strings.TrimSpace(spelling)))
for _, definition := range productDefinitions {
if definition.Ecosystem != ecosystem || !definition.Loader.recognizes(name) {
continue
}
return definition.Loader.Component, true
}
return "", false
}
func productDefinitionOf(p Product) (productDefinition, bool) {
for _, definition := range productDefinitions {
if definition.Product == p {
return definition, true
}
}
return productDefinition{}, false
}
type Match struct {
Product Product
Ecosystem catalog.Ecosystem
}
type productAlias struct {
Name catalog.Name
Ecosystem catalog.Ecosystem
}
// loaderDefinition names the runtime component a mod loader reports.
type loaderDefinition struct {
// Component is the component name the loader reports.
Component catalog.Name
// Spellings are the other accepted names of that component, such as the
// name without the hyphen.
Spellings []catalog.Name
}
func (l loaderDefinition) recognizes(name catalog.Name) bool {
if name == "" || l.Component == "" {
return false
}
return name == l.Component || slices.Contains(l.Spellings, name)
}
type productDefinition struct {
Product Product
Title string
// Ecosystem is the package ecosystem the product serves on its own.
Ecosystem catalog.Ecosystem
// Loader is set only on mod loader products.
Loader loaderDefinition
Aliases []productAlias
}
// productDefinitions maps accepted product spellings to canonical
// server products. Ecosystem disambiguates aliases such as Sponge's Forge
// variant. The table is also the single source of product titles and loader
// component names.
var productDefinitions = []productDefinition{
{
Product: ProductMinecraft,
Title: "Minecraft",
Ecosystem: catalog.EcosystemMinecraft,
Aliases: []productAlias{
{"minecraft", catalog.EcosystemUnspecified},
{"mc", catalog.EcosystemUnspecified},
{"vanilla", catalog.EcosystemUnspecified},
{"minecraft", catalog.EcosystemMinecraft},
{"mc", catalog.EcosystemMinecraft},
{"vanilla", catalog.EcosystemMinecraft},
},
},
{
Product: ProductFabric,
Title: "Fabric",
Ecosystem: catalog.EcosystemFabric,
Loader: loaderDefinition{
Component: "fabric-loader",
Spellings: []catalog.Name{"fabric", "fabricloader"},
},
Aliases: []productAlias{
{"fabric", catalog.EcosystemUnspecified},
{"fabric-loader", catalog.EcosystemUnspecified},
{"fabric", catalog.EcosystemFabric},
{"fabric-loader", catalog.EcosystemFabric},
},
},
{
Product: ProductQuilt,
Title: "Quilt",
Ecosystem: catalog.EcosystemQuilt,
Loader: loaderDefinition{
Component: "quilt-loader",
Spellings: []catalog.Name{"quilt", "quiltloader"},
},
Aliases: []productAlias{
{"quilt", catalog.EcosystemUnspecified},
{"quilt-loader", catalog.EcosystemUnspecified},
{"quilt", catalog.EcosystemQuilt},
{"quilt-loader", catalog.EcosystemQuilt},
},
},
{
Product: ProductForge,
Title: "Forge",
Ecosystem: catalog.EcosystemForge,
Loader: loaderDefinition{
Component: "forge",
},
Aliases: []productAlias{
{"forge", catalog.EcosystemUnspecified},
{"forge", catalog.EcosystemForge},
},
},
{
Product: ProductNeoForge,
Title: "NeoForge",
Ecosystem: catalog.EcosystemNeoForge,
Loader: loaderDefinition{
Component: "neoforge",
},
Aliases: []productAlias{
{"neoforge", catalog.EcosystemUnspecified},
{"neoforge", catalog.EcosystemNeoForge},
},
},
{
Product: ProductMCDReforged,
Title: "MCDReforged",
Ecosystem: catalog.EcosystemMCDR,
Aliases: []productAlias{
{"mcdreforged", catalog.EcosystemUnspecified},
{"mcdr", catalog.EcosystemUnspecified},
{"mcdreforged", catalog.EcosystemMCDR},
{"mcdr", catalog.EcosystemMCDR},
},
},
{
Product: ProductCraftBukkit,
Title: "CraftBukkit",
Ecosystem: catalog.EcosystemBukkit,
Aliases: []productAlias{
{"bukkit", catalog.EcosystemUnspecified},
{"craftbukkit", catalog.EcosystemUnspecified},
{"bukkit", catalog.EcosystemBukkit},
{"craftbukkit", catalog.EcosystemBukkit},
},
},
{
Product: ProductSpigot,
Title: "Spigot",
Ecosystem: catalog.EcosystemBukkit,
Aliases: []productAlias{
{"spigot", catalog.EcosystemUnspecified},
{"spigot", catalog.EcosystemBukkit},
},
},
{
Product: ProductPaper,
Title: "Paper",
Ecosystem: catalog.EcosystemPaper,
Aliases: []productAlias{
{"paper", catalog.EcosystemUnspecified},
{"paper", catalog.EcosystemPaper},
},
},
{
Product: ProductPurpur,
Title: "Purpur",
Ecosystem: catalog.EcosystemPaper,
Aliases: []productAlias{
{"purpur", catalog.EcosystemUnspecified},
{"purpur", catalog.EcosystemPaper},
},
},
{
Product: ProductFolia,
Title: "Folia",
Ecosystem: catalog.EcosystemPaper,
Aliases: []productAlias{
{"folia", catalog.EcosystemUnspecified},
{"folia", catalog.EcosystemPaper},
},
},
{
Product: ProductLeaves,
Title: "Leaves",
Ecosystem: catalog.EcosystemPaper,
Aliases: []productAlias{
{"leaves", catalog.EcosystemUnspecified},
{"leaves", catalog.EcosystemPaper},
},
},
{
Product: ProductArclight,
Title: "Arclight",
Aliases: []productAlias{{"arclight", catalog.EcosystemUnspecified}},
},
{
Product: ProductArclightForge,
Title: "Arclight Forge",
Aliases: []productAlias{{"arclight-forge", catalog.EcosystemUnspecified}},
},
{
Product: ProductArclightNeoForge,
Title: "Arclight NeoForge",
Aliases: []productAlias{
{
"arclight-neoforge",
catalog.EcosystemUnspecified,
},
},
},
{
Product: ProductArclightFabric,
Title: "Arclight Fabric",
Aliases: []productAlias{{"arclight-fabric", catalog.EcosystemUnspecified}},
},
{
Product: ProductCatServer,
Title: "CatServer",
Aliases: []productAlias{{"catserver", catalog.EcosystemUnspecified}},
},
{
Product: ProductYouer,
Title: "Youer",
Aliases: []productAlias{{"youer", catalog.EcosystemUnspecified}},
},
{
Product: ProductSpongeVanilla,
Title: "SpongeVanilla",
Ecosystem: catalog.EcosystemSponge,
Aliases: []productAlias{
{"sponge", catalog.EcosystemUnspecified},
{"spongevanilla", catalog.EcosystemUnspecified},
{"sponge", catalog.EcosystemSponge},
{"spongevanilla", catalog.EcosystemSponge},
{"vanilla", catalog.EcosystemSponge},
{"minecraft", catalog.EcosystemSponge},
{"mc", catalog.EcosystemSponge},
},
},
{
Product: ProductSpongeForge,
Title: "SpongeForge",
Ecosystem: catalog.EcosystemSponge,
Aliases: []productAlias{
{"spongeforge", catalog.EcosystemUnspecified},
{"spongeforge", catalog.EcosystemSponge},
{"forge", catalog.EcosystemSponge},
},
},
{
Product: ProductSpongeNeo,
Title: "SpongeNeo",
Ecosystem: catalog.EcosystemSponge,
Aliases: []productAlias{
{"spongeneo", catalog.EcosystemUnspecified},
{"spongeneo", catalog.EcosystemSponge},
{"neo", catalog.EcosystemSponge},
{"neoforge", catalog.EcosystemSponge},
},
},
{
Product: ProductBungeeCord,
Title: "BungeeCord",
Ecosystem: catalog.EcosystemBungeeCord,
Aliases: []productAlias{
{"bungeecord", catalog.EcosystemUnspecified},
{"bungeecord", catalog.EcosystemBungeeCord},
},
},
{
Product: ProductVelocity,
Title: "Velocity",
Ecosystem: catalog.EcosystemVelocity,
Aliases: []productAlias{
{"velocity", catalog.EcosystemUnspecified},
{"velocity", catalog.EcosystemVelocity},
},
},
{
Product: ProductWaterfall,
Title: "Waterfall",
Ecosystem: catalog.EcosystemBungeeCord,
Aliases: []productAlias{
{"waterfall", catalog.EcosystemUnspecified},
{"waterfall", catalog.EcosystemBungeeCord},
},
},
}
// NormalizeProduct resolves a request against the server product
// catalog. Provider is intentionally not considered.
func NormalizeProduct(request catalog.VersionedRef) (Match, bool) {
name := catalog.Name(strings.ToLower(request.Name.String()))
for _, definition := range productDefinitions {
for _, alias := range definition.Aliases {
if alias.Name == name && alias.Ecosystem == request.Ecosystem {
return Match{
Product: definition.Product,
Ecosystem: definition.Ecosystem,
}, true
}
}
}
return Match{}, false
}
// ParseProduct resolves a product spelling without an ecosystem
// qualifier. It is used for persisted server declarations.
func ParseProduct(name string) (Product, bool) {
match, ok := NormalizeProduct(catalog.VersionedRef{
Name: catalog.Name(strings.ToLower(strings.TrimSpace(name))),
})
return match.Product, ok
}
func IsProduct(request catalog.VersionedRef) bool {
_, ok := NormalizeProduct(request)
return ok
}
// Package serverregistry locates named workspaces through per-user registry
// entries that record canonical workspace paths.
package serverregistry
import (
"cmp"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"github.com/mclucy/lucy/document"
"github.com/mclucy/lucy/internal/appdata"
"github.com/mclucy/lucy/internal/fsutil"
)
const (
StateAvailable = "available"
StateLockOnly = "lock-only"
StateMissing = "missing"
StateUnreadable = "unreadable"
StateInvalid = "invalid"
)
// Entry describes a registered path and its current declaration. Unavailable
// entries remain registered.
type Entry struct {
Name string `json:"name"`
Path string `json:"path"`
State string `json:"state"`
Problem string `json:"problem,omitempty"`
}
type Registry struct {
directory string
}
// record is one registry entry file together with the workspace path it
// records. Target is empty when the entry file cannot be interpreted.
type record struct {
file string
target string
entry Entry
}
const registryLockName = "registry.lock"
const (
// entryTempPrefix names the staged file a registration publishes. List
// ignores it, so an abandoned stage is inert debris rather than an entry.
entryTempPrefix = ".tmp-"
// maxEntrySize bounds how much of an entry file List will read.
maxEntrySize = 64 << 10
)
// New locates durable per-user data without creating or changing the registry.
func New() (*Registry, error) {
root, err := appdata.Root()
if err != nil {
return nil, err
}
return &Registry{directory: filepath.Join(root, "servers")}, nil
}
// List checks every target on each call. It does not prune entries: a missing
// target can be an unmounted volume, and deletion could race registration. An
// entry that cannot be interpreted is reported as invalid, which makes
// collection refuse to run.
func (r *Registry) List() ([]Entry, error) {
records, err := r.records()
if err != nil {
return nil, err
}
entries := make([]Entry, 0, len(records))
for _, record := range records {
entries = append(entries, record.entry)
}
slices.SortFunc(entries, func(a, b Entry) int {
return cmp.Or(strings.Compare(a.Name, b.Name), strings.Compare(a.Path, b.Path))
})
return entries, nil
}
// records reads every registry entry without locking. Callers that must
// observe a stable set hold the registry lock while calling it.
func (r *Registry) records() ([]record, error) {
links, err := os.ReadDir(r.directory)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("read server registry: %w", err)
}
records := make([]record, 0, len(links))
for _, link := range links {
if link.Name() == registryLockName ||
strings.HasPrefix(link.Name(), entryTempPrefix) {
continue
}
file := filepath.Join(r.directory, link.Name())
target, err := readEntry(file)
if errors.Is(err, os.ErrNotExist) {
// A concurrent deinitialization removed this entry.
continue
}
if err != nil {
records = append(records, record{
file: file,
entry: Entry{
Path: file,
State: StateInvalid,
Problem: err.Error(),
},
})
continue
}
records = append(records, record{
file: file,
target: target,
entry: observe(target),
})
}
return records, nil
}
// Resolve requires exactly one available declaration with this name.
func (r *Registry) Resolve(name string) (Entry, error) {
name, err := document.NormalizeName(name)
if err != nil {
return Entry{}, err
}
entries, err := r.List()
if err != nil {
return Entry{}, err
}
var match Entry
count := 0
for _, entry := range entries {
if entry.State == StateAvailable && entry.Name == name {
match = entry
count++
}
}
switch count {
case 0:
return Entry{}, fmt.Errorf("no available registered server named %q; run `lucy server ls` to inspect registered paths", name)
case 1:
return match, nil
default:
var message strings.Builder
fmt.Fprintf(&message, "server name %q is ambiguous; matching directories:", name)
for _, entry := range entries {
if entry.State == StateAvailable && entry.Name == name {
fmt.Fprintf(&message, "\n %s", entry.Path)
}
}
message.WriteString("\nrun Lucy in the intended directory or give its manifest a unique name")
return Entry{}, errors.New(message.String())
}
}
// Register creates one entry per canonical workspace path for a workspace with
// a readable manifest. The caller must hold the workspace writer lock so
// deinitialization cannot remove a newer entry. Other available entries with
// the same name are returned for presentation.
func (r *Registry) Register(root string) ([]Entry, error) {
root, err := canonical(root)
if err != nil {
return nil, err
}
entry := observe(root)
if entry.State != StateAvailable {
return nil, fmt.Errorf("register server %s: %s", root, entry.Problem)
}
return r.registerEntry(root, entry)
}
// RegisterInstallation records a workspace whose installation completed. A
// workspace with a readable manifest is registered by name. A lock-only
// installation has no manifest name but still pins artifacts, so it is
// recorded as a lock-only entry that collection tracks and --server does not
// select. The caller must hold the workspace writer lock.
func (r *Registry) RegisterInstallation(root string) ([]Entry, error) {
root, err := canonical(root)
if err != nil {
return nil, err
}
entry := observe(root)
switch entry.State {
case StateAvailable, StateLockOnly:
default:
return nil, fmt.Errorf("register server %s: %s", root, entry.Problem)
}
return r.registerEntry(root, entry)
}
func (r *Registry) registerEntry(root string, entry Entry) ([]Entry, error) {
lock, err := r.lock()
if err != nil {
return nil, fmt.Errorf("lock server registry: %w", err)
}
defer func() { _ = lock.Close() }()
entryPath := filepath.Join(r.directory, pathKey(root))
target, err := readEntry(entryPath)
switch {
case err == nil:
if !samePath(target, root) {
return nil, fmt.Errorf("server registry entry %s does not point to %s", entryPath, root)
}
case errors.Is(err, os.ErrNotExist):
if err := writeEntry(entryPath, root); err != nil {
return nil, fmt.Errorf("register server directory entry: %w", err)
}
default:
return nil, fmt.Errorf("read server registry entry %s: %w", entryPath, err)
}
entries, err := r.List()
if err != nil {
return nil, err
}
if entry.Name == "" {
return nil, nil
}
duplicates := entries[:0]
for _, other := range entries {
if other.State == StateAvailable && other.Name == entry.Name && !samePath(other.Path, root) {
duplicates = append(duplicates, other)
}
}
return duplicates, nil
}
// Unregister removes only this path's entry, never the target directory. It
// must run while the caller still holds the workspace's original writer lock.
func (r *Registry) Unregister(root string) error {
root, err := canonical(root)
if err != nil {
return err
}
if _, err := os.Stat(r.directory); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return fmt.Errorf("inspect server registry: %w", err)
}
lock, err := r.lock()
if err != nil {
return fmt.Errorf("lock server registry: %w", err)
}
defer func() { _ = lock.Close() }()
entryPath := filepath.Join(r.directory, pathKey(root))
target, err := readEntry(entryPath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("read server registry entry: %w", err)
}
if !samePath(target, root) {
return fmt.Errorf("server registry entry %s does not point to %s", entryPath, root)
}
if err := os.Remove(entryPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("unregister server: %w", err)
}
return nil
}
// Forget removes the single registry entry whose recorded target is path. The
// target must be confirmed missing; a live, unreadable, or ambiguous target
// leaves the registry unchanged. The caller passes the path as List reports
// it, because canonicalizing a missing target cannot succeed. Forget holds the
// registry mutation lock and removes only the entry file, never the target or
// any other data.
func (r *Registry) Forget(path string) (Entry, error) {
if strings.TrimSpace(path) == "" {
return Entry{}, errors.New("forget server: path is empty")
}
target, err := filepath.Abs(path)
if err != nil {
return Entry{}, fmt.Errorf("resolve server directory: %w", err)
}
target = filepath.Clean(target)
if _, err := os.Stat(r.directory); errors.Is(err, os.ErrNotExist) {
return Entry{}, fmt.Errorf(
"no registered server at %s; run `lucy server ls` to inspect registered paths",
target,
)
} else if err != nil {
return Entry{}, fmt.Errorf("inspect server registry: %w", err)
}
lock, err := r.lock()
if err != nil {
return Entry{}, fmt.Errorf("lock server registry: %w", err)
}
defer func() { _ = lock.Close() }()
records, err := r.records()
if err != nil {
return Entry{}, err
}
matches := make([]record, 0, 1)
for _, record := range records {
if record.target != "" && samePath(filepath.Clean(record.target), target) {
matches = append(matches, record)
}
}
switch len(matches) {
case 0:
return Entry{}, fmt.Errorf(
"no registered server at %s; run `lucy server ls` to inspect registered paths",
target,
)
case 1:
default:
files := make([]string, 0, len(matches))
for _, match := range matches {
files = append(files, match.file)
}
return Entry{}, fmt.Errorf(
"server registry has %d entries for %s: %s",
len(matches), target, strings.Join(files, ", "),
)
}
match := matches[0]
if match.entry.State != StateMissing {
switch match.entry.State {
case StateAvailable, StateLockOnly:
return Entry{}, fmt.Errorf(
"registered server %s still exists; run `lucy deinit` in that directory to remove it",
target,
)
default:
return Entry{}, fmt.Errorf(
"cannot confirm registered server %s is missing (%s): %s",
target, match.entry.State, match.entry.Problem,
)
}
}
current, err := readEntry(match.file)
if errors.Is(err, os.ErrNotExist) {
return Entry{}, errors.New("server registry entry changed during forget; retry")
}
if err != nil {
return Entry{}, fmt.Errorf("read server registry entry: %w", err)
}
if !samePath(filepath.Clean(current), target) {
return Entry{}, errors.New("registered server changed during forget; retry")
}
if err := confirmMissing(target); err != nil {
return Entry{}, err
}
if err := os.Remove(match.file); err != nil {
if errors.Is(err, os.ErrNotExist) {
return Entry{}, errors.New("server registry entry changed during forget; retry")
}
return Entry{}, fmt.Errorf("forget server: %w", err)
}
return match.entry, nil
}
// confirmMissing requires the recorded path itself to be absent. Lstat is
// deliberate: a dangling symlink still occupies the path and is not the
// directory that registration recorded.
func confirmMissing(target string) error {
if _, err := os.Lstat(target); err == nil {
return fmt.Errorf(
"registered path %s exists and cannot be confirmed missing",
target,
)
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("cannot confirm registered path %s is missing: %w", target, err)
}
return nil
}
// Lock holds the registry mutation lock. Registration, unregistration, and
// forgetting use the same lock, so a caller can observe a stable registered
// set while it holds this lock. The lock file lives beside the entries and is
// skipped by List.
func (r *Registry) Lock() (*fsutil.FileLock, error) {
return r.lock()
}
func (r *Registry) lock() (*fsutil.FileLock, error) {
if err := fsutil.MkdirAllPrivate(r.directory); err != nil {
return nil, fmt.Errorf("create server registry: %w", err)
}
return fsutil.LockFile(filepath.Join(r.directory, registryLockName))
}
func observe(root string) Entry {
entry := Entry{Path: root, State: StateAvailable}
info, err := os.Stat(root)
if err != nil {
entry.State = StateUnreadable
if errors.Is(err, os.ErrNotExist) {
entry.State = StateMissing
}
entry.Problem = err.Error()
return entry
}
if !info.IsDir() {
entry.State = StateInvalid
entry.Problem = "registered target is not a directory"
return entry
}
manifest, err := document.ManifestFile(root).Read()
if err != nil {
if errors.Is(err, os.ErrNotExist) {
if _, lockErr := document.LockFile(root).Read(); lockErr == nil {
entry.State = StateLockOnly
return entry
} else if !errors.Is(lockErr, os.ErrNotExist) {
entry.State = StateUnreadable
entry.Problem = "read lockfile: " + lockErr.Error()
return entry
}
}
entry.State = StateInvalid
if _, pathError := errors.AsType[*os.PathError](err); pathError && !errors.Is(err, os.ErrNotExist) {
entry.State = StateUnreadable
}
entry.Problem = err.Error()
return entry
}
entry.Name = manifest.Name
return entry
}
func readEntry(path string) (string, error) {
info, err := os.Lstat(path)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", errors.New("registry entry is not a regular file")
}
if info.Size() > maxEntrySize {
return "", fmt.Errorf("registry entry exceeds %d bytes", maxEntrySize)
}
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
if !filepath.IsAbs(string(data)) {
return "", errors.New("registry entry does not contain an absolute path")
}
return string(data), nil
}
// writeEntry publishes a complete entry in one rename, so an unlocked List
// observes either the previous entry or the full target, never a partial file.
// An abandoned stage keeps the prefix List ignores.
func writeEntry(path, target string) (resultErr error) {
staged, err := os.CreateTemp(filepath.Dir(path), entryTempPrefix)
if err != nil {
return fmt.Errorf("stage server registry entry: %w", err)
}
stagedPath := staged.Name()
defer func() {
if resultErr != nil {
_ = os.Remove(stagedPath)
}
}()
if _, err := staged.WriteString(target); err != nil {
return errors.Join(err, staged.Close())
}
if err := staged.Sync(); err != nil {
return errors.Join(err, staged.Close())
}
if err := staged.Close(); err != nil {
return err
}
if err := os.Rename(stagedPath, path); err != nil {
return fmt.Errorf("publish server registry entry: %w", err)
}
return nil
}
func canonical(root string) (string, error) {
absolute, err := filepath.Abs(root)
if err != nil {
return "", fmt.Errorf("resolve server directory: %w", err)
}
resolved, err := filepath.EvalSymlinks(absolute)
if err != nil {
return "", fmt.Errorf("resolve server directory: %w", err)
}
return resolved, nil
}
func pathKey(root string) string {
if runtime.GOOS == "windows" {
root = strings.ToLower(root)
}
digest := sha256.Sum256([]byte(root))
return hex.EncodeToString(digest[:])
}
func samePath(a, b string) bool {
if runtime.GOOS == "windows" {
return strings.EqualFold(a, b)
}
return a == b
}
// Package pager displays long human documents in a scrollable terminal view.
package pager
import (
"fmt"
"io"
"os"
"strings"
"charm.land/bubbletea/v2"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
"github.com/mclucy/lucy/terminal/style"
)
// Mode selects when a document goes through the pager.
type Mode int
const (
// Auto pages documents that overflow the terminal.
Auto Mode = iota
// Always pages every non-empty document.
Always
// Never prints documents directly.
Never
)
// ParseMode reads the mode named by a flag value.
func ParseMode(raw string) (Mode, error) {
switch raw {
case "auto":
return Auto, nil
case "always":
return Always, nil
case "never":
return Never, nil
default:
return Auto, fmt.Errorf("want auto, always, or never, got %q", raw)
}
}
func (m Mode) String() string {
switch m {
case Always:
return "always"
case Never:
return "never"
default:
return "auto"
}
}
// Options describes one document and the streams that present it.
type Options struct {
Title string
Text string
Input io.Reader
Output io.Writer
// Render re-renders the document for a new terminal geometry. It must be
// side-effect-free and cheap enough to run during a resize. Text is the
// initial render; a nil Render only reflows the existing text.
Render func(width, height int) (string, error)
Terminal style.Terminal
Theme style.Theme
Mode Mode
}
// Show presents text in a pager when options allow it, and reports whether
// the pager handled the document. A false report leaves printing to the
// caller, which keeps pipes, redirected output, and tests byte-for-byte.
func Show(options Options) (bool, error) {
if !shouldPage(options) {
return false, nil
}
program := tea.NewProgram(
newModel(options),
tea.WithInput(options.Input),
tea.WithOutput(options.Output),
)
if _, err := program.Run(); err != nil {
return true, fmt.Errorf("run pager: %w", err)
}
return true, nil
}
func shouldPage(options Options) bool {
if !options.Terminal.IsTTY {
return false
}
if !isTerminal(options.Input) || !isTerminal(options.Output) {
return false
}
return needsPager(
options.Mode,
options.Text,
options.Terminal.Width,
options.Terminal.Height,
)
}
func needsPager(mode Mode, text string, width, terminalHeight int) bool {
if mode == Never || text == "" {
return false
}
if mode == Always {
return true
}
return textRows(text, width) > contentHeight(terminalHeight)
}
func isTerminal(stream any) bool {
file, ok := stream.(*os.File)
return ok && term.IsTerminal(file.Fd())
}
func textRows(text string, width int) int {
width = max(1, width)
rows := 0
for line := range strings.SplitSeq(text, "\n") {
rows += max(1, (ansi.StringWidth(line)+width-1)/width)
}
return rows
}
func contentHeight(terminalHeight int) int {
return max(1, terminalHeight-1)
}
package pager
import (
"strings"
"github.com/mclucy/lucy/terminal/style"
)
const (
sgrReset = "\x1b[0m"
sgrMatch = "\x1b[43;30m"
sgrSelected = "\x1b[45;37;1m"
sgrNoColorMatch = "\x1b[7m"
sgrNoColorSelected = "\x1b[1;7m"
)
// highlightMatches wraps every match in a visible style while preserving the
// document's existing styling. The selected match uses a stronger style so
// n and N have an anchor.
func highlightMatches(
text string,
matches []searchMatch,
selected int,
theme style.Theme,
) string {
if len(matches) == 0 {
return text
}
matchOn, selectedOn := highlightCodes(theme)
var output strings.Builder
matchIndex := 0
for lineIndex, line := range strings.Split(text, "\n") {
if lineIndex > 0 {
output.WriteByte('\n')
}
start := matchIndex
for matchIndex < len(matches) && matches[matchIndex].line == lineIndex {
matchIndex++
}
if start == matchIndex {
output.WriteString(line)
continue
}
output.WriteString(highlightLine(
line,
matches[start:matchIndex],
selected-start,
matchOn,
selectedOn,
))
}
return output.String()
}
// highlightCodes keeps attributes when color is off and uses distinct
// backgrounds for ordinary and selected matches when the theme allows color.
func highlightCodes(theme style.Theme) (match, selected string) {
if theme.Colors() {
return sgrMatch, sgrSelected
}
return sgrNoColorMatch, sgrNoColorSelected
}
// highlightLine inserts styles in one forward pass. It tracks active SGR
// sequences so the original styling resumes after each match.
func highlightLine(
line string,
matches []searchMatch,
selected int,
matchOn, selectedOn string,
) string {
var output strings.Builder
output.Grow(len(line) + len(matches)*8)
active := make([]string, 0, 4)
matchIndex := 0
visible := 0
inMatch := false
closeMatch := func() {
if !inMatch {
return
}
output.WriteString(sgrReset)
for _, sequence := range active {
output.WriteString(sequence)
}
inMatch = false
}
for i := 0; i < len(line); {
if line[i] == 0x1b {
end := ansiSequenceEnd(line, i)
sequence := line[i:end]
output.WriteString(sequence)
if isSGR(sequence) {
updateActiveSGR(&active, sequence)
if inMatch {
output.WriteString(highlightPrefix(matchIndex, selected, matchOn, selectedOn))
}
}
i = end
continue
}
for !inMatch && matchIndex < len(matches) && visible == matches[matchIndex].startByte {
output.WriteString(highlightPrefix(matchIndex, selected, matchOn, selectedOn))
inMatch = true
}
output.WriteByte(line[i])
visible++
i++
if inMatch && visible == matches[matchIndex].endByte {
closeMatch()
matchIndex++
}
}
closeMatch()
return output.String()
}
func highlightPrefix(matchIndex, selected int, matchOn, selectedOn string) string {
if matchIndex == selected {
return selectedOn
}
return matchOn
}
func updateActiveSGR(active *[]string, sequence string) {
params := sequence[2 : len(sequence)-1]
first, _, _ := strings.Cut(params, ";")
if first == "" || first == "0" {
*active = (*active)[:0]
}
*active = append(*active, sequence)
}
func isSGR(sequence string) bool {
return len(sequence) >= 3 &&
sequence[0] == 0x1b &&
sequence[1] == '[' &&
sequence[len(sequence)-1] == 'm'
}
// ansiSequenceEnd returns the end of the escape sequence starting at start.
func ansiSequenceEnd(s string, start int) int {
if start+1 >= len(s) {
return start + 1
}
switch s[start+1] {
case '[':
for i := start + 2; i < len(s); i++ {
if s[i] >= 0x40 && s[i] <= 0x7e {
return i + 1
}
}
return len(s)
case ']':
for i := start + 2; i < len(s); i++ {
if s[i] == 0x07 {
return i + 1
}
if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' {
return i + 2
}
}
return len(s)
default:
return start + 2
}
}
package pager
import (
"fmt"
"math"
"strings"
"charm.land/bubbles/v2/viewport"
"charm.land/bubbletea/v2"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/terminal/style"
)
// model owns one document's scroll position, search state, and footer.
type model struct {
viewport viewport.Model
title string
text string
render func(width, height int) (string, error)
theme style.Theme
width int
height int
search searchState
hint string
}
func newModel(options Options) *model {
width := max(1, options.Terminal.Width)
height := max(2, options.Terminal.Height)
m := &model{
title: options.Title,
text: options.Text,
render: options.Render,
theme: options.Theme,
width: width,
height: height,
}
m.viewport = viewport.New(
viewport.WithWidth(width),
viewport.WithHeight(contentHeight(height)),
)
m.viewport.SoftWrap = true
m.viewport.MouseWheelEnabled = false
m.viewport.SetContent(options.Text)
return m
}
func (m *model) Init() tea.Cmd { return nil }
func (m *model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
switch message := message.(type) {
case tea.WindowSizeMsg:
m.resize(message.Width, message.Height)
return m, nil
case tea.KeyPressMsg:
return m, m.handleKey(message)
case tea.PasteMsg:
if m.search.active {
m.search.paste(message.Content)
}
return m, nil
}
return m, nil
}
func (m *model) View() tea.View {
view := tea.NewView(m.viewport.View() + "\n" + m.footer())
view.AltScreen = true
return view
}
func (m *model) handleKey(key tea.KeyPressMsg) tea.Cmd {
if m.search.active {
m.hint = ""
return m.handleSearchKey(key)
}
if key.String() != "esc" {
m.hint = ""
}
switch key.String() {
case "q", "ctrl+c":
return tea.Quit
case "esc":
m.hint = "press q to quit"
return nil
case "g", "home":
m.viewport.GotoTop()
return nil
case "G", "end":
m.viewport.GotoBottom()
return nil
case "/":
m.search.begin()
return nil
case "n":
m.search.next(1)
m.refreshSearch()
return nil
case "N":
m.search.next(-1)
m.refreshSearch()
return nil
}
var command tea.Cmd
m.viewport, command = m.viewport.Update(key)
return command
}
func (m *model) handleSearchKey(key tea.KeyPressMsg) tea.Cmd {
switch key.String() {
case "esc", "ctrl+c":
m.search.cancel()
case "enter":
m.search.submit(&m.viewport, m.text, m.width)
m.refreshSearch()
case "backspace":
m.search.backspace()
case "ctrl+u":
m.search.query = ""
default:
m.search.typeText(key.Text)
}
return nil
}
// refreshSearch applies the committed matches to the viewport and reveals the
// selected match.
func (m *model) refreshSearch() {
m.viewport.SetContent(
highlightMatches(m.text, m.search.matches, m.search.index, m.theme),
)
if len(m.search.matches) > 0 {
showMatch(&m.viewport, m.search.matches[m.search.index])
}
}
func (m *model) resize(width, height int) {
oldPercent := 0.0
if total := m.viewport.TotalLineCount(); total > m.viewport.Height() {
oldPercent = float64(m.viewport.YOffset()) / float64(total-m.viewport.Height())
}
keepMatch := m.selectedMatchVisible()
m.width = max(1, width)
m.height = max(2, height)
m.viewport.SetWidth(m.width)
m.viewport.SetHeight(contentHeight(m.height))
m.reflow(oldPercent, keepMatch)
}
func (m *model) selectedMatchVisible() bool {
if len(m.search.matches) == 0 || m.search.index >= len(m.search.matches) {
return false
}
row := m.search.matches[m.search.index].row
return row >= m.viewport.YOffset() &&
row < m.viewport.YOffset()+m.viewport.Height()
}
// reflow rebuilds the document at the current geometry, then restores the
// selected search match when it was on screen or the previous scroll position.
func (m *model) reflow(oldPercent float64, keepMatch bool) {
if m.render != nil {
if text, err := m.render(m.width, m.height); err == nil {
m.text = text
m.search.recompute(m.text, m.width)
m.viewport.SetContent(
highlightMatches(m.text, m.search.matches, m.search.index, m.theme),
)
} else {
m.search.rewrap(m.text, m.width)
}
} else {
m.search.rewrap(m.text, m.width)
}
if keepMatch && len(m.search.matches) > 0 {
showMatch(&m.viewport, m.search.matches[m.search.index])
return
}
maxOffset := max(0, m.viewport.TotalLineCount()-m.viewport.Height())
m.viewport.SetYOffset(int(math.Round(oldPercent * float64(maxOffset))))
}
func (m *model) footer() string {
if m.search.active {
return fitStatus(
m.theme.Accent("/"+m.search.query+"\u258f"),
[]string{m.theme.Muted("enter search esc cancel")},
m.width,
)
}
if m.hint != "" {
return fitStatus(
m.theme.Accent(m.title),
[]string{m.theme.Warning(m.hint)},
m.width,
)
}
hints := "q quit / search j/k scroll"
if m.search.term != "" {
hints = m.search.label() + " n/N next/prev"
}
return fitStatus(
m.theme.Accent(m.title),
[]string{m.theme.Muted(hints), fmt.Sprintf("%3d%%", int(m.viewport.ScrollPercent()*100))},
m.width,
)
}
// fitStatus drops the least important right-hand piece first, keeping the
// title and position visible in narrow terminals.
func fitStatus(left string, right []string, width int) string {
for len(right) > 0 {
candidate := strings.Join(right, " ")
if ansi.StringWidth(left)+ansi.StringWidth(candidate)+1 <= width {
return fitLine(left, candidate, width)
}
right = right[1:]
}
if ansi.StringWidth(left) > width {
left = ansi.Truncate(left, width, "\u2026")
}
return left + strings.Repeat(" ", max(0, width-ansi.StringWidth(left)))
}
// fitLine places left and right on one width-limited line. The right side
// carries the live state, so the left label yields first when space runs out.
func fitLine(left, right string, width int) string {
leftWidth, rightWidth := ansi.StringWidth(left), ansi.StringWidth(right)
if leftWidth+rightWidth+1 > width {
left, leftWidth = "", 0
}
if leftWidth+rightWidth+1 > width {
right = ansi.Truncate(right, max(0, width-leftWidth-1), "\u2026")
rightWidth = ansi.StringWidth(right)
}
return left + strings.Repeat(" ", max(0, width-leftWidth-rightWidth)) + right
}
package pager
import (
"fmt"
"strings"
"unicode"
"charm.land/bubbles/v2/viewport"
"github.com/charmbracelet/x/ansi"
)
// searchState holds one pager's incremental search.
type searchState struct {
active bool
query string
term string
matches []searchMatch
index int
}
// searchMatch locates one occurrence by content line and display columns, and
// records the wrapped screen row at the width used for the search.
type searchMatch struct {
line int
column int
end int
startByte int
endByte int
row int
}
func (s *searchState) begin() {
s.active = true
s.query = s.term
}
func (s *searchState) cancel() {
s.active = false
}
func (s *searchState) typeText(text string) {
if text == "" {
return
}
s.query += text
}
// paste accepts one pasted line; an embedded newline marks a multi-line
// paste, which would not fit a single-line search prompt.
func (s *searchState) paste(text string) {
text = strings.TrimRight(text, "\r\n")
if text == "" || strings.ContainsAny(text, "\r\n") {
return
}
s.typeText(text)
}
func (s *searchState) backspace() {
runes := []rune(s.query)
if len(runes) == 0 {
return
}
s.query = string(runes[:len(runes)-1])
}
// submit scans the document and moves to the first match at or below the
// current top line. Matches stay available for n and N.
func (s *searchState) submit(target *viewport.Model, text string, width int) {
s.active = false
s.term = strings.TrimSpace(s.query)
s.index = 0
if s.term == "" {
s.matches = nil
return
}
s.find(s.term, text, width)
if len(s.matches) == 0 {
return
}
top := target.YOffset()
for i, match := range s.matches {
if match.row >= top {
s.index = i
break
}
}
}
// find replaces the match list for term at the given width.
func (s *searchState) find(term, text string, width int) {
s.matches = nil
caseSensitive := hasUpper(term)
lineNumber := 0
row := 0
for line := range strings.SplitSeq(text, "\n") {
for _, span := range matchSpans(line, term, caseSensitive) {
s.matches = append(s.matches, searchMatch{
line: lineNumber,
column: span.start,
end: span.end,
startByte: span.startByte,
endByte: span.endByte,
row: row + span.start/max(1, width),
})
}
row += wrappedRows(line, width)
lineNumber++
}
}
// recompute rebuilds matches after the document re-renders, keeping the
// selected match ordinal where possible.
func (s *searchState) recompute(text string, width int) {
if s.term == "" {
s.matches = nil
s.index = 0
return
}
selected := s.index
s.find(s.term, text, width)
if len(s.matches) == 0 {
s.index = 0
return
}
s.index = min(max(selected, 0), len(s.matches)-1)
}
func (s *searchState) next(step int) {
if len(s.matches) == 0 {
return
}
s.index = (s.index + step + len(s.matches)) % len(s.matches)
}
// matchSpan is one occurrence's display-column and visible-byte range.
type matchSpan struct {
start int
end int
startByte int
endByte int
}
// matchSpans returns every non-overlapping occurrence in one line, ignoring
// escape sequences in the visible text. Widths accumulate across disjoint
// segments so each line is measured once. Case-insensitive matches map back to
// original byte offsets, because lowercasing can change UTF-8 length.
func matchSpans(line, term string, caseSensitive bool) []matchSpan {
original := ansi.Strip(line)
haystack := original
needle := term
var loweredToOriginal []int
if !caseSensitive {
var lowered strings.Builder
lowered.Grow(len(original))
loweredToOriginal = make([]int, 0, len(original)+1)
for i, r := range original {
mapped := strings.ToLower(string(r))
for range len(mapped) {
loweredToOriginal = append(loweredToOriginal, i)
}
lowered.WriteString(mapped)
}
loweredToOriginal = append(loweredToOriginal, len(original))
haystack = lowered.String()
needle = strings.ToLower(needle)
}
if needle == "" {
return nil
}
var spans []matchSpan
lastByte, lastColumn := 0, 0
for offset := 0; offset < len(haystack); {
index := strings.Index(haystack[offset:], needle)
if index < 0 {
break
}
start := offset + index
end := start + len(needle)
startByte, endByte := start, end
if loweredToOriginal != nil {
startByte = loweredToOriginal[start]
endByte = loweredToOriginal[end]
}
lastColumn += ansi.StringWidth(original[lastByte:startByte])
startColumn := lastColumn
lastColumn += ansi.StringWidth(original[startByte:endByte])
spans = append(spans, matchSpan{
start: startColumn,
end: lastColumn,
startByte: startByte,
endByte: endByte,
})
lastByte = endByte
offset = end
}
return spans
}
// showMatch scrolls to the wrapped row that holds the match.
func showMatch(target *viewport.Model, match searchMatch) {
target.EnsureVisible(match.row, 0, 0)
}
// wrappedRows counts the screen rows one content line occupies.
func wrappedRows(line string, width int) int {
width = max(1, width)
return max(1, (ansi.StringWidth(line)+width-1)/width)
}
// rewrap updates stored rows after the terminal width changes.
func (s *searchState) rewrap(text string, width int) {
if len(s.matches) == 0 {
return
}
row := 0
lineNumber := 0
matchIndex := 0
for line := range strings.SplitSeq(text, "\n") {
for matchIndex < len(s.matches) && s.matches[matchIndex].line == lineNumber {
s.matches[matchIndex].row = row + s.matches[matchIndex].column/max(1, width)
matchIndex++
}
row += wrappedRows(line, width)
lineNumber++
}
}
func (s *searchState) label() string {
if len(s.matches) == 0 {
return fmt.Sprintf("/%s (no matches)", s.term)
}
return fmt.Sprintf("/%s (%d/%d)", s.term, s.index+1, len(s.matches))
}
func hasUpper(text string) bool {
return strings.ContainsFunc(text, unicode.IsUpper)
}
// Package progress presents command progress on stderr.
//
// A renderer is safe for concurrent use. Long phases announce themselves with
// PhaseStarted and PhaseDone, transient work with Status and Download, and
// permanent findings with Println, which keeps them above the animated area.
package progress
import (
"io"
"time"
"github.com/mclucy/lucy/terminal/style"
)
// Options carries the presentation state a renderer needs. The caller owns
// every value: a renderer never reads process streams or global styles.
type Options struct {
// Writer receives every permanent line and, when animated, the live area.
Writer io.Writer
Theme style.Theme
Terminal style.Terminal
// Interactive allows an animated area when Terminal is a terminal.
Interactive bool
}
// Renderer presents one command's progress.
type Renderer interface {
// PhaseStarted announces a long-running stage.
PhaseStarted(text string)
// PhaseDone ends the stage and prints text permanently. An empty text
// ends the stage silently, so a phase whose outcome has no prose does
// not leave a stale live area behind.
PhaseDone(text string, elapsed time.Duration)
// Status replaces the live status line. Non-interactive renderers print it
// at most once per heartbeat interval.
Status(text string)
// Download reports byte progress for the artifact being transferred.
Download(name string, read, total int64)
// DownloadDone clears the artifact progress.
DownloadDone()
// Println writes permanent lines above the live area.
Println(lines ...string)
// LogWriter returns a writer whose complete lines appear in the live area.
// A subprocess uses it to stream its output without owning the terminal.
LogWriter() io.Writer
// Close stops the renderer. It is safe to call more than once. An animated
// renderer emits a subprocess line still waiting for its newline before it
// stops.
Close()
}
// New returns the renderer that suits options: an animated area only when the
// caller allows interactivity and Writer is a terminal, append-only lines
// otherwise. A nil Writer yields Discard, which suits machine-readable
// commands that must keep stderr free of progress.
func New(options Options) Renderer {
if options.Writer == nil {
return Discard()
}
if options.Interactive && options.Terminal.IsTTY {
return newLive(options)
}
return newPlain(options.Writer, options.Theme)
}
// Discard drops every update. It suits machine-readable commands, which must
// keep stderr free of progress.
func Discard() Renderer { return discardRenderer{} }
type discardRenderer struct{}
func (discardRenderer) PhaseStarted(string) {}
func (discardRenderer) PhaseDone(string, time.Duration) {}
func (discardRenderer) Status(string) {}
func (discardRenderer) Download(string, int64, int64) {}
func (discardRenderer) DownloadDone() {}
func (discardRenderer) Println(...string) {}
func (discardRenderer) LogWriter() io.Writer { return io.Discard }
func (discardRenderer) Close() {}
package progress
import (
"fmt"
"time"
"github.com/mclucy/lucy/terminal/style"
)
// FormatElapsed renders a phase duration for people: 0.06s, 35.8s, 1m 02s.
func FormatElapsed(elapsed time.Duration) string {
switch {
case elapsed < time.Second:
return fmt.Sprintf("%.2fs", elapsed.Seconds())
case elapsed < time.Minute:
return fmt.Sprintf("%.1fs", elapsed.Seconds())
default:
minutes := int(elapsed / time.Minute)
seconds := int((elapsed % time.Minute) / time.Second)
return fmt.Sprintf("%dm %02ds", minutes, seconds)
}
}
func phaseLine(text string, elapsed time.Duration, theme style.Theme) string {
return theme.Success("✓") + " " + text + " " + theme.Muted("in "+FormatElapsed(elapsed))
}
// phaseStartLine announces a phase before it ends, so append-only output shows
// a long stage from its first second instead of only at completion.
func phaseStartLine(text string, theme style.Theme) string {
return theme.Note("›") + " " + theme.Accent(text)
}
package progress
import (
"io"
"strings"
"sync"
"time"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/terminal/style"
)
const (
liveTick = 100 * time.Millisecond
liveLogLines = 4
spinnerFrames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
)
var spinnerRunes = []rune(spinnerFrames)
type liveState struct {
phase string
status string
download string
read int64
total int64
logs []string
}
type liveSnapshot struct {
state liveState
frame int
}
// livePrint asks the model to emit a permanent line above the live area. The
// model closes done once the line is queued for rendering. snapshot is the
// state the line was queued with: the line and the redraw it precedes describe
// one instant, so an older snapshot can never redraw the finished phase below
// its completion.
type livePrint struct {
text string
snapshot liveSnapshot
done chan struct{}
}
// live renders one animated area on stderr. Updates are coalesced by a ticker
// so byte-level progress never floods the renderer.
type live struct {
out io.Writer
theme style.Theme
program *tea.Program
done chan struct{}
flushDone chan struct{}
stop chan struct{}
mu sync.Mutex
state liveState
frame int
dirty bool
closed bool
partial strings.Builder
}
func newLive(options Options) *live {
width := options.Terminal.Width
if width <= 0 {
width = style.DefaultTerminalWidth
}
l := &live{
out: options.Writer,
theme: options.Theme,
done: make(chan struct{}),
flushDone: make(chan struct{}),
stop: make(chan struct{}),
}
model := &liveModel{width: width, theme: options.Theme}
l.program = tea.NewProgram(
model,
tea.WithOutput(options.Writer),
tea.WithInput(nil),
tea.WithoutSignalHandler(),
)
go func() {
defer close(l.done)
_, _ = l.program.Run()
}()
go l.tick()
return l
}
func (l *live) tick() {
ticker := time.NewTicker(liveTick)
defer ticker.Stop()
for {
select {
case <-l.stop:
return
case <-ticker.C:
l.mu.Lock()
if l.closed || (!l.dirty && l.state.phase == "") {
l.mu.Unlock()
continue
}
l.dirty = false
l.frame++
// Send while the state lock is held. Program messages arrive in
// send order, so a snapshot captured for a phase that is ending
// cannot be queued after PhaseDone's completion line and redraw
// the finished phase below it. An active phase also animates when
// nothing else changed, which keeps long stages visibly alive.
l.program.Send(liveSnapshot{state: l.state, frame: l.frame})
l.mu.Unlock()
}
}
}
func (l *live) mutate(change func(*liveState)) {
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return
}
change(&l.state)
l.dirty = true
}
func (l *live) PhaseStarted(text string) {
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return
}
// A live area belongs to one phase. Subprocess lines and any unterminated
// tail from the previous phase must not reappear under the new one.
l.state = liveState{phase: text}
l.partial.Reset()
l.dirty = true
}
func (l *live) PhaseDone(text string, elapsed time.Duration) {
l.mu.Lock()
if !l.closed {
l.state = liveState{}
l.partial.Reset()
l.dirty = true
}
l.mu.Unlock()
if text == "" {
return
}
l.Println(phaseLine(text, elapsed, l.theme))
}
func (l *live) Status(text string) {
l.mutate(func(state *liveState) { state.status = text })
}
func (l *live) Download(name string, read, total int64) {
l.mutate(func(state *liveState) {
state.download = name
state.read = read
state.total = total
})
}
func (l *live) DownloadDone() {
l.mutate(func(state *liveState) {
state.download = ""
state.read = 0
state.total = 0
})
}
func (l *live) Println(lines ...string) {
if len(lines) == 0 {
return
}
text := strings.Join(lines, "\n")
l.mu.Lock()
if l.closed {
l.mu.Unlock()
// The caller that closed the renderer may still emit a trailing
// subprocess line. Wait for it before writing past the program.
<-l.flushDone
l.mu.Lock()
defer l.mu.Unlock()
_, _ = io.WriteString(l.out, text+"\n")
return
}
// The lock stays held until the model acknowledges the line, so Close
// cannot quit the program while a permanent line is still in flight.
defer l.mu.Unlock()
done := make(chan struct{})
snapshot := liveSnapshot{state: l.state, frame: l.frame}
// Send, unlike Program.Println, returns when the program has stopped, so a
// late line cannot block shutdown.
l.program.Send(livePrint{text: text, snapshot: snapshot, done: done})
select {
case <-done:
case <-l.done:
}
}
func (l *live) LogWriter() io.Writer { return logTail{l} }
func (l *live) appendLog(line string) {
l.mutate(func(state *liveState) {
state.logs = append(state.logs, line)
if len(state.logs) > liveLogLines {
state.logs = state.logs[len(state.logs)-liveLogLines:]
}
})
}
func (l *live) Close() {
l.mu.Lock()
if l.closed {
l.mu.Unlock()
// Another caller owns the final frame and the trailing line. Waiting
// for it keeps later output behind both.
<-l.flushDone
return
}
l.closed = true
partial := l.partial.String()
l.partial.Reset()
l.mu.Unlock()
close(l.stop)
l.program.Quit()
<-l.done
// The model learns log lines only from snapshots, so a trailing line
// without its newline terminator has no frame left to appear in. Emit it
// once as permanent output now that the program released the terminal.
if strings.TrimSpace(partial) != "" {
l.mu.Lock()
_, _ = io.WriteString(l.out, liveLogLine(l.theme, partial)+"\n")
l.mu.Unlock()
}
close(l.flushDone)
}
// liveLogLine formats one subprocess line the way the animated area shows it,
// so a line flushed at shutdown keeps the same shape.
func liveLogLine(theme style.Theme, line string) string {
return " " + theme.Muted("│ "+line)
}
type liveModel struct {
state liveState
frame int
width int
theme style.Theme
}
func (m *liveModel) Init() tea.Cmd { return nil }
func (m *liveModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case liveSnapshot:
m.state = msg.state
m.frame = msg.frame
case livePrint:
// Apply the state the line was queued with before emitting it. The
// model's previous view still holds the finished phase and its last
// subprocess lines; without this, bubbletea redraws them below the
// completion line.
m.state = msg.snapshot.state
m.frame = msg.snapshot.frame
return m, tea.Sequence(tea.Println(msg.text), func() tea.Msg {
close(msg.done)
return nil
})
case tea.WindowSizeMsg:
m.width = msg.Width
}
return m, nil
}
func (m *liveModel) View() tea.View {
width := m.width
if width <= 0 {
width = style.DefaultTerminalWidth
}
var lines []string
for _, line := range m.state.logs {
lines = append(lines, liveLogLine(m.theme, line))
}
if m.state.phase != "" {
frame := spinnerRunes[m.frame%len(spinnerRunes)]
head := m.theme.Note(string(frame)) + " " + m.theme.Accent(m.state.phase)
if m.state.status != "" {
available := width - lipgloss.Width(head) - 2
status := m.state.status
if available >= 0 && lipgloss.Width(status) > available {
status = ansi.Truncate(status, available, "…")
}
head += m.theme.Muted(": " + status)
}
lines = append(lines, clip(head, width))
}
if m.state.download != "" {
lines = append(lines, clip(m.downloadLine(width), width))
}
return tea.NewView(strings.Join(lines, "\n"))
}
func (m *liveModel) downloadLine(width int) string {
read := style.FormatBytesDecimal(m.state.read)
total := style.FormatBytesDecimal(m.state.total)
values := read + " / " + total
suffix := " " + m.theme.Muted(values)
prefix := " " + m.state.download + " "
barWidth := width - lipgloss.Width(prefix) - lipgloss.Width(values) - 2
if barWidth < 8 {
barWidth = 8
}
percent := 0.0
if m.state.total > 0 {
percent = float64(m.state.read) / float64(m.state.total)
if percent > 1 {
percent = 1
}
}
filled := int(percent * float64(barWidth))
bar := m.theme.Note(strings.Repeat("█", filled)) +
m.theme.Muted(strings.Repeat("░", barWidth-filled))
return prefix + bar + suffix
}
func clip(line string, width int) string {
if lipgloss.Width(line) <= width {
return line
}
return ansi.Truncate(line, width, "")
}
// logTail converts a subprocess's writes into whole lines for the live area.
type logTail struct{ renderer *live }
func (w logTail) Write(data []byte) (int, error) {
for _, line := range w.renderer.bufferLog(data) {
if strings.TrimSpace(line) != "" {
w.renderer.appendLog(line)
}
}
return len(data), nil
}
// bufferLog appends a subprocess chunk and returns the whole lines it
// completed. A closed renderer drops the chunk, as plain output does, so a
// late write cannot reach the terminal after the final frame.
func (l *live) bufferLog(data []byte) []string {
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return nil
}
l.partial.Write(data)
complete, remainder, found := strings.CutLast(l.partial.String(), "\n")
if !found {
return nil
}
lines := strings.Split(complete, "\n")
l.partial.Reset()
l.partial.WriteString(remainder)
return lines
}
package progress
import (
"io"
"strings"
"sync"
"time"
"github.com/mclucy/lucy/terminal/style"
)
const (
plainHeartbeat = 10 * time.Second
// plainStatusRepeat bounds how often an unchanged status line repeats.
// A long phase without counter updates still shows elapsed progress, but a
// silent minute does not flood an append-only log.
plainStatusRepeat = 30 * time.Second
)
// plain writes append-only lines. It suits pipes, logs, and CI, where a
// redrawn area would only add noise.
type plain struct {
out io.Writer
theme style.Theme
mu sync.Mutex
phase string
phaseStart time.Time
status string
lastStatus string
lastPrint time.Time
closed bool
stop chan struct{}
done chan struct{}
}
func newPlain(out io.Writer, theme style.Theme) *plain {
p := &plain{out: out, theme: theme, stop: make(chan struct{}), done: make(chan struct{})}
go p.heartbeat()
return p
}
func (p *plain) heartbeat() {
defer close(p.done)
ticker := time.NewTicker(plainHeartbeat)
defer ticker.Stop()
for {
select {
case <-p.stop:
return
case <-ticker.C:
p.mu.Lock()
if p.closed || p.phase == "" {
p.mu.Unlock()
continue
}
now := time.Now()
// A status that changed prints at the next heartbeat. An
// unchanged one repeats only after plainStatusRepeat, which
// still advances elapsed time for a silent phase.
if p.status == p.lastStatus && now.Sub(p.lastPrint) < plainStatusRepeat {
p.mu.Unlock()
continue
}
p.lastStatus = p.status
p.lastPrint = now
// The line is written while the state lock is held: PhaseDone
// clears the phase under the same lock and prints the completion
// under it, so a heartbeat can never land after its phase ended.
line := " " + p.phase + p.elapsedSuffix(now)
if p.status != "" {
line = " " + p.phase + ": " + p.status + p.elapsedSuffix(now)
}
p.writeLineLocked(line)
p.mu.Unlock()
}
}
}
func (p *plain) elapsedSuffix(now time.Time) string {
if p.phaseStart.IsZero() {
return ""
}
return p.theme.Muted(" (" + FormatElapsed(now.Sub(p.phaseStart)) + ")")
}
func (p *plain) PhaseStarted(text string) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
p.phase = text
p.phaseStart = time.Now()
p.status = ""
p.lastStatus = ""
p.lastPrint = p.phaseStart
if text != "" {
p.writeLineLocked(phaseStartLine(text, p.theme))
}
}
func (p *plain) PhaseDone(text string, elapsed time.Duration) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
p.phase = ""
p.phaseStart = time.Time{}
p.status = ""
p.lastStatus = ""
if text != "" {
p.writeLineLocked(phaseLine(text, elapsed, p.theme))
}
}
func (p *plain) Status(text string) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
p.status = text
}
func (p *plain) Download(string, int64, int64) {}
func (p *plain) DownloadDone() {}
func (p *plain) Println(lines ...string) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
for _, line := range lines {
p.writeLineLocked(line)
}
}
func (p *plain) LogWriter() io.Writer { return plainLogWriter{p} }
func (p *plain) Close() {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
p.closed = true
p.mu.Unlock()
close(p.stop)
<-p.done
}
func (p *plain) writeLineLocked(line string) {
if line == "" {
_, _ = io.WriteString(p.out, "\n")
return
}
_, _ = io.WriteString(p.out, line+"\n")
}
type plainLogWriter struct{ renderer *plain }
func (w plainLogWriter) Write(data []byte) (int, error) {
w.renderer.mu.Lock()
defer w.renderer.mu.Unlock()
if w.renderer.closed {
return io.Discard.Write(data)
}
for _, line := range strings.Split(strings.TrimRight(string(data), "\n"), "\n") {
_, _ = io.WriteString(w.renderer.out, w.renderer.theme.Muted(" │ "+line)+"\n")
}
return len(data), nil
}
// Package report presents warnings and errors on a caller-owned stream,
// independently of diagnostic logging.
package report
import (
"image/color"
"io"
"strings"
"charm.land/lipgloss/v2"
"charm.land/log/v2"
"github.com/mclucy/lucy/terminal/style"
)
// Reporter presents one invocation's notices on the stream it owns.
type Reporter struct {
logger *log.Logger
}
// New builds a reporter that writes level-prefixed notices to w. Machine
// modes pass io.Discard so no human notice joins their documents.
func New(w io.Writer, theme style.Theme) *Reporter {
logger := log.NewWithOptions(w, log.Options{Level: log.InfoLevel})
logger.SetStyles(levelStyles(theme.Colors()))
return &Reporter{logger: logger}
}
// Info presents a non-fatal observation.
func (r *Reporter) Info(message string) {
r.logger.Info(message)
}
// Warn presents a recoverable failure.
func (r *Reporter) Warn(err error) {
if err != nil {
r.logger.Warn(err.Error())
}
}
// Error presents a failure.
func (r *Reporter) Error(err error) {
if err != nil {
r.logger.Error(err.Error())
}
}
func levelStyles(colors bool) *log.Styles {
levelStyle := func(name string, foreground color.Color) lipgloss.Style {
level := lipgloss.NewStyle().
SetString(strings.ToUpper(name)).
Bold(true).
MaxWidth(5)
if colors {
level = level.Foreground(foreground)
}
return level
}
styles := log.DefaultStyles()
styles.Levels[log.InfoLevel] = levelStyle(log.InfoLevel.String(), lipgloss.Green)
styles.Levels[log.WarnLevel] = levelStyle(log.WarnLevel.String(), lipgloss.Yellow)
styles.Levels[log.ErrorLevel] = levelStyle(log.ErrorLevel.String(), lipgloss.Red)
styles.Levels[log.FatalLevel] = levelStyle(log.FatalLevel.String(), lipgloss.Red)
return styles
}
package report
import (
"fmt"
"io"
"github.com/mclucy/lucy/terminal/style"
)
// Detail is a multi-line failure that the command boundary chooses to render
// instead of the framework's single-line box. Cause preserves the chain.
type Detail struct {
Title string
Lines []string
Hint string
// Code is a stable machine-readable failure code. Human rendering ignores
// it; commands that emit JSON carry it into the error document.
Code string
Cause error
}
func (d *Detail) Error() string {
if d == nil {
return ""
}
return d.Title
}
func (d *Detail) Unwrap() error {
if d == nil {
return nil
}
return d.Cause
}
// RenderDetail writes one detail to w with the supplied theme. Every surface
// that reports failures uses it, so a failure reads the same wherever it
// appears.
func RenderDetail(w io.Writer, detail *Detail, theme style.Theme) {
if detail == nil {
return
}
_, _ = fmt.Fprintf(w, "%s %s\n", theme.Failure("error:"), detail.Title)
for _, line := range detail.Lines {
_, _ = fmt.Fprintf(w, " %s %s\n", theme.Muted("│"), line)
}
if detail.Hint != "" {
_, _ = fmt.Fprintf(w, " %s %s\n", theme.Note("hint:"), detail.Hint)
}
}
package style
import (
"io"
"os"
"sync"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/term"
)
// Conventional geometry when the stream cannot report its own size.
const (
DefaultTerminalWidth = 80
DefaultTerminalHeight = 24
)
// Terminal describes the capabilities of one output stream. Presentation that
// renders to a stream derives its geometry and terminal state from that
// stream alone, never from a package-level snapshot.
type Terminal struct {
Width int
Height int
IsTTY bool
Dark bool
background func() bool
}
// DetectTerminals detects geometry immediately and queries the background only
// when colored Markdown needs it. Streams on the same terminal share a query.
func DetectTerminals(input io.Reader, stdout, stderr io.Writer) (Terminal, Terminal) {
out := detectTerminal(input, stdout)
errOut := detectTerminal(input, stderr)
if out.background != nil && errOut.background != nil {
outFile := stdout.(*os.File)
errFile := stderr.(*os.File)
outInfo, outErr := outFile.Stat()
errInfo, errErr := errFile.Stat()
if outErr == nil && errErr == nil && os.SameFile(outInfo, errInfo) {
errOut.background = out.background
}
}
return out, errOut
}
func detectTerminal(input io.Reader, w io.Writer) Terminal {
detected := Terminal{
Width: DefaultTerminalWidth,
Height: DefaultTerminalHeight,
Dark: true,
}
file, ok := w.(*os.File)
if !ok || !term.IsTerminal(file.Fd()) {
return detected
}
detected.IsTTY = true
if width, height, err := term.GetSize(file.Fd()); err == nil {
if width > 0 {
detected.Width = width
}
if height > 0 {
detected.Height = height
}
}
if terminalInput, ok := input.(*os.File); ok && term.IsTerminal(terminalInput.Fd()) {
detected.background = sync.OnceValue(func() bool {
return lipgloss.HasDarkBackground(terminalInput, file)
})
}
return detected
}
package style
import (
"fmt"
"strings"
"time"
"charm.land/glamour/v2"
"charm.land/glamour/v2/ansi"
"charm.land/glamour/v2/styles"
"charm.land/lipgloss/v2"
"github.com/mclucy/lucy/internal/fn"
)
const CRLF = "\r\n"
// Markdown renders Markdown with the theme's color choice and the output
// stream's capabilities. A width of zero falls back to the terminal width.
func (t Theme) Markdown(md string, maxWidth int, terminal Terminal) string {
trimmed := strings.TrimSpace(md)
if trimmed == "" {
return ""
}
if maxWidth <= 0 {
maxWidth = terminal.Width
}
if maxWidth <= 0 {
maxWidth = DefaultTerminalWidth
}
options := []glamour.TermRendererOption{
glamour.WithWordWrap(maxWidth),
}
if t.colors {
dark := terminal.Dark
if terminal.background != nil {
dark = terminal.background()
}
if dark {
options = append(options, glamour.WithStandardStyle(styles.DarkStyle))
} else {
options = append(options, glamour.WithStandardStyle(styles.LightStyle))
}
} else {
options = append(options, glamour.WithStyles(noColorMarkdownStyle()))
}
renderer, err := glamour.NewTermRenderer(options...)
defer fn.CloseReader(renderer, func(err error) {})
if err != nil {
return trimmed
}
rendered, err := renderer.Render(trimmed)
if err != nil {
return trimmed
}
rendered = strings.TrimRight(rendered, "\n")
lines := strings.Split(rendered, "\n")
for i, line := range lines {
if lipgloss.Width(line) > maxWidth {
lines[i] = lipgloss.Wrap(line, maxWidth, "")
}
}
return strings.Join(lines, "\n")
}
// noColorMarkdownStyle renders Markdown without color while keeping emphasis
// as terminal attributes. The stock notty style falls back to literal
// `**bold**` and `*italic*` markers, which contradicts --no-color keeping
// text attributes.
func noColorMarkdownStyle() ansi.StyleConfig {
bold, italic, crossedOut := true, true, true
cfg := styles.NoTTYStyleConfig
cfg.Strong = ansi.StylePrimitive{Bold: &bold}
cfg.Emph = ansi.StylePrimitive{Italic: &italic}
cfg.Strikethrough = ansi.StylePrimitive{CrossedOut: &crossedOut}
return cfg
}
func Capitalize(v any) string {
s, ok := v.(string)
if !ok {
s = fmt.Sprintf("%v", v)
}
if len(s) == 0 {
return ""
}
return strings.ToUpper(s[:1]) + s[1:]
}
func FormatBytesBinary(bytes int64) string {
const (
kib = 1024
mib = kib * 1024
gib = mib * 1024
)
switch {
case bytes >= gib:
return fmt.Sprintf("%.1f GiB", float64(bytes)/float64(gib))
case bytes >= mib:
return fmt.Sprintf("%.1f MiB", float64(bytes)/float64(mib))
case bytes >= kib:
return fmt.Sprintf("%.1f KiB", float64(bytes)/float64(kib))
default:
return fmt.Sprintf("%d B", bytes)
}
}
func FormatBytesDecimal(bytes int64) string {
const (
kb = 1000
mb = kb * 1000
gb = mb * 1000
)
switch {
case bytes >= gb:
return fmt.Sprintf("%.1f GB", float64(bytes)/float64(gb))
case bytes >= mb:
return fmt.Sprintf("%.1f MB", float64(bytes)/float64(mb))
case bytes >= kb:
return fmt.Sprintf("%.1f KB", float64(bytes)/float64(kb))
default:
return fmt.Sprintf("%d B", bytes)
}
}
func FormatTTL(t time.Time) string {
remaining := time.Until(t)
if remaining <= 0 {
return "expired"
}
switch {
case remaining >= 24*time.Hour:
days := int(remaining.Hours() / 24)
return fmt.Sprintf("expires in %dd", days)
case remaining >= time.Hour:
return fmt.Sprintf("expires in %dh", int(remaining.Hours()))
default:
return fmt.Sprintf("expires in %dm", int(remaining.Minutes()))
}
}
package style
import (
"fmt"
"image/color"
"charm.land/lipgloss/v2"
)
// Theme is the immutable presentation style for one invocation. Construct it
// with New; every method returns rendered text and never mutates the theme.
// The zero value renders plain text without attributes.
type Theme struct {
colors bool
bold lipgloss.Style
dim lipgloss.Style
italic lipgloss.Style
underline lipgloss.Style
red lipgloss.Style
green lipgloss.Style
yellow lipgloss.Style
blue lipgloss.Style
magenta lipgloss.Style
cyan lipgloss.Style
key lipgloss.Style
}
// New builds a theme. When colors is false, foreground colors are dropped
// while text attributes such as bold, faint, italic, and underline survive,
// so --no-color output stays readable.
func New(colors bool) Theme {
colored := func(fg color.Color) lipgloss.Style {
base := lipgloss.NewStyle()
if !colors {
return base
}
return base.Foreground(fg)
}
return Theme{
colors: colors,
bold: lipgloss.NewStyle().Bold(true),
dim: lipgloss.NewStyle().Faint(true),
italic: lipgloss.NewStyle().Italic(true),
underline: lipgloss.NewStyle().Underline(true),
red: colored(lipgloss.Red),
green: colored(lipgloss.Green),
yellow: colored(lipgloss.Yellow),
blue: colored(lipgloss.Blue),
magenta: colored(lipgloss.Magenta),
cyan: colored(lipgloss.Cyan),
key: colored(lipgloss.Magenta).Bold(true),
}
}
// Colors reports whether the theme may carry ANSI foreground colors.
func (t Theme) Colors() bool { return t.colors }
func (t Theme) Bold(v any) string { return renderStyle(t.bold, v) }
func (t Theme) Dim(v any) string { return renderStyle(t.dim, v) }
func (t Theme) Italic(v any) string { return renderStyle(t.italic, v) }
func (t Theme) Underline(v any) string { return renderStyle(t.underline, v) }
func (t Theme) Red(v any) string { return renderStyle(t.red, v) }
func (t Theme) Green(v any) string { return renderStyle(t.green, v) }
func (t Theme) Yellow(v any) string { return renderStyle(t.yellow, v) }
func (t Theme) Blue(v any) string { return renderStyle(t.blue, v) }
func (t Theme) Magenta(v any) string { return renderStyle(t.magenta, v) }
func (t Theme) Cyan(v any) string { return renderStyle(t.cyan, v) }
// Semantic roles — use these instead of raw colors.
// Key styles KV field labels (bold magenta).
func (t Theme) Key(v any) string { return renderStyle(t.key, v) }
// Muted styles secondary information and annotations (faint).
func (t Theme) Muted(v any) string { return renderStyle(t.dim, v) }
// Accent styles emphasized names and highlights (bold).
func (t Theme) Accent(v any) string { return renderStyle(t.bold, v) }
// Success styles checkmarks and completion (green).
func (t Theme) Success(v any) string { return renderStyle(t.green, v) }
// Failure styles error indicators (red).
func (t Theme) Failure(v any) string { return renderStyle(t.red, v) }
// Warning styles warnings (yellow).
func (t Theme) Warning(v any) string { return renderStyle(t.yellow, v) }
// Link styles URLs (underline).
func (t Theme) Link(v any) string { return renderStyle(t.underline, v) }
// Note styles informational markers (cyan).
func (t Theme) Note(v any) string { return renderStyle(t.cyan, v) }
func renderStyle(s lipgloss.Style, v any) string {
switch v := v.(type) {
case rune:
return s.Render(string(v))
default:
return s.Render(fmt.Sprintf("%v", v))
}
}
// Package terminal renders human-facing status and fact views.
package terminal
import (
"strings"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/terminal/style"
)
// Fact is a human-facing label with a possibly multiline value.
type Fact struct {
Key string
Value string
}
// RenderFacts uses one label column for the entire document.
func RenderFacts(facts []Fact, width int, theme style.Theme) string {
return RenderFactGroups([][]Fact{facts}, width, theme)
}
// RenderFactGroups separates groups without shifting the shared label column.
func RenderFactGroups(groups [][]Fact, width int, theme style.Theme) string {
keyWidth := 0
for _, group := range groups {
for _, fact := range group {
keyWidth = max(keyWidth, ansi.StringWidth(fact.Key))
}
}
keyWidth = min(keyWidth, max(1, width/3))
valueWidth := max(1, width-keyWidth-2)
indent := strings.Repeat(" ", keyWidth+2)
var output strings.Builder
for _, group := range groups {
if len(group) == 0 {
continue
}
if output.Len() > 0 {
output.WriteByte('\n')
}
for _, fact := range group {
key := TruncateMiddle(fact.Key, keyWidth)
value := lipgloss.Wrap(fact.Value, valueWidth, "")
for i, line := range strings.Split(value, "\n") {
prefix := indent
if i == 0 {
prefix = theme.Key(key) + strings.Repeat(" ", keyWidth-ansi.StringWidth(key)+2)
}
if output.Len() > 0 {
output.WriteByte('\n')
}
output.WriteString(strings.TrimRight(prefix+line, " \t\r"))
}
}
}
return output.String()
}
package terminal
// StatusLayoutMode describes how the status view arranges the logo and info
// blocks within the available terminal width.
type StatusLayoutMode int
const (
// LayoutLargeLogoSideBySide places the large logo to the left of the
// info block with a gap between them.
LayoutLargeLogoSideBySide StatusLayoutMode = iota
// LayoutSmallLogoSideBySide places the small logo to the left of the
// info block with a gap between them.
LayoutSmallLogoSideBySide
// LayoutVertical stacks the logo above the info block.
LayoutVertical
// LayoutClipped renders only the info block, clipped to the terminal
// width. Used when the terminal is narrower than minInfoWidth.
LayoutClipped
// LayoutInfoOnly renders just the info block.
// Used in non-TTY (piped) contexts and when --logo=none.
LayoutInfoOnly
)
const (
// statusLayoutGapWidth is the number of blank columns between the logo
// and info blocks in side-by-side modes.
statusLayoutGapWidth = 3
// statusLayoutMinInfoWidth is the minimum number of columns the info
// block needs to be useful.
statusLayoutMinInfoWidth = 40
)
// StatusLayoutParams holds the result of layout negotiation: the chosen mode
// and the width budgets for each visual element.
type StatusLayoutParams struct {
Mode StatusLayoutMode
LogoWidth int
InfoWidth int
GapWidth int
}
func statusLayoutInfoOnly(termWidth int) StatusLayoutParams {
return StatusLayoutParams{
Mode: LayoutInfoOnly,
LogoWidth: 0,
InfoWidth: termWidth,
GapWidth: 0,
}
}
func statusLayoutSmallLogo(termWidth int, logoSmallWidth int) StatusLayoutParams {
if termWidth >= logoSmallWidth+statusLayoutGapWidth+statusLayoutMinInfoWidth {
return StatusLayoutParams{
Mode: LayoutSmallLogoSideBySide,
LogoWidth: logoSmallWidth,
InfoWidth: termWidth - logoSmallWidth - statusLayoutGapWidth,
GapWidth: statusLayoutGapWidth,
}
}
if termWidth >= statusLayoutMinInfoWidth {
return StatusLayoutParams{
Mode: LayoutVertical,
LogoWidth: logoSmallWidth,
InfoWidth: termWidth,
GapWidth: 0,
}
}
return StatusLayoutParams{
Mode: LayoutClipped,
LogoWidth: 0,
InfoWidth: termWidth,
GapWidth: 0,
}
}
func statusLayoutLargeLogo(termWidth int, logoLargeWidth int) StatusLayoutParams {
if termWidth >= logoLargeWidth+statusLayoutGapWidth+statusLayoutMinInfoWidth {
return StatusLayoutParams{
Mode: LayoutLargeLogoSideBySide,
LogoWidth: logoLargeWidth,
InfoWidth: termWidth - logoLargeWidth - statusLayoutGapWidth,
GapWidth: statusLayoutGapWidth,
}
}
if termWidth >= statusLayoutMinInfoWidth {
return StatusLayoutParams{
Mode: LayoutVertical,
LogoWidth: logoLargeWidth,
InfoWidth: termWidth,
GapWidth: 0,
}
}
return StatusLayoutParams{
Mode: LayoutClipped,
LogoWidth: 0,
InfoWidth: termWidth,
GapWidth: 0,
}
}
func statusLayoutAuto(
termWidth int,
logoLargeWidth int,
logoSmallWidth int,
) StatusLayoutParams {
if termWidth >= logoLargeWidth+statusLayoutGapWidth+statusLayoutMinInfoWidth {
return statusLayoutLargeLogo(termWidth, logoLargeWidth)
}
if termWidth >= logoSmallWidth+statusLayoutGapWidth+statusLayoutMinInfoWidth {
return statusLayoutSmallLogo(termWidth, logoSmallWidth)
}
return statusLayoutLargeLogo(termWidth, logoLargeWidth)
}
// NegotiateStatusLayout decides which layout mode to use given the terminal
// width, the widths of the two logo variants, TTY detection, and logo mode.
// It returns the mode together with column budgets so the status renderer can
// compose the view without further arithmetic.
func NegotiateStatusLayout(
termWidth int,
logoLargeWidth int,
logoSmallWidth int,
isTTY bool,
logoMode StatusLogoMode,
) StatusLayoutParams {
if logoMode == StatusLogoNone || !isTTY {
return statusLayoutInfoOnly(termWidth)
}
switch logoMode {
case StatusLogoLarge:
return statusLayoutLargeLogo(termWidth, logoLargeWidth)
case StatusLogoSmall:
return statusLayoutSmallLogo(termWidth, logoSmallWidth)
default:
return statusLayoutAuto(termWidth, logoLargeWidth, logoSmallWidth)
}
}
package terminal
import (
"embed"
"io/fs"
"regexp"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
// LogoVariant selects between the large and small logo variants.
type LogoVariant int
const (
// LogoLargePlain selects the full-size ASCII art logo.
LogoLargePlain LogoVariant = iota
// LogoSmallPlain selects the compact ASCII art logo.
LogoSmallPlain
LogoLargeColored
LogoSmallColored
)
// The logo assets are generated from assets/logos.yaml by tools/genlogo.
// Colored assets carry their own SGR escapes.
//
//go:embed assets/large_plain/*.txt assets/small_plain/*.txt assets/large_colored/*.txt assets/small_colored/*.txt
var logoAssets embed.FS
var embeddedLogoAssets = loadEmbeddedLogoAssets()
func loadEmbeddedLogoAssets() map[string]string {
assets := make(map[string]string)
err := fs.WalkDir(logoAssets, "assets", func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
data, err := fs.ReadFile(logoAssets, path)
if err != nil {
return err
}
assets[strings.TrimPrefix(path, "assets/")] = string(data)
return nil
})
if err != nil {
panic(err)
}
return assets
}
// GetLogo returns the logo for the server product, ecosystem, Minecraft
// version, and variant.
func GetLogo(
product server.Product,
ecosystem catalog.Ecosystem,
minecraftVersion version.Version,
variant LogoVariant,
) string {
name := logoAssetName(product, ecosystem, minecraftVersion)
if name == "" {
return ""
}
directory, ok := logoVariantDirectory(variant)
if !ok {
return ""
}
return embeddedLogoAssets[directory+"/"+name+".txt"]
}
func logoVariantDirectory(variant LogoVariant) (string, bool) {
switch variant {
case LogoLargePlain:
return "large_plain", true
case LogoSmallPlain:
return "small_plain", true
case LogoLargeColored:
return "large_colored", true
case LogoSmallColored:
return "small_colored", true
default:
return "", false
}
}
func logoAssetName(
product server.Product,
ecosystem catalog.Ecosystem,
minecraftVersion version.Version,
) string {
name := strings.ToLower(strings.TrimSpace(product.String()))
switch name {
case "minecraft", "vanilla":
if strings.Contains(strings.ToLower(minecraftVersion.String()), "snapshot") ||
snapshotVersionPattern.MatchString(minecraftVersion.String()) {
return "vanilla-snapshot"
}
return "vanilla"
case "paper":
return "papermc"
case "mcdreforged":
return "mcdr"
case "bukkit", "craftbukkit":
return "spigot"
case "spongevanilla", "spongeforge", "spongeneo":
return "sponge"
}
if embeddedLogoAssets["small_plain/"+name+".txt"] != "" {
return name
}
switch ecosystem {
case catalog.EcosystemFabric:
return "fabric"
case catalog.EcosystemForge:
return "forge"
case catalog.EcosystemNeoForge:
return "neoforge"
case catalog.EcosystemBukkit, catalog.EcosystemPaper:
return "spigot"
case catalog.EcosystemSponge:
return "sponge"
case catalog.EcosystemVelocity:
return "velocity"
case catalog.EcosystemMCDR:
return "mcdr"
default:
return ""
}
}
var snapshotVersionPattern = regexp.MustCompile(`^\d\dw\d+[a-z]$`)
package terminal
import "strings"
// StatusLogoMode selects how the status command shows the ASCII platform logo.
// The zero value leaves the mode unset for automatic layout selection.
type StatusLogoMode int
const (
statusLogoAuto StatusLogoMode = iota
// StatusLogoSmall selects the compact logo when layout allows.
StatusLogoSmall
// StatusLogoNone omits the logo.
StatusLogoNone
// StatusLogoLarge uses the full-size logo (side-by-side or stacked).
StatusLogoLarge
)
// ParseStatusLogoMode parses a --logo flag value (case-insensitive).
// Empty string means small (default).
func ParseStatusLogoMode(s string) (StatusLogoMode, bool) {
switch strings.ToLower(strings.TrimSpace(s)) {
case "", "small":
return StatusLogoSmall, true
case "none":
return StatusLogoNone, true
case "large":
return StatusLogoLarge, true
default:
return StatusLogoSmall, false
}
}
package terminal
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/x/ansi"
"github.com/mclucy/lucy/terminal/style"
)
func FoldHint(hidden int, theme style.Theme) string {
return theme.Muted(fmt.Sprintf("… %d more, use --long to expand", hidden))
}
func FoldLinesHint(hidden int, theme style.Theme) string {
return theme.Muted(fmt.Sprintf("… %d more lines, use --long to expand", hidden))
}
// CenterElide keeps both ends of prose and prefers complete paragraphs.
// The budget includes the omission marker; long output bypasses this function.
func CenterElide(text string, budget int, theme style.Theme) string {
lines := strings.Split(strings.TrimSpace(text), "\n")
if budget < 3 || len(lines) <= budget {
return text
}
head := (budget - 1 + 1) / 2
tail := len(lines) - (budget - 1 - head)
// Move cuts outward from the omitted range to the nearest paragraph edge.
// This never grows the visible output beyond its budget.
for head > 1 && strings.TrimSpace(ansi.Strip(lines[head])) != "" {
head--
}
for tail < len(lines)-1 && strings.TrimSpace(ansi.Strip(lines[tail-1])) != "" {
tail++
}
if head == 1 && tail == len(lines)-1 {
// A single paragraph has no internal boundary; retain readable ends.
head = budget / 2
tail = len(lines) - (budget - 1 - head)
}
for head > 0 && strings.TrimSpace(ansi.Strip(lines[head-1])) == "" {
head--
}
for tail < len(lines) && strings.TrimSpace(ansi.Strip(lines[tail])) == "" {
tail++
}
visible := append([]string{}, lines[:head]...)
visible = append(visible, FoldLinesHint(tail-head, theme))
visible = append(visible, lines[tail:]...)
return strings.Join(visible, "\n")
}
// TruncateMiddle preserves a path or reference's identifying suffix.
func TruncateMiddle(text string, width int) string {
length := ansi.StringWidth(text)
if width <= 0 {
return ""
}
if length <= width {
return text
}
if width == 1 {
return "…"
}
left := (width - 1) / 2
right := width - 1 - left
prefix := ansi.Cut(text, 0, left)
suffix := ansi.Cut(text, length-right, length)
prefixWidth, suffixWidth := ansi.StringWidth(prefix), ansi.StringWidth(suffix)
for prefixWidth+1+suffixWidth > width {
if left > 0 {
left--
prefix = ansi.Cut(text, 0, left)
prefixWidth = ansi.StringWidth(prefix)
} else {
right--
suffix = ansi.Cut(text, length-right, length)
suffixWidth = ansi.StringWidth(suffix)
}
}
return prefix + "…" + suffix
}
// DisplayPath uses workspace-relative paths, then the user's home shorthand.
func DisplayPath(root, path string) string {
if path == "" {
return ""
}
if !filepath.IsAbs(path) {
return filepath.ToSlash(filepath.Clean(path))
}
if relative, err := filepath.Rel(root, path); err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return filepath.ToSlash(relative)
}
if home, err := os.UserHomeDir(); err == nil {
if relative, err := filepath.Rel(home, path); err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
if relative == "." {
return "~"
}
return "~/" + filepath.ToSlash(relative)
}
}
return filepath.ToSlash(path)
}
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"flag"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"time"
)
func main() {
check := flag.Bool("check", false, "fail if generated docs.tar.gz differs from docs/ content")
outPath := flag.String("out", "docs/docs.tar.gz", "output path for compressed documentation archive")
docsDir := flag.String("docs", "docs", "path to documentation source directory")
flag.Parse()
archive, err := buildArchive(*docsDir)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] build docs archive: %v\n", err)
os.Exit(1)
}
if *check {
existing, err := os.ReadFile(*outPath)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] read %s: %v\n", *outPath, err)
os.Exit(1)
}
if !bytes.Equal(archive, existing) {
fmt.Fprintf(os.Stderr, "[ERROR] %s is out of date; run task docs:pack\n", *outPath)
os.Exit(1)
}
fmt.Printf("[OK] %s is up to date\n", *outPath)
return
}
if err := os.WriteFile(*outPath, archive, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] write %s: %v\n", *outPath, err)
os.Exit(1)
}
fmt.Printf("[OK] Wrote %s (%d bytes)\n", *outPath, len(archive))
}
func buildArchive(rootDir string) ([]byte, error) {
var filePaths []string
err := filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(path, ".mdx") || strings.HasSuffix(path, ".draft.mdx") {
return nil
}
rel, err := filepath.Rel(rootDir, path)
if err != nil {
return err
}
filePaths = append(filePaths, rel)
return nil
})
if err != nil {
return nil, err
}
slices.Sort(filePaths)
var buf bytes.Buffer
gw, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
if err != nil {
return nil, err
}
// Deterministic gzip header: clear modification time
gw.Header.ModTime = time.Time{}
gw.Header.OS = 255 // unknown OS for reproducibility
tw := tar.NewWriter(gw)
for _, rel := range filePaths {
data, err := os.ReadFile(filepath.Join(rootDir, rel))
if err != nil {
return nil, err
}
header := &tar.Header{
Name: filepath.ToSlash(rel),
Mode: 0o644,
Size: int64(len(data)),
ModTime: time.Unix(0, 0),
Typeflag: tar.TypeReg,
}
if err := tw.WriteHeader(header); err != nil {
return nil, err
}
if _, err := tw.Write(data); err != nil {
return nil, err
}
}
if err := tw.Close(); err != nil {
return nil, err
}
if err := gw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Command genlogo generates the status logos from the upstream images that
// the logo manifest pins. Every variant gets a plain and a colored text file
// per logo; both hold the same glyphs.
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"image"
"maps"
"os"
"path/filepath"
"slices"
"strings"
)
// defaultGlyphStyle draws filled shapes. Its letters give round corners and
// stems; letters that read as text instead of shape are left out.
const defaultGlyphStyle = "solid"
// glyphStyles maps a manifest glyph style to the glyphs that cells on shape
// edges choose from. The line style suits outline art, where letters along
// thin strokes read as noise.
var glyphStyles = map[string]string{
"solid": ` .,:;_-~=+*^"'` + "`" + `/\|()<>[]{}!?ilj7LTYyvxoadbpqg#@`,
"line": ` .,:;_-~^"'` + "`" + `/\|()<>[]{}!`,
}
// fillGlyphs fill uniform regions, picked by ink density.
const fillGlyphs = ".:-=+*#%@"
func main() {
defaultCache, _ := os.UserCacheDir()
manifestPath := flag.String("manifest", "terminal/assets/logos.yaml", "logo manifest")
outDir := flag.String("out", "terminal/assets", "directory that receives <variant>_plain/ and <variant>_colored/")
cacheDir := flag.String("cache", filepath.Join(defaultCache, "lucy-genlogo"), "download cache directory")
only := flag.String("only", "", "comma-separated logo ids to generate")
previewDir := flag.String("preview", "", "also write a PNG preview of each logo into this directory")
check := flag.Bool("check", false, "report generated files that differ from the files on disk, and write nothing")
flag.Parse()
m, err := loadManifest(*manifestPath)
if err != nil {
fatal("%v", err)
}
selected := map[string]bool{}
if *only != "" {
for id := range strings.SplitSeq(*only, ",") {
selected[strings.TrimSpace(id)] = true
}
}
gen, err := newGenerator(m, *cacheDir, *previewDir != "" && !*check)
if err != nil {
fatal("%v", err)
}
var files []outputFile
unknown := maps.Clone(selected)
for _, logo := range m.Logos {
if len(selected) > 0 && !selected[logo.ID] {
continue
}
delete(unknown, logo.ID)
result, err := gen.generate(logo)
if err != nil {
fatal("%s: %v", logo.ID, err)
}
files = append(files, result.files...)
if result.preview != nil && !*check {
if err := writePNG(filepath.Join(*previewDir, logo.ID+".png"), result.preview); err != nil {
fatal("%s: %v", logo.ID, err)
}
}
fmt.Printf("[OK] %s palette%s\n", logo.ID, result.palette)
}
for id := range unknown {
fatal("unknown logo id %q", id)
}
stale := []string{}
if *only == "" {
stale, err = staleFiles(*outDir, m)
if err != nil {
fatal("%v", err)
}
}
if *check {
if err := checkFiles(*outDir, files, stale); err != nil {
fatal("%v", err)
}
return
}
if err := writeFiles(*outDir, files, stale); err != nil {
fatal("%v", err)
}
}
// outputFile is one generated text file, relative to the output directory.
type outputFile struct {
path string
content string
}
type generator struct {
variants []variantSpec
cacheDir string
glyphs map[string]glyphSet
options renderOptions
preview *previewer
}
func newGenerator(m manifest, cacheDir string, withPreview bool) (generator, error) {
fontPath, err := fetchSource(m.Font, cacheDir)
if err != nil {
return generator{}, fmt.Errorf("font: %w", err)
}
f, err := loadCellFont(fontPath)
if err != nil {
return generator{}, err
}
face, err := cellFace(f, glyphCellWidth)
if err != nil {
return generator{}, err
}
gen := generator{
variants: m.Variants,
cacheDir: cacheDir,
glyphs: map[string]glyphSet{},
options: renderOptions{
uniformity: 0.2,
fill: newFillRamp(face, fillGlyphs),
},
}
windows := sampleWindows(3, 6, 0.5)
for style, glyphs := range glyphStyles {
gen.glyphs[style] = newGlyphSet(face, glyphs, windows)
}
if withPreview {
p, err := newPreviewer(f)
if err != nil {
return generator{}, err
}
gen.preview = &p
}
return gen, nil
}
// logoResult is the output of one logo. preview is nil unless the generator
// was built with previews. palette lists the palette colors with their
// tones, to help write a fixed palette into the manifest.
type logoResult struct {
files []outputFile
preview *image.NRGBA
palette string
}
// generate renders every variant of one logo.
func (gen generator) generate(logo logoSpec) (logoResult, error) {
path, err := fetchSource(logo.Source, gen.cacheDir)
if err != nil {
return logoResult{}, err
}
img, err := decodeImage(path, svgRasterSize)
if err != nil {
return logoResult{}, err
}
img, err = prepare(img, logo)
if err != nil {
return logoResult{}, err
}
pal, tones := logo.paletteAndTones(img)
if logo.Despeckle > 0 {
despeckle(img, pal, tones, logo.Despeckle)
}
planes := newInkPlanes(img, pal, tones)
if planes.bounds.Empty() {
return logoResult{}, errors.New("the source has no ink after preprocessing")
}
scale := 1
if logo.Pixel {
scale = detectPixelScale(img, planes.bounds)
if scale == 1 {
return logoResult{}, errors.New("pixel is set, but the source is not upscaled pixel art")
}
}
style := logo.Glyphs
if style == "" {
style = defaultGlyphStyle
}
result := logoResult{}
for i, c := range pal.colors {
result.palette += fmt.Sprintf(" %s:%.2f", hexColor(c), tones[i])
}
var rows []*image.NRGBA
for _, v := range gen.variants {
g, ok := grid{}, false
if scale > 1 {
g, ok = fitPixelGrid(planes.bounds, scale, v.Cols, v.Rows)
}
if !ok {
g = fitGrid(planes.bounds, v.Cols, v.Rows)
}
a := renderArt(planes, pal, g, gen.glyphs[style], gen.options)
result.files = append(result.files,
outputFile{path: filepath.Join(v.Name+"_plain", logo.ID+".txt"), content: plainText(a)},
outputFile{path: filepath.Join(v.Name+"_colored", logo.ID+".txt"), content: ansiText(a)},
)
if gen.preview != nil {
rows = append(rows, gen.preview.row(
[]*image.NRGBA{
gen.preview.render(a, previewDark, false),
gen.preview.render(a, previewDark, true),
gen.preview.render(a, previewLight, true),
},
[]string{fmt.Sprintf("%s %s %dx%d", logo.ID, v.Name, g.cols, g.rows)},
))
}
}
if gen.preview != nil {
result.preview = stack(rows)
}
return result, nil
}
// staleFiles lists text files in the variant directories that no logo in
// the manifest generates.
func staleFiles(outDir string, m manifest) ([]string, error) {
ids := map[string]bool{}
for _, logo := range m.Logos {
ids[logo.ID+".txt"] = true
}
var stale []string
for _, v := range m.Variants {
for _, dir := range []string{v.Name + "_plain", v.Name + "_colored"} {
entries, err := os.ReadDir(filepath.Join(outDir, dir))
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
for _, e := range entries {
if !e.IsDir() && filepath.Ext(e.Name()) == ".txt" && !ids[e.Name()] {
stale = append(stale, filepath.Join(dir, e.Name()))
}
}
}
}
slices.Sort(stale)
return stale, nil
}
func checkFiles(outDir string, files []outputFile, stale []string) error {
var problems []string
for _, f := range files {
current, err := os.ReadFile(filepath.Join(outDir, f.path))
if err != nil || !bytes.Equal(current, []byte(f.content)) {
problems = append(problems, "outdated: "+f.path)
}
}
for _, s := range stale {
problems = append(problems, "stale: "+s)
}
if len(problems) > 0 {
return fmt.Errorf("generated logos are out of date; run task logos:gen\n %s",
strings.Join(problems, "\n "))
}
return nil
}
func writeFiles(outDir string, files []outputFile, stale []string) error {
for _, f := range files {
path := filepath.Join(outDir, f.path)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, []byte(f.content), 0o644); err != nil {
return err
}
}
for _, s := range stale {
if err := os.Remove(filepath.Join(outDir, s)); err != nil {
return err
}
fmt.Printf("[DEL] %s\n", s)
}
return nil
}
func fatal(format string, args ...any) {
fmt.Fprintf(os.Stderr, "genlogo: "+format+"\n", args...)
os.Exit(1)
}
package main
import "image/color"
// art is a glyph grid in row-major order. Every row has cols cells.
type art struct {
cols, rows int
cells []artCell
}
// artCell is one terminal cell. A cell with tinted false uses the terminal's
// default foreground.
type artCell struct {
glyph byte
color color.NRGBA
tinted bool
}
func newArt(cols, rows int) art {
cells := make([]artCell, cols*rows)
for i := range cells {
cells[i].glyph = ' '
}
return art{cols: cols, rows: rows, cells: cells}
}
func (a art) at(col, row int) artCell {
return a.cells[row*a.cols+col]
}
func (a art) set(col, row int, c artCell) {
a.cells[row*a.cols+col] = c
}
package main
import (
"fmt"
"image/color"
"math"
"strconv"
"strings"
)
// oklab is a color in the OKLab perceptual space. Euclidean distance in it
// approximates perceived color difference.
type oklab struct {
l, a, b float64
}
func srgbToLinear(v uint8) float64 {
c := float64(v) / 255
if c <= 0.04045 {
return c / 12.92
}
return math.Pow((c+0.055)/1.055, 2.4)
}
func toOKLab(c color.NRGBA) oklab {
r, g, b := srgbToLinear(c.R), srgbToLinear(c.G), srgbToLinear(c.B)
l := math.Cbrt(0.4122214708*r + 0.5363325363*g + 0.0514459929*b)
m := math.Cbrt(0.2119034982*r + 0.6806995451*g + 0.1073969566*b)
s := math.Cbrt(0.0883024619*r + 0.2817188376*g + 0.6299787005*b)
return oklab{
l: 0.2104542553*l + 0.7936177850*m - 0.0040720468*s,
a: 1.9779984951*l - 2.4285922050*m + 0.4505937099*s,
b: 0.0259040371*l + 0.7827717662*m - 0.8086757660*s,
}
}
func (o oklab) distance2(p oklab) float64 {
dl, da, db := o.l-p.l, o.a-p.a, o.b-p.b
return dl*dl + da*da + db*db
}
func (o oklab) chroma() float64 {
return math.Hypot(o.a, o.b)
}
// parseHexColor accepts "#rrggbb" and "rrggbb".
func parseHexColor(s string) (color.NRGBA, error) {
hex := strings.TrimPrefix(s, "#")
if len(hex) != 6 {
return color.NRGBA{}, fmt.Errorf("color %q is not #rrggbb", s)
}
v, err := strconv.ParseUint(hex, 16, 32)
if err != nil {
return color.NRGBA{}, fmt.Errorf("color %q is not #rrggbb", s)
}
return color.NRGBA{R: uint8(v >> 16), G: uint8(v >> 8), B: uint8(v), A: 255}, nil
}
func linearToSRGB(v float64) uint8 {
v = min(max(v, 0), 1)
if v <= 0.0031308 {
v *= 12.92
} else {
v = 1.055*math.Pow(v, 1/2.4) - 0.055
}
return uint8(math.Round(v * 255))
}
// toSRGB clips colors outside the sRGB gamut per channel.
func (o oklab) toSRGB() color.NRGBA {
l := o.l + 0.3963377774*o.a + 0.2158037573*o.b
m := o.l - 0.1055613458*o.a - 0.0638541728*o.b
s := o.l - 0.0894841775*o.a - 1.2914855480*o.b
l, m, s = l*l*l, m*m*m, s*s*s
return color.NRGBA{
R: linearToSRGB(4.0767416621*l - 3.3077115913*m + 0.2309699292*s),
G: linearToSRGB(-1.2684380046*l + 2.6097574011*m - 0.3413193965*s),
B: linearToSRGB(-0.0041960863*l - 0.7034186147*m + 1.7076147010*s),
A: 255,
}
}
// Terminal themes can be dark or light, so logo colors must stay readable
// on both. Gray colors take the terminal foreground, which every theme makes
// readable. Other colors keep their hue with lightness held in a middle band.
const (
grayChroma = 0.02
terminalLightMin = 0.5
terminalLightMax = 0.8
)
// terminalColor returns the foreground to draw a palette color with, and
// false when the terminal default foreground fits better.
func terminalColor(c color.NRGBA) (color.NRGBA, bool) {
o := toOKLab(c)
if o.chroma() < grayChroma {
return color.NRGBA{}, false
}
o.l = min(max(o.l, terminalLightMin), terminalLightMax)
return o.toSRGB(), true
}
func hexColor(c color.NRGBA) string {
return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)
}
package main
import (
"fmt"
"image/color"
"strings"
)
// plainText renders the art without escape sequences. It keeps leading
// spaces, which position the glyphs, and drops trailing ones.
func plainText(a art) string {
var sb strings.Builder
for row := range a.rows {
end := rowEnd(a, row)
for col := range end {
sb.WriteByte(a.at(col, row).glyph)
}
sb.WriteByte('\n')
}
return sb.String()
}
// ansiText renders the art with 24-bit SGR foreground colors. It emits a
// color only where it changes and resets at the end of each row, so every
// line is self-contained.
func ansiText(a art) string {
var sb strings.Builder
for row := range a.rows {
end := rowEnd(a, row)
var current *color.NRGBA
tinted := false
for col := range end {
cell := a.at(col, row)
if cell.glyph == ' ' {
sb.WriteByte(' ')
continue
}
switch {
case cell.tinted && (current == nil || *current != cell.color):
fmt.Fprintf(&sb, "\x1b[38;2;%d;%d;%dm", cell.color.R, cell.color.G, cell.color.B)
c := cell.color
current = &c
tinted = true
case !cell.tinted && current != nil:
sb.WriteString("\x1b[39m")
current = nil
}
sb.WriteByte(cell.glyph)
}
if tinted {
sb.WriteString("\x1b[0m")
}
sb.WriteByte('\n')
}
return sb.String()
}
func rowEnd(a art, row int) int {
end := a.cols
for end > 0 && a.at(end-1, row).glyph == ' ' {
end--
}
return end
}
package main
import (
"fmt"
"os"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
// loadCellFont parses the monospace font that glyph shapes are measured with
// and previews are drawn with.
func loadCellFont(path string) (*opentype.Font, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
f, err := opentype.Parse(data)
if err != nil {
return nil, fmt.Errorf("parse font %s: %w", path, err)
}
return f, nil
}
// cellFace returns a face of the monospace font f whose glyph advance is
// cellWidth pixels.
func cellFace(f *opentype.Font, cellWidth int) (font.Face, error) {
const probeSize = 1000
probe, err := opentype.NewFace(f, &opentype.FaceOptions{Size: probeSize, DPI: 72})
if err != nil {
return nil, err
}
advance, ok := probe.GlyphAdvance('M')
if !ok || advance <= 0 {
return nil, fmt.Errorf("font has no advance for 'M'")
}
em := float64(advance) / 64 / probeSize
return opentype.NewFace(f, &opentype.FaceOptions{
Size: float64(cellWidth) / em,
DPI: 72,
Hinting: font.HintingNone,
})
}
// cellBaseline centers ascent and descent vertically in a cell, so that
// descenders and tall glyphs stay inside it.
func cellBaseline(face font.Face, cellHeight int) fixed.Int26_6 {
m := face.Metrics()
leading := fixed.I(cellHeight) - m.Ascent - m.Descent
return leading/2 + m.Ascent
}
package main
import (
"image"
"math"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
)
// glyphCellWidth is the raster width of one glyph cell. Cells are twice as
// tall as wide, which is the usual terminal cell shape.
const (
glyphCellWidth = 24
glyphCellHeight = 2 * glyphCellWidth
)
// sampleWindow is a rectangle in unit cell coordinates: (0,0) is the top left
// corner of the cell and (1,1) the bottom right.
type sampleWindow struct {
x0, y0, x1, y1 float64
}
// sampleWindows tiles the cell with cols×rows windows. Each window grows by
// overlap times its size on every side and is clipped to the cell. Overlap
// makes a feature respond to ink near its window, not only inside it.
func sampleWindows(cols, rows int, overlap float64) []sampleWindow {
windows := make([]sampleWindow, 0, cols*rows)
w, h := 1/float64(cols), 1/float64(rows)
for row := range rows {
for col := range cols {
x, y := float64(col)*w, float64(row)*h
windows = append(windows, sampleWindow{
x0: max(0, x-overlap*w),
y0: max(0, y-overlap*h),
x1: min(1, x+w+overlap*w),
y1: min(1, y+h+overlap*h),
})
}
}
return windows
}
// glyphSet holds the shape vector of each candidate glyph. Each vector
// component is the glyph's ink coverage in one sample window, divided by the
// largest coverage any glyph has in that window. A fully inked image region
// thus maps to the densest available glyph shape.
type glyphSet struct {
glyphs []byte
windows []sampleWindow
vectors [][]float64
}
func newGlyphSet(face font.Face, glyphs string, windows []sampleWindow) glyphSet {
baseline := cellBaseline(face, glyphCellHeight)
set := glyphSet{
glyphs: []byte(glyphs),
windows: windows,
vectors: make([][]float64, len(glyphs)),
}
scale := make([]float64, len(windows))
for i, g := range set.glyphs {
coverage := rasterizeGlyph(face, baseline, g)
v := make([]float64, len(windows))
for k, w := range windows {
v[k] = coverage.mean(
w.x0*glyphCellWidth, w.y0*glyphCellHeight,
w.x1*glyphCellWidth, w.y1*glyphCellHeight,
)
scale[k] = max(scale[k], v[k])
}
set.vectors[i] = v
}
for _, v := range set.vectors {
for k := range v {
if scale[k] > 0 {
v[k] /= scale[k]
}
}
}
return set
}
// fillRamp holds the glyphs that fill uniform regions, with their ink
// density relative to the densest of them.
type fillRamp struct {
glyphs []byte
density []float64
}
func newFillRamp(face font.Face, glyphs string) fillRamp {
baseline := cellBaseline(face, glyphCellHeight)
ramp := fillRamp{glyphs: []byte(glyphs), density: make([]float64, len(glyphs))}
densest := 0.0
for i, g := range ramp.glyphs {
coverage := rasterizeGlyph(face, baseline, g)
ramp.density[i] = coverage.mean(0, 0, glyphCellWidth, glyphCellHeight)
densest = max(densest, ramp.density[i])
}
for i := range ramp.density {
ramp.density[i] /= densest
}
return ramp
}
// pick returns the glyph whose relative density is nearest to tone, or a
// space when tone is nearer to no ink.
func (r fillRamp) pick(tone float64) byte {
best, bestDistance := byte(' '), tone
for i, d := range r.density {
if distance := math.Abs(d - tone); distance < bestDistance {
best, bestDistance = r.glyphs[i], distance
}
}
return best
}
func rasterizeGlyph(face font.Face, baseline fixed.Int26_6, g byte) plane {
mask := image.NewAlpha(image.Rect(0, 0, glyphCellWidth, glyphCellHeight))
d := font.Drawer{
Dst: mask,
Src: image.Opaque,
Face: face,
Dot: fixed.Point26_6{Y: baseline},
}
d.DrawString(string(g))
values := make([]float64, glyphCellWidth*glyphCellHeight)
for i, a := range mask.Pix {
values[i] = float64(a) / 255
}
return newPlane(glyphCellWidth, glyphCellHeight, values)
}
// match returns the index of the glyph whose shape vector is nearest to v.
// Ties resolve to the earlier glyph, so output is deterministic.
func (s glyphSet) match(v []float64) int {
best, bestDistance := 0, -1.0
for i, g := range s.vectors {
d := 0.0
for k, x := range v {
diff := x - g[k]
d += diff * diff
}
if bestDistance < 0 || d < bestDistance {
best, bestDistance = i, d
}
}
return best
}
package main
import (
"fmt"
"image"
"image/color"
"os"
"path/filepath"
"go.yaml.in/yaml/v4"
)
// manifest pins every input of the generated logos: the font that glyph
// shapes are measured with, the art sizes, and one upstream image per logo.
type manifest struct {
Font source `yaml:"font"`
Variants []variantSpec `yaml:"variants"`
Logos []logoSpec `yaml:"logos"`
}
// variantSpec is one art size. Art fills the box on its limiting axis.
type variantSpec struct {
Name string `yaml:"name"`
Cols int `yaml:"cols"`
Rows int `yaml:"rows"`
}
type logoSpec struct {
ID string `yaml:"id"`
Source source `yaml:"source"`
// Crop is x0, y0, x1, y1 in source pixels. For SVG, pixels of the
// raster at svgRasterSize.
Crop []int `yaml:"crop,omitempty"`
// Blur smooths the source with this radius in source pixels before the
// palette is taken. It turns fine texture into the shading of larger
// faces, which reads better at terminal size.
Blur int `yaml:"blur,omitempty"`
// Knockout clears the background that touches the image border. The
// value is the largest OKLab step between neighbor pixels that still
// belongs to the background, so gradients clear too.
Knockout float64 `yaml:"knockout,omitempty"`
// Pixel marks upscaled pixel art. Cells then align to art pixels.
Pixel bool `yaml:"pixel,omitempty"`
// Flat gives every color full ink. The plain art is then a silhouette,
// and only color tells regions apart. This suits gradients, which
// otherwise turn into a noisy mix of fill glyphs.
Flat bool `yaml:"flat,omitempty"`
// Glyphs names the glyph style of shape edges: solid (the default) or
// line.
Glyphs string `yaml:"glyphs,omitempty"`
// Despeckle clears ink islands smaller than this share of all ink, such
// as lettering around a badge.
Despeckle float64 `yaml:"despeckle,omitempty"`
// Colors is the k-means palette size when Palette is empty.
Colors int `yaml:"colors,omitempty"`
Palette []paletteSpec `yaml:"palette,omitempty"`
}
// paletteSpec fixes one palette color. Tone is its ink density from 0 to 1;
// 0 makes the color background. Without a tone, density follows lightness.
type paletteSpec struct {
Color string `yaml:"color"`
Tone *float64 `yaml:"tone,omitempty"`
}
const defaultPaletteColors = 4
func loadManifest(path string) (manifest, error) {
data, err := os.ReadFile(path)
if err != nil {
return manifest{}, err
}
var m manifest
if err := yaml.Unmarshal(data, &m); err != nil {
return manifest{}, fmt.Errorf("parse %s: %w", path, err)
}
if err := m.validate(); err != nil {
return manifest{}, fmt.Errorf("%s: %w", path, err)
}
return m, nil
}
func (m manifest) validate() error {
if len(m.Variants) == 0 {
return fmt.Errorf("no variants")
}
for _, v := range m.Variants {
if !filepath.IsLocal(v.Name) || v.Cols <= 0 || v.Rows <= 0 {
return fmt.Errorf("variant %q: need a plain name and positive cols and rows", v.Name)
}
}
seen := map[string]bool{}
for _, logo := range m.Logos {
if !filepath.IsLocal(logo.ID) || filepath.Base(logo.ID) != logo.ID {
return fmt.Errorf("logo %q: id must be a plain file name", logo.ID)
}
if seen[logo.ID] {
return fmt.Errorf("logo %q: duplicate id", logo.ID)
}
seen[logo.ID] = true
if logo.Crop != nil &&
(len(logo.Crop) != 4 || logo.Crop[0] >= logo.Crop[2] || logo.Crop[1] >= logo.Crop[3]) {
return fmt.Errorf("logo %q: crop must be [x0, y0, x1, y1] with x0 < x1 and y0 < y1", logo.ID)
}
if logo.Colors < 0 || logo.Knockout < 0 || logo.Blur < 0 {
return fmt.Errorf("logo %q: colors, knockout, and blur must not be negative", logo.ID)
}
if logo.Despeckle < 0 || logo.Despeckle >= 1 {
return fmt.Errorf("logo %q: despeckle must be at least 0 and below 1", logo.ID)
}
if _, ok := glyphStyles[logo.Glyphs]; logo.Glyphs != "" && !ok {
return fmt.Errorf("logo %q: unknown glyph style %q", logo.ID, logo.Glyphs)
}
for _, p := range logo.Palette {
if _, err := parseHexColor(p.Color); err != nil {
return fmt.Errorf("logo %q: %w", logo.ID, err)
}
if p.Tone != nil && (*p.Tone < 0 || *p.Tone > 1) {
return fmt.Errorf("logo %q: tone of %s must be within 0 and 1", logo.ID, p.Color)
}
}
}
return nil
}
// paletteAndTones returns the fixed palette of the logo when it has one, and
// otherwise the k-means palette of img, with the ink tone of each color.
// Colors without a fixed tone spread over the tone range by lightness.
func (logo logoSpec) paletteAndTones(img *image.NRGBA) (palette, []float64) {
if len(logo.Palette) == 0 {
k := logo.Colors
if k == 0 {
k = defaultPaletteColors
}
pal := extractPalette(img, k)
return pal, logo.defaultTones(pal.lab)
}
colors := make([]color.NRGBA, len(logo.Palette))
fixed := map[color.NRGBA]float64{}
for i, p := range logo.Palette {
colors[i], _ = parseHexColor(p.Color)
if p.Tone != nil {
fixed[colors[i]] = *p.Tone
}
}
pal := newPalette(colors)
var free []int
var freeLab []oklab
tones := make([]float64, len(pal.colors))
for i, c := range pal.colors {
if tone, ok := fixed[c]; ok {
tones[i] = tone
continue
}
free = append(free, i)
freeLab = append(freeLab, pal.lab[i])
}
for j, tone := range logo.defaultTones(freeLab) {
tones[free[j]] = tone
}
return pal, tones
}
func (logo logoSpec) defaultTones(colors []oklab) []float64 {
if !logo.Flat {
return lightnessTones(colors, toneFloor)
}
tones := make([]float64, len(colors))
for i := range tones {
tones[i] = 1
}
return tones
}
package main
import (
"image"
"image/color"
"slices"
)
// palette holds the flat colors that a logo is reduced to, sorted from dark
// to light.
type palette struct {
colors []color.NRGBA
lab []oklab
}
func newPalette(colors []color.NRGBA) palette {
p := palette{colors: slices.Clone(colors)}
slices.SortStableFunc(p.colors, func(x, y color.NRGBA) int {
lx, ly := toOKLab(x).l, toOKLab(y).l
switch {
case lx < ly:
return -1
case lx > ly:
return 1
default:
return 0
}
})
p.lab = make([]oklab, len(p.colors))
for i, c := range p.colors {
p.lab[i] = toOKLab(c)
}
return p
}
func (p palette) nearest(o oklab) int {
best, bestDistance := 0, -1.0
for i, lab := range p.lab {
if d := o.distance2(lab); bestDistance < 0 || d < bestDistance {
best, bestDistance = i, d
}
}
return best
}
// colorBin accumulates the opaque pixels that share one quantized color.
type colorBin struct {
weight float64
r, g, b float64
lab oklab
cluster int
}
// paletteMinShare drops clusters that cover less than this share of the
// opaque area. Such clusters are usually antialiasing between two flat colors.
const paletteMinShare = 0.01
// extractPalette reduces the opaque pixels of img to at most k flat colors
// with weighted k-means in OKLab. Each output color is the most frequent
// source color of its cluster, so flat brand colors stay exact.
func extractPalette(img *image.NRGBA, k int) palette {
bins := histogram(img)
if len(bins) == 0 || k <= 0 {
return palette{}
}
k = min(k, len(bins))
centers := seedCenters(bins, k)
for range 64 {
changed := assignClusters(bins, centers)
centers = updateCenters(bins, centers)
if !changed {
break
}
}
centers = dropMinorCenters(bins, centers)
assignClusters(bins, centers)
medoids := make([]*colorBin, len(centers))
for i := range bins {
bin := &bins[i]
if m := medoids[bin.cluster]; m == nil || bin.weight > m.weight {
medoids[bin.cluster] = bin
}
}
colors := make([]color.NRGBA, 0, len(medoids))
for _, m := range medoids {
if m == nil {
continue
}
colors = append(colors, color.NRGBA{
R: uint8(m.r/m.weight + 0.5),
G: uint8(m.g/m.weight + 0.5),
B: uint8(m.b/m.weight + 0.5),
A: 255,
})
}
return newPalette(colors)
}
// histogram groups pixels with alpha of at least one half by color quantized
// to 5 bits per channel. Weights are alpha, so faint edges count less.
func histogram(img *image.NRGBA) []colorBin {
index := map[uint16]int{}
var bins []colorBin
b := img.Bounds()
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
c := img.NRGBAAt(x, y)
if c.A < 128 {
continue
}
key := uint16(c.R>>3)<<10 | uint16(c.G>>3)<<5 | uint16(c.B>>3)
i, ok := index[key]
if !ok {
i = len(bins)
index[key] = i
bins = append(bins, colorBin{})
}
w := float64(c.A) / 255
bins[i].weight += w
bins[i].r += w * float64(c.R)
bins[i].g += w * float64(c.G)
bins[i].b += w * float64(c.B)
}
}
for i := range bins {
bin := &bins[i]
bin.lab = toOKLab(color.NRGBA{
R: uint8(bin.r/bin.weight + 0.5),
G: uint8(bin.g/bin.weight + 0.5),
B: uint8(bin.b/bin.weight + 0.5),
A: 255,
})
}
// Map iteration order is random; sort so that seeding is reproducible.
slices.SortFunc(bins, func(x, y colorBin) int {
switch {
case x.weight > y.weight:
return -1
case x.weight < y.weight:
return 1
}
return cmpLab(x.lab, y.lab)
})
return bins
}
func cmpLab(x, y oklab) int {
for _, d := range [3]float64{x.l - y.l, x.a - y.a, x.b - y.b} {
if d < 0 {
return -1
}
if d > 0 {
return 1
}
}
return 0
}
// seedCenters is a deterministic k-means++: it starts at the heaviest color
// and then takes the color with the largest weight times squared distance to
// the chosen centers.
func seedCenters(bins []colorBin, k int) []oklab {
centers := []oklab{bins[0].lab}
nearest := make([]float64, len(bins))
for i := range bins {
nearest[i] = bins[i].lab.distance2(centers[0])
}
for len(centers) < k {
best, bestScore := -1, 0.0
for i := range bins {
if score := bins[i].weight * nearest[i]; score > bestScore {
best, bestScore = i, score
}
}
if best < 0 {
break
}
centers = append(centers, bins[best].lab)
for i := range bins {
nearest[i] = min(nearest[i], bins[i].lab.distance2(bins[best].lab))
}
}
return centers
}
func assignClusters(bins []colorBin, centers []oklab) bool {
p := palette{lab: centers}
changed := false
for i := range bins {
c := p.nearest(bins[i].lab)
if c != bins[i].cluster {
bins[i].cluster = c
changed = true
}
}
return changed
}
func updateCenters(bins []colorBin, centers []oklab) []oklab {
sums := make([]oklab, len(centers))
weights := make([]float64, len(centers))
for _, bin := range bins {
s := &sums[bin.cluster]
s.l += bin.weight * bin.lab.l
s.a += bin.weight * bin.lab.a
s.b += bin.weight * bin.lab.b
weights[bin.cluster] += bin.weight
}
next := make([]oklab, len(centers))
for i, w := range weights {
if w == 0 {
next[i] = centers[i]
continue
}
next[i] = oklab{l: sums[i].l / w, a: sums[i].a / w, b: sums[i].b / w}
}
return next
}
func dropMinorCenters(bins []colorBin, centers []oklab) []oklab {
weights := make([]float64, len(centers))
total := 0.0
for _, bin := range bins {
weights[bin.cluster] += bin.weight
total += bin.weight
}
kept := centers[:0:0]
for i, c := range centers {
if weights[i] >= paletteMinShare*total {
kept = append(kept, c)
}
}
if len(kept) == 0 {
return centers
}
return kept
}
package main
// plane is a summed-area table over a scalar image. It gives exact box
// filter integrals over rectangles with fractional corners, which treats
// pixels as constant squares. Areas outside the image add nothing.
type plane struct {
w, h int
sum []float64
}
// newPlane builds the table from row-major values of a w×h image.
func newPlane(w, h int, values []float64) plane {
p := plane{w: w, h: h, sum: make([]float64, (w+1)*(h+1))}
stride := w + 1
for y := range h {
row := 0.0
for x := range w {
row += values[y*w+x]
p.sum[(y+1)*stride+x+1] = p.sum[y*stride+x+1] + row
}
}
return p
}
// cumulative is the integral over [0,x)×[0,y). It is bilinear inside each
// pixel, so interpolating the table corners is exact.
func (p plane) cumulative(x, y float64) float64 {
x = min(max(x, 0), float64(p.w))
y = min(max(y, 0), float64(p.h))
x0, y0 := int(x), int(y)
x1, y1 := min(x0+1, p.w), min(y0+1, p.h)
fx, fy := x-float64(x0), y-float64(y0)
stride := p.w + 1
s00 := p.sum[y0*stride+x0]
s10 := p.sum[y0*stride+x1]
s01 := p.sum[y1*stride+x0]
s11 := p.sum[y1*stride+x1]
top := s00 + (s10-s00)*fx
bottom := s01 + (s11-s01)*fx
return top + (bottom-top)*fy
}
// mean is the average value over [x0,x1)×[y0,y1), counting the part outside
// the image as zero.
func (p plane) mean(x0, y0, x1, y1 float64) float64 {
area := (x1 - x0) * (y1 - y0)
if area <= 0 {
return 0
}
total := p.cumulative(x1, y1) - p.cumulative(x0, y1) -
p.cumulative(x1, y0) + p.cumulative(x0, y0)
return total / area
}
package main
import (
"fmt"
"image"
"image/color"
stddraw "image/draw"
"golang.org/x/image/draw"
)
const (
// svgRasterSize is the longer side of rasterized SVG sources.
svgRasterSize = 1024
// workingSize caps the longer side of raster sources other than pixel
// art. At the largest variant it still gives each cell more than
// ten source pixels per side.
workingSize = 1024
)
// prepare crops, clears the background, smooths, and scales the source as
// the logo asks. The result always starts at the origin.
func prepare(img *image.NRGBA, logo logoSpec) (*image.NRGBA, error) {
if logo.Crop != nil {
r := image.Rect(logo.Crop[0], logo.Crop[1], logo.Crop[2], logo.Crop[3])
if !r.In(img.Bounds()) {
return nil, fmt.Errorf("crop %v is outside the source bounds %v", r, img.Bounds())
}
img = rebase(img.SubImage(r).(*image.NRGBA))
}
if logo.Knockout > 0 {
knockout(img, logo.Knockout)
}
if logo.Blur > 0 {
blur(img, logo.Blur)
}
if !logo.Pixel {
img = downscale(img, workingSize)
}
return img, nil
}
func rebase(img *image.NRGBA) *image.NRGBA {
out := image.NewNRGBA(image.Rect(0, 0, img.Bounds().Dx(), img.Bounds().Dy()))
stddraw.Draw(out, out.Bounds(), img, img.Bounds().Min, stddraw.Src)
return out
}
// knockout makes transparent every pixel reachable from the image border
// through steps between neighbors of at most tolerance in OKLab.
func knockout(img *image.NRGBA, tolerance float64) {
b := img.Bounds()
w, h := b.Dx(), b.Dy()
limit := tolerance * tolerance
cleared := make([]bool, w*h)
lab := func(x, y int) oklab {
c := img.NRGBAAt(x, y)
return toOKLab(color.NRGBA{R: c.R, G: c.G, B: c.B, A: 255})
}
var queue []image.Point
for x := range w {
queue = append(queue, image.Pt(x, 0), image.Pt(x, h-1))
}
for y := range h {
queue = append(queue, image.Pt(0, y), image.Pt(w-1, y))
}
for _, p := range queue {
cleared[p.Y*w+p.X] = true
}
for len(queue) > 0 {
p := queue[len(queue)-1]
queue = queue[:len(queue)-1]
from := lab(p.X, p.Y)
transparent := img.NRGBAAt(p.X, p.Y).A == 0
for _, d := range [4]image.Point{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
n := p.Add(d)
if n.X < 0 || n.Y < 0 || n.X >= w || n.Y >= h || cleared[n.Y*w+n.X] {
continue
}
next := img.NRGBAAt(n.X, n.Y)
if next.A != 0 && (transparent || from.distance2(lab(n.X, n.Y)) > limit) {
continue
}
cleared[n.Y*w+n.X] = true
queue = append(queue, n)
}
}
for i, c := range cleared {
if c {
img.Pix[i*4+3] = 0
}
}
}
// downscale shrinks img so that its longer side is at most size. The
// bilinear kernel widens with the scale factor, so it averages every source
// pixel instead of sampling a few.
func downscale(img *image.NRGBA, size int) *image.NRGBA {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
if max(w, h) <= size {
return img
}
scale := float64(size) / float64(max(w, h))
dst := image.NewRGBA(image.Rect(
0, 0,
max(1, int(float64(w)*scale+0.5)),
max(1, int(float64(h)*scale+0.5)),
))
draw.BiLinear.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Src, nil)
return straightAlpha(dst)
}
// blur smooths img with two passes of a box filter of the given radius,
// which approximates a Gaussian. It works on premultiplied color, so
// transparent pixels do not darken edges.
func blur(img *image.NRGBA, radius int) {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
channels := make([][]float64, 4)
for c := range channels {
channels[c] = make([]float64, w*h)
}
for i := range w * h {
a := float64(img.Pix[i*4+3]) / 255
channels[3][i] = a
for c := range 3 {
channels[c][i] = float64(img.Pix[i*4+c]) * a
}
}
scratch := make([]float64, max(w, h))
for _, values := range channels {
for range 2 {
for y := range h {
boxBlur(values[y*w:(y+1)*w], 1, radius, scratch[:w])
}
for x := range w {
boxBlur(values[x:], w, radius, scratch[:h])
}
}
}
for i := range w * h {
a := channels[3][i]
img.Pix[i*4+3] = uint8(min(255, a*255+0.5))
if a <= 0 {
continue
}
for c := range 3 {
img.Pix[i*4+c] = uint8(min(255, channels[c][i]/a+0.5))
}
}
}
// boxBlur averages len(scratch) values that lie stride apart in values over
// a window of 2·radius+1. The window shrinks at the ends.
func boxBlur(values []float64, stride, radius int, scratch []float64) {
n := len(scratch)
sum, count := 0.0, 0
for i := range min(radius, n) {
sum += values[i*stride]
count++
}
for i := range n {
if j := i + radius; j < n {
sum += values[j*stride]
count++
}
if j := i - radius - 1; j >= 0 {
sum -= values[j*stride]
count--
}
scratch[i] = sum / float64(count)
}
for i := range n {
values[i*stride] = scratch[i]
}
}
// despeckle clears ink islands smaller than minShare of all ink. Ink is a
// pixel with alpha of at least one half whose palette color has a tone; an
// island is an 8-connected group of ink. Lettering around a badge falls
// apart into such islands, while the mark stays one large island. The
// antialiased fringe of a cleared island goes with it.
func despeckle(img *image.NRGBA, pal palette, tones []float64, minShare float64) {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
ink := make([]bool, w*h)
total := 0
cache := map[color.NRGBA]bool{}
for y := range h {
for x := range w {
c := img.NRGBAAt(x, y)
if c.A < 128 {
continue
}
opaque := color.NRGBA{R: c.R, G: c.G, B: c.B, A: 255}
isInk, ok := cache[opaque]
if !ok {
isInk = tones[pal.nearest(toOKLab(opaque))] > 0
cache[opaque] = isInk
}
if isInk {
ink[y*w+x] = true
total++
}
}
}
neighbors := func(i int, visit func(n int)) {
x, y := i%w, i/w
for ny := max(y-1, 0); ny <= min(y+1, h-1); ny++ {
for nx := max(x-1, 0); nx <= min(x+1, w-1); nx++ {
visit(ny*w + nx)
}
}
}
seen := make([]bool, w*h)
var island, stack []int
for start := range ink {
if !ink[start] || seen[start] {
continue
}
island, stack = island[:0], append(stack[:0], start)
seen[start] = true
for len(stack) > 0 {
i := stack[len(stack)-1]
stack = stack[:len(stack)-1]
island = append(island, i)
neighbors(i, func(n int) {
if ink[n] && !seen[n] {
seen[n] = true
stack = append(stack, n)
}
})
}
if float64(len(island)) >= minShare*float64(total) {
continue
}
for _, i := range island {
neighbors(i, func(n int) {
if n == i || !ink[n] {
img.Pix[n*4+3] = 0
}
})
}
}
}
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
"path/filepath"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
const (
previewCellWidth = 10
previewCellHeight = previewCellWidth * 2
previewGap = 20
)
// previewTheme is the terminal background and default foreground a preview
// simulates.
type previewTheme struct {
background color.NRGBA
foreground color.NRGBA
}
var (
previewDark = previewTheme{
background: color.NRGBA{R: 0x1e, G: 0x1e, B: 0x1e, A: 0xff},
foreground: color.NRGBA{R: 0xd4, G: 0xd4, B: 0xd4, A: 0xff},
}
previewLight = previewTheme{
background: color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff},
foreground: color.NRGBA{R: 0x24, G: 0x29, B: 0x2f, A: 0xff},
}
previewSheetBackground = color.NRGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xff}
previewCaptionColor = color.NRGBA{R: 0x10, G: 0x10, B: 0x10, A: 0xff}
)
// previewer draws art as a terminal with the cell font would show it.
type previewer struct {
face font.Face
baseline fixed.Int26_6
}
func newPreviewer(f *opentype.Font) (previewer, error) {
face, err := cellFace(f, previewCellWidth)
if err != nil {
return previewer{}, err
}
return previewer{face: face, baseline: cellBaseline(face, previewCellHeight)}, nil
}
// render draws the art with a one-cell margin. When colored is false, every
// glyph uses the theme foreground.
func (p previewer) render(a art, theme previewTheme, colored bool) *image.NRGBA {
img := image.NewNRGBA(image.Rect(
0, 0,
(a.cols+2)*previewCellWidth,
(a.rows+2)*previewCellHeight,
))
draw.Draw(img, img.Bounds(), image.NewUniform(theme.background), image.Point{}, draw.Src)
for row := range a.rows {
for col := range a.cols {
cell := a.at(col, row)
if cell.glyph == ' ' {
continue
}
ink := theme.foreground
if colored && cell.tinted {
ink = cell.color
}
d := font.Drawer{
Dst: img,
Src: image.NewUniform(ink),
Face: p.face,
Dot: fixed.Point26_6{
X: fixed.I((col + 1) * previewCellWidth),
Y: fixed.I((row+1)*previewCellHeight) + p.baseline,
},
}
d.DrawString(string(cell.glyph))
}
}
return img
}
// row places images left to right, top-aligned, each under its caption.
func (p previewer) row(images []*image.NRGBA, captions []string) *image.NRGBA {
width := previewGap * max(len(images)-1, 0)
height := 0
for _, img := range images {
width += img.Bounds().Dx()
height = max(height, img.Bounds().Dy())
}
out := image.NewNRGBA(image.Rect(0, 0, width, previewCellHeight+height))
draw.Draw(out, out.Bounds(), image.NewUniform(previewSheetBackground), image.Point{}, draw.Src)
x := 0
for i, img := range images {
if i < len(captions) && captions[i] != "" {
d := font.Drawer{
Dst: out,
Src: image.NewUniform(previewCaptionColor),
Face: p.face,
Dot: fixed.Point26_6{X: fixed.I(x), Y: p.baseline},
}
d.DrawString(captions[i])
}
bounds := img.Bounds().Add(image.Pt(x, previewCellHeight))
draw.Draw(out, bounds, img, image.Point{}, draw.Src)
x += img.Bounds().Dx() + previewGap
}
return out
}
// stack places images top to bottom with a gap.
func stack(images []*image.NRGBA) *image.NRGBA {
width, height := 0, previewGap*max(len(images)-1, 0)
for _, img := range images {
width = max(width, img.Bounds().Dx())
height += img.Bounds().Dy()
}
out := image.NewNRGBA(image.Rect(0, 0, width, height))
draw.Draw(out, out.Bounds(), image.NewUniform(previewSheetBackground), image.Point{}, draw.Src)
y := 0
for _, img := range images {
draw.Draw(out, img.Bounds().Add(image.Pt(0, y)), img, image.Point{}, draw.Src)
y += img.Bounds().Dy() + previewGap
}
return out
}
// writePNG encodes img to path, creating parent directories.
func writePNG(path string, img image.Image) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
file, err := os.Create(path)
if err != nil {
return err
}
if err := png.Encode(file, img); err != nil {
_ = file.Close()
return err
}
return file.Close()
}
package main
import (
"image"
"image/color"
"math"
)
// cellAspect is terminal cell width over height.
const cellAspect = 0.5
// grid maps terminal cells onto source pixels.
type grid struct {
cols, rows int
x0, y0 float64
cellW, cellH float64
}
// fitGrid scales content to fill a box of maxCols×maxRows cells on its
// limiting axis, rounds the other axis to whole cells, and centers it.
func fitGrid(content image.Rectangle, maxCols, maxRows int) grid {
w, h := float64(content.Dx()), float64(content.Dy())
cols, rows := maxCols, maxRows
if fitRows := h * cellAspect * float64(maxCols) / w; fitRows <= float64(maxRows) {
rows = max(1, int(math.Round(fitRows)))
} else {
cols = max(1, int(math.Round(w*float64(maxRows)/(h*cellAspect))))
}
cellW := max(w/float64(cols), h*cellAspect/float64(rows))
cellH := cellW / cellAspect
return grid{
cols: cols,
rows: rows,
x0: float64(content.Min.X) - (float64(cols)*cellW-w)/2,
y0: float64(content.Min.Y) - (float64(rows)*cellH-h)/2,
cellW: cellW,
cellH: cellH,
}
}
// pixelCellRatios lists how many cells one art pixel spans horizontally,
// largest first. Each keeps cells aligned to art pixel edges.
var pixelCellRatios = []float64{4, 3, 2, 1, 0.5}
// fitPixelGrid maps each art pixel of side scale source pixels to whole or
// half cells, so every cell edge lies on an art pixel edge. It reports false
// when even the smallest ratio does not fit the box.
func fitPixelGrid(content image.Rectangle, scale, maxCols, maxRows int) (grid, bool) {
w := float64(content.Dx()) / float64(scale)
h := float64(content.Dy()) / float64(scale)
for _, ratio := range pixelCellRatios {
cols := int(math.Ceil(w * ratio))
rows := int(math.Ceil(h * ratio * cellAspect))
if cols > maxCols || rows > maxRows {
continue
}
cellW := float64(scale) / ratio
return grid{
cols: cols,
rows: rows,
x0: float64(content.Min.X),
y0: float64(content.Min.Y),
cellW: cellW,
cellH: cellW / cellAspect,
}, true
}
return grid{}, false
}
// detectPixelScale returns the side, in source pixels, of the square blocks
// that an upscaled pixel art image is made of, or 1 when it is not pixel art.
func detectPixelScale(img *image.NRGBA, content image.Rectangle) int {
for scale := min(content.Dx(), content.Dy()) / 4; scale >= 2; scale-- {
if content.Dx()%scale != 0 || content.Dy()%scale != 0 {
continue
}
if uniformBlockShare(img, content, scale) >= 0.97 {
return scale
}
}
return 1
}
func uniformBlockShare(img *image.NRGBA, content image.Rectangle, scale int) float64 {
uniform, total := 0, 0
for by := content.Min.Y; by < content.Max.Y; by += scale {
for bx := content.Min.X; bx < content.Max.X; bx += scale {
total++
if blockIsUniform(img, bx, by, scale) {
uniform++
}
}
}
return float64(uniform) / float64(total)
}
func blockIsUniform(img *image.NRGBA, bx, by, scale int) bool {
ref := img.NRGBAAt(bx, by)
for y := by; y < by+scale; y++ {
for x := bx; x < bx+scale; x++ {
c := img.NRGBAAt(x, y)
if ref.A == 0 && c.A == 0 {
continue
}
if channelDiff(ref.R, c.R) > 8 || channelDiff(ref.G, c.G) > 8 ||
channelDiff(ref.B, c.B) > 8 || channelDiff(ref.A, c.A) > 8 {
return false
}
}
}
return true
}
func channelDiff(a, b uint8) int {
if a > b {
return int(a - b)
}
return int(b - a)
}
// inkThreshold is the least ink that counts as content when trimming.
const inkThreshold = 0.03
// inkPlanes holds the source image reduced to its palette. tone is the ink
// density of every pixel; labels[k] is the alpha of pixels that belong to
// palette color k. bounds encloses all pixels with ink.
type inkPlanes struct {
tone plane
labels []plane
bounds image.Rectangle
}
// newInkPlanes expects img to start at the origin. Pixels of a color with
// tone 0 count as background.
func newInkPlanes(img *image.NRGBA, pal palette, tones []float64) inkPlanes {
w, h := img.Bounds().Dx(), img.Bounds().Dy()
tone := make([]float64, w*h)
labels := make([][]float64, len(pal.colors))
for k := range labels {
labels[k] = make([]float64, w*h)
}
bounds := image.Rectangle{}
cache := map[color.NRGBA]int{}
for y := range h {
for x := range w {
c := img.NRGBAAt(x, y)
if c.A == 0 {
continue
}
opaque := color.NRGBA{R: c.R, G: c.G, B: c.B, A: 255}
k, ok := cache[opaque]
if !ok {
k = pal.nearest(toOKLab(opaque))
cache[opaque] = k
}
if tones[k] == 0 {
continue
}
alpha := float64(c.A) / 255
tone[y*w+x] = alpha * tones[k]
labels[k][y*w+x] = alpha
if tone[y*w+x] >= inkThreshold {
bounds = bounds.Union(image.Rect(x, y, x+1, y+1))
}
}
}
planes := inkPlanes{
tone: newPlane(w, h, tone),
labels: make([]plane, len(labels)),
bounds: bounds,
}
for k, values := range labels {
planes.labels[k] = newPlane(w, h, values)
}
return planes
}
// renderOptions tunes how renderArt turns ink into glyphs.
type renderOptions struct {
// uniformity is the largest spread of window ink inside a cell that
// still counts as a uniform region. Such cells take a fill glyph, so
// close tones inside a region do not turn into shape glyphs.
uniformity float64
fill fillRamp
}
// renderArt fills uniform cells from the fill ramp and gives every other
// cell the glyph whose shape best matches its ink. Each glyph takes the
// palette color that lies under its ink.
func renderArt(planes inkPlanes, pal palette, g grid, set glyphSet, opts renderOptions) art {
out := newArt(g.cols, g.rows)
inks := make([]artCell, len(pal.colors))
for i, c := range pal.colors {
inks[i].color, inks[i].tinted = terminalColor(c)
}
v := make([]float64, len(set.windows))
rects := make([][4]float64, len(set.windows))
flat := make([]float64, len(set.windows))
for k := range flat {
flat[k] = 1
}
for row := range g.rows {
for col := range g.cols {
cx := g.x0 + float64(col)*g.cellW
cy := g.y0 + float64(row)*g.cellH
peak, floor, sum := 0.0, math.Inf(1), 0.0
for k, w := range set.windows {
rects[k] = [4]float64{
cx + w.x0*g.cellW, cy + w.y0*g.cellH,
cx + w.x1*g.cellW, cy + w.y1*g.cellH,
}
v[k] = planes.tone.mean(rects[k][0], rects[k][1], rects[k][2], rects[k][3])
peak = max(peak, v[k])
floor = min(floor, v[k])
sum += v[k]
}
if peak == 0 {
continue
}
glyph, weights := byte(0), flat
if peak-floor <= opts.uniformity {
glyph = opts.fill.pick(sum / float64(len(v)))
} else {
i := set.match(v)
glyph, weights = set.glyphs[i], set.vectors[i]
}
if glyph == ' ' {
continue
}
best, bestScore := 0, -1.0
for label, p := range planes.labels {
score := 0.0
for k, r := range rects {
score += weights[k] * p.mean(r[0], r[1], r[2], r[3])
}
if score > bestScore {
best, bestScore = label, score
}
}
cell := inks[best]
cell.glyph = glyph
out.set(col, row, cell)
}
}
return out
}
// toneFloor is the lowest tone that lightnessTones gives. Darker colors
// still need visible ink, or they vanish on dark terminals.
const toneFloor = 0.35
// lightnessTones gives each color an ink density that rises with its OKLab
// lightness from floor to 1. A single color gets full ink.
func lightnessTones(colors []oklab, floor float64) []float64 {
tones := make([]float64, len(colors))
if len(tones) == 0 {
return tones
}
lo, hi := colors[0].l, colors[0].l
for _, c := range colors {
lo, hi = min(lo, c.l), max(hi, c.l)
}
for i, c := range colors {
if hi-lo < 1e-6 {
tones[i] = 1
continue
}
tones[i] = floor + (1-floor)*(c.l-lo)/(hi-lo)
}
return tones
}
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"errors"
"fmt"
"image"
"image/draw"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/NimbleMarkets/oksvg"
"github.com/srwiley/rasterx"
_ "golang.org/x/image/webp"
)
const (
sourceAttempts = 3
sourceTimeout = 60 * time.Second
sourceAgent = "lucy-genlogo"
)
// source pins one upstream image.
type source struct {
URL string `yaml:"url"`
SHA256 string `yaml:"sha256"`
}
// digestError reports a download whose bytes do not match the pinned digest.
type digestError struct {
url string
got string
want string
}
func (e digestError) Error() string {
return fmt.Sprintf("sha256 mismatch for %s: got %s want %s", e.url, e.got, e.want)
}
// fetchSource returns the path of the cached, digest-verified source file and
// downloads it on a cache miss.
func fetchSource(src source, cacheDir string) (string, error) {
digest, err := normalizeDigest(src.SHA256)
if err != nil {
return "", err
}
path := filepath.Join(cacheDir, digest[:2], digest)
hit, err := hasDigest(path, digest)
if err != nil {
return "", err
}
if hit {
return path, nil
}
// A file with another digest cannot become valid, so drop it.
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("drop stale cache %s: %w", path, err)
}
if err := downloadSource(src.URL, path, digest); err != nil {
return "", err
}
return path, nil
}
// normalizeDigest accepts hex in either case and returns lowercase hex.
func normalizeDigest(raw string) (string, error) {
digest := strings.ToLower(strings.TrimSpace(raw))
if len(digest) != sha256.Size*2 {
return "", fmt.Errorf("sha256 must be 64 hex characters, got %d", len(digest))
}
if _, err := hex.DecodeString(digest); err != nil {
return "", fmt.Errorf("sha256 %q is not hex: %w", raw, err)
}
return digest, nil
}
// hasDigest reports whether path exists with the wanted digest.
func hasDigest(path, want string) (bool, error) {
got, err := fileDigest(path)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
return got == want, nil
}
func fileDigest(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("hash %s: %w", path, err)
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
// downloadSource retries network failures but not a digest mismatch, which
// retrying cannot fix.
func downloadSource(url, path, want string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create cache dir %s: %w", dir, err)
}
client := &http.Client{Timeout: sourceTimeout}
var lastErr error
for range sourceAttempts {
lastErr = downloadOnce(client, url, path, want)
if lastErr == nil {
return nil
}
var bad digestError
if errors.As(lastErr, &bad) {
break
}
}
return lastErr
}
func downloadOnce(client *http.Client, url, path, want string) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("build request for %s: %w", url, err)
}
req.Header.Set("User-Agent", sourceAgent)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("download %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("download %s: %s", url, resp.Status)
}
tmp, err := os.CreateTemp(filepath.Dir(path), ".download-*")
if err != nil {
return fmt.Errorf("create temp file for %s: %w", path, err)
}
tmpName := tmp.Name()
done := false
defer func() {
if done {
return
}
tmp.Close()
os.Remove(tmpName)
}()
hash := sha256.New()
if _, err := io.Copy(io.MultiWriter(tmp, hash), resp.Body); err != nil {
return fmt.Errorf("download %s: %w", url, err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("write %s: %w", tmpName, err)
}
got := hex.EncodeToString(hash.Sum(nil))
if got != want {
return digestError{url: url, got: got, want: want}
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("store %s: %w", path, err)
}
done = true
return nil
}
// decodeImage decodes PNG, JPEG, GIF, WebP, or SVG into straight-alpha NRGBA.
// It sniffs the content, not the file name. It rasterizes SVG so that the
// longer side is svgSize pixels.
func decodeImage(path string, svgSize int) (*image.NRGBA, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if isSVG(data) {
img, err := rasterizeSVG(data, svgSize)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return img, nil
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return straightAlpha(img), nil
}
// isSVG reports whether the content, after any BOM and XML preamble, has an
// svg root. Upstream URLs do not always carry an .svg suffix.
func isSVG(data []byte) bool {
rest := bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
for {
rest = bytes.TrimLeft(rest, " \t\r\n")
var cut bool
switch {
case bytes.HasPrefix(rest, []byte("<?")):
rest, cut = skipPast(rest, []byte("?>"))
case bytes.HasPrefix(rest, []byte("<!--")):
rest, cut = skipPast(rest, []byte("-->"))
case bytes.HasPrefix(rest, []byte("<!DOCTYPE")),
bytes.HasPrefix(rest, []byte("<!doctype")):
rest, cut = skipPast(rest, []byte(">"))
default:
return bytes.Contains(rest, []byte("<svg"))
}
if !cut {
return false
}
}
}
// skipPast returns the content after the first delim, and false when absent.
func skipPast(data, delim []byte) ([]byte, bool) {
idx := bytes.Index(data, delim)
if idx < 0 {
return nil, false
}
return data[idx+len(delim):], true
}
// rasterizeSVG draws data with a transparent background. oksvg and rasterx
// panic on some valid-looking input, so a panic becomes an error.
func rasterizeSVG(data []byte, size int) (img *image.NRGBA, err error) {
if size < 1 {
return nil, fmt.Errorf("svg size %d is below 1 pixel", size)
}
defer func() {
if reason := recover(); reason != nil {
img = nil
err = fmt.Errorf("rasterize svg: %v", reason)
}
}()
icon, err := oksvg.ReadIconStream(bytes.NewReader(data), oksvg.WarnErrorMode)
if err != nil {
return nil, fmt.Errorf("parse svg: %w", err)
}
width, height := svgExtent(data, icon.ViewBox.W, icon.ViewBox.H)
scale := float64(size) / max(width, height)
cols := max(1, int(math.Round(width*scale)))
rows := max(1, int(math.Round(height*scale)))
// Scale before translating: oksvg's SetTarget translates by the unscaled
// viewBox origin, which shifts icons with a non-zero origin.
icon.Transform = rasterx.Identity.Scale(scale, scale).Translate(
-icon.ViewBox.X,
-icon.ViewBox.Y,
)
// oksvg transforms path points before stroking, so line widths and dashes
// stay in user units and would render too thin on a scaled raster.
for i := range icon.SVGPaths {
path := &icon.SVGPaths[i]
path.LineWidth *= scale
for j := range path.Dash {
path.Dash[j] *= scale
}
}
canvas := image.NewRGBA(image.Rect(0, 0, cols, rows))
scanner := rasterx.NewScannerGV(cols, rows, canvas, canvas.Bounds())
icon.Draw(rasterx.NewDasher(cols, rows, scanner), 1)
return straightAlpha(canvas), nil
}
// svgExtent falls back to the root width and height when the viewBox has no
// positive extent. Without either, the drawing is assumed square.
func svgExtent(data []byte, width, height float64) (float64, float64) {
if width > 0 && height > 0 {
return width, height
}
attrW, attrH := rootLengths(data)
if width <= 0 {
width = attrW
}
if height <= 0 {
height = attrH
}
if width <= 0 || height <= 0 {
return 1, 1
}
return width, height
}
func rootLengths(data []byte) (width, height float64) {
decoder := xml.NewDecoder(bytes.NewReader(data))
for {
token, err := decoder.Token()
if err != nil {
return 0, 0
}
start, ok := token.(xml.StartElement)
if !ok {
continue
}
if start.Name.Local != "svg" {
return 0, 0
}
for _, attr := range start.Attr {
switch attr.Name.Local {
case "width":
width = lengthPixels(attr.Value)
case "height":
height = lengthPixels(attr.Value)
}
}
return width, height
}
}
// lengthPixels parses a length as user units. Only the width to height ratio
// matters, so physical units are not converted.
func lengthPixels(value string) float64 {
value = strings.TrimSpace(value)
for _, unit := range []string{"px", "pt", "pc", "mm", "cm", "in", "em", "ex", "%"} {
value = strings.TrimSuffix(value, unit)
}
length, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
if err != nil {
return 0
}
return length
}
// straightAlpha converts any image to non-premultiplied NRGBA. draw.Draw
// performs the unpremultiply step when the destination is NRGBA.
func straightAlpha(src image.Image) *image.NRGBA {
if img, ok := src.(*image.NRGBA); ok {
return img
}
bounds := src.Bounds()
dst := image.NewNRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
draw.Draw(dst, dst.Bounds(), src, bounds.Min, draw.Src)
return dst
}
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"os"
"reflect"
"github.com/mclucy/lucy/java"
"github.com/invopop/jsonschema"
"github.com/mclucy/lucy/document"
orderedmap "github.com/pb33f/ordered-map/v2"
)
const schemaURL = "https://lucy.lc/manifest.schema.json"
func main() {
requirementSchema := &jsonschema.Schema{
OneOf: []*jsonschema.Schema{
{
Type: "string",
Description: "A version selector: any, stable, beta, a tag, or an exact version.",
},
func() *jsonschema.Schema {
selector := &jsonschema.Schema{
Type: "string",
Description: "A version selector: any, stable, beta, a tag, or an exact version.",
}
filePattern := &jsonschema.Schema{
Type: "string",
Description: "Glob pattern matching the upstream artifact filename.",
}
enabled := &jsonschema.Schema{
Type: "boolean",
Default: true,
Description: "Whether the requirement is active in the resolved environment.",
}
properties := orderedmap.New[string, *jsonschema.Schema]()
properties.Set("selector", selector)
properties.Set("file_pattern", filePattern)
properties.Set("enabled", enabled)
return &jsonschema.Schema{
Type: "object",
Properties: properties,
AdditionalProperties: jsonschema.FalseSchema,
}
}(),
},
}
trackedFileSchema := func() *jsonschema.Schema {
path := &jsonschema.Schema{
Type: "string",
Description: "Workspace-relative forward-slash path to the tracked file.",
}
immutable := &jsonschema.Schema{
Type: "boolean",
Default: false,
Description: "Whether deviation from the accepted digest produces an immutable-file warning.",
}
hash := &jsonschema.Schema{
Type: "string",
Pattern: `^sha256:[0-9a-f]{64}$`,
Description: "Accepted SHA-256 digest in canonical sha256:<hex> form.",
}
recoverURL := &jsonschema.Schema{
Type: "string",
Format: "uri",
Pattern: `^https?://`,
Description: "Remote HTTP(S) URL used to restore missing file contents.",
}
properties := orderedmap.New[string, *jsonschema.Schema]()
properties.Set("path", path)
properties.Set("immutable", immutable)
properties.Set("hash", hash)
properties.Set("recover_url", recoverURL)
return &jsonschema.Schema{
Type: "object",
Properties: properties,
Required: []string{"path"},
AdditionalProperties: jsonschema.FalseSchema,
AllOf: []*jsonschema.Schema{
{
If: &jsonschema.Schema{
Properties: func() *orderedmap.OrderedMap[string, *jsonschema.Schema] {
p := orderedmap.New[string, *jsonschema.Schema]()
p.Set("immutable", &jsonschema.Schema{Const: true})
return p
}(),
Required: []string{"immutable"},
},
Then: &jsonschema.Schema{
Required: []string{"hash"},
},
},
{
If: &jsonschema.Schema{
Required: []string{"recover_url"},
},
Then: &jsonschema.Schema{
Required: []string{"hash"},
},
},
},
}
}()
javaSchema := func() *jsonschema.Schema {
major := func() *jsonschema.Schema {
return &jsonschema.Schema{
Type: "integer",
Extras: map[string]any{"minimum": document.MinimumJava},
}
}
version := &jsonschema.Schema{
OneOf: []*jsonschema.Schema{
major(),
{Const: document.JavaAuto},
},
Description: "The Java major version, or auto.",
}
distributions := []any{document.JavaAuto, "any"}
for _, distribution := range java.Distributions {
distributions = append(distributions, string(distribution))
}
distribution := &jsonschema.Schema{
Enum: distributions,
Description: "The Java distribution. Omit it to accept any distribution.",
}
properties := orderedmap.New[string, *jsonschema.Schema]()
properties.Set("version", version)
properties.Set("distribution", distribution)
short := major()
short.Description = "The Java major version."
return &jsonschema.Schema{
OneOf: []*jsonschema.Schema{
short,
{
Const: document.JavaAuto,
Description: "Follow the Java version Mojang recommends.",
},
{
Type: "object",
Properties: properties,
AdditionalProperties: jsonschema.FalseSchema,
},
},
}
}()
r := &jsonschema.Reflector{
DoNotReference: true,
BaseSchemaID: jsonschema.ID(schemaURL),
Mapper: func(t reflect.Type) *jsonschema.Schema {
switch t {
case reflect.TypeFor[document.Requirement]():
return requirementSchema
case reflect.TypeFor[document.ManifestJava]():
return javaSchema
case reflect.TypeFor[document.TrackedFile]():
return trackedFileSchema
default:
return nil
}
},
}
schema := r.Reflect(&document.Manifest{})
schema.Version = jsonschema.Version
schema.ID = schemaURL
schema.Title = "Lucy manifest"
schema.Description = "Desired-state manifest (lucy.yaml) for a Lucy-managed Minecraft server."
raw, err := json.Marshal(schema, jsontext.Multiline(true), jsontext.WithIndent(" "))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
raw = append(raw, '\n')
path := "assets/public/manifest.schema.json"
if err := os.WriteFile(path, raw, 0o644); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("regenerated", path)
}
// Command genwiki renders the documentation site as GitHub wiki pages.
//
// GitHub wikis store every page as a flat Markdown file in one Git repository.
// The site navigation defines which pages exist and in what order; the page
// title defines the file name. Links between site pages are rewritten to the
// flat wiki page names.
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
)
const (
homeSlug = "Home"
docsSite = "https://lucy.lc/docs"
docsRepo = "https://github.com/mclucy/lucy/tree/main/docs"
)
type siteConfig struct {
Navigation struct {
Pages []jsontext.Value `json:"pages"`
} `json:"navigation"`
}
type section struct {
Name string
Paths []string
}
type page struct {
Path string
Title string
Description string
Slug string
Body string
}
func main() {
docsDir := flag.String("docs", "docs", "path to the documentation site directory")
outDir := flag.String("out", "dist/wiki", "output directory for wiki pages")
flag.Parse()
if err := run(*docsDir, *outDir); err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] generate wiki: %v\n", err)
os.Exit(1)
}
}
func run(docsDir, outDir string) error {
sections, err := readNavigation(filepath.Join(docsDir, "docs.json"))
if err != nil {
return err
}
pages, err := readPages(docsDir, sections)
if err != nil {
return err
}
links := make(map[string]string, len(pages))
for _, p := range pages {
links[p.Path] = p.Slug
}
for i := range pages {
body, err := render(pages[i].Body, links)
if err != nil {
return fmt.Errorf("%s: %w", pages[i].Path, err)
}
pages[i].Body = body
}
if err := os.MkdirAll(outDir, 0o755); err != nil {
return err
}
if err := removeStalePages(outDir); err != nil {
return err
}
for _, p := range pages {
if err := os.WriteFile(filepath.Join(outDir, p.Slug+".md"), []byte(renderPage(p)), 0o644); err != nil {
return err
}
}
if err := os.WriteFile(filepath.Join(outDir, "_Sidebar.md"), []byte(renderSidebar(sections, pages)), 0o644); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(outDir, "_Footer.md"), []byte(renderFooter()), 0o644); err != nil {
return err
}
return nil
}
func readNavigation(path string) ([]section, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg siteConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse %s: %w", path, err)
}
sections := []section{{}}
for _, raw := range cfg.Navigation.Pages {
var pagePath string
if err := json.Unmarshal(raw, &pagePath); err == nil {
sections[0].Paths = append(sections[0].Paths, pagePath)
continue
}
var group struct {
Group string `json:"group"`
Pages []string `json:"pages"`
}
if err := json.Unmarshal(raw, &group); err != nil {
return nil, fmt.Errorf("parse %s navigation entry: %w", path, err)
}
sections = append(sections, section{
Name: group.Group,
Paths: group.Pages,
})
}
return sections, nil
}
func readPages(docsDir string, sections []section) ([]page, error) {
var paths []string
for _, s := range sections {
paths = append(paths, s.Paths...)
}
if len(paths) == 0 {
return nil, errors.New("docs.json defines no pages")
}
pages := make([]page, 0, len(paths))
slugs := make(map[string]string, len(paths))
for _, p := range paths {
data, err := os.ReadFile(filepath.Join(docsDir, p+".mdx"))
if err != nil {
return nil, fmt.Errorf("read page %q: %w", p, err)
}
title, description, body, err := parseFrontmatter(string(data))
if err != nil {
return nil, fmt.Errorf("page %q: %w", p, err)
}
if title == "" {
return nil, fmt.Errorf("page %q has no title", p)
}
slug := homeSlug
if p != "index" {
slug = slugify(title)
}
if slug == "" {
return nil, fmt.Errorf("page %q title %q produces an empty file name", p, title)
}
if other, ok := slugs[slug]; ok {
return nil, fmt.Errorf("pages %q and %q both map to %s.md", other, p, slug)
}
slugs[slug] = p
pages = append(pages, page{
Path: p,
Title: title,
Description: description,
Slug: slug,
Body: body,
})
}
return pages, nil
}
func parseFrontmatter(src string) (title, description, body string, err error) {
src = strings.ReplaceAll(src, "\r\n", "\n")
if !strings.HasPrefix(src, "---\n") {
return "", "", "", errors.New("missing frontmatter")
}
rest := src[len("---\n"):]
index := strings.Index(rest, "\n---\n")
if index < 0 {
return "", "", "", errors.New("unterminated frontmatter")
}
for _, line := range strings.Split(rest[:index], "\n") {
key, value, ok := strings.Cut(line, ":")
if !ok {
continue
}
value = strings.TrimSpace(value)
if unquoted, err := strconv.Unquote(value); err == nil {
value = unquoted
}
switch strings.TrimSpace(key) {
case "title":
title = value
case "description":
description = value
}
}
return title, description, strings.TrimLeft(rest[index+len("\n---\n"):], "\n"), nil
}
var slugSeparators = regexp.MustCompile(`[^A-Za-z0-9]+`)
func slugify(title string) string {
return strings.Trim(slugSeparators.ReplaceAllString(title, "-"), "-")
}
func renderPage(p page) string {
var b strings.Builder
fmt.Fprintf(&b, "# %s\n", p.Title)
if p.Description != "" {
fmt.Fprintf(&b, "\n*%s*\n", p.Description)
}
b.WriteString("\n")
b.WriteString(strings.TrimRight(p.Body, "\n"))
b.WriteString("\n")
return b.String()
}
func renderSidebar(sections []section, pages []page) string {
byPath := make(map[string]page, len(pages))
for _, p := range pages {
byPath[p.Path] = p
}
var b strings.Builder
b.WriteString("<!-- Generated by tools/genwiki from docs/docs.json. Do not edit this wiki by hand. -->\n")
for _, s := range sections {
if len(s.Paths) == 0 {
continue
}
if s.Name != "" {
fmt.Fprintf(&b, "\n### %s\n\n", s.Name)
}
for _, path := range s.Paths {
p := byPath[path]
fmt.Fprintf(&b, "- [%s](%s)\n", p.Title, p.Slug)
}
}
return b.String()
}
func renderFooter() string {
return fmt.Sprintf("---\n\nGenerated from the [`docs/`](%s) directory. [Read the documentation site](%s).\n", docsRepo, docsSite)
}
func removeStalePages(dir string) error {
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
continue
}
if err := os.Remove(filepath.Join(dir, entry.Name())); err != nil {
return err
}
}
return nil
}
var (
componentOpen = regexp.MustCompile(`^<(Warning|Note|Tip|Important|Caution)>`)
componentClose = regexp.MustCompile(`^</(Warning|Note|Tip|Important|Caution)>$`)
stepOpen = regexp.MustCompile(`^<Step\s+title="([^"]*)">$`)
attribute = regexp.MustCompile(`([A-Za-z][A-Za-z0-9_-]*)(?:="([^"]*)")?`)
internalLink = regexp.MustCompile(`\]\((/[^)\s]*)\)`)
)
func render(body string, links map[string]string) (string, error) {
lines := strings.Split(body, "\n")
out := make([]string, 0, len(lines))
inFence := false
for i := 0; i < len(lines); i++ {
line := lines[i]
trimmed := strings.TrimSpace(line)
if inFence {
out = append(out, line)
if strings.HasPrefix(trimmed, "```") {
inFence = false
}
continue
}
if strings.HasPrefix(trimmed, "```") {
out = append(out, line)
inFence = true
continue
}
switch {
case componentOpen.MatchString(trimmed):
kind := strings.ToUpper(componentOpen.FindStringSubmatch(trimmed)[1])
if end := strings.Index(trimmed, "</"); end >= 0 {
inner := strings.TrimSpace(trimmed[len(componentOpen.FindStringSubmatch(trimmed)[0]):end])
out = appendAlert(out, kind, []string{inner})
continue
}
content, next, err := collectComponent(lines, i+1, "</"+componentOpen.FindStringSubmatch(trimmed)[1]+">")
if err != nil {
return "", err
}
out = appendAlert(out, kind, content)
i = next
case trimmed == "<Steps>" || trimmed == "</Steps>" || trimmed == "</Step>":
continue
case stepOpen.MatchString(trimmed):
title := stepOpen.FindStringSubmatch(trimmed)[1]
content, next, err := collectComponent(lines, i+1, "</Step>")
if err != nil {
return "", err
}
out = append(out, "", "### "+title, "")
out = append(out, dedent(trimBlank(content))...)
out = append(out, "")
i = next
case strings.HasPrefix(trimmed, "<ParamField "):
attrs := parseAttributes(strings.TrimSuffix(strings.TrimSuffix(trimmed, ">"), "/"))
content, next, err := collectComponent(lines, i+1, "</ParamField>")
if err != nil {
return "", err
}
out = append(out, "", renderParamField(attrs), "")
out = append(out, dedent(trimBlank(content))...)
out = append(out, "")
i = next
case strings.HasPrefix(trimmed, "<GitHub.Repo "):
repo := parseAttributes(trimmed)["repo"]
if repo == "" {
return "", fmt.Errorf("GitHub.Repo without repo at line %d", i+1)
}
out = append(out, "", fmt.Sprintf("[github.com/%s](https://github.com/%s)", repo, repo), "")
default:
if componentClose.MatchString(trimmed) {
return "", fmt.Errorf("unexpected %s at line %d", trimmed, i+1)
}
out = append(out, line)
}
}
text := strings.TrimLeft(strings.Join(out, "\n"), "\n")
text = normalizeBlankLines(text)
text = strings.TrimRight(text, "\n") + "\n"
return rewriteLinks(text, links)
}
func normalizeBlankLines(text string) string {
lines := strings.Split(text, "\n")
out := make([]string, 0, len(lines))
inFence := false
blank := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "```") {
inFence = !inFence
blank = false
out = append(out, line)
continue
}
if !inFence && trimmed == "" {
if blank {
continue
}
blank = true
out = append(out, "")
continue
}
blank = false
out = append(out, line)
}
return strings.Join(out, "\n")
}
func collectComponent(lines []string, start int, closeTag string) ([]string, int, error) {
for i := start; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == closeTag {
return lines[start:i], i, nil
}
}
return nil, 0, fmt.Errorf("missing %s", closeTag)
}
func appendAlert(out []string, kind string, content []string) []string {
content = dedent(trimBlank(content))
out = append(out, "", "> [!"+kind+"]")
for _, line := range content {
if line == "" {
out = append(out, ">")
continue
}
out = append(out, "> "+line)
}
return append(out, "")
}
func renderParamField(attrs map[string]string) string {
label := attrs["query"]
if label == "" {
label = attrs["path"]
}
parts := make([]string, 0, 3)
if kind := attrs["type"]; kind != "" {
parts = append(parts, kind)
}
if _, ok := attrs["required"]; ok {
parts = append(parts, "required")
}
if value, ok := attrs["default"]; ok {
parts = append(parts, "default: `"+value+"`")
}
line := "**`" + label + "`**"
if len(parts) > 0 {
line += " (" + strings.Join(parts, ", ") + ")"
}
return line
}
func parseAttributes(s string) map[string]string {
attrs := make(map[string]string)
for _, match := range attribute.FindAllStringSubmatch(s, -1) {
attrs[match[1]] = match[2]
}
return attrs
}
func dedent(lines []string) []string {
indent := -1
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
width := len(line) - len(strings.TrimLeft(line, " "))
if indent < 0 || width < indent {
indent = width
}
}
if indent <= 0 {
return lines
}
result := make([]string, len(lines))
for i, line := range lines {
if len(line) >= indent {
result[i] = line[indent:]
continue
}
result[i] = strings.TrimLeft(line, " ")
}
return result
}
func trimBlank(lines []string) []string {
lines = slices.Clone(lines)
for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
lines = lines[1:]
}
for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
lines = lines[:len(lines)-1]
}
return lines
}
func rewriteLinks(text string, links map[string]string) (string, error) {
lines := strings.Split(text, "\n")
inFence := false
var firstErr error
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if inFence {
if strings.HasPrefix(trimmed, "```") {
inFence = false
}
continue
}
if strings.HasPrefix(trimmed, "```") {
inFence = true
continue
}
if strings.Contains(line, "(") {
lines[i] = rewriteLineLinks(line, links, &firstErr)
}
}
if firstErr != nil {
return "", firstErr
}
return strings.Join(lines, "\n"), nil
}
func rewriteLineLinks(line string, links map[string]string, firstErr *error) string {
return internalLink.ReplaceAllStringFunc(line, func(match string) string {
target := strings.TrimSuffix(strings.TrimPrefix(match, "]("), ")")
path, anchor, hasAnchor := strings.Cut(target, "#")
key := strings.TrimPrefix(path, "/")
if key == "" {
key = "index"
}
slug, ok := links[key]
if !ok {
if *firstErr == nil {
*firstErr = fmt.Errorf("link target %q has no page in docs.json", target)
}
return match
}
if hasAnchor {
return "](" + slug + "#" + anchor + ")"
}
return "](" + slug + ")"
})
}
// Package curseforge provides functions to interact with CurseForge API.
//
// CurseForge identifies mods by numeric modId, not by slug. Slug resolution
// is done via the search endpoint with the slug query parameter.
//
// All API requests require an x-api-key header. The key is supplied once to
// New and never read from ambient global state.
package curseforge
import (
"context"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/upstream"
)
// Provider is one configured CurseForge API client. Every request it performs
// shares the network cache, logger, and API key it was constructed with.
type Provider struct {
network *cache.Client
logger *log.Logger
apiKey string
}
// New constructs a CurseForge provider over network, logger, and apiKey.
// Construction performs no network requests and decodes no key.
func New(
network *cache.Client,
logger *log.Logger,
apiKey string,
) *Provider {
return &Provider{
network: network,
logger: logger,
apiKey: strings.TrimSpace(apiKey),
}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderCurseForge
}
func (p *Provider) Search(
ctx context.Context,
q upstream.Query,
) (upstream.SearchResponse, error) {
// CurseForge exposes no client/server search facet; IncludeClient cannot
// be applied upstream and is left to post-filtering. An ecosystem that
// accepts more than one loader (Quilt accepts Fabric) needs one request
// per loader filter, merged by project identity.
search := searchResponse{}
seen := make(map[int32]bool)
for _, loaderType := range modLoaderTypes(q.FilterEcosystem) {
u := searchUrlForLoader(catalog.Name(q.Keyword), loaderType)
p.logger.Debug("searching via curseforge api: " + u)
var resp searchResponse
if err := p.get(ctx, u, &resp); err != nil {
return upstream.SearchResponse{}, err
}
for _, mod := range resp.Data {
if seen[mod.ID] {
continue
}
seen[mod.ID] = true
search.Data = append(search.Data, mod)
}
}
return search.ToSearchResults(p.Provider()), nil
}
func (p *Provider) Info(
ctx context.Context,
ref catalog.Ref,
) (catalog.Metadata, error) {
mod, err := p.resolveSlug(ctx, ref.Name)
if err != nil {
return catalog.Metadata{}, err
}
description, err := p.getModDescription(ctx, mod.ID)
if err != nil {
return catalog.Metadata{}, err
}
info := rawProjectInformation{
mod: mod, description: description,
}.ToProjectInformation()
return info, nil
}
package curseforge
import (
"context"
"strings"
"github.com/mclucy/lucy/upstream"
)
// Builds lists every file published by a CurseForge project. project accepts
// either a numeric mod ID or a slug. The list is unfiltered: no game version,
// loader, channel, availability flag, or download URL state is excluded.
func (p *Provider) Builds(
ctx context.Context,
project string,
) ([]upstream.Build, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
modID, err := p.resolveProjectID(ctx, project)
if err != nil {
return nil, err
}
files, err := p.listAllFiles(ctx, modID, "", 0)
if err != nil {
return nil, err
}
builds := make([]upstream.Build, len(files))
for i := range files {
gameVersions, loaders := splitGameVersions(files[i].GameVersions)
builds[i] = upstream.Build{
Version: files[i].DisplayName,
GameVersions: gameVersions,
Loaders: loaders,
Channel: string(curseForgeChannel(files[i].ChannelCode)),
Published: parseCurseforgeDate(files[i].FileDate),
}
}
return builds, nil
}
// curseForgeLoaderMarkers holds the loader names CurseForge mixes into a
// file's gameVersions list. Keys are the lowercase loader identifiers used by
// the other providers.
var curseForgeLoaderMarkers = map[string]struct{}{
"forge": {},
"cauldron": {},
"liteloader": {},
"fabric": {},
"quilt": {},
"neoforge": {},
"modloader": {},
"rift": {},
"bukkit": {},
"spigot": {},
"paper": {},
"purpur": {},
"folia": {},
"sponge": {},
"velocity": {},
"bungeecord": {},
"waterfall": {},
"travertine": {},
}
// splitGameVersions separates CurseForge's mixed gameVersions list into game
// versions and loader identifiers. Game versions start with a digit; loader
// markers are matched case-insensitively against the known loader names.
// Unrecognized markers are left out rather than being misreported as either.
func splitGameVersions(entries []string) (
gameVersions []string,
loaders []string,
) {
for _, entry := range entries {
trimmed := strings.TrimSpace(entry)
if trimmed == "" {
continue
}
lower := strings.ToLower(trimmed)
if _, ok := curseForgeLoaderMarkers[lower]; ok {
loaders = append(loaders, lower)
continue
}
if isGameVersion(trimmed) {
gameVersions = append(gameVersions, trimmed)
}
}
return gameVersions, loaders
}
func isGameVersion(s string) bool {
if s == "" {
return false
}
c := s[0]
return c >= '0' && c <= '9'
}
package curseforge
import (
"context"
"fmt"
"strconv"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
func (p *Provider) Candidates(ctx context.Context, project, minecraft string, loader catalog.Ecosystem) ([]upstream.Candidate, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
id, err := p.resolveProjectID(ctx, project)
if err != nil {
return nil, err
}
// Pagination is required: exact older files are not necessarily on page one.
// A Quilt request accepts both Quilt and Fabric files, so each loader
// filter is listed and the union is deduplicated by file identity.
var files []fileResponse
seen := make(map[int32]bool)
for _, loaderType := range modLoaderTypes(loader) {
page, err := p.listAllFiles(ctx, id, minecraft, loaderType)
if err != nil {
return nil, err
}
for _, f := range page {
if seen[f.ID] {
continue
}
seen[f.ID] = true
files = append(files, f)
}
}
var out []upstream.Candidate
for _, f := range files {
if f.DownloadUrl == nil {
continue
}
out = append(out, candidateFromCurseForgeFile(id, f))
}
if len(out) == 0 {
return nil, fmt.Errorf("curseforge project %s has no downloadable %s release for Minecraft %s", project, loader, minecraft)
}
return out, nil
}
// candidateFromCurseForgeFile converts one CurseForge file record into a
// candidate. The file is the primary file of its release. A null downloadUrl
// yields an empty URL; callers that need a downloadable candidate must skip
// such files beforehand.
func candidateFromCurseForgeFile(
modID int32,
f fileResponse,
) upstream.Candidate {
downloadURL := ""
if f.DownloadUrl != nil {
downloadURL = *f.DownloadUrl
}
hashes := map[string]string{}
for _, h := range f.Hashes {
if h.Algo == 1 {
hashes["sha1"] = h.Digest
}
}
c := upstream.Candidate{
Provider: catalog.ProviderCurseForge,
ProjectID: strconv.FormatInt(int64(modID), 10),
ReleaseID: strconv.Itoa(int(f.ID)),
FileID: strconv.Itoa(int(f.ID)),
Version: version.Version(f.DisplayName),
Filename: f.FileName,
URL: downloadURL,
Hashes: hashes,
Channel: curseForgeChannel(f.ChannelCode),
PublishedAt: parseCurseforgeDate(f.FileDate),
PrimaryFile: true,
Dependencies: []upstream.ProjectDependency{},
}
for _, d := range f.Dependencies {
var kind catalog.DependencyKind
switch d.RelationType {
case 3:
kind = catalog.DependencyKindRequired
case 2:
kind = catalog.DependencyKindOptional
case 5:
kind = catalog.DependencyKindIncompatible
}
if kind != catalog.DependencyKindUnknown {
c.Dependencies = append(c.Dependencies, upstream.ProjectDependency{
Provider: catalog.ProviderCurseForge,
ProjectID: strconv.Itoa(int(d.ModId)),
Kind: kind,
})
}
}
return c
}
package curseforge
import (
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/upstream"
)
// --- API response wrappers ---
// searchResponse wraps the CurseForge /v1/mods/search response.
type searchResponse struct {
Data []modResponse `json:"data"`
Pagination pagination `json:"pagination"`
}
func (s *searchResponse) ToSearchResults(source catalog.Provider) upstream.SearchResponse {
res := upstream.SearchResponse{
Provider: source,
Items: make([]upstream.SearchResult, 0, len(s.Data)),
}
for _, mod := range s.Data {
res.Items = append(
res.Items, upstream.SearchResult{
ProjectName: input.ToProjectName(mod.Slug).String(),
Provider: source,
Title: mod.Name,
Description: mod.Summary,
Downloads: mod.DownloadCount,
LastUpdated: parseCurseforgeDate(mod.DateModified),
},
)
}
return res
}
// parseCurseforgeDate parses CurseForge's RFC3339 timestamp.
// Returns zero time on failure or empty input.
func parseCurseforgeDate(s string) time.Time {
if s == "" {
return time.Time{}
}
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return time.Time{}
}
return t
}
// modDataResponse wraps /v1/mods/{modId} response.
type modDataResponse struct {
Data modResponse `json:"data"`
}
// modsDataResponse wraps the POST /v1/mods response. Unknown IDs are omitted.
type modsDataResponse struct {
Data []modResponse `json:"data"`
}
type stringDataResponse struct {
Data string `json:"data"`
}
// modResponse is the CurseForge Mod schema.
type modResponse struct {
ID int32 `json:"id"`
GameId int32 `json:"gameId"`
Name string `json:"name"`
Slug string `json:"slug"`
Links modLinks `json:"links"`
Summary string `json:"summary"`
Status int32 `json:"status"`
DownloadCount int64 `json:"downloadCount"`
IsFeatured bool `json:"isFeatured"`
CategoryID int32 `json:"primaryCategoryId"`
ClassId *int32 `json:"classId"`
Authors []modAuthor `json:"authors"`
Logo *modAsset `json:"logo"`
MainFileId int32 `json:"mainFileId"`
LatestFiles []fileResponse `json:"latestFiles"`
LatestFilesIndexes []fileIndex `json:"latestFilesIndexes"`
DateCreated string `json:"dateCreated"`
DateModified string `json:"dateModified"`
DateReleased string `json:"dateReleased"`
AllowModDistribution *bool `json:"allowModDistribution"`
GamePopularityRank int32 `json:"gamePopularityRank"`
IsAvailable bool `json:"isAvailable"`
ThumbsUpCount int32 `json:"thumbsUpCount"`
}
type rawProjectInformation struct {
mod *modResponse
description string
}
func (m *modResponse) ToProjectInformation() catalog.Metadata {
return rawProjectInformation{mod: m}.ToProjectInformation()
}
func (r rawProjectInformation) ToProjectInformation() catalog.Metadata {
m := r.mod
info := catalog.Metadata{
Title: m.Name,
Brief: m.Summary,
Description: r.description,
DescriptionIsMarkdown: upstream.LooksLikeMarkdown(r.description),
URLs: make([]catalog.URL, 0),
Authors: make([]catalog.Person, 0, len(m.Authors)),
}
if m.Links.WebsiteUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Website",
Type: catalog.URLHome,
URL: m.Links.WebsiteUrl,
},
)
}
if m.Links.WikiUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Wiki",
Type: catalog.URLWiki,
URL: m.Links.WikiUrl,
},
)
}
if m.Links.IssuesUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Issues",
Type: catalog.URLIssues,
URL: m.Links.IssuesUrl,
},
)
}
if m.Links.SourceUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Source",
Type: catalog.URLSource,
URL: m.Links.SourceUrl,
},
)
}
for _, author := range m.Authors {
info.Authors = append(
info.Authors, catalog.Person{
Name: author.Name,
URL: author.URL,
},
)
}
return info
}
type modLinks struct {
WebsiteUrl string `json:"websiteUrl"`
WikiUrl string `json:"wikiUrl"`
IssuesUrl string `json:"issuesUrl"`
SourceUrl string `json:"sourceUrl"`
}
type modAuthor struct {
ID int32 `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
}
type modAsset struct {
ID int32 `json:"id"`
ModId int32 `json:"modId"`
Title string `json:"title"`
Description string `json:"description"`
ThumbnailUrl string `json:"thumbnailUrl"`
URL string `json:"url"`
}
// --- File-level structs ---
// filesResponse wraps /v1/mods/{modId}/files response.
type filesResponse struct {
Data []fileResponse `json:"data"`
Pagination pagination `json:"pagination"`
}
// filesDataResponse wraps the POST /v1/mods/files response. Unknown IDs are
// omitted.
type filesDataResponse struct {
Data []fileResponse `json:"data"`
}
// fileResponse is the CurseForge File schema.
type fileResponse struct {
ID int32 `json:"id"`
GameId int32 `json:"gameId"`
ModId int32 `json:"modId"`
IsAvailable bool `json:"isAvailable"`
DisplayName string `json:"displayName"`
FileName string `json:"fileName"`
ChannelCode int32 `json:"releaseType"` // 1=Release, 2=Beta, 3=Alpha
FileStatus int32 `json:"fileStatus"`
Hashes []fileHash `json:"hashes"`
FileDate string `json:"fileDate"`
FileLength int64 `json:"fileLength"`
DownloadCount int64 `json:"downloadCount"`
// Docs: https://docs.curseforge.com/rest-api/#get-mod-files
DownloadUrl *string `json:"downloadUrl"` // CAN BE NULL
GameVersions []string `json:"gameVersions"`
Dependencies []fileDependency `json:"dependencies"`
IsServerPack *bool `json:"isServerPack"`
ServerPackFileId *int32 `json:"serverPackFileId"`
// FileFingerprint is the CurseForge MurmurHash used to correlate a file
// with the fingerprint that was looked up. A pointer keeps a present zero
// fingerprint distinct from an absent field.
FileFingerprint *int64 `json:"fileFingerprint"`
}
type fileHash struct {
Digest string `json:"value"`
Algo int32 `json:"algo"` // 1=Sha1, 2=Md5
}
type fileDependency struct {
ModId int32 `json:"modId"`
RelationType int32 `json:"relationType"` // 3=Required, 2=Optional, etc.
}
type fileIndex struct {
GameVersion string `json:"gameVersion"`
FileId int32 `json:"fileId"`
Filename string `json:"filename"`
ChannelCode int32 `json:"releaseType"`
GameVersionTypeId *int32 `json:"gameVersionTypeId"`
ModLoader *int32 `json:"modLoader"` // 0=Any, 1=Forge, 4=Fabric, 6=NeoForge
}
type pagination struct {
Index int32 `json:"index"`
PageSize int32 `json:"pageSize"`
ResultCount int32 `json:"resultCount"`
TotalCount int32 `json:"totalCount"`
}
package curseforge
import (
"errors"
"fmt"
)
type ApiResponseError struct {
StatusCode int
}
func (e ApiResponseError) Error() string {
return fmt.Sprintf("curseforge: API returned status %d", e.StatusCode)
}
// HTTPStatus reports the API status so lookup retry policy can classify the
// failure without parsing its message.
func (e ApiResponseError) HTTPStatus() int {
return e.StatusCode
}
var (
ErrProjectNotFound = errors.New("curseforge: project not found")
ErrAmbiguousSlug = errors.New("curseforge: ambiguous slug, multiple projects matched")
ErrNoApiKey = errors.New("curseforge: API key not configured")
ErrInvalidApiKey = errors.New("curseforge: API key rejected")
ErrApiResponse = func(statusCode int) error {
return ApiResponseError{StatusCode: statusCode}
}
)
package curseforge
import (
"context"
"errors"
"fmt"
"math"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
"github.com/mclucy/lucy/version"
)
// fingerprintRequest is the body for POST /v1/fingerprints/432.
type fingerprintRequest struct {
Fingerprints []uint32 `json:"fingerprints"`
}
// fingerprintMatch is one exact fingerprint match. The response's top-level
// ID is a project identity the official schema leaves unspecified, so matching
// correlates on the file's own fileFingerprint and takes project ownership
// from its modId.
type fingerprintMatch struct {
ID int32 `json:"id"`
File fileResponse `json:"file"`
}
// fingerprintResponse wraps the /v1/fingerprints/432 response.
// Verified against https://docs.curseforge.com/rest-api/#get-fingerprints-matches
// Only exactMatches are decoded: partial and fuzzy matches do not describe the
// exact artifact on disk and must never stand in for one.
type fingerprintResponse struct {
Data struct {
ExactMatches []fingerprintMatch `json:"exactMatches"`
} `json:"data"`
}
// ReleaseByHash identifies the installed artifact by its MurmurHash
// fingerprint and returns the release it was published as, in one lookup.
// A fingerprint with no exact match is a miss with no error.
func (p *Provider) ReleaseByHash(
ctx context.Context,
artifact upstream.ArtifactFingerprint,
) (
upstream.Release,
bool,
error,
) {
lookups := p.ReleasesByHash(
ctx,
[]upstream.ArtifactFingerprint{artifact},
)
result := lookups[0]
return result.Release, result.Matched, result.Err
}
// ReleasesByHash resolves every fingerprint into the release it was published
// as, returning one result per input in input order.
//
// Fingerprints are deduplicated and looked up in bounded batches, so identical
// inputs share one lookup and the number of requests does not grow with a
// project's file count. Only exact matches count. An unknown fingerprint is a
// miss, not an error. A transient batch failure is retried with backoff and
// then isolated by splitting the batch within a bounded split budget; a part
// that still fails is an error for every input it covered. A throttle that
// asks for a delay ends the lookup: no smaller batch, refetch, or project
// fan-out is sent before that delay passes. An exact match whose file or
// project details cannot be completed is an incomplete lookup, reported as an
// error rather than a miss.
func (p *Provider) ReleasesByHash(
ctx context.Context,
artifacts []upstream.ArtifactFingerprint,
) []upstream.ArtifactReleaseLookup {
results := make([]upstream.ArtifactReleaseLookup, len(artifacts))
if len(artifacts) == 0 {
return results
}
if err := ctx.Err(); err != nil {
for i := range results {
results[i].Err = err
}
return results
}
unique, indexByFingerprint := fingerprintIndex(artifacts, results)
files, throttle := p.exactFiles(ctx, unique, indexByFingerprint, results)
if throttle != nil {
// Matched files still need requests to become releases.
failFiles(results, indexByFingerprint, files, throttle)
return results
}
throttle = p.refetchIncompleteFiles(ctx, files, indexByFingerprint, results)
if throttle != nil {
failFiles(results, indexByFingerprint, files, throttle)
return results
}
p.fillReleases(ctx, files, indexByFingerprint, results)
return results
}
// fingerprintIndex computes every artifact fingerprint and records computation
// failures on their results. It returns the distinct fingerprints in first-seen
// order and maps each fingerprint to the input positions that asked for it.
func fingerprintIndex(
artifacts []upstream.ArtifactFingerprint,
results []upstream.ArtifactReleaseLookup,
) ([]uint32, map[uint32][]int) {
unique := make([]uint32, 0, len(artifacts))
indexByFingerprint := make(map[uint32][]int, len(artifacts))
for i, artifact := range artifacts {
fingerprint, err := artifact.MurmurHash()
if err != nil {
results[i].Err = err
continue
}
if _, ok := indexByFingerprint[fingerprint]; !ok {
unique = append(unique, fingerprint)
}
indexByFingerprint[fingerprint] = append(
indexByFingerprint[fingerprint],
i,
)
}
return unique, indexByFingerprint
}
// failFingerprints records one batch error for every input that asked for any
// of fingerprints.
func failFingerprints(
results []upstream.ArtifactReleaseLookup,
indexByFingerprint map[uint32][]int,
fingerprints []uint32,
err error,
) {
for _, fingerprint := range fingerprints {
failFingerprint(results, indexByFingerprint, fingerprint, err)
}
}
// failFingerprint records one error for every input that asked for fingerprint,
// naming the fingerprint so a shared batch failure stays correlated per input.
func failFingerprint(
results []upstream.ArtifactReleaseLookup,
indexByFingerprint map[uint32][]int,
fingerprint uint32,
err error,
) {
correlated := fmt.Errorf("fingerprint %d: %w", fingerprint, err)
for _, i := range indexByFingerprint[fingerprint] {
results[i].Err = correlated
}
}
// failMatchedFile records err for every input whose exact match resolved to
// fingerprints and drops those matches so they cannot produce a release. A
// matched artifact whose details cannot be completed is an incomplete lookup,
// not a clean miss.
func failMatchedFile(
results []upstream.ArtifactReleaseLookup,
indexByFingerprint map[uint32][]int,
files map[uint32]fileResponse,
fingerprints []uint32,
err error,
) {
for _, fingerprint := range fingerprints {
failFingerprint(results, indexByFingerprint, fingerprint, err)
delete(files, fingerprint)
}
}
// failFiles records err for every matched file and drops it, so a lookup that
// stops before its project fan-out reports an incomplete lookup instead of a
// clean miss.
func failFiles(
results []upstream.ArtifactReleaseLookup,
indexByFingerprint map[uint32][]int,
files map[uint32]fileResponse,
err error,
) {
for fingerprint := range files {
failFingerprint(results, indexByFingerprint, fingerprint, err)
delete(files, fingerprint)
}
}
// exactFiles resolves fingerprints through POST /v1/fingerprints/432 in
// bounded batches. A match is kept only when its wire fingerprint is in the
// uint32 fingerprint space, names a requested input, and the record carries
// file identity. A fingerprint the API omits stays a miss, unless the batch
// carries a match it cannot correlate: such a match proves the batch matched
// something, so any input it leaves undetermined is an incomplete lookup
// rather than a clean miss. A throttle ends the fan-out; the batches that were
// not sent report the same throttle instead of reaching the provider early.
func (p *Provider) exactFiles(
ctx context.Context,
fingerprints []uint32,
indexByFingerprint map[uint32][]int,
results []upstream.ArtifactReleaseLookup,
) (map[uint32]fileResponse, error) {
files := make(map[uint32]fileResponse, len(fingerprints))
// A request body independent of discovery order lets a repeated lookup
// reuse the cached response.
slices.Sort(fingerprints)
var throttle error
for batch := range slices.Chunk(fingerprints, lookupBatchSize) {
if throttle != nil {
failFingerprints(results, indexByFingerprint, batch, throttle)
continue
}
throttle = p.resolveFingerprintBatch(
ctx,
batch,
0,
indexByFingerprint,
results,
files,
)
}
return files, throttle
}
// resolveFingerprintBatch resolves one request's fingerprints into files. A
// batch that still fails after its retry budget is split in halves and retried
// per part, so one transient failure cannot mark every input unresolved.
// Permanent statuses, cancellation, and the split-depth budget end the split;
// only the inputs carried by a failed part report that error. A throttle stops
// the split without sending the sibling batch, and is returned so no later
// batch is requested either.
func (p *Provider) resolveFingerprintBatch(
ctx context.Context,
batch []uint32,
depth int,
indexByFingerprint map[uint32][]int,
results []upstream.ArtifactReleaseLookup,
files map[uint32]fileResponse,
) error {
matches, err := p.fingerprintMatches(ctx, batch)
partial := errors.Is(err, errPartialLookupResponse)
if err != nil && !partial {
if len(batch) > 1 &&
depth < retry.MaxSplitDepth &&
ctx.Err() == nil &&
retry.Splittable(err) {
middle := len(batch) / 2
throttle := p.resolveFingerprintBatch(
ctx,
batch[:middle],
depth+1,
indexByFingerprint,
results,
files,
)
if throttle != nil {
failFingerprints(
results,
indexByFingerprint,
batch[middle:],
throttle,
)
return throttle
}
return p.resolveFingerprintBatch(
ctx,
batch[middle:],
depth+1,
indexByFingerprint,
results,
files,
)
}
failFingerprints(results, indexByFingerprint, batch, err)
if retry.Throttled(err) {
return err
}
return nil
}
uncorrelated := 0
for _, match := range matches {
if match.File.FileFingerprint == nil {
if len(batch) == 1 {
failFingerprint(
results,
indexByFingerprint,
batch[0],
fmt.Errorf(
"curseforge: exact match for file %d has no fingerprint",
match.File.ID,
),
)
continue
}
uncorrelated++
continue
}
fingerprint, requested := match.requestedFingerprint(batch)
if !requested {
uncorrelated++
continue
}
if match.File.ID == 0 || match.File.ModId == 0 {
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: exact fingerprint match for file %d is missing file identity",
match.File.ID,
),
)
continue
}
if _, seen := files[fingerprint]; seen {
continue
}
files[fingerprint] = match.File
}
if uncorrelated == 0 {
return nil
}
// The batch matched at least one file, but this record cannot be tied
// to an input. Correlated matches stay matchable and inputs with a
// more specific error keep it; the rest are undetermined, not missing.
for _, fingerprint := range batch {
if _, matched := files[fingerprint]; matched {
continue
}
if indexes := indexByFingerprint[fingerprint]; len(indexes) > 0 &&
results[indexes[0]].Err != nil {
continue
}
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: %d exact matches in a batch of %d fingerprints cannot be correlated, so fingerprint %d is undetermined",
uncorrelated,
len(batch),
fingerprint,
),
)
}
return nil
}
// refetchIncompleteFiles replaces inline match records that lack release
// details with authoritative records from POST /v1/mods/files, batched by file
// ID. Once a refetch is required, an omitted, incomplete or contradictory
// authoritative record is an incomplete lookup for that input, never a
// fallback to partial inline data and never a clean miss. A throttle ends the
// fan-out; batches that were not sent report the same throttle.
func (p *Provider) refetchIncompleteFiles(
ctx context.Context,
files map[uint32]fileResponse,
indexByFingerprint map[uint32][]int,
results []upstream.ArtifactReleaseLookup,
) error {
fileIDs := make([]int32, 0, len(files))
fingerprintsByFileID := make(map[int32][]uint32, len(files))
for fingerprint, file := range files {
if file.completeForRelease() {
continue
}
if _, ok := fingerprintsByFileID[file.ID]; !ok {
fileIDs = append(fileIDs, file.ID)
}
fingerprintsByFileID[file.ID] = append(
fingerprintsByFileID[file.ID],
fingerprint,
)
}
// The request order must not depend on map iteration order.
slices.Sort(fileIDs)
var throttle error
for batch := range slices.Chunk(fileIDs, lookupBatchSize) {
if throttle != nil {
for _, fileID := range batch {
failMatchedFile(
results,
indexByFingerprint,
files,
fingerprintsByFileID[fileID],
throttle,
)
}
continue
}
throttle = p.refetchFileBatch(
ctx,
batch,
0,
fingerprintsByFileID,
files,
indexByFingerprint,
results,
)
}
return throttle
}
// refetchFileBatch replaces incomplete file records for one request batch. A
// failed batch is split and retried per part while its failure is transient
// and the split budget allows, so a permanent failure stays bounded and each
// input reports its own outcome. A throttle stops the split and returns the
// throttle so no later batch is requested.
func (p *Provider) refetchFileBatch(
ctx context.Context,
batch []int32,
depth int,
fingerprintsByFileID map[int32][]uint32,
files map[uint32]fileResponse,
indexByFingerprint map[uint32][]int,
results []upstream.ArtifactReleaseLookup,
) error {
authoritative, err := p.getModFilesByIds(ctx, batch)
if err != nil {
if len(batch) > 1 &&
depth < retry.MaxSplitDepth &&
ctx.Err() == nil &&
retry.Splittable(err) {
middle := len(batch) / 2
throttle := p.refetchFileBatch(
ctx,
batch[:middle],
depth+1,
fingerprintsByFileID,
files,
indexByFingerprint,
results,
)
if throttle != nil {
for _, fileID := range batch[middle:] {
failMatchedFile(
results,
indexByFingerprint,
files,
fingerprintsByFileID[fileID],
throttle,
)
}
return throttle
}
return p.refetchFileBatch(
ctx,
batch[middle:],
depth+1,
fingerprintsByFileID,
files,
indexByFingerprint,
results,
)
}
for _, fileID := range batch {
failMatchedFile(
results,
indexByFingerprint,
files,
fingerprintsByFileID[fileID],
err,
)
}
if retry.Throttled(err) {
return err
}
return nil
}
for _, fileID := range batch {
fingerprints := fingerprintsByFileID[fileID]
file, ok := authoritative[fileID]
if !ok {
failMatchedFile(
results,
indexByFingerprint,
files,
fingerprints,
fmt.Errorf(
"curseforge: exact file %d is missing from the mod files lookup",
fileID,
),
)
continue
}
if file.ModId == 0 {
failMatchedFile(
results,
indexByFingerprint,
files,
fingerprints,
fmt.Errorf(
"curseforge: file %d lookup returned no project identity",
fileID,
),
)
continue
}
for _, fingerprint := range fingerprints {
if file.FileFingerprint != nil &&
*file.FileFingerprint != int64(fingerprint) {
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: file %d has fingerprint %d, exact match reported %d",
fileID,
*file.FileFingerprint,
fingerprint,
),
)
delete(files, fingerprint)
continue
}
exactModID := files[fingerprint].ModId
if file.ModId != exactModID {
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: file %d belongs to mod %d, exact match reported mod %d",
fileID,
file.ModId,
exactModID,
),
)
delete(files, fingerprint)
continue
}
if !file.completeForRelease() {
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: file %d lookup returned incomplete release details",
fileID,
),
)
delete(files, fingerprint)
continue
}
files[fingerprint] = file
}
}
return nil
}
// fillReleases resolves each matched file's project through POST /v1/mods and
// converts the pair into a release. An exact match whose project the API omits
// is an incomplete lookup: the release has no project identity to name. A
// throttle stops the project fan-out without sending the batches that remain;
// releases already resolved from earlier batches are still returned.
func (p *Provider) fillReleases(
ctx context.Context,
files map[uint32]fileResponse,
indexByFingerprint map[uint32][]int,
results []upstream.ArtifactReleaseLookup,
) {
modIDs := make([]int32, 0, len(files))
seen := make(map[int32]struct{}, len(files))
for _, file := range files {
if _, ok := seen[file.ModId]; ok {
continue
}
seen[file.ModId] = struct{}{}
modIDs = append(modIDs, file.ModId)
}
// The request order must not depend on map iteration order.
slices.Sort(modIDs)
mods := make(map[int32]modResponse, len(modIDs))
modErrors := make(map[int32]error)
var throttle error
for batch := range slices.Chunk(modIDs, lookupBatchSize) {
if throttle != nil {
failModsBatch(batch, throttle, modErrors)
continue
}
throttle = p.resolveModsBatch(ctx, batch, 0, mods, modErrors)
}
for fingerprint, file := range files {
if err := modErrors[file.ModId]; err != nil {
failFingerprint(results, indexByFingerprint, fingerprint, err)
continue
}
mod, ok := mods[file.ModId]
if !ok {
if throttle != nil {
failFingerprint(
results,
indexByFingerprint,
fingerprint,
throttle,
)
continue
}
failFingerprint(
results,
indexByFingerprint,
fingerprint,
fmt.Errorf(
"curseforge: project %d is missing from the mods lookup for exact file %d",
file.ModId,
file.ID,
),
)
continue
}
release := p.releaseFromCurseForgeFile(&mod, &file)
for _, i := range indexByFingerprint[fingerprint] {
results[i] = upstream.ArtifactReleaseLookup{
Release: release,
Matched: true,
}
}
}
}
// failModsBatch records one error per project. The release pass correlates
// those errors with their fingerprints without scanning files for each batch.
func failModsBatch(batch []int32, err error, modErrors map[int32]error) {
for _, modID := range batch {
modErrors[modID] = err
}
}
// resolveModsBatch resolves one request's projects. A transient failure is
// split and retried per part while the split budget allows, so one transient
// response does not discard every file in the batch; a permanent failure ends
// the split and reports only the inputs that part carried. A throttle stops
// the split and is returned so no later batch is requested.
func (p *Provider) resolveModsBatch(
ctx context.Context,
batch []int32,
depth int,
mods map[int32]modResponse,
modErrors map[int32]error,
) error {
found, err := p.getModsByIds(ctx, batch)
if err != nil {
if len(batch) > 1 &&
depth < retry.MaxSplitDepth &&
ctx.Err() == nil &&
retry.Splittable(err) {
middle := len(batch) / 2
throttle := p.resolveModsBatch(
ctx,
batch[:middle],
depth+1,
mods,
modErrors,
)
if throttle != nil {
failModsBatch(batch[middle:], throttle, modErrors)
return throttle
}
return p.resolveModsBatch(
ctx,
batch[middle:],
depth+1,
mods,
modErrors,
)
}
failModsBatch(batch, err, modErrors)
if retry.Throttled(err) {
return err
}
return nil
}
for _, mod := range found {
mods[mod.ID] = mod
}
return nil
}
// fingerprintMatches returns CurseForge's exact matches for a sorted batch.
// A 404 reports an empty match set. A partial result must be correlated per input.
// Docs: https://docs.curseforge.com/rest-api/#get-fingerprints-matches
func (p *Provider) fingerprintMatches(
ctx context.Context,
fingerprints []uint32,
) ([]fingerprintMatch, error) {
if len(fingerprints) == 0 {
return nil, nil
}
u := fmt.Sprintf("%s/v1/fingerprints/%d", baseUrl, minecraftGameId)
var resp fingerprintResponse
err := p.readPost(
ctx,
u,
fingerprintRequest{Fingerprints: fingerprints},
&resp,
func(resp *fingerprintResponse) error {
if resp.Data.ExactMatches == nil {
return fmt.Errorf("curseforge: fingerprint response has no exactMatches array")
}
for _, match := range resp.Data.ExactMatches {
if _, requested := match.requestedFingerprint(fingerprints); !requested ||
match.File.ID == 0 || match.File.ModId == 0 {
return errPartialLookupResponse
}
}
return nil
},
)
if err != nil {
if errors.Is(err, errPartialLookupResponse) {
return resp.Data.ExactMatches, err
}
if isNotFound(err) {
return nil, nil
}
return nil, err
}
return resp.Data.ExactMatches, nil
}
func (m *fingerprintMatch) requestedFingerprint(sorted []uint32) (uint32, bool) {
wire := m.File.FileFingerprint
if wire == nil || *wire < 0 || *wire > math.MaxUint32 {
return 0, false
}
fingerprint := uint32(*wire)
_, requested := slices.BinarySearch(sorted, fingerprint)
return fingerprint, requested
}
// releaseFromCurseForgeFile converts a project and one of its exact files into
// the release the file was published as.
func (p *Provider) releaseFromCurseForgeFile(
mod *modResponse,
file *fileResponse,
) upstream.Release {
gameVersions, loaders := splitGameVersions(file.GameVersions)
return upstream.Release{
Ref: catalog.VersionedRef{
Name: catalog.Name(mod.Slug),
Provider: p.Provider(),
Ecosystem: platformFromCurseForgeFile(mod, file),
Version: version.Version(file.DisplayName),
},
Candidate: candidateFromCurseForgeFile(mod.ID, *file),
MinecraftVersions: gameVersions,
Loaders: loaders,
}
}
func platformFromCurseForgeFile(
mod *modResponse,
file *fileResponse,
) catalog.Ecosystem {
for _, idx := range mod.LatestFilesIndexes {
if idx.FileId == file.ID && idx.ModLoader != nil {
return platformFromCurseForgeModLoader(*idx.ModLoader)
}
}
return catalog.EcosystemUnspecified
}
func platformFromCurseForgeModLoader(loader int32) catalog.Ecosystem {
for ecosystem, loaderType := range curseForgeLoaderTypes {
if int32(loaderType) == loader {
return ecosystem
}
}
return catalog.EcosystemUnspecified
}
package curseforge
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
)
// Docs: https://docs.curseforge.com/rest-api/
const baseUrl = "https://api.curseforge.com"
// maxLookupResponseBytes bounds one batched lookup response. CurseForge
// documents no cap on request arrays; lookupBatchSize bounds them here, so a
// response stays bounded even when a project carries many files.
const maxLookupResponseBytes = 16 << 20
// get performs an authenticated GET request to the CurseForge API and
// unmarshals the JSON response into dest.
func (p *Provider) get(ctx context.Context, url string, dest any) error {
if p.apiKey == "" {
return ErrNoApiKey
}
p.logger.Debug("curseforge api: GET " + url)
headers := http.Header{}
headers.Set("x-api-key", p.apiKey)
headers.Set("Accept", "application/json")
res, err := p.network.CachedGetRequest(
ctx,
url,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
Headers: headers,
},
)
if attempt := lookupAttempt(res, err); attempt.Status != http.StatusOK {
return lookupOutcome(attempt)
}
if err != nil {
return fmt.Errorf("curseforge: request failed: %w", err)
}
if err := json.Unmarshal(res.Data, dest); err != nil {
return fmt.Errorf("curseforge: failed to parse response: %w", err)
}
return nil
}
// readPost performs an authenticated read-only JSON POST lookup to the
// CurseForge API and unmarshals a 200 response into dest. Successful responses
// are cached by URL, body, and credential. Transient statuses are retried with
// bounded backoff. A final non-200 status is returned as ApiResponseError so
// callers can tell a missing resource (404) from a failed lookup.
//
// Only lookups may use it. A request that mutates remote state must go through
// the transport directly so a repeated attempt cannot repeat the mutation.
//
// validate may reject decoded data before cache publication. A rejected
// response still reaches dest so callers can handle a partial lookup.
func (p *Provider) readPost[T any](
ctx context.Context,
url string,
payload any,
dest *T,
validate func(*T) error,
) error {
if p.apiKey == "" {
return retry.Permanent(ErrNoApiKey)
}
body, err := json.Marshal(payload)
if err != nil {
return retry.Permanent(
fmt.Errorf("curseforge: failed to encode request: %w", err),
)
}
headers := http.Header{}
headers.Set("x-api-key", p.apiKey)
headers.Set("Content-Type", "application/json")
headers.Set("Accept", "application/json")
p.logger.Debug("curseforge api: POST " + url)
outcome := retry.Do(ctx, retry.Default, func(ctx context.Context) retry.Attempt {
res, err := p.network.CachedPostRequest(
ctx,
url,
body,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
Headers: headers,
MaxBytes: maxLookupResponseBytes,
},
func(raw []byte) error {
var decoded T
if err := json.Unmarshal(raw, &decoded); err != nil {
return retry.Permanent(fmt.Errorf("curseforge: failed to parse response: %w", err))
}
*dest = decoded
if validate != nil {
if err := validate(dest); err != nil {
return retry.Permanent(err)
}
}
return nil
},
)
if res != nil && res.StatusCode != http.StatusOK {
p.logger.Debug(
fmt.Sprintf(
"curseforge api: POST %s returned status %d",
url,
res.StatusCode,
),
)
}
return lookupAttempt(res, err)
})
return lookupOutcome(outcome)
}
// errPartialLookupResponse prevents caching a decoded response while letting
// its caller report outcomes for each input, including any usable matches.
var errPartialLookupResponse = errors.New("curseforge: partial lookup response")
// lookupAttempt retains the response status and retry headers even when
// reading a non-2xx body failed, so the status still classifies the failure.
func lookupAttempt(res *cache.BytesResponse, err error) retry.Attempt {
attempt := retry.Attempt{Err: err}
if res != nil {
attempt.Status = res.StatusCode
attempt.RetryAfter = retry.RetryAfter(res.Header)
}
return attempt
}
// lookupOutcome converts a finished lookup. A non-200 status that asked for a
// delay becomes a ThrottledError so no smaller batch or later request is sent
// before it passes. A final non-200 status keeps its meaning, so a 404 still
// reads as a missing resource rather than a read failure, and any body read
// failure stays in the error chain as diagnostics.
func lookupOutcome(outcome retry.Attempt) error {
if outcome.Status == 0 {
if outcome.Err == nil {
return fmt.Errorf("curseforge: lookup returned no response")
}
return fmt.Errorf("curseforge: request failed: %w", outcome.Err)
}
if outcome.Status != http.StatusOK {
var statusErr error
if retry.TransientStatus(outcome.Status) && outcome.RetryAfter > 0 {
statusErr = &retry.ThrottledError{
Status: outcome.Status,
RetryAfter: outcome.RetryAfter,
}
} else {
statusErr = ErrApiResponse(outcome.Status)
}
if outcome.Err != nil {
return errors.Join(statusErr, outcome.Err)
}
return statusErr
}
if outcome.Err != nil {
return fmt.Errorf("curseforge: request failed: %w", outcome.Err)
}
return nil
}
// isNotFound reports whether err is an API 404 response.
func isNotFound(err error) bool {
var apiErr ApiResponseError
return errors.As(err, &apiErr) &&
apiErr.StatusCode == http.StatusNotFound
}
package curseforge
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/upstream"
)
var (
ErrNotModpack = errors.New("curseforge: project is not a modpack")
ErrInvalidFileID = errors.New("curseforge: version must be a numeric file ID")
ErrNoServerPack = errors.New("curseforge: file has no server pack")
ErrFileUnavailable = errors.New("curseforge: file is not available for download")
)
// ResolveImportPack resolves a CurseForge modpack and an optional file
// selector to the server pack of that file. project accepts a numeric mod ID
// or a slug. version is a numeric file ID; an empty version selects the newest
// available release file, preferring the release channel.
func (p *Provider) ResolveImportPack(
ctx context.Context,
project, version string,
) (upstream.ImportPack, error) {
if err := ctx.Err(); err != nil {
return upstream.ImportPack{}, err
}
mod, err := p.resolveModpack(ctx, project)
if err != nil {
return upstream.ImportPack{}, err
}
selected, err := p.selectModpackFile(ctx, mod, version)
if err != nil {
return upstream.ImportPack{}, err
}
serverPack, err := p.serverPackFor(ctx, mod.ID, selected)
if err != nil {
return upstream.ImportPack{}, err
}
downloadLink, ok := downloadableURL(serverPack)
if !ok {
return upstream.ImportPack{}, fmt.Errorf(
"%w: server pack %q of %s",
ErrFileUnavailable,
serverPack.FileName,
mod.Slug,
)
}
return upstream.ImportPack{
Provider: catalog.ProviderCurseForge,
Project: mod.Slug,
Name: mod.Name,
Version: selected.DisplayName,
Filename: serverPack.FileName,
URL: downloadLink,
Hashes: fileSHA1Hashes(serverPack.Hashes),
}, nil
}
// resolveModpack resolves project to a mod in the modpack class. A numeric
// project is a mod ID; anything else is a slug.
func (p *Provider) resolveModpack(
ctx context.Context,
project string,
) (*modResponse, error) {
var (
mod *modResponse
err error
)
if id, parseErr := strconv.ParseInt(project, 10, 32); parseErr == nil {
mod, err = p.getModById(ctx, int32(id))
} else {
mod, err = p.resolveModpackSlug(ctx, catalog.Name(project))
}
if err != nil {
return nil, err
}
if mod.ClassId == nil || *mod.ClassId != modpacksClassId {
return nil, fmt.Errorf("%w: %s", ErrNotModpack, mod.Slug)
}
return mod, nil
}
// resolveModpackSlug looks up a modpack by slug within the modpack class. It
// mirrors resolveSlug, which searches the mod class only.
func (p *Provider) resolveModpackSlug(
ctx context.Context,
slug catalog.Name,
) (*modResponse, error) {
var resp searchResponse
if err := p.get(ctx, slugSearchUrlForClass(slug, modpacksClassId), &resp); err != nil {
return nil, err
}
if len(resp.Data) == 0 {
return nil, ErrProjectNotFound
}
if len(resp.Data) == 1 {
return &resp.Data[0], nil
}
for i := range resp.Data {
if input.ToProjectName(resp.Data[i].Slug) == slug {
return &resp.Data[i], nil
}
}
return nil, ErrAmbiguousSlug
}
// selectModpackFile returns the file an import is based on: the file named by
// version when set, otherwise the newest available release file.
func (p *Provider) selectModpackFile(
ctx context.Context,
mod *modResponse,
version string,
) (*fileResponse, error) {
if version != "" {
id, err := strconv.ParseInt(version, 10, 32)
if err != nil {
return nil, fmt.Errorf("%w: %q", ErrInvalidFileID, version)
}
file, err := p.getModFileById(ctx, mod.ID, int32(id))
if err != nil {
return nil, err
}
if file.ModId != mod.ID {
return nil, fmt.Errorf(
"curseforge: file %d does not belong to %s",
id,
mod.Slug,
)
}
return file, nil
}
files, err := p.listAllFiles(ctx, mod.ID, "", 0)
if err != nil {
return nil, err
}
file := newestReleaseFile(files)
if file == nil {
return nil, fmt.Errorf("%w: %s has no available files", ErrFileUnavailable, mod.Slug)
}
return file, nil
}
// newestReleaseFile returns the newest available file, preferring release
// channel files over beta and alpha ones. Newest means the latest FileDate,
// with the higher file ID breaking ties. It returns nil when no file is
// available.
func newestReleaseFile(files []fileResponse) *fileResponse {
var best *fileResponse
for i := range files {
f := &files[i]
if !f.IsAvailable {
continue
}
if best == nil || fileRanksAbove(f, best) {
best = f
}
}
return best
}
func fileRanksAbove(a, b *fileResponse) bool {
aRelease := curseForgeChannel(a.ChannelCode) == upstream.ReleaseChannelRelease
bRelease := curseForgeChannel(b.ChannelCode) == upstream.ReleaseChannelRelease
if aRelease != bRelease {
return aRelease
}
aDate := parseCurseforgeDate(a.FileDate)
bDate := parseCurseforgeDate(b.FileDate)
if !aDate.Equal(bDate) {
return aDate.After(bDate)
}
return a.ID > b.ID
}
// serverPackFor returns the server pack for file: the file itself when it is
// a server pack, otherwise the file named by its serverPackFileId.
func (p *Provider) serverPackFor(
ctx context.Context,
modID int32,
file *fileResponse,
) (*fileResponse, error) {
if file.IsServerPack != nil && *file.IsServerPack {
return file, nil
}
if file.ServerPackFileId == nil {
return nil, fmt.Errorf(
"%w: file %q; choose a file ID whose release ships a server pack",
ErrNoServerPack,
file.DisplayName,
)
}
return p.getModFileById(ctx, modID, *file.ServerPackFileId)
}
// downloadableURL returns the file's download URL when the file is available
// and publishes one.
func downloadableURL(f *fileResponse) (string, bool) {
if !f.IsAvailable || f.DownloadUrl == nil || *f.DownloadUrl == "" {
return "", false
}
return *f.DownloadUrl, true
}
// fileSHA1Hashes returns the file's SHA-1 digest under the "sha1" key.
func fileSHA1Hashes(hashes []fileHash) map[string]string {
out := map[string]string{}
for _, h := range hashes {
if h.Algo == 1 && h.Digest != "" {
out["sha1"] = h.Digest
}
}
return out
}
package curseforge
import "github.com/mclucy/lucy/upstream"
// curseForgeChannel maps the CurseForge releaseType enum (1=Release,
// 2=Beta, 3=Alpha) to a typed release channel.
func curseForgeChannel(releaseType int32) upstream.ReleaseChannel {
switch releaseType {
case 1:
return upstream.ReleaseChannelRelease
case 2:
return upstream.ReleaseChannelBeta
case 3:
return upstream.ReleaseChannelAlpha
default:
return upstream.ReleaseChannelUnknown
}
}
package curseforge
import (
"context"
"strconv"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
)
// lookupBatchSize bounds one array-lookup request. CurseForge documents no cap
// for these arrays; a fixed batch keeps each response inside
// maxLookupResponseBytes and makes the request count independent of how many
// files a project publishes.
const lookupBatchSize = 100
// resolveProjectID resolves a project identity to a CurseForge mod ID. A
// numeric string is treated as an ID; anything else is resolved as a slug.
func (p *Provider) resolveProjectID(
ctx context.Context,
project string,
) (int32, error) {
if id, err := strconv.ParseInt(project, 10, 32); err == nil {
return int32(id), nil
}
mod, err := p.resolveSlug(ctx, catalog.Name(project))
if err != nil {
return 0, err
}
return mod.ID, nil
}
// resolveSlug resolves a project slug to its mod data. CurseForge has no
// get-by-slug endpoint, so it searches by slug and requires an exact match.
// Docs: https://docs.curseforge.com/rest-api/#search-mods
func (p *Provider) resolveSlug(
ctx context.Context,
slug catalog.Name,
) (*modResponse, error) {
u := slugSearchUrl(slug)
var resp searchResponse
if err := p.get(ctx, u, &resp); err != nil {
return nil, err
}
if len(resp.Data) == 0 {
return nil, ErrProjectNotFound
}
if len(resp.Data) == 1 {
return &resp.Data[0], nil
}
for i := range resp.Data {
if input.ToProjectName(resp.Data[i].Slug) == slug {
return &resp.Data[i], nil
}
}
return nil, ErrAmbiguousSlug
}
// Docs: https://docs.curseforge.com/rest-api/#get-mod
func (p *Provider) getModById(
ctx context.Context,
modId int32,
) (*modResponse, error) {
u := modUrl(modId)
var resp modDataResponse
if err := p.get(ctx, u, &resp); err != nil {
return nil, err
}
return &resp.Data, nil
}
// getModsByIds returns many projects in one POST /v1/mods request. Projects
// the API does not know are omitted; a 404 response means the same, not a
// failed lookup. Every returned project's ID is its own identity.
// Docs: https://docs.curseforge.com/rest-api/#get-mods
func (p *Provider) getModsByIds(
ctx context.Context,
modIDs []int32,
) ([]modResponse, error) {
if len(modIDs) == 0 {
return nil, nil
}
payload := struct {
ModIds []int32 `json:"modIds"`
}{ModIds: modIDs}
var resp modsDataResponse
if err := p.readPost(ctx, baseUrl+"/v1/mods", payload, &resp, nil); err != nil {
if isNotFound(err) {
return nil, nil
}
return nil, err
}
return resp.Data, nil
}
func (p *Provider) getModDescription(
ctx context.Context,
modId int32,
) (string, error) {
u := modDescriptionUrl(modId, true)
var resp stringDataResponse
if err := p.get(ctx, u, &resp); err != nil {
return "", err
}
return resp.Data, nil
}
package curseforge
import (
"fmt"
"net/url"
"slices"
"strconv"
"github.com/mclucy/lucy/catalog"
)
const (
minecraftGameId = 432
modsClassId = 6
modpacksClassId = 4471
)
// curseForgeLoaderTypes maps a lucy ecosystem to the CurseForge ModLoaderType
// enum. An ecosystem absent from the table searches every loader.
// Docs: https://docs.curseforge.com/rest-api/#search-mods
var curseForgeLoaderTypes = map[catalog.Ecosystem]int{
catalog.EcosystemForge: 1,
catalog.EcosystemFabric: 4,
catalog.EcosystemQuilt: 5,
catalog.EcosystemNeoForge: 6,
}
// modLoaderType maps a lucy ecosystem to its CurseForge ModLoaderType enum.
func modLoaderType(p catalog.Ecosystem) int {
return curseForgeLoaderTypes[p]
}
// modLoaderTypes lists the loader filters that serve a runtime of p, in
// descriptor precedence order. A runtime that loads more than one ecosystem
// (Quilt loads Fabric) needs one request per distinct enum value; the REST
// filter takes one value per request, so callers union the results. Any
// runtime without a mapped loader yields exactly one unfiltered request.
func modLoaderTypes(p catalog.Ecosystem) []int {
loaders := p.Loads()
if len(loaders) == 0 {
return []int{0}
}
types := make([]int, 0, len(loaders))
for _, loader := range loaders {
loaderType := modLoaderType(loader)
if slices.Contains(types, loaderType) {
continue
}
types = append(types, loaderType)
}
return types
}
// searchUrl builds a project search: https://docs.curseforge.com/rest-api/#search-mods.
func searchUrl(
query catalog.Name,
ecosystem catalog.Ecosystem,
) string {
return searchUrlForLoader(query, modLoaderType(ecosystem))
}
// searchUrlForLoader builds a project search constrained to one CurseForge
// loader type. A zero loader type searches every loader.
func searchUrlForLoader(query catalog.Name, loader int) string {
params := url.Values{}
params.Set("gameId", fmt.Sprintf("%d", minecraftGameId))
params.Set("classId", fmt.Sprintf("%d", modsClassId))
params.Set("searchFilter", string(query))
// sortField=2 maps to Popularity in CurseForge ModsSearchSortField enum;
// sortOrder=desc is its required direction. See Docs link above.
params.Set("sortField", "2")
params.Set("sortOrder", "desc")
params.Set("pageSize", "50")
if loader != 0 {
params.Set("modLoaderType", fmt.Sprintf("%d", loader))
}
return baseUrl + "/v1/mods/search?" + params.Encode()
}
// slugSearchUrl builds a mod slug lookup: https://docs.curseforge.com/rest-api/#search-mods.
func slugSearchUrl(slug catalog.Name) string {
return slugSearchUrlForClass(slug, modsClassId)
}
// slugSearchUrlForClass builds a slug lookup constrained to one CurseForge
// class: https://docs.curseforge.com/rest-api/#search-mods.
func slugSearchUrlForClass(slug catalog.Name, classId int) string {
params := url.Values{}
params.Set("gameId", fmt.Sprintf("%d", minecraftGameId))
params.Set("classId", fmt.Sprintf("%d", classId))
params.Set("slug", string(slug))
params.Set("pageSize", "50")
return baseUrl + "/v1/mods/search?" + params.Encode()
}
// modUrl builds a project lookup: https://docs.curseforge.com/rest-api/#get-mod.
func modUrl(modId int32) string {
return fmt.Sprintf("%s/v1/mods/%d", baseUrl, modId)
}
// modDescriptionUrl builds a description request: https://docs.curseforge.com/rest-api/#get-mod-description.
func modDescriptionUrl(modId int32, stripped bool) string {
params := url.Values{}
if stripped {
params.Set("stripped", "true")
}
u := fmt.Sprintf("%s/v1/mods/%d/description", baseUrl, modId)
if len(params) == 0 {
return u
}
return u + "?" + params.Encode()
}
// modFilesUrl builds a file-list request: https://docs.curseforge.com/rest-api/#get-mod-files.
func modFilesUrl(modId int32, gameVersion string, loaderType int) string {
params := url.Values{}
params.Set("pageSize", strconv.Itoa(modFilesPageSize))
if gameVersion != "" {
params.Set("gameVersion", gameVersion)
}
if loaderType != 0 {
params.Set("modLoaderType", fmt.Sprintf("%d", loaderType))
}
return fmt.Sprintf(
"%s/v1/mods/%d/files?%s",
baseUrl,
modId,
params.Encode(),
)
}
// modFileURL builds a file lookup: https://docs.curseforge.com/rest-api/#get-mod-file.
func modFileURL(modId, fileId int32) string {
return fmt.Sprintf("%s/v1/mods/%d/files/%d", baseUrl, modId, fileId)
}
package curseforge
import (
"context"
"errors"
"strconv"
)
const modFilesPageSize = 50
// listAllFiles pages through every file of a mod for the given compatibility
// filter. An empty gameVersion and zero loaderType list all files unfiltered.
func (p *Provider) listAllFiles(
ctx context.Context,
modID int32,
gameVersion string,
loaderType int,
) ([]fileResponse, error) {
var files []fileResponse
for offset := 0; ; offset += modFilesPageSize {
u := modFilesUrl(modID, gameVersion, loaderType) +
"&index=" + strconv.Itoa(offset)
var page filesResponse
if err := p.get(ctx, u, &page); err != nil {
return nil, err
}
files = append(files, page.Data...)
if len(page.Data) < modFilesPageSize {
break
}
if page.Pagination.TotalCount > 0 &&
int32(len(files)) >= page.Pagination.TotalCount {
break
}
}
return files, nil
}
type modFileDataResponse struct {
Data fileResponse `json:"data"`
}
func (p *Provider) getModFileById(
ctx context.Context,
modId, fileId int32,
) (*fileResponse, error) {
u := modFileURL(modId, fileId)
var resp modFileDataResponse
if err := p.get(ctx, u, &resp); err != nil {
return nil, err
}
return &resp.Data, nil
}
// getModFilesByIds returns many files in one POST /v1/mods/files request.
// An omitted file is left out of the result so the caller can report an error
// for that file. Responses that omit requested files are not cached.
// Docs: https://docs.curseforge.com/rest-api/#get-files
func (p *Provider) getModFilesByIds(
ctx context.Context,
fileIDs []int32,
) (map[int32]fileResponse, error) {
if len(fileIDs) == 0 {
return nil, nil
}
payload := struct {
FileIds []int32 `json:"fileIds"`
}{FileIds: fileIDs}
var resp filesDataResponse
var files map[int32]fileResponse
err := p.readPost(
ctx,
baseUrl+"/v1/mods/files",
payload,
&resp,
func(resp *filesDataResponse) error {
files = make(map[int32]fileResponse, len(resp.Data))
for _, file := range resp.Data {
files[file.ID] = file
}
for _, fileID := range fileIDs {
if _, ok := files[fileID]; !ok {
return errPartialLookupResponse
}
}
return nil
},
)
if err != nil && !errors.Is(err, errPartialLookupResponse) {
if isNotFound(err) {
return nil, nil
}
return nil, err
}
return files, nil
}
// hasSHA1 reports whether the file record carries a SHA-1 digest.
func (f fileResponse) hasSHA1() bool {
for _, h := range f.Hashes {
if h.Algo == 1 && h.Digest != "" {
return true
}
}
return false
}
// completeForRelease reports whether an inline file record already carries the
// identity and release details a release conversion needs. An incomplete
// record is refetched through POST /v1/mods/files, which returns the
// authoritative file schema.
func (f fileResponse) completeForRelease() bool {
return f.ID != 0 && f.ModId != 0 && f.DisplayName != "" &&
f.FileName != "" && f.hasSHA1() && len(f.GameVersions) > 0
}
package forge
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/url"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
const (
docsURL = "https://files.minecraftforge.net/"
promotionsURL = "https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json"
mavenBaseURL = "https://maven.minecraftforge.net/net/minecraftforge/forge"
neoForgeComparisonURL = "https://docs.neoforged.net/user/docs/server"
)
// Provider resolves Forge promotions and installer artifacts over the shared
// network cache.
type Provider struct {
network *cache.Client
}
// New constructs a Forge installer provider. network supplies the cached HTTP
// transport; construction performs no requests.
func New(network *cache.Client) *Provider {
return &Provider{network: network}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderForge
}
type promotions struct {
Promos map[string]string `json:"promos"`
}
// LatestMinecraftVersion reports the newest Minecraft version the promotions
// list a build for. Forge publishes release builds only.
func (p *Provider) LatestMinecraftVersion(ctx context.Context) (
version.Version,
error,
) {
body, err := p.network.CachedGetBytes(
ctx,
promotionsURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return "", fmt.Errorf("fetch forge promotions failed: %w", err)
}
var data promotions
if err := json.Unmarshal(body, &data); err != nil {
return "", fmt.Errorf("parse forge promotions failed: %w", err)
}
versions := make([]version.Version, 0, len(data.Promos))
for key := range data.Promos {
minecraft, _, found := strings.Cut(key, "-")
if found && minecraft != "" {
versions = append(versions, version.Version(minecraft))
}
}
return version.NewestMinecraft(versions)
}
func (p *Provider) Fetch(
ctx context.Context,
minecraft version.Version,
id catalog.VersionedRef,
) (upstream.ResolvedPackage, error) {
gameVersion, err := minecraftVersionForInstall(minecraft)
if err != nil {
return upstream.ResolvedPackage{}, err
}
forgeVersion, err := p.forgeVersionFromPackageRef(ctx, id, gameVersion)
if err != nil {
return upstream.ResolvedPackage{}, err
}
fileURL := installerURL(gameVersion, forgeVersion)
return upstream.ResolvedPackage{
FileURL: fileURL,
Filename: fmt.Sprintf(
"forge-%s-%s-installer.jar",
gameVersion.String(),
forgeVersion,
),
}, nil
}
func minecraftVersionForInstall(minecraft version.Version) (version.Version, error) {
if minecraft == "" || minecraft.IsInvalid() || minecraft.CanInfer() {
return "", errors.New(
"forge bootstrap requires a concrete Minecraft version",
)
}
return minecraft, nil
}
func (p *Provider) forgeVersionFromPackageRef(
ctx context.Context,
ref catalog.VersionedRef,
gameVersion version.Version,
) (string, error) {
if ref.Version != version.Beta &&
ref.Version != version.Stable &&
ref.Version != version.Any &&
ref.Version != version.Unknown {
return ref.Version.String(), nil
}
return p.fetchVersion(ctx, gameVersion, ref.Version)
}
// fetchVersion selects a Forge version from the `promotions` data. stable
// accepts the recommended promotion only; beta accepts the latest promotion;
// any prefers the recommended release and falls back to the latest.
func (p *Provider) fetchVersion(
ctx context.Context,
gameVersion version.Version,
selector version.Version,
) (string, error) {
body, err := p.network.CachedGetBytes(
ctx,
promotionsURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return "", fmt.Errorf("fetch forge promotions failed: %w", err)
}
var data promotions
if err := json.Unmarshal(body, &data); err != nil {
return "", fmt.Errorf("parse forge promotions failed: %w", err)
}
if len(data.Promos) == 0 {
return "", fmt.Errorf("forge promotions is empty; see %s", docsURL)
}
keyBase := gameVersion.String()
recommended := data.Promos[keyBase+"-recommended"]
latest := data.Promos[keyBase+"-latest"]
switch selector {
case version.Stable:
if recommended != "" {
return recommended, nil
}
case version.Beta:
if latest != "" {
return latest, nil
}
if recommended != "" {
return recommended, nil
}
default:
if recommended != "" {
return recommended, nil
}
if latest != "" {
return latest, nil
}
}
return "", fmt.Errorf(
"no forge version found for minecraft %s in promotions data; see %s (Forge) and %s (NeoForge comparison)",
gameVersion,
docsURL,
neoForgeComparisonURL,
)
}
func installerURL(
gameVersion version.Version,
forgeVersion string,
) string {
combinedVersion := fmt.Sprintf("%s-%s", gameVersion.String(), forgeVersion)
escaped := url.PathEscape(combinedVersion)
return fmt.Sprintf(
"%s/%s/forge-%s-installer.jar",
mavenBaseURL,
escaped,
escaped,
)
}
package hangar
import (
"context"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/upstream"
)
// Provider resolves Hangar projects and versions through one configured
// network cache. logger may be nil, which records nothing.
type Provider struct {
network *cache.Client
logger *log.Logger
}
// New constructs a Hangar provider. network supplies the cached HTTP
// transport; construction performs no requests.
func New(network *cache.Client, logger *log.Logger) *Provider {
return &Provider{network: network, logger: logger}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderHangar
}
// Builds lists every published version. Hangar versions declare supported
// platforms independently, so each platform becomes its own build entry.
func (p *Provider) Builds(ctx context.Context, project string) ([]upstream.Build, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
versions, err := p.listVersions(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
var builds []upstream.Build
for i := range versions {
builds = append(builds, versions[i].ToBuilds()...)
}
return builds, nil
}
func (p *Provider) Search(ctx context.Context, q upstream.Query) (upstream.SearchResponse, error) {
// Hangar publishes server plugins only; IncludeClient needs no filter.
res, err := p.searchProjects(ctx, q.Keyword, q.FilterEcosystem)
if err != nil {
return upstream.SearchResponse{}, err
}
return res.ToSearchResults(p.Provider()), nil
}
func (p *Provider) Info(ctx context.Context, ref catalog.Ref) (catalog.Metadata, error) {
project, err := p.getProject(ctx, ref.Name)
if err != nil {
return catalog.Metadata{}, err
}
info := project.ToProjectInformation()
return info, nil
}
package hangar
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
// Candidates lists Hangar releases for one explicit project identity. Each
// candidate comes from the requested Hangar platform only: Hangar publishes
// platform-specific downloads, so another platform's file is never a
// substitute. Minecraft compatibility is enforced only where Hangar's
// platformDependencies enumerate Minecraft versions; otherwise the candidate
// carries CompatibilityUnknown instead of a compatibility claim.
func (p *Provider) Candidates(
ctx context.Context,
project, minecraft string,
loader catalog.Ecosystem,
) ([]upstream.Candidate, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
platformKeys, supported := hangarPlatformKeysFor(loader)
if !supported {
return nil, fmt.Errorf(
"hangar serves Paper, Waterfall, and Velocity plugins; %s is not a Hangar platform",
loader,
)
}
resolved, err := p.getProject(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
if resolved.ID <= 0 {
return nil, fmt.Errorf(
"%w: project %s has no numeric identity",
ErrInvalidAPIResponse,
project,
)
}
versions, err := p.listProjectVersions(ctx, resolved)
if err != nil {
return nil, err
}
projectID := strconv.FormatInt(resolved.ID, 10)
minecraftVersion := versionpkg.Version(
strings.TrimSpace(minecraft),
)
minecraftKnown := minecraftVersion != "" &&
!minecraftVersion.CanInfer() &&
!minecraftVersion.IsInvalid()
candidates := make([]upstream.Candidate, 0, len(versions))
for i := range versions {
version := &versions[i]
if version.ProjectID != 0 && version.ProjectID != resolved.ID {
continue
}
platformKey, download, ok := version.candidateDownload(platformKeys)
if !ok {
continue
}
filename := download.metadataFilename()
fileURL := download.URL()
if filename == "" || fileURL == "" ||
!strings.HasSuffix(strings.ToLower(filename), ".jar") {
// External links and non-jar uploads have no digest or filename
// from Hangar metadata, so the lock could not pin them honestly.
continue
}
compatibilityUnknown := false
if hangarPlatformTracksMinecraft(platformKey) {
declared, present := version.platformDependenciesFor(platformKey)
switch {
case !present:
compatibilityUnknown = true
case !minecraftKnown:
compatibilityUnknown = true
case !containsMinecraft(declared, string(minecraftVersion)):
continue
}
} else {
// Velocity platform dependencies list Velocity versions, not
// Minecraft versions, so Hangar cannot verify this claim.
compatibilityUnknown = true
}
dependencies, dependenciesKnown := version.candidateDependencies(
platformKey,
)
hashes := map[string]string{}
if hash := download.SHA256(); hash != "" {
hashes["sha256"] = hash
}
candidates = append(candidates, upstream.Candidate{
Artifact: catalog.Artifact{
Provider: catalog.ProviderHangar,
ProjectID: projectID,
ReleaseID: version.Name,
FileID: strconv.FormatInt(version.ID, 10),
Version: versionpkg.Version(version.Name),
Filename: filename,
URL: fileURL,
Hashes: hashes,
},
Channel: upstream.ParseReleaseChannel(version.Channel.Name),
PublishedAt: hangarPublishedAt(version.CreatedAt),
PrimaryFile: true,
Dependencies: dependencies,
DependenciesUnknown: !dependenciesKnown,
CompatibilityUnknown: compatibilityUnknown,
})
}
if len(candidates) == 0 {
return nil, fmt.Errorf(
"hangar project %s has no downloadable %s build for Minecraft %s",
resolved.ProjectRef().LookupPath(),
loader,
minecraft,
)
}
return candidates, nil
}
// candidateDownload selects the download for exactly the requested platform.
// An unspecified ecosystem uses the documented preferred-platform order. It
// never crosses from an explicitly requested platform to another platform.
func (v *hangarVersion) candidateDownload(
requested []string,
) (string, hangarDownload, bool) {
platforms := requested
if len(platforms) == 0 {
platforms = hangarPreferredPlatforms
}
for _, platform := range platforms {
download, ok := v.downloadForPlatformKey(platform)
if !ok {
continue
}
if download.URL() == "" {
continue
}
return platform, download, true
}
return "", hangarDownload{}, false
}
// candidateDependencies maps Hangar's plugin dependency entries to upstream
// project identities. Entries hosted outside Hangar, or without a project ID,
// cannot be resolved through the Hangar catalogue; any such entry makes the
// declaration incomplete so resolution reports the gap.
func (v *hangarVersion) candidateDependencies(
platformKey string,
) ([]upstream.ProjectDependency, bool) {
declared, known := v.platformPluginDependencies(platformKey)
dependencies := make([]upstream.ProjectDependency, 0, len(declared))
complete := known
for _, dependency := range declared {
if dependency.Name == "" ||
dependency.ProjectID == nil ||
*dependency.ProjectID <= 0 {
complete = false
continue
}
if dependency.ExternalURL != nil && *dependency.ExternalURL != "" {
complete = false
continue
}
kind := catalog.DependencyKindOptional
if dependency.Required {
kind = catalog.DependencyKindRequired
}
dependencies = append(dependencies, upstream.ProjectDependency{
Provider: catalog.ProviderHangar,
ProjectID: strconv.FormatInt(*dependency.ProjectID, 10),
Kind: kind,
})
}
return dependencies, complete
}
func containsMinecraft(declared []string, minecraft string) bool {
for _, supported := range declared {
if strings.EqualFold(strings.TrimSpace(supported), minecraft) {
return true
}
}
return false
}
package hangar
import (
"crypto/sha256"
"encoding/hex"
"maps"
"net/url"
"path"
"slices"
"strings"
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/upstream"
)
const hangarSiteBaseURL = "https://hangar.papermc.io"
type hangarProjectRef struct {
Owner string
Slug string
}
func (p hangarProject) ProjectRef() hangarProjectRef {
return p.Namespace.ProjectRef()
}
func (n hangarProjectNamespace) ProjectRef() hangarProjectRef {
return hangarProjectRef(n)
}
func (r hangarProjectRef) CanonicalName() catalog.Name {
return input.ToProjectName(r.Slug)
}
func (r hangarProjectRef) LookupPath() string {
if r.Owner == "" {
return r.Slug
}
return r.Owner + "/" + r.Slug
}
func (r hangarProjectRef) ProjectURL() string {
if r.Owner == "" || r.Slug == "" {
return ""
}
return hangarSiteBaseURL + "/" + r.Owner + "/" + r.Slug
}
// ToSearchResults preserves the owner-qualified identity, which is the
// coordinate an install can resolve without relying on a display name that
// two projects could share.
func (s *projectSearchResponse) ToSearchResults(source catalog.Provider) upstream.SearchResponse {
res := upstream.SearchResponse{
Provider: source,
Items: make([]upstream.SearchResult, 0, len(s.Result)),
}
for _, project := range s.Result {
ref := project.ProjectRef()
res.Items = append(
res.Items, upstream.SearchResult{
ProjectName: ref.LookupPath(),
Provider: source,
Title: project.Name,
Description: project.Description,
LastUpdated: hangarPublishedAt(project.LastUpdated),
},
)
}
return res
}
func (p *hangarProject) ToProjectInformation() catalog.Metadata {
info := catalog.Metadata{
Title: p.Name,
Brief: p.Description,
Description: p.MainPageContent,
DescriptionIsMarkdown: p.MainPageContent != "" && (upstream.LooksLikeMarkdown(p.MainPageContent) || strings.Contains(
p.MainPageContent,
"#",
)),
License: firstNonEmpty(
p.Settings.License.Name,
p.Settings.License.Type,
),
Authors: make([]catalog.Person, 0, len(p.MemberNames)),
URLs: make([]catalog.URL, 0, len(p.Settings.Links)+1),
}
if projectURL := p.ProjectRef().ProjectURL(); projectURL != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Hangar",
Type: catalog.URLHome,
URL: projectURL,
},
)
}
for _, memberName := range p.MemberNames {
info.Authors = append(info.Authors, catalog.Person{Name: memberName})
}
for _, section := range p.Settings.Links {
for _, link := range section.Links {
linkURL := safeHangarURL(link.URL)
if linkURL == "" {
continue
}
info.URLs = append(
info.URLs, catalog.URL{
Name: link.Name,
Type: classifyHangarURL(link.Name),
URL: linkURL,
},
)
}
}
return info
}
// ToBuilds maps one Hangar version to one build entry per declared platform.
// Game versions stay attached to the platform that declared them.
func (v *hangarVersion) ToBuilds() []upstream.Build {
channel := strings.ToLower(strings.TrimSpace(v.Channel.Name))
published := hangarPublishedAt(v.CreatedAt)
platforms := make(map[string]struct{})
for platform := range v.PlatformDependencies {
platforms[strings.ToLower(platform)] = struct{}{}
}
for platform := range v.Downloads {
platforms[strings.ToLower(platform)] = struct{}{}
}
if len(platforms) == 0 {
return []upstream.Build{{
Version: v.Name,
Channel: channel,
Published: published,
}}
}
builds := make([]upstream.Build, 0, len(platforms))
for _, platform := range sortedMapKeys(platforms) {
builds = append(
builds, upstream.Build{
Version: v.Name,
GameVersions: v.platformGameVersions(platform),
Loaders: []string{platform},
Channel: channel,
Published: published,
},
)
}
return builds
}
func (v *hangarVersion) platformGameVersions(platform string) []string {
for key, versions := range v.PlatformDependencies {
if strings.EqualFold(key, platform) {
return versions
}
}
return nil
}
func hangarPublishedAt(raw string) time.Time {
published, err := time.Parse(time.RFC3339, raw)
if err != nil {
return time.Time{}
}
return published
}
// platformPluginDependencies returns the plugin dependencies Hangar declared
// for one platform. known is false only when the response carried no
// dependency object at all, which is different from an empty declaration.
func (v *hangarVersion) platformPluginDependencies(platformKey string) (
[]hangarPluginDependency,
bool,
) {
if v.PluginDependencies == nil {
return []hangarPluginDependency{}, false
}
if len(v.PluginDependencies) == 0 {
return []hangarPluginDependency{}, true
}
for key, dependencies := range v.PluginDependencies {
if !strings.EqualFold(key, platformKey) {
continue
}
if dependencies == nil {
return []hangarPluginDependency{}, true
}
return dependencies, true
}
// Another platform declared dependencies, but this platform's list is
// unknown. Falling back would attribute another platform's dependencies.
return []hangarPluginDependency{}, false
}
// platformDependenciesFor returns the Minecraft versions declared for one
// platform. ok is false when the response carried no entry for the platform,
// which leaves compatibility unverified rather than incompatible.
func (v *hangarVersion) platformDependenciesFor(platformKey string) (
[]string,
bool,
) {
if len(v.PlatformDependencies) == 0 {
return nil, false
}
for key, versions := range v.PlatformDependencies {
if strings.EqualFold(key, platformKey) {
return versions, true
}
}
return nil, false
}
// safeHangarURL accepts only absolute HTTP(S) URLs. Remote metadata is
// untrusted input and must not become a local file path or another scheme.
func safeHangarURL(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
parsed, err := url.Parse(raw)
if err != nil {
return ""
}
switch strings.ToLower(parsed.Scheme) {
case "http", "https":
default:
return ""
}
if parsed.Host == "" {
return ""
}
return parsed.String()
}
// hangarArtifactFilename accepts a single path segment only. Download
// metadata is the only filename source: a URL path can change independently
// of the uploaded artifact and must not rename what the lock pins.
func hangarArtifactFilename(name string) string {
name = strings.TrimSpace(name)
if name == "" || name == "." || name == ".." {
return ""
}
if path.Base(name) != name || strings.ContainsAny(name, `/\`) {
return ""
}
return name
}
func (d hangarDownload) metadataFilename() string {
return hangarArtifactFilename(d.FileInfo.Name)
}
func (d hangarDownload) URL() string {
if direct := safeHangarURL(d.DownloadURL); direct != "" {
return direct
}
if d.ExternalURL == nil {
return ""
}
return safeHangarURL(*d.ExternalURL)
}
func (d hangarDownload) SHA256() string {
hash := strings.ToLower(strings.TrimSpace(d.FileInfo.SHA256Hash))
if len(hash) != sha256.Size*2 {
return ""
}
if _, err := hex.DecodeString(hash); err != nil {
return ""
}
return hash
}
func classifyHangarURL(name string) catalog.URLType {
switch strings.ToLower(name) {
case "issues":
return catalog.URLIssues
case "source":
return catalog.URLSource
case "wiki":
return catalog.URLWiki
case "support", "discord":
return catalog.URLForum
default:
return catalog.URLMisc
}
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}
func sortedMapKeys[T any](m map[string]T) []string {
return slices.Sorted(maps.Keys(m))
}
package hangar
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
)
const hangarAPIBaseURL = "https://hangar.papermc.io/api/v1"
var (
ErrInvalidAPIResponse = errors.New("hangar: invalid api response")
ErrNoProject = errors.New("hangar: project not found")
ErrNoVersion = errors.New("hangar: version not found")
ErrAmbiguousProject = errors.New("hangar: project name is ambiguous")
)
// getProject resolves one explicit project identity. A numeric Hangar project
// ID is the stable coordinate; an owner/slug path is accepted and verified
// against the response because Hangar itself resolves the slug without
// checking the owner segment. A bare slug is accepted for older references and
// is resolved to exactly one project or rejected as ambiguous.
func (p *Provider) getProject(
ctx context.Context,
name catalog.Name,
) (*hangarProject, error) {
raw := strings.TrimSpace(string(name))
if raw == "" {
return nil, ErrNoProject
}
if id, ok := hangarNumericProjectID(raw); ok {
project, err := p.getProjectByPath(ctx, strconv.FormatInt(id, 10))
if err != nil {
return nil, err
}
if project.ID != id {
return nil, ErrNoProject
}
return project, nil
}
if owner, slug, ok := splitHangarProjectPath(raw); ok {
return p.getProjectByRef(
ctx,
hangarProjectRef{Owner: owner, Slug: slug},
)
}
project, err := p.getProjectByPath(ctx, raw)
if err != nil && !errors.Is(err, ErrNoProject) {
return nil, err
}
if err == nil && strings.EqualFold(project.Namespace.Slug, raw) {
return project, nil
}
return p.searchProjectByName(ctx, name)
}
func (p *Provider) getProjectByRef(
ctx context.Context,
ref hangarProjectRef,
) (*hangarProject, error) {
if ref.Owner == "" || ref.Slug == "" {
return nil, ErrNoProject
}
project, err := p.getProjectByPath(ctx, ref.LookupPath())
if err != nil {
return nil, err
}
// Hangar resolves the slug even when the owner segment is wrong, so the
// response must be checked before it becomes a stable identity.
resolved := project.ProjectRef()
if !strings.EqualFold(resolved.Owner, ref.Owner) ||
!strings.EqualFold(resolved.Slug, ref.Slug) {
return nil, ErrNoProject
}
return project, nil
}
func (p *Provider) getProjectByPath(
ctx context.Context,
lookupPath string,
) (*hangarProject, error) {
lookupPath = strings.Trim(strings.TrimSpace(lookupPath), "/")
if lookupPath == "" {
return nil, ErrNoProject
}
project := &hangarProject{}
if err := p.getJSON(ctx, hangarProjectURL(lookupPath), project); err != nil {
return nil, err
}
return project, nil
}
// searchProjectByName resolves a display name only when exactly one project
// shares its normalized slug. Picking the first search hit would make the
// identity depend on result ordering.
func (p *Provider) searchProjectByName(
ctx context.Context,
name catalog.Name,
) (*hangarProject, error) {
search, err := p.searchProjects(
ctx,
string(name),
catalog.EcosystemUnspecified,
)
if err != nil {
return nil, err
}
canonical := input.ToProjectName(string(name))
var matches []hangarProject
seen := make(map[int64]struct{})
for _, project := range search.Result {
if project.ProjectRef().CanonicalName() != canonical {
continue
}
if project.ID > 0 {
if _, duplicate := seen[project.ID]; duplicate {
continue
}
seen[project.ID] = struct{}{}
}
matches = append(matches, project)
}
switch len(matches) {
case 0:
return nil, ErrNoProject
case 1:
return p.getProjectByRef(ctx, matches[0].ProjectRef())
default:
return nil, ErrAmbiguousProject
}
}
func (p *Provider) searchProjects(
ctx context.Context,
query string,
ecosystem catalog.Ecosystem,
) (*projectSearchResponse, error) {
params := url.Values{}
if query != "" {
params.Set("query", query)
}
params.Set("limit", "25")
if eco := searchEcosystem(ecosystem); eco != "" {
params.Set("platform", eco)
}
res := &projectSearchResponse{}
if err := p.getJSON(ctx, hangarProjectsURL(params), res); err != nil {
return nil, err
}
return res, nil
}
func (p *Provider) listVersions(
ctx context.Context,
name catalog.Name,
) ([]hangarVersion, error) {
project, err := p.getProject(ctx, name)
if err != nil {
return nil, err
}
return p.listProjectVersions(ctx, project)
}
func (p *Provider) listProjectVersions(
ctx context.Context,
project *hangarProject,
) ([]hangarVersion, error) {
lookup := hangarProjectLookup(project)
if lookup == "" {
return nil, ErrNoProject
}
// pageSize respects Hangar's maximum of 25 versions per response.
const pageSize = 25
var versions []hangarVersion
for offset := 0; ; {
params := url.Values{}
params.Set("limit", strconv.Itoa(pageSize))
params.Set("offset", strconv.Itoa(offset))
res := &VersionListResponse{}
if err := p.getJSON(
ctx,
hangarVersionsURL(lookup, params),
res,
); err != nil {
return nil, err
}
versions = append(versions, res.Result...)
offset += len(res.Result)
if len(res.Result) == 0 || offset >= res.Pagination.Count {
break
}
}
if len(versions) == 0 {
return nil, ErrNoVersion
}
return versions, nil
}
// hangarProjectLookup prefers the numeric project ID: Hangar project IDs are
// immutable while owner and slug can change.
func hangarProjectLookup(project *hangarProject) string {
if project == nil {
return ""
}
if project.ID > 0 {
return strconv.FormatInt(project.ID, 10)
}
return project.ProjectRef().LookupPath()
}
func (p *Provider) getJSON(
ctx context.Context,
rawURL string,
out any,
) error {
p.logger.Debug("hangar request: " + rawURL)
res, err := p.network.CachedGetRequest(
ctx,
rawURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return fmt.Errorf("hangar: request failed: %w", err)
}
if res.StatusCode == http.StatusNotFound {
return ErrNoProject
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("hangar: unexpected status %d", res.StatusCode)
}
if err := json.Unmarshal(res.Data, out); err != nil {
return fmt.Errorf("hangar: failed to decode response: %w", err)
}
return nil
}
func hangarProjectsURL(params url.Values) string {
return withQuery(hangarAPIBaseURL+"/projects", params)
}
func hangarProjectURL(lookupPath string) string {
segments := strings.Split(lookupPath, "/")
for i := range segments {
segments[i] = url.PathEscape(segments[i])
}
return hangarAPIBaseURL + "/projects/" + strings.Join(segments, "/")
}
func hangarVersionsURL(lookupPath string, params url.Values) string {
return withQuery(hangarProjectURL(lookupPath)+"/versions", params)
}
func withQuery(base string, params url.Values) string {
if len(params) == 0 {
return base
}
return base + "?" + params.Encode()
}
func searchEcosystem(ecosystem catalog.Ecosystem) string {
switch ecosystem {
case catalog.EcosystemBukkit, catalog.EcosystemPaper:
return hangarPlatformPaper
case catalog.EcosystemBungeeCord:
return hangarPlatformWaterfall
case catalog.EcosystemVelocity:
return hangarPlatformVelocity
default:
return ""
}
}
func hangarNumericProjectID(raw string) (int64, bool) {
if raw == "" {
return 0, false
}
for _, character := range raw {
if character < '0' || character > '9' {
return 0, false
}
}
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func splitHangarProjectPath(raw string) (owner, slug string, ok bool) {
parts := strings.Split(raw, "/")
if len(parts) != 2 {
return "", "", false
}
owner = strings.TrimSpace(parts[0])
slug = strings.TrimSpace(parts[1])
if owner == "" || slug == "" {
return "", "", false
}
return owner, slug, true
}
package hangar
import (
"strings"
"github.com/mclucy/lucy/catalog"
)
// Hangar identifies plugin platforms by these names in both the downloads map
// and the platformDependencies map. Waterfall is the BungeeCord-compatible
// proxy platform Hangar hosts; Velocity is a separate proxy API. Hangar never
// hosts Fabric, Forge, NeoForge, or Vanilla artifacts.
const (
hangarPlatformPaper = "PAPER"
hangarPlatformWaterfall = "WATERFALL"
hangarPlatformVelocity = "VELOCITY"
)
// hangarPreferredPlatforms orders platforms for a request that does not name
// one. The order is a documented default, never a fallback from an explicitly
// requested platform.
var hangarPreferredPlatforms = []string{
hangarPlatformPaper,
hangarPlatformWaterfall,
hangarPlatformVelocity,
}
// hangarPlatformKeysFor maps a package ecosystem to Hangar platform
// identifiers in preference order. An empty slice with supported true means
// the request did not name a platform. supported false means Hangar cannot
// serve the ecosystem at all.
func hangarPlatformKeysFor(ecosystem catalog.Ecosystem) (
[]string,
bool,
) {
switch catalog.Ecosystem(
strings.ToLower(strings.TrimSpace(string(ecosystem))),
) {
case "":
return nil, true
case catalog.EcosystemPaper, catalog.EcosystemBukkit:
return []string{hangarPlatformPaper}, true
case catalog.EcosystemBungeeCord:
return []string{hangarPlatformWaterfall}, true
case catalog.EcosystemVelocity:
return []string{hangarPlatformVelocity}, true
default:
return nil, false
}
}
// hangarPlatformTracksMinecraft reports whether the platform's dependency
// list enumerates Minecraft versions. Velocity lists Velocity API versions
// instead, so a Minecraft version cannot be verified against it.
func hangarPlatformTracksMinecraft(platformKey string) bool {
switch strings.ToUpper(platformKey) {
case hangarPlatformPaper, hangarPlatformWaterfall:
return true
default:
return false
}
}
// downloadForPlatformKey returns the platform's download only when it carries
// a usable URL. A declared platform without a fetchable artifact is not a
// downloadable build.
func (v *hangarVersion) downloadForPlatformKey(
platformKey string,
) (hangarDownload, bool) {
for key, download := range v.Downloads {
if !strings.EqualFold(key, platformKey) {
continue
}
if download.URL() == "" || download.metadataFilename() == "" {
return hangarDownload{}, false
}
return download, true
}
return hangarDownload{}, false
}
// Package loadermeta resolves the loader metadata that Fabric and Quilt
// publish in the same shape: loader and game version lists, and a server
// profile that names Maven libraries.
package loadermeta
import (
"fmt"
"path"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/maven"
"github.com/mclucy/lucy/version"
)
// Definition is the per-loader difference the shared meta client needs.
type Definition struct {
// APIBase is the meta API origin, without a trailing slash.
APIBase string
// APIVersion is the API version segment the endpoints share.
APIVersion string
// MavenBase is the repository base URL of the loader artifact.
MavenBase string
// Coordinate is the Maven group and artifact of the loader.
Coordinate string
// Provider identifies the loader as an artifact source.
Provider catalog.Provider
// ProjectID is the artifact project name.
ProjectID string
// StableFlag reports whether loader entries carry a stable boolean. A
// loader without it encodes prereleases in the version suffix.
StableFlag bool
}
// Provider resolves one loader's version lists, server profile, and Maven
// artifacts over the shared network cache.
type Provider struct {
network *cache.Client
definition Definition
}
// New constructs a loader meta provider. network supplies the cached HTTP
// transport; construction performs no requests.
func New(network *cache.Client, definition Definition) *Provider {
return &Provider{network: network, definition: definition}
}
// LoaderVersion is the loader entry a selector resolved to.
type LoaderVersion struct {
Version version.Version
Maven string
Hashes map[string]string
}
// loaderVersionEntry is one entry of a loader version list. Quilt publishes
// the Maven coordinate and hashes of its loader; Fabric derives both from the
// definition.
type loaderVersionEntry struct {
Version string `json:"version"`
Stable bool `json:"stable"`
Maven string `json:"maven"`
Hashes map[string]string `json:"hashes"`
}
type gameVersionEntry struct {
Version string `json:"version"`
Stable bool `json:"stable"`
}
// Profile is the launch profile of one game/loader pair.
type Profile struct {
Libraries []Library `json:"libraries"`
}
// Library is one Maven library a profile names. URL is the repository base,
// not the artifact URL.
type Library struct {
Name string `json:"name"`
URL string `json:"url"`
}
// LoaderArtifact pins a resolved loader entry to its Maven repository. The
// entry's published hashes are copied; the repository sidecar is added by the
// caller.
func (p *Provider) LoaderArtifact(
selected LoaderVersion,
) (catalog.Artifact, error) {
coordinate := selected.Maven
if coordinate == "" {
coordinate = p.definition.Coordinate + ":" +
selected.Version.String()
}
repositoryPath, err := maven.Path(coordinate)
if err != nil {
return catalog.Artifact{}, fmt.Errorf(
"invalid %s Maven coordinate %q: %w",
p.definition.ProjectID,
coordinate,
err,
)
}
return catalog.Artifact{
Provider: p.definition.Provider,
ProjectID: p.definition.ProjectID,
Version: selected.Version,
Filename: path.Base(repositoryPath),
URL: p.definition.MavenBase + repositoryPath,
Hashes: cloneHashes(selected.Hashes),
}, nil
}
// IsLoaderLibrary reports whether a profile coordinate is the loader itself,
// which bootstrap installs from the core artifact.
func (p *Provider) IsLoaderLibrary(coordinate string) bool {
base, _, _ := strings.Cut(coordinate, "@")
parts := strings.Split(base, ":")
return len(parts) >= 2 &&
parts[0]+":"+parts[1] == p.definition.Coordinate
}
func cloneHashes(hashes map[string]string) map[string]string {
clone := make(map[string]string, len(hashes))
for name, value := range hashes {
clone[name] = value
}
return clone
}
package loadermeta
import (
"context"
"encoding/json/v2"
"fmt"
"net/url"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/version"
)
// ServerProfile fetches the launch profile of one game/loader pair. The API
// publishes no profile for an incompatible pair; that response is an error.
func (p *Provider) ServerProfile(
ctx context.Context,
game, loader version.Version,
) (Profile, error) {
if floating(game) {
return Profile{}, fmt.Errorf(
"%s server profile requires a concrete Minecraft version",
p.definition.ProjectID,
)
}
if floating(loader) {
return Profile{}, fmt.Errorf(
"%s server profile requires a concrete loader version",
p.definition.ProjectID,
)
}
endpoint := p.definition.APIBase + "/" +
p.definition.APIVersion + "/versions/loader/" +
url.PathEscape(game.String()) + "/" +
url.PathEscape(loader.String()) + "/server/json"
data, err := p.network.CachedGetBytes(
ctx,
endpoint,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
TTL: metaTTL,
},
)
if err != nil {
return Profile{}, fmt.Errorf(
"fetch %s server profile failed: %w",
p.definition.ProjectID,
err,
)
}
var profile Profile
if err := json.Unmarshal(data, &profile); err != nil {
return Profile{}, fmt.Errorf(
"parse %s server profile failed: %w",
p.definition.ProjectID,
err,
)
}
return profile, nil
}
// floating reports whether a version names a selector instead of an exact
// version.
func floating(v version.Version) bool {
switch v {
case "", version.Any, version.Beta, version.Stable, version.Unknown,
"latest":
return true
default:
return false
}
}
package loadermeta
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"strings"
"time"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/version"
)
const metaTTL = 3 * 24 * time.Hour
// ResolveLoaderVersion resolves a loader selector into the concrete loader
// version the API publishes. Stable picks the newest release, Beta and Any
// pick the newest entry, and any other value must match exactly.
func (p *Provider) ResolveLoaderVersion(
ctx context.Context,
selector version.Version,
) (LoaderVersion, error) {
versions, err := p.loaderVersions(ctx)
if err != nil {
return LoaderVersion{}, err
}
entry, err := selectLoaderVersion(
versions,
p.definition.StableFlag,
selector,
)
if err != nil {
return LoaderVersion{}, err
}
return LoaderVersion{
Version: version.Version(entry.Version),
Maven: entry.Maven,
Hashes: cloneHashes(entry.Hashes),
}, nil
}
// LatestGameVersion reports the newest Minecraft release the loader publishes
// builds for.
func (p *Provider) LatestGameVersion(
ctx context.Context,
) (version.Version, error) {
versions, err := p.gameVersions(ctx)
if err != nil {
return "", err
}
entry, err := selectGameVersion(versions, version.Stable)
if err != nil {
return "", err
}
return version.Version(entry.Version), nil
}
func (p *Provider) loaderVersions(
ctx context.Context,
) ([]loaderVersionEntry, error) {
var versions []loaderVersionEntry
if err := p.fetchVersionsMeta(ctx, "loader", &versions); err != nil {
return nil, err
}
return versions, nil
}
func (p *Provider) gameVersions(
ctx context.Context,
) ([]gameVersionEntry, error) {
var versions []gameVersionEntry
if err := p.fetchVersionsMeta(ctx, "game", &versions); err != nil {
return nil, err
}
return versions, nil
}
// fetchVersionsMeta reads one version list of the loader meta API.
func (p *Provider) fetchVersionsMeta(
ctx context.Context,
kind string,
target any,
) error {
endpoint := p.definition.APIBase + "/" +
p.definition.APIVersion + "/versions/" + kind
data, err := p.network.CachedGetBytes(
ctx,
endpoint,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
TTL: metaTTL,
},
)
if err != nil {
return fmt.Errorf(
"fetch %s %s versions meta failed: %w",
p.definition.ProjectID,
kind,
err,
)
}
if err := json.Unmarshal(data, target); err != nil {
return fmt.Errorf(
"parse %s %s versions meta failed: %w",
p.definition.ProjectID,
kind,
err,
)
}
return nil
}
// isStable reports whether a loader entry is a release. A loader that omits
// the stable flag marks a prerelease with a version suffix.
func isStable(entry loaderVersionEntry, stableFlag bool) bool {
if stableFlag {
return entry.Stable
}
return !strings.Contains(entry.Version, "-")
}
// selectLoaderVersion picks from the newest-first loader list. Stable picks
// the newest release, Beta and Any pick the newest entry, and any other value
// must match exactly.
func selectLoaderVersion(
versions []loaderVersionEntry,
stableFlag bool,
selector version.Version,
) (loaderVersionEntry, error) {
if selector.IsInvalid() || selector == "" {
return loaderVersionEntry{}, errors.New("unknown loader selector")
}
if len(versions) == 0 {
return loaderVersionEntry{}, errors.New(
"no loader versions available",
)
}
switch selector {
case version.Stable:
for _, entry := range versions {
if isStable(entry, stableFlag) {
return entry, nil
}
}
return loaderVersionEntry{}, errors.New(
"no stable loader version available",
)
case version.Beta, version.Any:
return versions[0], nil
}
for _, entry := range versions {
if entry.Version == selector.String() {
return entry, nil
}
}
return loaderVersionEntry{}, fmt.Errorf(
"loader version %s not found", selector.String(),
)
}
// selectGameVersion picks from the newest-first Minecraft version list.
func selectGameVersion(
versions []gameVersionEntry,
selector version.Version,
) (gameVersionEntry, error) {
if selector.IsInvalid() || selector == "" {
return gameVersionEntry{}, errors.New("unknown game selector")
}
if len(versions) == 0 {
return gameVersionEntry{}, errors.New(
"no game versions available",
)
}
switch selector {
case version.Stable:
for _, entry := range versions {
if entry.Stable {
return entry, nil
}
}
return gameVersionEntry{}, errors.New(
"no stable Minecraft version in loader metadata",
)
case version.Beta, version.Any:
return versions[0], nil
}
for _, entry := range versions {
if entry.Version == selector.String() {
return entry, nil
}
}
return gameVersionEntry{}, fmt.Errorf(
"game version %s not found", selector.String(),
)
}
package mcdr
import (
"context"
"fmt"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/internal/github"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/upstream"
)
// Provider resolves MCDR plugin catalogue entries through the official
// catalogue API and, for search ids, GitHub. logger may be nil, which records
// nothing.
type Provider struct {
network *cache.Client
logger *log.Logger
githubClient *github.Client
}
// New constructs an MCDR provider. network supplies the cached HTTP transport;
// construction performs no requests.
func New(network *cache.Client, logger *log.Logger) *Provider {
return &Provider{
network: network,
logger: logger,
githubClient: github.New(network, logger),
}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderMCDR
}
// Builds lists every release in the plugin catalogue release history.
func (p *Provider) Builds(ctx context.Context, project string) ([]upstream.Build, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
history, err := p.getReleaseHistory(ctx, catalog.Name(project).PythonName())
if err != nil {
return nil, err
}
builds := make([]upstream.Build, 0, len(history.Releases))
for _, rel := range history.Releases {
builds = append(builds, rel.ToBuild())
}
return builds, nil
}
type mcdrSearchResult []string
func (m mcdrSearchResult) ToSearchResults(source catalog.Provider) upstream.SearchResponse {
res := upstream.SearchResponse{Provider: source}
for _, id := range m {
res.Items = append(
res.Items, upstream.SearchResult{
ProjectName: input.ToProjectName(id).String(),
Provider: source,
},
)
}
return res
}
// Search returns the provider's default result set; tags and limit are not
// applied.
func (p *Provider) Search(ctx context.Context, q upstream.Query) (upstream.SearchResponse, error) {
// MCDR publishes server plugins only; IncludeClient needs no filter.
if q.FilterEcosystem != catalog.EcosystemMCDR && q.FilterEcosystem != catalog.EcosystemUnspecified {
return upstream.SearchResponse{}, fmt.Errorf(
"invalid search platform: expected %s, got %s",
catalog.EcosystemMCDR,
q.FilterEcosystem,
)
}
res, err := p.search(ctx, q.Keyword)
if err != nil {
return upstream.SearchResponse{}, err
}
return res.ToSearchResults(p.Provider()), nil
}
// Info resolves plugin metadata from the catalogue's per-plugin aggregate
// document in one request, plus the shared author index when the plugin lists
// authors. Sections the catalogue marks null stay absent.
func (p *Provider) Info(ctx context.Context, ref catalog.Ref) (catalog.Metadata, error) {
name := ref.Name.PythonName()
all, err := p.getPlugin(ctx, name)
if err != nil {
return catalog.Metadata{}, err
}
var authorLinks map[string]string
if all.Plugin != nil && len(all.Plugin.Authors) > 0 {
authorLinks, err = p.getAuthorLinks(ctx)
if err != nil {
return catalog.Metadata{}, err
}
}
info := rawProjectInformation{
Info: all.Plugin,
Meta: all.Meta,
Repository: all.Repository,
AuthorLinks: authorLinks,
}.ToProjectInformation()
return info, nil
}
package mcdr
import (
"context"
"fmt"
"strconv"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
func (p *Provider) Candidates(ctx context.Context, project, _ string, loader catalog.Ecosystem) ([]upstream.Candidate, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if loader != catalog.EcosystemMCDR {
return nil, fmt.Errorf("MCDR catalogue requires the mcdr loader")
}
history, err := p.getReleaseHistory(ctx, project)
if err != nil {
return nil, err
}
out := make([]upstream.Candidate, 0, len(history.Releases))
for _, rel := range history.Releases {
hashes := map[string]string{}
if rel.Asset.HashSha256 != "" {
hashes["sha256"] = rel.Asset.HashSha256
}
channel := rel.Channel()
projectID := history.ID
if projectID == "" {
projectID = project
}
c := upstream.Candidate{
Provider: catalog.ProviderMCDR,
ProjectID: projectID,
ReleaseID: rel.TagName,
FileID: strconv.Itoa(rel.Asset.ID),
Version: version.Version(rel.Meta.Version),
Filename: rel.Asset.Name,
URL: rel.Asset.BrowserDownloadUrl,
Hashes: hashes,
Channel: channel,
PublishedAt: rel.CreatedAt,
PrimaryFile: true,
Dependencies: []upstream.ProjectDependency{},
}
for id := range rel.Meta.Dependencies {
if id != "mcdreforged" {
c.Dependencies = append(c.Dependencies, upstream.ProjectDependency{
Provider: catalog.ProviderMCDR,
ProjectID: id,
Kind: catalog.DependencyKindRequired,
})
}
}
out = append(out, c)
}
if len(out) == 0 {
return nil, fmt.Errorf("MCDR catalogue project %s has no releases", project)
}
return out, nil
}
package mcdr
import "errors"
var (
ErrorGhApi = errors.New("error from GitHub API")
ErrorCatalogueApi = errors.New("error from MCDR plugin catalogue API")
ErrPluginNotFound = func(id string) error { return errors.New("plugin not found: " + id) }
)
package mcdr
import (
"context"
"encoding/json/v2"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"github.com/junegunn/fzf/src/algo"
"github.com/junegunn/fzf/src/util"
"github.com/mclucy/lucy/cache"
)
const (
pluginCatalogueRepoEndpoint = `https://api.github.com/repos/MCDReforged/PluginCatalogue/contents/`
branchCatalogue = "?ref=catalogue"
mcdrCatalogueEndpoint = `https://api.mcdreforged.com/catalogue/`
)
// search lists plugin ids through the GitHub contents API. The official
// plugins.json carries the same ids in about 1.35 MB for one request, so this
// listing is kept while it stays far below the contents API's 1000-entry cap;
// switching would buy no request reduction and only grow the payload.
func (p *Provider) search(
ctx context.Context,
query string,
) (mcdrSearchResult, error) {
ghEndpoint := pluginCatalogueRepoEndpoint + "plugins/" + branchCatalogue
err, msg, items := p.githubClient.GetDirectoryFromGitHub(ctx, ghEndpoint)
if err != nil {
return nil, err
}
if msg != nil && msg.Message != "" {
return nil, fmt.Errorf("%w: %s", ErrorGhApi, msg.Message)
}
pluginIds := make([]string, 0)
for _, file := range items {
pluginIds = append(pluginIds, file.Name)
}
return fuzzySearch(query, pluginIds), nil
}
var initFuzzyScoring sync.Once
// fuzzySearch ranks ids by how well they match query.
func fuzzySearch(query string, ids []string) []string {
if query == "" {
return nil
}
initFuzzyScoring.Do(func() { algo.Init("default") })
pattern := []rune(strings.ToLower(query))
slab := util.MakeSlab(16, 32)
type ranked struct {
index int
score int
}
matches := make([]ranked, 0, len(ids))
for i, id := range ids {
chars := util.ToChars([]byte(id))
result, _ := algo.FuzzyMatchV2(
false, true, true, &chars, pattern, false, slab,
)
if result.Start >= 0 {
matches = append(matches, ranked{i, result.Score})
}
}
sort.SliceStable(matches, func(i, j int) bool {
return matches[i].score > matches[j].score
})
result := make([]string, 0, len(matches))
for _, match := range matches {
result = append(result, ids[match.index])
}
return result
}
// getPlugin fetches one plugin's aggregate catalogue document. Its meta,
// plugin, and repository sections replace the three former GitHub contents
// requests with a single request. Sections the catalogue failed to refresh are
// null and stay absent from the resulting metadata.
func (p *Provider) getPlugin(
ctx context.Context,
id string,
) (*pluginAll, error) {
var all pluginAll
if err := p.getPluginDocument(ctx, id, "all.json", &all); err != nil {
return nil, err
}
if all.Meta == nil && all.Plugin == nil && all.Repository == nil {
return nil, fmt.Errorf("%w: %s has no catalogue data", ErrorCatalogueApi, id)
}
return &all, nil
}
// getReleaseHistory fetches the plugin's narrow release document. It carries
// the same release history as the catalogue aggregate without the plugin's
// readme and introduction.
func (p *Provider) getReleaseHistory(
ctx context.Context,
id string,
) (*pluginRelease, error) {
var releaseHistory pluginRelease
if err := p.getPluginDocument(ctx, id, "release.json", &releaseHistory); err != nil {
return nil, err
}
return &releaseHistory, nil
}
// getAuthorLinks fetches the catalogue-wide author index. Author links are the
// one field the aggregate drops from plugin_info.json, and the index is
// shared by every plugin and cached under its own URL, so it is requested only
// when a plugin lists authors and reused across plugins.
func (p *Provider) getAuthorLinks(
ctx context.Context,
) (map[string]string, error) {
var summary authorSummary
if err := p.getCatalogueJSON(ctx, mcdrCatalogueEndpoint+"authors.json", &summary); err != nil {
return nil, err
}
links := make(map[string]string, len(summary.Authors))
for name, record := range summary.Authors {
if record.Link != "" {
links[name] = record.Link
}
}
return links, nil
}
func (p *Provider) getPluginDocument(
ctx context.Context,
id string,
document string,
out any,
) error {
rawURL := mcdrCatalogueEndpoint + url.PathEscape(id) + "/" + document
res, err := p.fetchCatalogue(ctx, rawURL)
if err != nil {
return err
}
switch res.StatusCode {
case http.StatusOK:
return decodeCatalogue(res.Data, out)
case http.StatusNotFound:
return ErrPluginNotFound(id)
default:
return fmt.Errorf("%w: unexpected status %d", ErrorCatalogueApi, res.StatusCode)
}
}
func (p *Provider) getCatalogueJSON(
ctx context.Context,
rawURL string,
out any,
) error {
res, err := p.fetchCatalogue(ctx, rawURL)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("%w: unexpected status %d", ErrorCatalogueApi, res.StatusCode)
}
return decodeCatalogue(res.Data, out)
}
func (p *Provider) fetchCatalogue(
ctx context.Context,
rawURL string,
) (*cache.BytesResponse, error) {
p.logger.Debug("mcdr catalogue: GET " + rawURL)
res, err := p.network.CachedGetRequest(
ctx,
rawURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrorCatalogueApi, err)
}
return res, nil
}
func decodeCatalogue(data []byte, out any) error {
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("%w: %w", ErrorCatalogueApi, err)
}
return nil
}
package mcdr
import (
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// pluginInfo supplies authorship and the source repository URL from the
// "plugin" section of
// https://api.mcdreforged.com/catalogue/{plugin_id}/all.json.
// Metadata comes from the "meta" section instead.
type pluginInfo struct {
ID string `json:"id"`
Authors []string `json:"authors"`
Repository string `json:"repository"`
Branch string `json:"branch"`
RelatedPath string `json:"related_path"`
Labels []string `json:"labels"`
Introduction struct {
EnUs string `json:"en_us"`
ZhCn string `json:"zh_cn"`
} `json:"introduction"`
}
type author struct {
Name string `json:"name"`
Link string `json:"link"`
}
// authorSummary is the catalogue-wide author index from
// https://api.mcdreforged.com/catalogue/authors.json. It maps each author name
// to the record the catalogue collected from plugin_info.json, keeping the
// author links the aggregate omits.
type authorSummary struct {
Amount int `json:"amount"`
Authors map[string]author `json:"authors"`
}
// pluginAll is the official per-plugin catalogue aggregate from
// https://api.mcdreforged.com/catalogue/{plugin_id}/all.json. The catalogue
// documents meta, release, and repository as null when refreshing that section
// failed, so Info treats those sections as optional. The release section is
// not decoded here: release history uses the narrower release.json document.
type pluginAll struct {
Meta *pluginMeta `json:"meta"`
Plugin *pluginInfo `json:"plugin"`
Repository *pluginRepo `json:"repository"`
}
// pluginRelease contains releases from https://api.mcdreforged.com/catalogue/{plugin_id}/release.json.
type pluginRelease struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"id"`
Releases []release `json:"releases"`
}
type release struct {
URL string `json:"url"`
Name string `json:"name"`
TagName string `json:"tag_name"`
CreatedAt time.Time `json:"created_at"`
Description string `json:"description"`
Prerelease bool `json:"prerelease"`
Asset asset `json:"asset"`
Meta pluginMeta `json:"meta"`
}
// Channel reports the stability channel from the release's prerelease flag.
func (r release) Channel() upstream.ReleaseChannel {
if r.Prerelease {
return upstream.ReleaseChannelBeta
}
return upstream.ReleaseChannelRelease
}
// ToBuild maps a catalogue release to its MCDR compatibility.
func (r release) ToBuild() upstream.Build {
return upstream.Build{
Version: r.Meta.Version,
Loaders: []string{"mcdr"},
Channel: string(r.Channel()),
Published: r.CreatedAt,
}
}
type asset struct {
ID int `json:"id"`
Name string `json:"name"`
Size int `json:"size"`
DownloadCount int `json:"download_count"`
CreatedAt time.Time `json:"created_at"`
BrowserDownloadUrl string `json:"browser_download_url"`
HashMd5 string `json:"hash_md5"`
HashSha256 string `json:"hash_sha256"`
}
// pluginMeta contains the "meta" section of https://api.mcdreforged.com/catalogue/{plugin_id}/all.json.
type pluginMeta struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
Link string `json:"link"`
Authors []string `json:"authors"`
Dependencies map[string]string `json:"dependencies"`
Requirements []string `json:"requirements"`
Description struct {
EnUs string `json:"en_us"`
ZhCn string `json:"zh_cn"`
} `json:"description"`
}
// pluginRepo contains the "repository" section of https://api.mcdreforged.com/catalogue/{plugin_id}/all.json.
type pluginRepo struct {
URL string `json:"url"`
Name string `json:"name"`
FullName string `json:"full_name"`
HtmlUrl string `json:"html_url"`
Description string `json:"description"`
Archived bool `json:"archived"`
StargazersCount int `json:"stargazers_count"`
WatchersCount int `json:"watchers_count"`
ForksCount int `json:"forks_count"`
Readme string `json:"readme"`
ReadmeUrl string `json:"readme_url"`
License *struct {
Key string `json:"key"`
Name string `json:"name"`
SpdxId string `json:"spdx_id"`
URL string `json:"url"`
} `json:"license"`
}
type rawProjectInformation struct {
Info *pluginInfo
Meta *pluginMeta
Repository *pluginRepo
AuthorLinks map[string]string
}
func (r rawProjectInformation) ToProjectInformation() catalog.Metadata {
info := catalog.Metadata{
DescriptionIsMarkdown: true,
Authors: make([]catalog.Person, 0),
URLs: make([]catalog.URL, 0),
License: "n/a",
}
if r.Meta != nil {
info.Title = r.Meta.Name
info.Brief = r.Meta.Description.EnUs
if r.Meta.Link != "" {
info.URLs = append(info.URLs, catalog.URL{
Name: "Plugin Page",
Type: catalog.URLHome,
URL: r.Meta.Link,
})
}
}
if r.Repository != nil {
info.Description = r.Repository.Readme
info.DescriptionURL = r.Repository.HtmlUrl
if r.Repository.License != nil {
info.License = r.Repository.License.Name
}
}
if r.Info != nil {
for _, name := range r.Info.Authors {
if name == "" {
continue
}
info.Authors = append(
info.Authors, catalog.Person{
Name: name,
URL: r.AuthorLinks[name],
},
)
}
if r.Info.Repository != "" {
info.URLs = append(info.URLs, catalog.URL{
Name: "SourceGitHub Repo",
Type: catalog.URLSource,
URL: r.Info.Repository,
})
}
}
return info
}
// Package modrinth provides functions to interact with Modrinth API.
//
// Terminology: a Modrinth project maps to a Lucy project, and a Modrinth
// version maps to a Lucy package version. Lucy-side names are Modrinth slugs;
// private helpers say "slug" for the project and "version" for a release,
// beta, or alpha.
package modrinth
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/upstream"
)
// Provider is one configured Modrinth API client. Every request it performs
// shares the network cache and logger it was constructed with.
type Provider struct {
network *cache.Client
logger *log.Logger
}
// New constructs a Modrinth provider over network and logger. Construction
// performs no network requests.
func New(network *cache.Client, logger *log.Logger) *Provider {
return &Provider{network: network, logger: logger}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderModrinth
}
func (p *Provider) Search(ctx context.Context, q upstream.Query) (
resp upstream.SearchResponse,
err error,
) {
var facets []facetItems
facets = append(facets, loaderFacets(q.FilterEcosystem))
if !q.IncludeClient {
facets = append(facets, facetServerSupported)
}
internalOptions := searchOptions{
index: "relevance",
facets: facets,
}
searchUrl := searchUrl(q.Keyword, internalOptions)
p.logger.Debug("searching via modrinth api: " + searchUrl)
res, err := p.requestBytes(ctx, searchUrl)
if res != nil && res.StatusCode != http.StatusOK {
statusErr := fmt.Errorf(
"%w: %w",
ErrInvalidAPIResponse,
responseStatusError(res),
)
if err != nil {
return resp, errors.Join(statusErr, err)
}
return resp, statusErr
}
if err != nil {
return resp, fmt.Errorf("modrinth: search request failed: %w", err)
}
result := &searchResultResponse{}
err = json.Unmarshal(res.Data, result)
if err != nil {
return resp, err
}
items := make([]upstream.SearchResult, len(result.Hits))
for i, hit := range result.Hits {
items[i] = upstream.SearchResult{
ProjectName: hit.Slug,
Provider: p.Provider(),
Title: hit.Title,
Description: hit.Description,
Downloads: int64(hit.Downloads),
LastUpdated: hit.DateModified,
}
}
resp = upstream.SearchResponse{
Provider: p.Provider(),
Items: items,
Warnings: nil,
}
return
}
func (p *Provider) Info(
ctx context.Context,
ref catalog.Ref,
) (catalog.Metadata, error) {
project, err := p.getProjectByName(ctx, ref.Name)
if err != nil {
return catalog.Metadata{}, err
}
info := project.ToProjectInformation()
return info, nil
}
var ErrInvalidAPIResponse = errors.New("received non-200 code from modrinth api")
package modrinth
import (
"context"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// Builds lists every version published by a Modrinth project. project accepts
// either a slug or a project ID; the project version endpoint resolves both.
// The list is unfiltered: no game version, loader, channel, or status is
// excluded.
func (p *Provider) Builds(
ctx context.Context,
project string,
) ([]upstream.Build, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
versions, err := p.listVersions(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
builds := make([]upstream.Build, len(versions))
for i, v := range versions {
builds[i] = upstream.Build{
Version: v.VersionNumber,
GameVersions: v.GameVersions,
Loaders: v.Loaders,
Channel: string(upstream.ParseReleaseChannel(v.VersionType)),
Published: v.DatePublished,
}
}
return builds, nil
}
package modrinth
import (
"context"
"fmt"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
func (p *Provider) Candidates(ctx context.Context, project, minecraft string, loader catalog.Ecosystem) ([]upstream.Candidate, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
versions, err := p.listVersions(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
eligible := make([]*versionResponse, 0, len(versions))
for _, v := range versions {
if v == nil {
continue
}
if v.Status != "" && v.Status != "listed" {
continue
}
if !slices.Contains(v.GameVersions, minecraft) || !versionSupportsLoader(v, loader) {
continue
}
eligible = append(eligible, v)
}
// Resolving every pinned dependency version in one fan-out keeps the
// catalogue from requesting the same version once per candidate.
dependencies := p.pinnedVersionLookup(ctx, eligible)
var out []upstream.Candidate
for _, v := range eligible {
// Modrinth infers the first file as primary when no file carries the
// flag, so a version without a marked primary still must produce a
// primary candidate instead of losing every candidate to the check
// in resolve.
unmarked := !slices.ContainsFunc(v.Files, func(f fileResponse) bool { return f.IsPrimary })
for i, f := range v.Files {
if f.FileType != "" {
continue
}
c, err := p.candidateFromVersion(
ctx,
v,
f,
f.IsPrimary || (unmarked && i == 0),
false,
dependencies,
)
if err != nil {
return nil, err
}
out = append(out, c)
}
}
if len(out) == 0 {
return nil, fmt.Errorf("modrinth project %s has no %s release for Minecraft %s", project, loader, minecraft)
}
return out, nil
}
// candidateFromVersion builds the candidate for one file of a version. The
// caller owns the primary flag. lookup resolves a dependency whose project is
// carried by its version; nil reads the version endpoint per dependency. A
// hash identification keeps the matched release when that metadata is
// incomplete, because the installed bytes already establish the release; a
// catalogue listing treats the failure as fatal.
func (p *Provider) candidateFromVersion(
ctx context.Context,
v *versionResponse,
f fileResponse,
primary bool,
tolerateIncompleteDependencies bool,
lookup versionByIdLookup,
) (upstream.Candidate, error) {
hashes := map[string]string{}
if f.Hashes.Sha512 != "" {
hashes["sha512"] = f.Hashes.Sha512
}
if f.Hashes.Sha1 != "" {
hashes["sha1"] = f.Hashes.Sha1
}
c := upstream.Candidate{
Provider: catalog.ProviderModrinth,
ProjectID: v.ProjectId,
ReleaseID: v.ID,
FileID: f.ID,
Version: version.Version(v.VersionNumber),
Filename: f.Filename,
URL: f.URL,
Hashes: hashes,
Channel: upstream.ParseReleaseChannel(v.VersionType),
PublishedAt: v.DatePublished,
PrimaryFile: primary,
Dependencies: []upstream.ProjectDependency{},
}
for _, d := range v.Dependencies {
projectID := d.ProjectId
if projectID == "" && d.VersionId != "" {
pinned, e := p.resolveVersionById(ctx, lookup, d.VersionId)
if e != nil {
if ctx.Err() != nil {
return upstream.Candidate{}, ctx.Err()
}
if !tolerateIncompleteDependencies {
return upstream.Candidate{}, e
}
p.logger.Debug(
"modrinth: dependency metadata incomplete",
"version", d.VersionId,
"error", e,
)
c.DependenciesUnknown = true
continue
}
projectID = pinned.ProjectId
}
if projectID != "" {
c.Dependencies = append(c.Dependencies, upstream.ProjectDependency{
Provider: catalog.ProviderModrinth,
ProjectID: projectID,
ReleaseID: d.VersionId,
Kind: catalog.ParseDependencyKind(string(d.DependencyType)),
})
}
}
return c, nil
}
package modrinth
import (
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// projectResponse
//
// API Example:
// - https://api.modrinth.com/v2/project/P7dR8mSH
// (Fabric API)
// - https://api.modrinth.com/v2/project/1IjD5062
// (Continuity)
type projectResponse struct {
ClientSide string `json:"client_side"`
ServerSide string `json:"server_side"`
GameVersions []string `json:"game_versions"`
ID string `json:"id"`
Slug string `json:"slug"`
ProjectType string `json:"project_type"`
Team string `json:"team"`
Organization string `json:"organization"`
Title string `json:"title"`
Description string `json:"description"`
Body string `json:"body"`
BodyUrl string `json:"body_url"`
PublishedAt time.Time `json:"published"`
Updated time.Time `json:"updated"`
Approved time.Time `json:"approved"`
Queued any `json:"queued"`
Status string `json:"status"`
RequestedStatus any `json:"requested_status"`
ModeratorMessage any `json:"moderator_message"`
License struct {
ID string `json:"id"`
Name string `json:"name"`
URL any `json:"url"`
} `json:"license"`
Downloads int `json:"downloads"`
Followers int `json:"followers"`
Categories []string `json:"categories"`
AdditionalCategories []string `json:"additional_categories"`
Loaders []string `json:"loaders"`
Versions []string `json:"versions"`
IconUrl string `json:"icon_url"`
IssuesUrl string `json:"issues_url"`
SourceUrl string `json:"source_url"`
WikiUrl string `json:"wiki_url"`
DiscordUrl string `json:"discord_url"`
DonationUrls []struct {
ID string `json:"id"`
Platform string `json:"platform"`
URL string `json:"url"`
} `json:"donation_urls"`
Gallery []any `json:"gallery"`
Color int `json:"color"`
ThreadId string `json:"thread_id"`
MonetizationStatus string `json:"monetization_status"`
}
func (p *projectResponse) ToProjectInformation() (info catalog.Metadata) {
info = catalog.Metadata{
Title: p.Title,
Brief: p.Description,
Description: p.Body,
DescriptionIsMarkdown: upstream.LooksLikeMarkdown(p.Body),
License: p.License.Name,
URLs: make([]catalog.URL, 0),
}
if p.DiscordUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Discord",
Type: catalog.URLForum,
URL: p.DiscordUrl,
},
)
}
if p.IssuesUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Issues",
Type: catalog.URLSource,
URL: "",
},
)
}
if p.SourceUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Source",
Type: catalog.URLSource,
URL: p.SourceUrl,
},
)
}
if p.WikiUrl != "" {
info.URLs = append(
info.URLs, catalog.URL{
Name: "Wiki",
Type: catalog.URLWiki,
URL: p.WikiUrl,
},
)
}
for _, donationUrl := range p.DonationUrls {
info.URLs = append(
info.URLs, catalog.URL{
Name: donationUrl.Platform,
Type: catalog.URLSponsor,
URL: donationUrl.URL,
},
)
}
return info
}
// searchResultResponse
//
// Docs
// https://docs.modrinth.com/api/operations/searchprojects/
//
// Example
// https://api.modrinth.com/v2/search?query=carpet&limit=100&index=relevance&facets=%5B%5B%22server_side:required%22,%22server_side:optional%22%5D%5D
type searchResultResponse struct {
Hits []*hit `json:"hits"`
Offset int `json:"offset"`
Limit int `json:"limit"`
TotalHits int `json:"total_hits"`
}
type hit struct {
ProjectId string `json:"project_id"`
ProjectType string `json:"project_type"`
Slug string `json:"slug"`
Author string `json:"author"`
Title string `json:"title"`
Description string `json:"description"`
Categories []string `json:"categories"`
DisplayCategories []string `json:"display_categories"`
Versions []string `json:"versions"`
Downloads int `json:"downloads"`
Follows int `json:"follows"`
IconUrl string `json:"icon_url"`
DateCreated time.Time `json:"date_created"`
DateModified time.Time `json:"date_modified"`
LatestVersion string `json:"latest_version"`
License string `json:"license"`
ClientSide string `json:"client_side"`
ServerSide string `json:"server_side"`
Gallery []string `json:"gallery"`
FeaturedGallery *string `json:"featured_gallery"`
Color *int `json:"color"`
}
// versionResponse
//
// Docs
// https://docs.modrinth.com/api/operations/getversion/
//
// Example
// https://api.modrinth.com/v2/version/F7LVluUL
type versionResponse struct {
GameVersions []string `json:"game_versions"`
Loaders []string `json:"loaders"`
ID string `json:"id"`
ProjectId string `json:"project_id"`
AuthorId string `json:"author_id"`
Featured bool `json:"featured"`
Name string `json:"name"`
VersionNumber string `json:"version_number"`
Changelog string `json:"changelog"`
ChangelogUrl string `json:"changelog_url"`
DatePublished time.Time `json:"date_published"`
Downloads int `json:"downloads"`
VersionType string `json:"version_type"`
Status string `json:"status"`
RequestedStatus any `json:"requested_status"`
Files []fileResponse `json:"files"`
Dependencies []dependenciesResponse `json:"dependencies"`
}
type dependencyType string
type fileResponse struct {
ID string `json:"id"`
Hashes struct {
Sha1 string `json:"sha1"`
Sha512 string `json:"sha512"`
} `json:"hashes"`
URL string `json:"url"`
Filename string `json:"filename"`
IsPrimary bool `json:"primary"`
Size int `json:"size"`
FileType string `json:"file_type"`
}
type dependenciesResponse struct {
VersionId string `json:"version_id"`
ProjectId string `json:"project_id"`
FileName string `json:"file_name"`
DependencyType dependencyType `json:"dependency_type"`
}
package modrinth
import (
"context"
"encoding/hex"
"encoding/json/v2"
"errors"
"fmt"
"maps"
"net/http"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
versionpkg "github.com/mclucy/lucy/version"
)
// https://docs.modrinth.com/api/operations/versionfromhash/
// https://docs.modrinth.com/api/operations/versionsfromhashes/
// https://docs.modrinth.com/api/operations/getversions/
// https://docs.modrinth.com/api/operations/getprojects/
const versionFileURLPrefix = "https://api.modrinth.com/v2/version_file/"
var _ upstream.ArtifactBatchReleaseMapper = (*Provider)(nil)
// ReleaseByHash identifies an installed artifact by its SHA-1 hash and
// returns the release it was published as, in one lookup. An unrecognized hash
// is a miss with no error.
func (p *Provider) ReleaseByHash(
ctx context.Context,
artifact upstream.ArtifactFingerprint,
) (
upstream.Release,
bool,
error,
) {
hashBytes, err := artifact.SHA1()
if err != nil {
return upstream.Release{}, false, err
}
hash := hex.EncodeToString(hashBytes[:])
u := versionFileURLPrefix + hash + "?algorithm=sha1"
p.logger.Debug("modrinth hash lookup: " + u)
var data []byte
outcome := retry.Do(
ctx,
retry.Default,
func(ctx context.Context) retry.Attempt {
res, err := p.requestBytes(ctx, u)
if res != nil && res.StatusCode == http.StatusOK {
data = res.Data
}
return lookupAttempt(res, err)
},
)
if outcome.Status == 0 {
if outcome.Err == nil {
return upstream.Release{}, false, fmt.Errorf(
"modrinth: hash lookup returned no response",
)
}
return upstream.Release{}, false, fmt.Errorf(
"modrinth: request failed: %w",
outcome.Err,
)
}
if outcome.Status == http.StatusNotFound {
return upstream.Release{}, false, nil
}
if outcome.Status != http.StatusOK {
statusErr := fmt.Errorf(
"modrinth: hash lookup: %w",
outcomeStatusError(outcome),
)
if outcome.Err != nil {
return upstream.Release{}, false, errors.Join(
statusErr,
outcome.Err,
)
}
return upstream.Release{}, false, statusErr
}
if outcome.Err != nil {
return upstream.Release{}, false, fmt.Errorf(
"modrinth: request failed: %w",
outcome.Err,
)
}
var ver versionResponse
if err := json.Unmarshal(data, &ver); err != nil {
return upstream.Release{}, false, err
}
// Validate the match before asking for the project, so an entry whose
// files cannot identify the installed artifact costs one request.
file, err := requireVersionFile(&ver, hash)
if err != nil {
return upstream.Release{}, false, err
}
project, err := p.getProjectById(ctx, ver.ProjectId)
if err != nil {
return upstream.Release{}, false, err
}
candidate, err := p.candidateFromVersion(ctx, &ver, file, true, true, nil)
if err != nil {
return upstream.Release{}, false, err
}
return p.releaseFromVersion(project, &ver, candidate), true, nil
}
// releaseFromVersion labels the release with the project's slug and side
// labels and the version's compatibility tags.
func (p *Provider) releaseFromVersion(
project *projectResponse,
ver *versionResponse,
candidate upstream.Candidate,
) upstream.Release {
return upstream.Release{
Ref: catalog.VersionedRef{
Name: catalog.Name(project.Slug),
Provider: p.Provider(),
Ecosystem: ecosystemFromModrinthLoaders(ver.Loaders),
Version: versionpkg.Version(ver.VersionNumber),
},
Candidate: candidate,
MinecraftVersions: ver.GameVersions,
Loaders: ver.Loaders,
ServerSide: upstream.ServerSide(project.ServerSide),
ClientSide: project.ClientSide,
}
}
// ReleasesByHash resolves fingerprints in input order. SHA-1 digests are
// looked up in bounded batches through POST /v2/version_files, matched
// projects in one bounded GET /v2/projects fan-out, and their pinned
// dependency versions in one bounded GET /v2/versions fan-out. A digest the
// API omits is a miss. Transient failures are retried with backoff and can
// split into smaller batches. A throttle that asks for a delay ends the
// lookup: no smaller batch, later batch, or follow-on fan-out is sent before
// that delay passes. A returned entry without a project or a file carrying the
// requested digest is an incomplete lookup, not a miss.
func (p *Provider) ReleasesByHash(
ctx context.Context,
artifacts []upstream.ArtifactFingerprint,
) []upstream.ArtifactReleaseLookup {
lookups := make([]upstream.ArtifactReleaseLookup, len(artifacts))
if len(artifacts) == 0 {
return lookups
}
// One fingerprint keeps the original single-hash path, which is the
// query the endpoint offers for it.
if len(artifacts) == 1 {
release, matched, err := p.ReleaseByHash(ctx, artifacts[0])
lookups[0] = upstream.ArtifactReleaseLookup{
Release: release,
Matched: matched,
Err: err,
}
return lookups
}
if err := ctx.Err(); err != nil {
for i := range lookups {
lookups[i].Err = err
}
return lookups
}
hashes := make([]string, len(artifacts))
resolved := make([]bool, len(artifacts))
unique := make([]string, 0, len(artifacts))
for i, artifact := range artifacts {
digest, err := artifact.SHA1()
if err != nil {
lookups[i].Err = err
continue
}
hashes[i] = hex.EncodeToString(digest[:])
resolved[i] = true
unique = append(unique, hashes[i])
}
matches := make(map[string]versionFileMatch, len(unique))
versionErrors := make(map[string]error)
var throttle error
for batch := range slices.Chunk(batchIds(unique), batchSize) {
if throttle != nil {
for _, hash := range batch {
versionErrors[hash] = throttle
}
continue
}
found, batchErrors := p.versionFilesBatch(ctx, batch, 0)
for hash, err := range batchErrors {
versionErrors[hash] = err
if throttle == nil && retry.Throttled(err) {
throttle = err
}
}
maps.Copy(matches, found)
}
if throttle != nil {
// The project and dependency fan-outs need more requests. Stop here
// instead of reaching the provider before its delay passes.
failPending(
lookups,
hashes,
resolved,
matches,
versionErrors,
throttle,
)
return lookups
}
matched := make([]*versionResponse, 0, len(matches))
projectIds := make([]string, 0, len(matches))
for _, match := range matches {
if match.err != nil {
continue
}
matched = append(matched, match.version)
projectIds = append(projectIds, match.version.ProjectId)
}
projects, projectErrors := p.getProjectsByIds(ctx, projectIds)
var dependencies versionByIdLookup
if err := firstThrottled(projectErrors); err != nil {
// The dependency fan-out would reach the provider before its delay,
// so pinned metadata is reported as unavailable without a request.
dependencies = func(context.Context, string) (*versionResponse, error) {
return nil, err
}
} else {
dependencies = p.pinnedVersionLookup(ctx, matched)
}
for i := range artifacts {
if !resolved[i] {
continue
}
hash := hashes[i]
match, ok := matches[hash]
if !ok {
if err := versionErrors[hash]; err != nil {
lookups[i].Err = fmt.Errorf(
"modrinth: hash lookup for %s: %w",
hash,
err,
)
}
continue
}
if match.err != nil {
lookups[i].Err = match.err
continue
}
ver := match.version
project := projects[ver.ProjectId]
if project == nil {
lookups[i].Err = projectErrors[ver.ProjectId]
if lookups[i].Err == nil {
lookups[i].Err = fmt.Errorf("%w: %s", ErrNoProject, ver.ProjectId)
}
lookups[i].Err = fmt.Errorf(
"modrinth: project lookup for %s (hash %s): %w",
ver.ProjectId,
hash,
lookups[i].Err,
)
continue
}
candidate, err := p.candidateFromVersion(ctx, ver, match.file, true, true, dependencies)
if err != nil {
lookups[i].Err = fmt.Errorf(
"modrinth: release for hash %s: %w",
hash,
err,
)
continue
}
lookups[i].Release = p.releaseFromVersion(project, ver, candidate)
lookups[i].Matched = true
}
return lookups
}
// failPending reports the throttle for every input whose release lookup
// stopped before it could complete. A hash from a batch that was answered
// stays a clean miss when the API omitted it.
func failPending(
lookups []upstream.ArtifactReleaseLookup,
hashes []string,
resolved []bool,
matches map[string]versionFileMatch,
versionErrors map[string]error,
throttle error,
) {
for i := range lookups {
if !resolved[i] {
continue
}
hash := hashes[i]
if match, found := matches[hash]; found {
if match.err != nil {
lookups[i].Err = match.err
continue
}
lookups[i].Err = fmt.Errorf(
"modrinth: release lookup for hash %s stopped after throttle: %w",
hash,
throttle,
)
continue
}
if err := versionErrors[hash]; err != nil {
lookups[i].Err = fmt.Errorf(
"modrinth: hash lookup for %s: %w",
hash,
err,
)
}
}
}
// firstThrottled returns a throttle recorded by a batch coordinator, if any.
func firstThrottled(errs map[string]error) error {
for _, err := range errs {
if retry.Throttled(err) {
return err
}
}
return nil
}
// requireVersionFile returns the file whose sha1 matches the requested digest.
// A record without a project or without that exact file cannot identify the
// installed artifact, so it is an invalid response for the lookup, not a
// miss.
func requireVersionFile(
version *versionResponse,
hash string,
) (fileResponse, error) {
if version == nil {
return fileResponse{}, fmt.Errorf("%w: null version for hash %s", ErrInvalidAPIResponse, hash)
}
if version.ProjectId == "" {
return fileResponse{}, fmt.Errorf(
"%w: version %s for hash %s has no project",
ErrInvalidAPIResponse,
version.ID,
hash,
)
}
file, ok := fileBySha1(version.Files, hash)
if !ok {
return fileResponse{}, fmt.Errorf(
"%w: version %s for hash %s has no file with that sha1",
ErrInvalidAPIResponse,
version.ID,
hash,
)
}
return file, nil
}
// versionFilesBatch resolves one batch of hashes. A batch that still fails
// after its retry budget is split and retried per part while the failure is
// transient, so one transient response cannot leave every hash unresolved.
// A throttle that asked for a delay is not split, so no part reaches the
// provider early. Errors stay attached to the hashes of the part that carried
// them, and the caller stops the lookup when any error is a throttle.
func (p *Provider) versionFilesBatch(
ctx context.Context,
hashes []string,
depth int,
) (map[string]versionFileMatch, map[string]error) {
found, err := p.versionFilesByHash(ctx, hashes)
if err == nil {
return found, nil
}
if len(hashes) > 1 &&
depth < retry.MaxSplitDepth &&
ctx.Err() == nil &&
retry.Splittable(err) {
middle := len(hashes) / 2
leftFound, leftErrors := p.versionFilesBatch(ctx, hashes[:middle], depth+1)
if throttle := firstThrottled(leftErrors); throttle != nil {
for _, hash := range hashes[middle:] {
leftErrors[hash] = throttle
}
return leftFound, leftErrors
}
rightFound, rightErrors := p.versionFilesBatch(ctx, hashes[middle:], depth+1)
mergedFound := make(
map[string]versionFileMatch,
len(leftFound)+len(rightFound),
)
maps.Copy(mergedFound, leftFound)
maps.Copy(mergedFound, rightFound)
mergedErrors := make(
map[string]error,
len(leftErrors)+len(rightErrors),
)
maps.Copy(mergedErrors, leftErrors)
maps.Copy(mergedErrors, rightErrors)
return mergedFound, mergedErrors
}
errorsByHash := make(map[string]error, len(hashes))
for _, hash := range hashes {
errorsByHash[hash] = err
}
return nil, errorsByHash
}
// fileBySha1 picks the file whose sha1 equals hash, case-insensitive. The
// matched file stands in for the artifact, so a version whose files carry no
// matching sha1 has no match: another file's bytes cannot stand in for the
// installed artifact.
func fileBySha1(files []fileResponse, hash string) (fileResponse, bool) {
i := slices.IndexFunc(files, func(f fileResponse) bool {
return strings.EqualFold(f.Hashes.Sha1, hash)
})
if i < 0 {
return fileResponse{}, false
}
return files[i], true
}
func ecosystemFromModrinthLoaders(loaders []string) catalog.Ecosystem {
for _, loader := range loaders {
p := catalog.Ecosystem(loader)
if p.IsModding() || p == catalog.EcosystemBukkit || p == catalog.EcosystemPaper {
return p
}
}
if len(loaders) > 0 {
return catalog.Ecosystem(loaders[0])
}
return catalog.EcosystemUnspecified
}
package modrinth
import (
"context"
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
var (
ErrNotModpack = errors.New("modrinth project is not a modpack")
ErrNoMrpack = errors.New("modrinth version has no downloadable .mrpack file")
)
const (
modpackProjectType = "modpack"
mrpackExtension = ".mrpack"
)
// ResolveImportPack resolves a Modrinth modpack and an optional version
// selector to its downloadable .mrpack file. project accepts a slug or a
// project ID. version accepts a version number or a version ID; an empty
// version selects the newest release, falling back to the newest version of
// any type when the project has no release.
func (p *Provider) ResolveImportPack(
ctx context.Context,
project, version string,
) (upstream.ImportPack, error) {
if err := ctx.Err(); err != nil {
return upstream.ImportPack{}, err
}
proj, err := p.getProjectById(ctx, project)
if err != nil {
return upstream.ImportPack{}, err
}
if proj.ProjectType != modpackProjectType {
return upstream.ImportPack{}, fmt.Errorf(
"%w: %s is a %s",
ErrNotModpack,
proj.Slug,
proj.ProjectType,
)
}
// The version endpoint accepts the project ID, which is stable across
// slug renames.
versions, err := p.listVersions(ctx, catalog.Name(proj.ID))
if err != nil {
return upstream.ImportPack{}, err
}
selected, err := selectImportVersion(versions, version)
if err != nil {
return upstream.ImportPack{}, err
}
file, ok := mrpackFile(selected.Files)
if !ok {
return upstream.ImportPack{}, fmt.Errorf(
"%w: %s %s",
ErrNoMrpack,
proj.Slug,
selected.VersionNumber,
)
}
return upstream.ImportPack{
Provider: catalog.ProviderModrinth,
Project: proj.Slug,
Name: proj.Title,
Version: selected.VersionNumber,
Filename: file.Filename,
URL: file.URL,
Hashes: fileHashes(file),
}, nil
}
// selectImportVersion picks the version an import resolves to. A non-empty
// selector matches a version number or version ID exactly. An empty selector
// picks the newest release, falling back to the newest version of any type.
func selectImportVersion(
versions []*versionResponse,
selector string,
) (*versionResponse, error) {
if selector != "" {
for _, v := range versions {
if v != nil && (v.VersionNumber == selector || v.ID == selector) {
return v, nil
}
}
return nil, fmt.Errorf("%w: no version matches %q", ErrNoVersion, selector)
}
if v := newestVersion(versions, isReleaseVersion); v != nil {
return v, nil
}
if v := newestVersion(versions, nil); v != nil {
return v, nil
}
return nil, fmt.Errorf("%w: project has no versions", ErrNoVersion)
}
func isReleaseVersion(v *versionResponse) bool {
return v.VersionType == "release"
}
// newestVersion returns the version with the latest DatePublished that keep
// accepts, or nil when none is accepted. A nil keep accepts every version.
func newestVersion(
versions []*versionResponse,
keep func(*versionResponse) bool,
) *versionResponse {
var newest *versionResponse
for _, v := range versions {
if v == nil || (keep != nil && !keep(v)) {
continue
}
if newest == nil || v.DatePublished.After(newest.DatePublished) {
newest = v
}
}
return newest
}
// mrpackFile chooses the .mrpack file of a version: the primary one when it
// is marked, otherwise the first downloadable .mrpack. The bool is false when
// the version has no such file.
func mrpackFile(files []fileResponse) (fileResponse, bool) {
var found fileResponse
ok := false
for _, f := range files {
if !isDownloadableMrpack(f) {
continue
}
if f.IsPrimary {
return f, true
}
if !ok {
found, ok = f, true
}
}
return found, ok
}
func isDownloadableMrpack(f fileResponse) bool {
return f.URL != "" &&
strings.HasSuffix(strings.ToLower(f.Filename), mrpackExtension)
}
// fileHashes returns the file's digests keyed by algorithm name.
func fileHashes(f fileResponse) map[string]string {
hashes := map[string]string{}
if f.Hashes.Sha512 != "" {
hashes["sha512"] = f.Hashes.Sha512
}
if f.Hashes.Sha1 != "" {
hashes["sha1"] = f.Hashes.Sha1
}
return hashes
}
package modrinth
import (
"context"
"errors"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
)
func (p *Provider) getProjectById(
ctx context.Context,
id string,
) (project *projectResponse, err error) {
project = &projectResponse{}
if err := p.requestJSON(
ctx,
projectUrl(id),
project,
ErrNoProject,
); err != nil {
return nil, err
}
return
}
// getProjectsByIds resolves project IDs in deterministic bounded batches. A
// failed batch records its error against every ID it carried; an ID the API
// omits has neither an entry nor an error. A throttle ends the fan-out; the
// batches not yet sent record the same throttle instead of asking the provider
// again before its delay passes.
func (p *Provider) getProjectsByIds(
ctx context.Context,
ids []string,
) (map[string]*projectResponse, map[string]error) {
projects := make(map[string]*projectResponse, len(ids))
errs := make(map[string]error)
var throttle error
for batch := range slices.Chunk(batchIds(ids), batchSize) {
if throttle != nil {
for _, id := range batch {
errs[id] = throttle
}
continue
}
var list []*projectResponse
if err := p.requestJSON(ctx, projectsByIdsUrl(batch), &list, nil); err != nil {
for _, id := range batch {
errs[id] = err
}
if retry.Throttled(err) {
throttle = err
}
continue
}
for _, project := range list {
if project != nil {
projects[project.ID] = project
}
}
}
return projects, errs
}
// ServerSideByName reports the project's dedicated-server label. A project the
// provider does not host is not an error.
func (p *Provider) ServerSideByName(
ctx context.Context,
name string,
) (upstream.ProjectServerSide, bool, error) {
project, err := p.getProjectByName(ctx, catalog.Name(name))
if errors.Is(err, ErrNoProject) {
return upstream.ProjectServerSide{}, false, nil
}
if err != nil {
return upstream.ProjectServerSide{}, false, err
}
return upstream.ProjectServerSide{
ServerSide: upstream.ServerSide(project.ServerSide),
ClientSide: project.ClientSide,
Title: project.Title,
}, true, nil
}
func (p *Provider) getProjectByName(
ctx context.Context,
slug catalog.Name,
) (project *projectResponse, err error) {
project = &projectResponse{}
if err := p.requestJSON(
ctx,
projectUrl(string(slug)),
project,
ErrNoProject,
); err != nil {
return nil, err
}
return project, nil
}
package modrinth
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
)
// Modrinth documents no batch cap. One hundred keeps request URLs short and
// each response bounded; the API accepts this size.
const batchSize = 100
// Modrinth requires a distinctive User-Agent on every request.
const modrinthUserAgent = "lucy/1.0 (+https://github.com/mclucy/lucy)"
// metadataRequestHeaders is shared read-only by every GET.
var metadataRequestHeaders = http.Header{
"User-Agent": []string{modrinthUserAgent},
}
const (
versionFilesUrl = "https://api.modrinth.com/v2/version_files"
versionsByIdsUrlPrefix = "https://api.modrinth.com/v2/versions?ids="
projectsByIdsUrlPrefix = "https://api.modrinth.com/v2/projects?ids="
)
// maxBatchResponseBytes bounds one batch response body. A batch of 100 version
// objects with long changelogs stays well under it; the limit only stops a
// runaway body.
const maxBatchResponseBytes = 16 * 1024 * 1024
// versionFilesRequest is the body for POST /v2/version_files.
type versionFilesRequest struct {
Hashes []string `json:"hashes"`
Algorithm string `json:"algorithm"`
}
type versionFileMatch struct {
version *versionResponse
file fileResponse
err error
}
// versionFilesByHash identifies returned matches against their requested
// digests. An incomplete match is reported for its own digest and prevents
// caching the response. A hash the API omits is a clean miss.
func (p *Provider) versionFilesByHash(
ctx context.Context,
hashes []string,
) (map[string]versionFileMatch, error) {
body, err := json.Marshal(versionFilesRequest{
Hashes: hashes,
Algorithm: "sha1",
})
if err != nil {
return nil, retry.Permanent(
fmt.Errorf("modrinth: encode hash lookup: %w", err),
)
}
headers := http.Header{}
headers.Set("Content-Type", "application/json")
headers.Set("Accept", "application/json")
headers.Set("User-Agent", modrinthUserAgent)
p.logger.Debug("modrinth api: POST " + versionFilesUrl)
var out map[string]versionFileMatch
var incomplete error
outcome := retry.Do(
ctx,
retry.Default,
func(ctx context.Context) retry.Attempt {
res, err := p.network.CachedPostRequest(
ctx,
versionFilesUrl,
body,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
Headers: headers,
MaxBytes: maxBatchResponseBytes,
},
func(raw []byte) error {
var versions map[string]*versionResponse
if err := json.Unmarshal(raw, &versions); err != nil {
return retry.Permanent(fmt.Errorf("modrinth: failed to parse response: %w", err))
}
if versions == nil {
return retry.Permanent(fmt.Errorf("%w: expected a hash-to-version object", ErrInvalidAPIResponse))
}
out = make(map[string]versionFileMatch, min(len(versions), len(hashes)))
incomplete = nil
for _, hash := range hashes {
version, ok := versions[hash]
if !ok {
continue
}
file, err := requireVersionFile(version, hash)
out[hash] = versionFileMatch{version: version, file: file, err: err}
if incomplete == nil {
incomplete = err
}
}
if incomplete != nil {
return retry.Permanent(incomplete)
}
return nil
},
)
if res != nil && res.StatusCode != http.StatusOK {
p.logger.Debug(
fmt.Sprintf(
"modrinth api: POST %s returned status %d",
versionFilesUrl,
res.StatusCode,
),
)
}
return lookupAttempt(res, err)
},
)
if incomplete != nil && errors.Is(outcome.Err, incomplete) {
// Cache admission failed, but each returned hash has its own result.
return out, nil
}
if outcome.Status == 0 {
if outcome.Err == nil {
return nil, fmt.Errorf("modrinth: hash lookup returned no response")
}
return nil, fmt.Errorf("modrinth: request failed: %w", outcome.Err)
}
if outcome.Status != http.StatusOK {
statusErr := fmt.Errorf(
"%w: %w",
ErrInvalidAPIResponse,
outcomeStatusError(outcome),
)
if outcome.Err != nil {
return nil, errors.Join(statusErr, outcome.Err)
}
return nil, statusErr
}
if outcome.Err != nil {
return nil, fmt.Errorf("modrinth: request failed: %w", outcome.Err)
}
return out, nil
}
// lookupAttempt retains the response status and retry headers even when
// reading a non-2xx body failed, so the status still classifies the failure.
func lookupAttempt(res *cache.BytesResponse, err error) retry.Attempt {
attempt := retry.Attempt{Err: err}
if res != nil {
attempt.Status = res.StatusCode
attempt.RetryAfter = retry.RetryAfter(res.Header)
}
return attempt
}
// outcomeStatusError classifies a finished lookup's non-OK status. A retryable
// status that asked for a delay becomes a ThrottledError so splitting and
// later batches stop instead of reaching the provider early.
func outcomeStatusError(outcome retry.Attempt) error {
if retry.TransientStatus(outcome.Status) && outcome.RetryAfter > 0 {
return &retry.ThrottledError{
Status: outcome.Status,
RetryAfter: outcome.RetryAfter,
}
}
return &retry.StatusError{Status: outcome.Status}
}
// responseStatusError classifies one response that is not retried.
func responseStatusError(res *cache.BytesResponse) error {
return outcomeStatusError(retry.Attempt{
Status: res.StatusCode,
RetryAfter: retry.RetryAfter(res.Header),
})
}
// versionsByIdsUrl and projectsByIdsUrl serialize IDs as one JSON array in a
// query parameter, as the Modrinth API expects.
func versionsByIdsUrl(ids []string) string {
return versionsByIdsUrlPrefix + url.QueryEscape(jsonArray(ids))
}
func projectsByIdsUrl(ids []string) string {
return projectsByIdsUrlPrefix + url.QueryEscape(jsonArray(ids))
}
func jsonArray(values []string) string {
encoded, _ := json.Marshal(values)
return string(encoded)
}
// batchIds sorts and deduplicates ids in place. Every caller owns its slice.
func batchIds(ids []string) []string {
slices.Sort(ids)
return slices.Compact(ids)
}
func (p *Provider) requestBytes(
ctx context.Context,
rawURL string,
) (*cache.BytesResponse, error) {
p.logger.Debug("modrinth api: GET " + rawURL)
return p.network.CachedGetRequest(
ctx,
rawURL,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
Headers: metadataRequestHeaders,
},
)
}
// requestJSON decodes one GET response. A non-2xx status is classified even
// when reading its body failed, so a 404 still names the caller's not-found
// answer and a throttled response carries the delay that later requests must
// observe.
func (p *Provider) requestJSON(
ctx context.Context,
rawURL string,
out any,
notFound error,
) error {
res, err := p.requestBytes(ctx, rawURL)
if res != nil && res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusNotFound && notFound != nil {
return notFound
}
statusErr := fmt.Errorf(
"%w: %w",
ErrInvalidAPIResponse,
responseStatusError(res),
)
if err != nil {
return errors.Join(statusErr, err)
}
return statusErr
}
if err != nil {
return fmt.Errorf("modrinth: request failed: %w", err)
}
if err := json.Unmarshal(res.Data, out); err != nil {
if notFound != nil {
return fmt.Errorf("%w: %w", notFound, err)
}
return fmt.Errorf("modrinth: failed to parse response: %w", err)
}
return nil
}
package modrinth
import (
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
)
type searchOptions struct {
index string
facets []facetItems
}
type facetItemOperation uint8
const (
operationEq facetItemOperation = iota
operationNeq
operationLeq
operationGeq
operationLt
operationGt
)
func (op facetItemOperation) String() string {
switch op {
case operationEq:
return ":"
case operationNeq:
return "!="
case operationLeq:
return "<="
case operationGeq:
return ">="
case operationLt:
return "<"
case operationGt:
return ">"
default:
return ""
}
}
// facet is the data structure to construct an advanced Modrinth search. It
// covers the search options this program expects.
//
// From Modrinth docs:
//
// In order to then use these facets, you need a value to filter by, as well as
// an operation to perform on this value. The most common operation is ':'
// (same as =), though you can also use !=, >=, >, <=, and <. Join together the
// type, operation, and value, and you’ve got your string.
//
// {type} {operation} {value}
//
// categories = adventure
// versions != 1.20.1
// downloads <= 100
//
// You then join these strings together in arrays to signal AND OR operators.
//
// OR
// All elements in a single array are considered to be joined by OR statements.
// For example, the search [["versions:1.16.5", "versions:1.17.1"]] translates
// to Projects that support 1.16.5 OR 1.17.1.
//
// AND
// Separate arrays are considered to be joined by AND statements. For example,
// the search [["versions:1.16.5"], ["project_type:modpack"]] translates to
// Projects that support 1.16.5 AND are modpacks.
//
// API Docs: https://docs.modrinth.com/api/operations/searchprojects/
type facetItem struct {
Type string
Operation facetItemOperation
Match string
}
func (f *facetItem) String() string {
return `"` + f.Type + f.Operation.String() + f.Match + `"`
}
// facetItems is an array of facetItem. It represents an expression joined by
// OR statements. A complete facet is an array of facetItems, with each array
// joined by AND statements.
type facetItems []facetItem
// serializeFacet renders expressions as Modrinth's nested JSON arrays; see
// facetItems for the OR/AND semantics.
func serializeFacet(expressions ...facetItems) string {
var sb strings.Builder
sb.WriteRune('[')
for i, expression := range expressions {
if i > 0 {
sb.WriteRune(',')
}
sb.WriteRune('[')
for j, item := range expression {
if j > 0 {
sb.WriteRune(',')
}
sb.WriteString(item.String())
}
sb.WriteRune(']')
}
sb.WriteRune(']')
return sb.String()
}
var facetAllLoaders = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "forge",
},
{
Type: "categories",
Operation: operationEq,
Match: "fabric",
},
{
Type: "categories",
Operation: operationEq,
Match: "quilt",
},
{
Type: "categories",
Operation: operationEq,
Match: "liteloader",
},
{
Type: "categories",
Operation: operationEq,
Match: "modloader",
},
{
Type: "categories",
Operation: operationEq,
Match: "rift",
},
{
Type: "categories",
Operation: operationEq,
Match: "neoforge",
},
{
Type: "categories",
Operation: operationEq,
Match: "bukkit",
},
}
var facetForgeOnly = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "forge",
},
}
var facetFabricOnly = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "fabric",
},
}
// facetQuiltOnly selects projects published under the Quilt loader category.
var facetQuiltOnly = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "quilt",
},
}
var facetNeoforgeOnly = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "neoforge",
},
}
var facetBukkitOnly = facetItems{
{
Type: "categories",
Operation: operationEq,
Match: "bukkit",
},
}
// loaderFacetsByEcosystem maps an ecosystem to the loader category that
// identifies its packages. An ecosystem absent from the table searches every
// loader.
var loaderFacetsByEcosystem = map[catalog.Ecosystem]facetItems{
catalog.EcosystemForge: facetForgeOnly,
catalog.EcosystemFabric: facetFabricOnly,
catalog.EcosystemQuilt: facetQuiltOnly,
catalog.EcosystemNeoForge: facetNeoforgeOnly,
catalog.EcosystemBukkit: facetBukkitOnly,
}
// loaderFacets returns the loader categories a runtime of ecosystem loads, in
// descriptor precedence order. A runtime that loads more than one ecosystem
// (Quilt loads Fabric) matches their union.
func loaderFacets(ecosystem catalog.Ecosystem) facetItems {
facets, ok := loaderFacetsByEcosystem[ecosystem]
if !ok {
return facetAllLoaders
}
facets = slices.Clone(facets)
for _, loaded := range ecosystem.Loads() {
if loaded == ecosystem {
continue
}
facets = append(facets, loaderFacetsByEcosystem[loaded]...)
}
return facets
}
var facetServerSupported = facetItems{
{
Type: "server_side",
Operation: operationEq,
Match: "required",
},
{
Type: "server_side",
Operation: operationEq,
Match: "optional",
},
}
var facetClientSupported = facetItems{
{
Type: "client_side",
Operation: operationEq,
Match: "required",
},
{
Type: "client_side",
Operation: operationEq,
Match: "optional",
},
}
var facetBothRequired = []facetItems{
{
{
Type: "server_side",
Operation: operationEq,
Match: "required",
},
},
{
{
Type: "client_side",
Operation: operationEq,
Match: "required",
},
},
}
var facetBothSupported = []facetItems{
{
{
Type: "server_side",
Operation: operationEq,
Match: "required",
},
{
Type: "server_side",
Operation: operationEq,
Match: "optional",
},
},
{
{
Type: "client_side",
Operation: operationEq,
Match: "required",
},
{
Type: "client_side",
Operation: operationEq,
Match: "optional",
},
},
}
package modrinth
import (
"net/url"
"github.com/mclucy/lucy/catalog"
)
const projectUrlPrefix = "https://api.modrinth.com/v2/project/"
func versionsUrl(slug catalog.Name) (urlString string) {
urlString, _ = url.JoinPath(
projectUrlPrefix,
string(slug),
"version",
)
return
}
const versionUrlPrefix = `https://api.modrinth.com/v2/version/`
func versionUrl(id string) (urlString string) {
return versionUrlPrefix + url.PathEscape(id)
}
// projectUrl returns the URL for a project with the given SourceModrinth project id
// or slug (package name).
func projectUrl(suffix string) (urlString string) {
return projectUrlPrefix + url.PathEscape(suffix)
}
const searchUrlPrefix = "https://api.modrinth.com/v2/search?query="
func searchUrl(
query string,
option searchOptions,
) string {
return searchUrlPrefix + url.QueryEscape(query) +
"&limit=100&index=" + option.index +
"&facets=" + url.QueryEscape(serializeFacet(option.facets...))
}
package modrinth
import (
"context"
"errors"
"fmt"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream/internal/providers/retry"
)
var (
ErrNoVersion = errors.New("modrinth version not found")
ErrNoProject = errors.New("modrinth project not found")
)
// listVersions has a known crash risk: this path has caused segmentation faults.
func (p *Provider) listVersions(
ctx context.Context,
slug catalog.Name,
) (versions []*versionResponse, err error) {
var out []*versionResponse
if err := p.requestJSON(
ctx,
versionsUrl(slug),
&out,
ErrNoProject,
); err != nil {
return nil, err
}
return out, nil
}
func (p *Provider) getVersionById(
ctx context.Context,
id string,
) (v *versionResponse, err error) {
v = &versionResponse{}
if err := p.requestJSON(ctx, versionUrl(id), v, ErrNoVersion); err != nil {
return nil, err
}
return
}
// getVersionsBatch reads one bounded batch of version IDs. IDs the API omits
// stay absent from the map.
func (p *Provider) getVersionsBatch(
ctx context.Context,
ids []string,
) (map[string]*versionResponse, error) {
var list []*versionResponse
if err := p.requestJSON(ctx, versionsByIdsUrl(ids), &list, nil); err != nil {
return nil, err
}
out := make(map[string]*versionResponse, len(list))
for _, v := range list {
if v != nil {
out[v.ID] = v
}
}
return out, nil
}
// getVersionsByIds resolves version IDs in deterministic bounded batches. A
// failed batch records its error against every ID it carried; an ID the API
// omits has neither an entry nor an error. A throttle ends the fan-out; the
// batches not yet sent record the same throttle instead of asking the provider
// again before its delay passes.
func (p *Provider) getVersionsByIds(
ctx context.Context,
ids []string,
) (map[string]*versionResponse, map[string]error) {
versions := make(map[string]*versionResponse, len(ids))
errs := make(map[string]error)
var throttle error
for batch := range slices.Chunk(batchIds(ids), batchSize) {
if throttle != nil {
for _, id := range batch {
errs[id] = throttle
}
continue
}
found, err := p.getVersionsBatch(ctx, batch)
if err != nil {
for _, id := range batch {
errs[id] = err
}
if retry.Throttled(err) {
throttle = err
}
continue
}
for id, v := range found {
versions[id] = v
}
}
return versions, errs
}
// versionByIdLookup answers one pinned dependency version. A nil lookup falls
// back to the single-version endpoint.
type versionByIdLookup func(context.Context, string) (*versionResponse, error)
// dependencyVersionIds returns the pinned dependency version IDs that a
// version does not also label with a project ID.
func dependencyVersionIds(versions ...*versionResponse) []string {
var ids []string
for _, v := range versions {
if v == nil {
continue
}
for _, d := range v.Dependencies {
if d.VersionId != "" && d.ProjectId == "" {
ids = append(ids, d.VersionId)
}
}
}
return ids
}
// requireVersionProject returns the version only when it names its project.
// A pinned dependency needs that project to become a dependency edge, so a
// record without one is an invalid response rather than a usable version.
func requireVersionProject(
id string,
version *versionResponse,
) (*versionResponse, error) {
if version.ProjectId == "" {
return nil, fmt.Errorf(
"%w: version %s has no project",
ErrInvalidAPIResponse,
id,
)
}
return version, nil
}
// pinnedVersionLookup resolves every pinned dependency version across versions
// in one bounded fan-out. A nil result means no version pins a dependency, so
// the caller makes no request. A version the batch left without a project is
// malformed, so the caller reads that ID from the single-version endpoint
// instead; the retry is remembered so duplicate dependency edges share one
// request. A failed batch also retries that way when a caller asks for it. A
// valid bulk result stays authoritative, an ID the API omitted is not found,
// and a failed retry keeps both causes. A throttled batch is reported as-is
// instead of retrying the ID individually, so no request reaches the provider
// before its delay. A retry that resolves no project is an invalid response,
// never a usable dependency.
func (p *Provider) pinnedVersionLookup(
ctx context.Context,
versions []*versionResponse,
) versionByIdLookup {
ids := dependencyVersionIds(versions...)
if len(ids) == 0 {
return nil
}
type attempt struct {
version *versionResponse
err error
}
found, errs := p.getVersionsByIds(ctx, ids)
throttle := firstThrottled(errs)
attempts := make(map[string]attempt)
return func(callCtx context.Context, id string) (*versionResponse, error) {
if err := callCtx.Err(); err != nil {
return nil, err
}
var batchErr error
if v := found[id]; v != nil {
if v.ProjectId != "" {
return v, nil
}
batchErr = fmt.Errorf(
"%w: version %s has no project",
ErrInvalidAPIResponse,
id,
)
} else {
batchErr = errs[id]
}
if batchErr == nil {
return nil, fmt.Errorf("%w: %s", ErrNoVersion, id)
}
if retry.Throttled(batchErr) {
// The batch stopped because the provider asked for a delay. A
// single-version fallback would reach it before that delay.
return nil, batchErr
}
if prior, ok := attempts[id]; ok {
return prior.version, prior.err
}
if throttle != nil {
return nil, errors.Join(batchErr, throttle)
}
v, err := p.getVersionById(callCtx, id)
if retry.Throttled(err) {
throttle = err
}
if err == nil {
v, err = requireVersionProject(id, v)
}
if err != nil {
v = nil
err = errors.Join(batchErr, err)
}
attempts[id] = attempt{version: v, err: err}
return v, err
}
}
// resolveVersionById prefers the caller's batch lookup, so a candidate never
// fans out per dependency. Without one it reads the single-version endpoint,
// preserving the original identification path, and rejects a project-less
// record like the batch lookup does.
func (p *Provider) resolveVersionById(
ctx context.Context,
lookup versionByIdLookup,
id string,
) (*versionResponse, error) {
if lookup != nil {
return lookup(ctx, id)
}
version, err := p.getVersionById(ctx, id)
if err != nil {
return nil, err
}
return requireVersionProject(id, version)
}
// versionSupportsLoader reports whether a server in loader can load the
// version. The requested server ecosystem is the capability, so a superset
// accepts its base loader: Quilt accepts Fabric builds and Paper accepts
// Bukkit plugins, never the reverse. An unspecified request accepts any
// loader tag.
func versionSupportsLoader(
version *versionResponse,
loader catalog.Ecosystem,
) bool {
if loader == catalog.EcosystemUnspecified {
return true
}
for _, l := range version.Loaders {
if loader.Satisfy(catalog.Ecosystem(l)) {
return true
}
}
return false
}
package mojang
import (
"context"
"encoding/json/v2"
"errors"
"fmt"
"strings"
"time"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
const VersionManifestURL = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
// Provider resolves Mojang's version manifest and per-version metadata over
// the shared network cache.
type Provider struct {
network *cache.Client
}
// New constructs a Mojang installer provider. network supplies the cached HTTP
// transport; construction performs no requests.
func New(network *cache.Client) *Provider {
return &Provider{network: network}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderMojang
}
type versionDetail struct {
JavaVersion *struct {
MajorVersion int `json:"majorVersion"`
} `json:"javaVersion"`
Downloads struct {
Server *struct {
Sha1 string `json:"sha1"`
URL string `json:"url"`
} `json:"server"`
} `json:"downloads"`
}
func (p *Provider) VersionManifest(ctx context.Context) (
*fileschema.ApiMojangMinecraftVersionManifest,
error,
) {
data, err := p.network.CachedGetBytes(
ctx,
VersionManifestURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return nil, fmt.Errorf("fetch mojang version manifest failed: %w", err)
}
manifest := &fileschema.ApiMojangMinecraftVersionManifest{}
if err := json.Unmarshal(data, manifest); err != nil {
return nil, fmt.Errorf("parse mojang version manifest failed: %w", err)
}
if len(manifest.Versions) == 0 {
return nil, errors.New("mojang version manifest has no versions")
}
return manifest, nil
}
func ResolveVersionEntry(
manifest *fileschema.ApiMojangMinecraftVersionManifest,
targetVersion version.Version,
) (string, string, error) {
selected := targetVersion.String()
if targetVersion == "" || targetVersion.CanInfer() || targetVersion == version.Unknown {
selected = manifest.Latest.Release
}
if strings.EqualFold(selected, "snapshot") {
selected = manifest.Latest.Snapshot
}
for i := range manifest.Versions {
if manifest.Versions[i].ID == selected {
return manifest.Versions[i].ID, manifest.Versions[i].URL, nil
}
}
return "", "", fmt.Errorf(
"minecraft version %s not found in mojang manifest",
targetVersion.String(),
)
}
func (p *Provider) Fetch(
ctx context.Context,
id catalog.VersionedRef,
) (upstream.ResolvedPackage, error) {
manifest, err := p.VersionManifest(ctx)
if err != nil {
return upstream.ResolvedPackage{}, err
}
versionID, versionURL, err := ResolveVersionEntry(manifest, id.Version)
if err != nil {
return upstream.ResolvedPackage{}, err
}
detail, err := p.fetchVersionDetail(ctx, versionURL)
if err != nil {
return upstream.ResolvedPackage{}, err
}
if detail.Downloads.Server == nil {
return upstream.ResolvedPackage{}, fmt.Errorf(
"minecraft version %s does not provide a dedicated server jar",
versionID,
)
}
return upstream.ResolvedPackage{
FileURL: detail.Downloads.Server.URL,
Filename: "server.jar",
Hash: detail.Downloads.Server.Sha1,
HashAlgorithm: "sha1",
}, nil
}
// legacyJavaAdvisory is the Java major version for versions whose metadata
// predates the javaVersion block.
const legacyJavaAdvisory = 8
// JavaAdvisory returns the Java major version Mojang's launcher ships for the
// Minecraft version. Lucy treats it as an advisory minimum.
//
// Versions from 13w24a through 1.6.4 carry no javaVersion block. That metadata
// field arrived later, and Mojang pairs the versions on both sides of the gap
// with JRE 8, so those versions fall back to 8.
func (p *Provider) JavaAdvisory(
ctx context.Context,
minecraft version.Version,
) (int, error) {
manifest, err := p.VersionManifest(ctx)
if err != nil {
return 0, err
}
versionID, versionURL, err := ResolveVersionEntry(manifest, minecraft)
if err != nil {
return 0, err
}
detail, err := p.fetchVersionDetail(ctx, versionURL)
if err != nil {
return 0, err
}
if detail.JavaVersion == nil {
return legacyJavaAdvisory, nil
}
if detail.JavaVersion.MajorVersion <= 0 {
return 0, fmt.Errorf(
"minecraft version %s declares no java major version",
versionID,
)
}
return detail.JavaVersion.MajorVersion, nil
}
func (p *Provider) fetchVersionDetail(
ctx context.Context,
versionURL string,
) (*versionDetail, error) {
data, err := p.network.CachedGetBytes(
ctx,
versionURL,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
TTL: 7 * 24 * time.Hour,
},
)
if err != nil {
return nil, fmt.Errorf(
"fetch minecraft version metadata failed: %w",
err,
)
}
detail := &versionDetail{}
if err := json.Unmarshal(data, detail); err != nil {
return nil, fmt.Errorf(
"parse minecraft version metadata failed: %w",
err,
)
}
return detail, nil
}
package neoforge
import (
"context"
"encoding/xml"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
var (
mavenBaseURL = "https://maven.neoforged.net/releases/net/neoforged/neoforge"
metadataURL = "https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml"
docsURL = "https://docs.neoforged.net/user/docs/server/"
)
// Provider resolves NeoForge Maven metadata and installer artifacts over the
// shared network cache.
type Provider struct {
network *cache.Client
}
// New constructs a NeoForge installer provider. network supplies the cached
// HTTP transport; construction performs no requests.
func New(network *cache.Client) *Provider {
return &Provider{network: network}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderNeoForge
}
type mavenMetadata struct {
Versioning struct {
Latest string `xml:"latest"`
Release string `xml:"release"`
Versions []string `xml:"versions>version"`
} `xml:"versioning"`
}
// LatestMinecraftVersion reports the newest Minecraft version the metadata
// lists a build for. NeoForge encodes the Minecraft version in the loader
// version prefix.
func (p *Provider) LatestMinecraftVersion(ctx context.Context) (
versionpkg.Version,
error,
) {
body, err := p.network.CachedGetBytes(
ctx,
metadataURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return "", fmt.Errorf("fetch NeoForge metadata failed: %w", err)
}
var meta mavenMetadata
if err := xml.Unmarshal(body, &meta); err != nil {
return "", fmt.Errorf("parse NeoForge metadata failed: %w", err)
}
versions := make([]versionpkg.Version, 0, len(meta.Versioning.Versions))
for _, loader := range meta.Versioning.Versions {
if minecraft, ok := minecraftVersionOf(loader); ok {
versions = append(versions, minecraft)
}
}
return versionpkg.NewestMinecraft(versions)
}
// neoForgePrefix names the loader version prefix for a Minecraft version. A
// 1.x release drops the leading 1 (1.21.4 → 21.4.), while a year-based
// release keeps its full version (26.3 → 26.3.).
func neoForgePrefix(gameVersion versionpkg.Version) (string, bool) {
parts := strings.Split(gameVersion.String(), ".")
if len(parts) < 2 {
return "", false
}
year, err := strconv.Atoi(parts[0])
if err != nil {
return "", false
}
if year >= 26 {
return gameVersion.String() + ".", true
}
return strings.Join(parts[1:], ".") + ".", true
}
// minecraftVersionOf inverts the loader version prefix: 21.4.16 belongs to
// Minecraft 1.21.4, 21.1.66 to 1.21.1, and 26.3.0.98 to 26.3.
func minecraftVersionOf(loader string) (versionpkg.Version, bool) {
base, _, _ := strings.Cut(loader, "-")
parts := strings.Split(base, ".")
if len(parts) < 3 {
return "", false
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return "", false
}
minor, err := strconv.Atoi(parts[1])
if err != nil {
return "", false
}
if major >= 26 {
patch, err := strconv.Atoi(parts[2])
if err != nil {
return "", false
}
if patch != 0 {
return versionpkg.Version(fmt.Sprintf("%d.%d.%d", major, minor, patch)), true
}
return versionpkg.Version(fmt.Sprintf("%d.%d", major, minor)), true
}
if minor == 0 {
return versionpkg.Version(fmt.Sprintf("1.%d", major)), true
}
return versionpkg.Version(fmt.Sprintf("1.%d.%d", major, minor)), true
}
func (p *Provider) Fetch(
ctx context.Context,
minecraft versionpkg.Version,
id catalog.VersionedRef,
) (upstream.ResolvedPackage, error) {
gameVersion, err := minecraftVersionForInstall(minecraft)
if err != nil {
return upstream.ResolvedPackage{}, err
}
neoForgeVersion, err := p.neoForgeVersionFromPackageRef(ctx, id, gameVersion)
if err != nil {
return upstream.ResolvedPackage{}, err
}
fileURL := installerURL(neoForgeVersion)
return upstream.ResolvedPackage{
FileURL: fileURL,
Filename: fmt.Sprintf(
"neoforge-%s-installer.jar",
neoForgeVersion,
),
}, nil
}
func minecraftVersionForInstall(minecraft versionpkg.Version) (versionpkg.Version, error) {
if minecraft == "" || minecraft.IsInvalid() || minecraft.CanInfer() {
return "", errors.New(
"neoforge bootstrap requires a concrete Minecraft version",
)
}
return minecraft, nil
}
func (p *Provider) neoForgeVersionFromPackageRef(
ctx context.Context,
ref catalog.VersionedRef,
gameVersion versionpkg.Version,
) (string, error) {
if ref.Version != versionpkg.Beta &&
ref.Version != versionpkg.Stable &&
ref.Version != versionpkg.Any &&
ref.Version != versionpkg.Unknown {
return ref.Version.String(), nil
}
return p.fetchVersion(ctx, gameVersion, ref.Version)
}
// fetchVersion selects the newest NeoForge version for the Minecraft
// version. stable excludes prerelease builds; beta accepts any build; any
// prefers a release and falls back to a prerelease.
func (p *Provider) fetchVersion(
ctx context.Context,
gameVersion versionpkg.Version,
selector versionpkg.Version,
) (string, error) {
body, err := p.network.CachedGetBytes(
ctx,
metadataURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return "", fmt.Errorf("fetch NeoForge metadata failed: %w", err)
}
var meta mavenMetadata
if err := xml.Unmarshal(body, &meta); err != nil {
return "", fmt.Errorf("parse NeoForge metadata failed: %w", err)
}
neoPrefix, ok := neoForgePrefix(gameVersion)
if !ok {
return "", fmt.Errorf(
"cannot derive NeoForge version prefix from Minecraft version %s",
gameVersion,
)
}
matching := make([]string, 0, len(meta.Versioning.Versions))
for _, v := range meta.Versioning.Versions {
if strings.HasPrefix(v, neoPrefix) {
matching = append(matching, v)
}
}
if len(matching) == 0 {
return "", fmt.Errorf(
"no NeoForge version found for Minecraft %s (looked for prefix %s); see %s",
gameVersion,
neoPrefix,
docsURL,
)
}
switch selector {
case versionpkg.Stable:
for _, v := range slices.Backward(matching) {
if !isPrereleaseVersion(v) {
return v, nil
}
}
return "", fmt.Errorf(
"no stable NeoForge release found for Minecraft %s; see %s",
gameVersion,
docsURL,
)
case versionpkg.Beta:
return matching[len(matching)-1], nil
default:
for _, v := range slices.Backward(matching) {
if !isPrereleaseVersion(v) {
return v, nil
}
}
return matching[len(matching)-1], nil
}
}
func isPrereleaseVersion(version string) bool {
lower := strings.ToLower(version)
for _, marker := range []string{
"-beta", "-alpha", "-pre", "-rc", "-snapshot",
} {
if strings.Contains(lower, marker) {
return true
}
}
return false
}
func installerURL(neoForgeVersion string) string {
return fmt.Sprintf(
"%s/%s/neoforge-%s-installer.jar",
mavenBaseURL,
neoForgeVersion,
neoForgeVersion,
)
}
// Package retry performs bounded retries with backoff for read-only provider
// lookups. It never wraps a mutation: callers use it only for requests whose
// repetition has no side effect.
package retry
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"strconv"
"strings"
"time"
)
// StatusError carries the HTTP status of a failed lookup so callers can tell a
// transient failure from a permanent one.
type StatusError struct {
Status int
}
func (e *StatusError) Error() string {
return fmt.Sprintf("status %d", e.Status)
}
// HTTPStatus reports the response status that failed.
func (e *StatusError) HTTPStatus() int {
return e.Status
}
// HTTPStatusError is implemented by provider errors that carry a response
// status, letting Splittable classify failures without sharing one error type.
type HTTPStatusError interface {
error
HTTPStatus() int
}
// StatusOf reports the HTTP status carried by err, if any.
func StatusOf(err error) (int, bool) {
var statusErr HTTPStatusError
if errors.As(err, &statusErr) {
return statusErr.HTTPStatus(), true
}
return 0, false
}
// ThrottledError reports a lookup the provider asked callers to delay before
// asking again. Callers stop the affected lookup instead of shortening the
// delay or retrying a smaller batch early. It is only created when the
// provider asked for a delay; a transient status without one stays an
// ordinary retryable failure.
type ThrottledError struct {
Status int
RetryAfter time.Duration
}
func (e *ThrottledError) Error() string {
return fmt.Sprintf(
"status %d: throttled, retry after %s",
e.Status,
e.RetryAfter,
)
}
// HTTPStatus reports the throttle status so batch splitting can classify it.
func (e *ThrottledError) HTTPStatus() int {
return e.Status
}
// Throttled reports whether err is a rate limit that asked for a delay. Such a
// failure ends the affected lookup: splitting it or starting the next batch
// would reach the provider before the delay it requested.
func Throttled(err error) bool {
var throttled *ThrottledError
return errors.As(err, &throttled)
}
// permanentError marks a failure that repeating a request cannot fix.
type permanentError struct {
err error
}
func (e permanentError) Error() string {
return e.err.Error()
}
func (e permanentError) Unwrap() error {
return e.err
}
// Permanent marks err as unretryable. Callers use it for local failures such as
// an unencodable request or an undecodable response, which a smaller batch
// would repeat unchanged.
func Permanent(err error) error {
if err == nil {
return nil
}
return permanentError{err: err}
}
// Policy bounds one retryable operation.
type Policy struct {
// MaxAttempts includes the first attempt.
MaxAttempts int
BaseDelay time.Duration
MaxDelay time.Duration
// MaxThrottleWait bounds the total server-requested delay one operation
// may spend. Zero uses the default.
MaxThrottleWait time.Duration
}
// Default retries a lookup twice after its first attempt with exponential
// backoff. A server-provided Retry-After wins over the computed delay.
var Default = Policy{
MaxAttempts: 3,
BaseDelay: 200 * time.Millisecond,
MaxDelay: 2 * time.Second,
MaxThrottleWait: defaultMaxThrottleWait,
}
// defaultMaxThrottleWait bounds the cumulative server-requested delay one
// retry operation may spend. A delay that would exceed it is never silently
// shortened: the lookup stops with the throttled outcome instead, so no
// request reaches the provider before the delay it requested.
const defaultMaxThrottleWait = 30 * time.Second
// MaxSplitDepth bounds how many times a failed lookup batch is bisected.
// Three levels turn one 100-item failure into at most eight parts, keeping the
// work spent isolating a persistent failure bounded.
const MaxSplitDepth = 3
// Attempt is one lookup outcome. A non-transient HTTP failure is final even
// if the response body failed to read. A zero Status means no response arrived.
type Attempt struct {
Status int
RetryAfter time.Duration
Err error
}
// TransientStatus reports whether a read-only request status is worth
// retrying: a rate limit or a server-side failure.
func TransientStatus(status int) bool {
return status == http.StatusTooManyRequests ||
(status >= 500 && status <= 599)
}
// Do runs attempt until it returns a final outcome, the policy exhausts its
// attempts, or ctx ends. A transport error is retried like a transient status.
// A non-transient HTTP failure stays final even if reading its body failed.
// A requested throttle delay is honored as given. If the remaining budget
// cannot cover it, the lookup stops rather than retrying early.
func Do(
ctx context.Context,
policy Policy,
attempt func(context.Context) Attempt,
) Attempt {
policy = policy.normalized()
var last Attempt
var throttleWaited time.Duration
for number := 1; number <= policy.MaxAttempts; number++ {
if err := ctx.Err(); err != nil {
return Attempt{Err: err}
}
last = attempt(ctx)
if _, permanent := errors.AsType[permanentError](last.Err); permanent {
return last
}
httpFailure := last.Status != 0 && (last.Status < 200 || last.Status >= 300)
if !TransientStatus(last.Status) && (last.Err == nil || httpFailure) {
return last
}
if number == policy.MaxAttempts {
return last
}
if !policy.fitsThrottleWait(ctx, throttleWaited, last.RetryAfter) {
return last
}
throttleWaited += last.RetryAfter
if err := wait(ctx, policy.delay(number, last.RetryAfter)); err != nil {
return Attempt{Err: err}
}
}
return last
}
// fitsThrottleWait reports whether a requested delay fits the operation's
// cumulative throttle budget and the context deadline. Zero means the attempt
// requested no delay.
func (p Policy) fitsThrottleWait(
ctx context.Context,
waited, requested time.Duration,
) bool {
if requested <= 0 {
return true
}
if requested > p.MaxThrottleWait-waited {
return false
}
if deadline, ok := ctx.Deadline(); ok && requested >= time.Until(deadline) {
return false
}
return true
}
// RetryAfter parses the Retry-After header as either delay-seconds or an HTTP
// date. A missing, past, or malformed value reports no requested delay. The
// parsed delay is returned as given: a value beyond the operation budget stops
// the lookup in Do rather than being shortened here. A numeric value too large
// for the duration type saturates instead of reading as absent.
func RetryAfter(header http.Header) time.Duration {
value := strings.TrimSpace(header.Get("Retry-After"))
if value == "" {
return 0
}
seconds, err := strconv.ParseUint(value, 10, 64)
if err == nil && seconds > 0 {
const maxSeconds = uint64(math.MaxInt64 / time.Second)
if seconds > maxSeconds {
// Parsed seconds fit uint64 but exceed what time.Duration can
// represent after scaling; saturate.
return time.Duration(math.MaxInt64)
}
return time.Duration(seconds) * time.Second
}
if errors.Is(err, strconv.ErrRange) && strings.IndexFunc(value, func(c rune) bool {
return c < '0' || c > '9'
}) == -1 {
// Syntactically valid digits overflowed; the provider asked to wait
// longer than any duration can express, so saturate.
return time.Duration(math.MaxInt64)
}
if at, err := http.ParseTime(value); err == nil {
if delay := time.Until(at); delay > 0 {
return delay
}
}
return 0
}
// Splittable reports whether a failed batch lookup may be retried per part.
// Permanent statuses and caller cancellation are final; every other failure,
// including a wrapped transport error, may still succeed for a smaller batch.
// A rate limit that asked for a delay is final too: splitting it would reach
// the provider before that delay. A rate limit without a delay stays
// splittable like any other transient status.
func Splittable(err error) bool {
if err == nil ||
errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return false
}
var permanent permanentError
if errors.As(err, &permanent) {
return false
}
if Throttled(err) {
return false
}
if status, ok := StatusOf(err); ok {
return TransientStatus(status)
}
return true
}
func (p Policy) normalized() Policy {
if p.MaxAttempts < 1 {
p.MaxAttempts = 1
}
if p.BaseDelay <= 0 {
p.BaseDelay = Default.BaseDelay
}
if p.MaxDelay <= 0 {
p.MaxDelay = Default.MaxDelay
}
if p.MaxDelay < p.BaseDelay {
p.MaxDelay = p.BaseDelay
}
if p.MaxThrottleWait <= 0 {
p.MaxThrottleWait = Default.MaxThrottleWait
}
return p
}
func (p Policy) delay(number int, retryAfter time.Duration) time.Duration {
// A server-requested delay is returned as given. Do decides whether it
// fits the operation budget before waiting.
if retryAfter > 0 {
return retryAfter
}
delay := p.BaseDelay
for step := 1; step < number && delay < p.MaxDelay; step++ {
delay *= 2
}
if delay > p.MaxDelay {
return p.MaxDelay
}
return delay
}
func wait(ctx context.Context, delay time.Duration) error {
if delay <= 0 {
return ctx.Err()
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
package spiget
import (
"context"
"errors"
"fmt"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/upstream"
)
// Provider resolves Spiget resources and versions through one configured
// network cache. logger may be nil, which records nothing.
type Provider struct {
network *cache.Client
logger *log.Logger
}
// New constructs a Spiget provider. network supplies the cached HTTP
// transport; construction performs no requests.
func New(network *cache.Client, logger *log.Logger) *Provider {
return &Provider{network: network, logger: logger}
}
func (p *Provider) Provider() catalog.Provider {
return catalog.ProviderSpiget
}
// Builds lists every published resource version. Spiget exposes no per-version
// game versions, loaders, or channel, so those stay unknown.
func (p *Provider) Builds(ctx context.Context, project string) ([]upstream.Build, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
resource, err := p.resolveResourceByProjectName(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
versions, err := p.listVersions(ctx, resource.ID)
if err != nil {
return nil, err
}
builds := make([]upstream.Build, 0, len(versions))
for _, v := range versions {
builds = append(builds, v.ToBuild())
}
return builds, nil
}
func (p *Provider) Search(ctx context.Context, q upstream.Query) (upstream.SearchResponse, error) {
// Spiget publishes server resources only; IncludeClient needs no filter.
if q.FilterEcosystem == catalog.EcosystemBukkit || q.FilterEcosystem == catalog.EcosystemPaper {
p.logger.Debug("spiget: platform filter is not supported upstream; search will run without a platform query parameter")
}
resp, err := p.searchResources(ctx, q.Keyword)
if err != nil {
return upstream.SearchResponse{}, err
}
return resp.ToSearchResults(p.Provider()), nil
}
func (p *Provider) Info(ctx context.Context, ref catalog.Ref) (catalog.Metadata, error) {
resource, err := p.resolveResourceByProjectName(ctx, ref.Name)
if err != nil {
return catalog.Metadata{}, err
}
info := resource.ToProjectInformation()
return info, nil
}
var (
ErrNoProject = errors.New("spiget: project not found")
ErrNoVersion = errors.New("spiget: version not found")
)
func unexpectedStatusError(url string, statusCode int) error {
return fmt.Errorf("spiget: unexpected status %d for %s", statusCode, url)
}
package spiget
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// ErrAmbiguousProject reports a display-name lookup that matches more than one
// Spiget resource. SpigotMC publishes distinct resources under identical names,
// so the catalogue refuses to pick one of them.
var ErrAmbiguousProject = errors.New("spiget: project name is ambiguous")
// Candidates lists the downloadable version of one Spiget resource.
//
// Spiget exposes exactly one download per resource that Lucy can fetch:
//
// - The resource-scoped endpoint (/resources/{id}/download) redirects to the
// CDN copy of the CURRENT file. It accepts no version selector, so it can
// only ever serve resource.Version.ID.
// - The version-scoped endpoint (/versions/{id}/download) redirects to
// spigotmc.org, which answers automated clients with a Cloudflare challenge,
// so it yields no bytes and no usable pinned URL.
//
// Candidates therefore reports the current version only, identified by the
// numeric resource and version IDs. Listing older versions would resolve
// metadata and then fail during materialization. The candidate URL is mutable
// upstream, so the lock records the SHA-256 of the bytes actually fetched and a
// later re-download that differs fails verification instead of installing
// different bytes under the pinned version.
//
// Spiget reports no hashes, release channel, dependency declarations, or
// per-version game and loader compatibility. Candidates therefore assert none of
// them: Channel stays unknown and both DependenciesUnknown and
// CompatibilityUnknown are set. Resource-level testedVersions describe the
// resource as a whole, not one published version, so they are not used as
// compatibility evidence; the requested Minecraft version cannot be verified or
// filtered here.
func (p *Provider) Candidates(
ctx context.Context,
project, _ string,
loader catalog.Ecosystem,
) ([]upstream.Candidate, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if !spigetServesLoader(loader) {
return nil, fmt.Errorf(
"spiget: %s packages are not published upstream; Spiget serves Bukkit and Paper plugins",
loader,
)
}
resource, err := p.resolveCatalogueResource(ctx, catalog.Name(project))
if err != nil {
return nil, err
}
if err := downloadCapabilityError(*resource); err != nil {
return nil, err
}
currentVersionID := resource.currentVersionID()
versions, err := p.listVersions(ctx, resource.ID)
if err != nil {
return nil, err
}
downloadURL := resourceDownloadURL(resource.ID)
if resource.External {
downloadURL = strings.TrimSpace(resource.File.ExternalURL)
}
for _, version := range versions {
if version.ID != currentVersionID {
continue
}
return []upstream.Candidate{{
Artifact: catalog.Artifact{
Provider: catalog.ProviderSpiget,
ProjectID: strconv.FormatInt(resource.ID, 10),
ReleaseID: strconv.FormatInt(version.ID, 10),
FileID: strconv.FormatInt(version.ID, 10),
Version: spigetVersion(version.Name, version.ID),
Filename: artifactFilename(
resource.ID,
resource.Name,
version.Name,
version.ID,
resource.File.Type,
downloadURL,
),
URL: downloadURL,
},
Channel: upstream.ReleaseChannelUnknown,
PublishedAt: releaseTime(version.ReleaseDate),
PrimaryFile: true,
DependenciesUnknown: true,
CompatibilityUnknown: true,
}}, nil
}
return nil, fmt.Errorf(
"spiget: resource %d (%s) does not publish its current version %d in its version history",
resource.ID,
resource.Name,
currentVersionID,
)
}
// spigetServesLoader reports whether Lucy may hand this ecosystem to Spiget.
// SpigotMC publishes Bukkit plugins, which Paper also loads; an unspecified
// ecosystem states no constraint to check.
func spigetServesLoader(loader catalog.Ecosystem) bool {
switch loader {
case catalog.EcosystemUnspecified, catalog.EcosystemBukkit,
catalog.EcosystemPaper:
return true
default:
return false
}
}
func releaseTime(unix int64) time.Time {
if unix <= 0 {
return time.Time{}
}
return time.Unix(unix, 0).UTC()
}
package spiget
import (
"encoding/base64"
"net/url"
"path"
"strconv"
"strings"
"unicode"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/upstream"
versionpkg "github.com/mclucy/lucy/version"
)
const (
spigetAPIBaseURL = "https://api.spiget.org/v2"
spigotWebsiteBaseURL = "https://www.spigotmc.org/"
)
type decodedHTML struct {
Text string
Valid bool
}
// ToSearchResults exposes Spiget's numeric resource ID as the project
// identity. SpigotMC publishes several resources under one display name, so a
// normalized name is not stable or installable; the ID is, and the display name
// travels as the result title.
func (s searchResponse) ToSearchResults(source catalog.Provider) upstream.SearchResponse {
results := upstream.SearchResponse{
Provider: source,
Items: make([]upstream.SearchResult, 0, len(s)),
}
for _, resource := range s {
if resource.ID <= 0 || resource.Name == "" {
continue
}
results.Items = append(
results.Items, upstream.SearchResult{
ProjectName: strconv.FormatInt(resource.ID, 10),
Provider: source,
Title: resource.Name,
Description: resource.Tag,
Downloads: resource.Downloads,
},
)
}
return results
}
func (r resourceResponse) ToProjectInformation() catalog.Metadata {
description := combineHTMLSections(
decodeBase64HTML(r.Description),
decodeBase64HTML(r.Documentation),
)
info := catalog.Metadata{
Title: r.Name,
Brief: r.Tag,
Description: description,
DescriptionIsMarkdown: false,
URLs: make([]catalog.URL, 0, len(r.Links)+2),
}
appendLinkURLs(&info, r.Links)
if r.SourceCodeLink != "" {
info.URLs = append(
info.URLs,
catalog.URL{
Name: "Source", Type: catalog.URLSource, URL: r.SourceCodeLink,
},
)
}
if r.DonationLink != "" {
info.URLs = append(
info.URLs,
catalog.URL{
Name: "Donate", Type: catalog.URLSponsor, URL: r.DonationLink,
},
)
}
return info
}
// ToBuild maps one Spiget resource version to a build. Spiget version records
// carry no game versions, loaders, or channel; resource-level tested versions
// are not build-specific and stay out of the build.
func (v versionResponse) ToBuild() upstream.Build {
build := upstream.Build{
Version: strings.TrimSpace(v.Name),
Published: releaseTime(v.ReleaseDate),
}
if build.Version == "" && v.ID > 0 {
build.Version = strconv.FormatInt(v.ID, 10)
}
return build
}
// spigetVersion reports the human version label, falling back to the numeric
// version ID when the publisher left the label empty. The ID is always kept
// separately as the release and file identity.
func spigetVersion(name string, id int64) versionpkg.Version {
if name = strings.TrimSpace(name); name != "" {
return versionpkg.Version(name)
}
if id > 0 {
return versionpkg.Version(strconv.FormatInt(id, 10))
}
return versionpkg.Unknown
}
// artifactFilename names the local file for one published version. Spiget's API
// reports the archive type but never the uploaded file name, so a Spiget-hosted
// version gets a name derived from provider fields. An external download URL
// names the file itself, so its last path element is used unchanged.
func artifactFilename(
resourceID int64,
projectName, versionName string,
versionID int64,
fileType, downloadURL string,
) string {
if name := archiveFilename(downloadURL); name != "" {
return name
}
base := normalizedProjectName(projectName).String()
if base == "" {
base = strconv.FormatInt(resourceID, 10)
}
label := sanitizeFilenamePart(versionName)
if label == "" && versionID > 0 {
label = strconv.FormatInt(versionID, 10)
}
if label != "" {
base += "-" + label
}
if ext := normalizedFileExtension(fileType); ext != "" {
return base + ext
}
return base
}
// archiveFilename returns the file name of a direct plugin-archive URL, or ""
// when the URL does not address one. Spiget's external URLs sometimes point at
// a release page rather than an archive; installing such a page would not
// produce a plugin.
func archiveFilename(rawURL string) string {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil {
return ""
}
name := path.Base(parsed.Path)
if name == "" || name == "." || name == "/" {
return ""
}
if !strings.EqualFold(path.Ext(name), ".jar") {
return ""
}
if strings.ContainsAny(name, "/\\") {
return ""
}
return name
}
// sanitizeFilenamePart keeps a version label safe for a file name without
// dropping its readable form.
func sanitizeFilenamePart(part string) string {
part = strings.TrimSpace(part)
var b strings.Builder
b.Grow(len(part))
lastReplaced := false
for _, r := range part {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r) || r == '.' ||
r == '_' || r == '-':
b.WriteRune(r)
lastReplaced = false
case !lastReplaced:
b.WriteByte('-')
lastReplaced = true
}
}
return strings.Trim(b.String(), "-.")
}
func normalizedFileExtension(fileType string) string {
trimmed := strings.TrimSpace(fileType)
if trimmed == "" || strings.EqualFold(trimmed, "external") {
return ""
}
if strings.HasPrefix(trimmed, ".") {
return trimmed
}
return "." + trimmed
}
func decodeBase64HTML(encoded string) decodedHTML {
encoded = strings.TrimSpace(encoded)
if encoded == "" {
return decodedHTML{}
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return decodedHTML{}
}
return decodedHTML{Text: string(decoded), Valid: true}
}
func combineHTMLSections(description, documentation decodedHTML) string {
switch {
case description.Valid && documentation.Valid:
return description.Text + "\n\n<hr />\n\n<h2>Documentation</h2>\n" + documentation.Text
case description.Valid:
return description.Text
case documentation.Valid:
return documentation.Text
default:
return ""
}
}
func appendLinkURLs(info *catalog.Metadata, links map[string]string) {
for key, rawValue := range links {
value := normalizeSpigetURL(rawValue)
if value == "" {
continue
}
name, kind := classifySpigetLink(key)
info.URLs = append(
info.URLs,
catalog.URL{Name: name, Type: kind, URL: value},
)
}
}
func normalizeSpigetURL(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
return raw
}
if strings.HasPrefix(raw, "/") {
return spigotWebsiteBaseURL[:len(spigotWebsiteBaseURL)-1] + raw
}
if strings.HasPrefix(raw, "threads/") || strings.HasPrefix(
raw,
"resources/",
) || strings.HasPrefix(raw, "members/") {
return spigotWebsiteBaseURL + raw
}
return raw
}
func classifySpigetLink(key string) (string, catalog.URLType) {
switch key {
case "additionalInformation":
return "Additional information", catalog.URLHome
case "alternativeSupport":
return "Support", catalog.URLForum
case "discussion":
return "Discussion", catalog.URLForum
}
decoded := decodeBase64HTML(key)
if decoded.Valid {
if _, err := url.ParseRequestURI(decoded.Text); err == nil {
return "Link", catalog.URLMisc
}
return prettifyLinkName(decoded.Text), catalog.URLMisc
}
return prettifyLinkName(key), catalog.URLMisc
}
func prettifyLinkName(name string) string {
name = strings.TrimSpace(name)
if name == "" {
return "Link"
}
replacer := strings.NewReplacer("-", " ", "_", " ")
name = replacer.Replace(name)
return strings.ToUpper(name[:1]) + name[1:]
}
func normalizedProjectName(name string) catalog.Name {
name = input.ToProjectName(name).String()
var b strings.Builder
b.Grow(len(name))
lastHyphen := false
for _, r := range name {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
b.WriteRune(unicode.ToLower(r))
lastHyphen = false
case !lastHyphen:
b.WriteByte('-')
lastHyphen = true
}
}
return catalog.Name(strings.Trim(b.String(), "-"))
}
package spiget
import (
"context"
"encoding/json/v2"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
)
func (p *Provider) requestJSON(
ctx context.Context,
requestURL string,
out any,
notFound error,
) error {
p.logger.Debug("spiget api: GET " + requestURL)
resp, err := p.network.CachedGetRequest(
ctx,
requestURL,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return fmt.Errorf("spiget: request failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound && notFound != nil {
return notFound
}
return unexpectedStatusError(requestURL, resp.StatusCode)
}
if err := json.Unmarshal(resp.Data, out); err != nil {
return fmt.Errorf("spiget: failed to decode response: %w", err)
}
return nil
}
func (p *Provider) searchResources(
ctx context.Context,
query string,
) (
searchResponse,
error,
) {
u := searchResourcesURL(query)
resp := searchResponse{}
if err := p.requestJSON(ctx, u, &resp, nil); err != nil {
return nil, err
}
return resp, nil
}
func (p *Provider) getResource(
ctx context.Context,
id int64,
) (*resourceResponse, error) {
resp := &resourceResponse{}
if err := p.requestJSON(ctx, resourceURL(id), resp, ErrNoProject); err != nil {
return nil, err
}
return resp, nil
}
const spigetVersionPageSize = 1000
func (p *Provider) listVersions(
ctx context.Context,
resourceID int64,
) ([]versionResponse, error) {
var versions []versionResponse
for page := 1; ; page++ {
var resp []versionResponse
if err := p.requestJSON(
ctx,
versionsURL(resourceID, page),
&resp,
ErrNoVersion,
); err != nil {
return nil, err
}
versions = append(versions, resp...)
if len(resp) < spigetVersionPageSize {
break
}
}
return versions, nil
}
func searchResourcesURL(query string) string {
values := url.Values{}
values.Set("size", "20")
return spigetAPIBaseURL + "/search/resources/" + url.PathEscape(query) + "?" + values.Encode()
}
func resourceURL(id int64) string {
return spigetAPIBaseURL + "/resources/" + strconv.FormatInt(id, 10)
}
// resourceDownloadURL returns the resource-scoped download endpoint. Spiget
// redirects it to the CDN copy of the resource's CURRENT file; the endpoint
// accepts no version selector, so it is only used for the current version.
func resourceDownloadURL(resourceID int64) string {
return resourceURL(resourceID) + "/download"
}
// currentVersionID reports which published version the resource's file belongs
// to. Spiget exposes it as the resource's version pointer and repeats it as the
// version query of file.url; either identifies the single external download.
func (r resourceResponse) currentVersionID() int64 {
if r.Version.ID > 0 {
return r.Version.ID
}
return fileURLVersionID(r.File.URL)
}
func fileURLVersionID(raw string) int64 {
parsed, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return 0
}
versionID, err := strconv.ParseInt(parsed.Query().Get("version"), 10, 64)
if err != nil || versionID <= 0 {
return 0
}
return versionID
}
func versionsURL(resourceID int64, page int) string {
values := url.Values{}
values.Set("size", strconv.Itoa(spigetVersionPageSize))
values.Set("page", strconv.Itoa(page))
values.Set("sort", "-releaseDate")
return resourceURL(resourceID) + "/versions?" + values.Encode()
}
func parseNumericResourceID(name catalog.Name) (int64, bool) {
trimmed := strings.TrimSpace(name.String())
if trimmed == "" {
return 0, false
}
id, err := strconv.ParseInt(trimmed, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
package spiget
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/mclucy/lucy/catalog"
)
// resolveResourceByProjectName resolves a resource for identity lookups such as
// info and build listing. It keeps the lenient single-search-hit fallback that
// explicit installs do not use.
func (p *Provider) resolveResourceByProjectName(
ctx context.Context,
name catalog.Name,
) (
*resourceResponse,
error,
) {
resource, err := p.resolveCatalogueResource(ctx, name)
if err == nil {
return resource, nil
}
if !errors.Is(err, ErrNoProject) {
return nil, err
}
// A lone search hit is accepted even when its name differs slightly; one
// result cannot be confused with another project.
results, err := p.searchResources(ctx, name.String())
if err != nil {
return nil, err
}
if len(results) == 1 && results[0].ID > 0 {
return p.getResource(ctx, results[0].ID)
}
return nil, ErrNoProject
}
// resolveCatalogueResource resolves the explicit identity a package request
// carries. A numeric resource ID is Spiget's only stable, installable identity.
// A display name is accepted only when exactly one resource matches it:
// SpigotMC publishes distinct resources under identical names, and choosing one
// of them would install an arbitrary project.
func (p *Provider) resolveCatalogueResource(
ctx context.Context,
name catalog.Name,
) (
*resourceResponse,
error,
) {
if id, ok := parseNumericResourceID(name); ok {
return p.getResource(ctx, id)
}
results, err := p.searchResources(ctx, name.String())
if err != nil {
return nil, err
}
wanted := normalizedProjectName(name.String())
matches := make([]resourceResponse, 0, 1)
seen := make(map[int64]struct{}, len(results))
for _, candidate := range results {
if candidate.ID <= 0 {
continue
}
if _, duplicate := seen[candidate.ID]; duplicate {
continue
}
if normalizedProjectName(candidate.Name) != wanted &&
!strings.EqualFold(candidate.Name, name.String()) {
continue
}
seen[candidate.ID] = struct{}{}
matches = append(matches, candidate)
}
switch len(matches) {
case 0:
return nil, ErrNoProject
case 1:
return p.getResource(ctx, matches[0].ID)
default:
ids := make([]string, 0, len(matches))
for _, match := range matches {
ids = append(ids, strconv.FormatInt(match.ID, 10))
}
return nil, fmt.Errorf(
"%w: %q matches resources %s; use one Spiget resource ID",
ErrAmbiguousProject,
name,
strings.Join(ids, ", "),
)
}
}
// downloadCapabilityError reports why a resource cannot provide a pinned
// artifact at all. Premium resources have no public file; every resource must
// report which version its single download URL serves; and an external URL must
// name a plugin archive, because SpigotMC external resources sometimes point at
// release pages instead.
func downloadCapabilityError(resource resourceResponse) error {
if resource.Premium {
return fmt.Errorf(
"spiget: resource %d (%s) is a premium resource with no public download",
resource.ID,
resource.Name,
)
}
if resource.currentVersionID() == 0 {
return fmt.Errorf(
"spiget: resource %d (%s) does not report which version its download serves",
resource.ID,
resource.Name,
)
}
if resource.External {
if archiveFilename(resource.File.ExternalURL) == "" {
return fmt.Errorf(
"spiget: resource %d (%s) downloads from %q, which is not a plugin archive pinned to a version",
resource.ID,
resource.Name,
resource.File.ExternalURL,
)
}
return nil
}
if normalizedFileExtension(resource.File.Type) == "" {
return fmt.Errorf(
"spiget: resource %d (%s) does not report the archive type of its download",
resource.ID,
resource.Name,
)
}
return nil
}
// Package routing composes configured provider instances with provider
// selection and execution policy.
//
// Responsibilities:
// - Resolve ProviderUnspecified against an Ecosystem into ordered provider
// candidates.
// - Map an explicit Provider (or Registry for search) to exactly one
// capability when supported.
// - Route search, project metadata, package catalogues, and server products.
// - Return typed selection errors for invalid/unsupported inputs.
//
// Non-responsibilities:
// - Do not aggregate or merge upstream result payloads.
package routing
import (
"context"
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/cache"
catalogpkg "github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/log"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/curseforge"
"github.com/mclucy/lucy/upstream/internal/providers/forge"
"github.com/mclucy/lucy/upstream/internal/providers/hangar"
"github.com/mclucy/lucy/upstream/internal/providers/loadermeta"
"github.com/mclucy/lucy/upstream/internal/providers/mcdr"
"github.com/mclucy/lucy/upstream/internal/providers/modrinth"
"github.com/mclucy/lucy/upstream/internal/providers/mojang"
"github.com/mclucy/lucy/upstream/internal/providers/neoforge"
"github.com/mclucy/lucy/upstream/internal/providers/spiget"
)
var (
ErrUnknownProvider = errors.New("unknown provider")
ErrUnsupportedProvider = errors.New("unsupported provider")
ErrInvalidEcosystem = errors.New("cannot find providers for ecosystem")
ErrNoCatalogue = errors.New("registry has no package catalogue")
)
type providerCatalog struct {
searchProviders map[catalogpkg.Registry]upstream.SearchProvider
infoProviders map[catalogpkg.Provider]upstream.InfoProvider
artifactReleases map[catalogpkg.Provider]upstream.ArtifactReleaseMapper
catalogues map[catalogpkg.Provider]upstream.PackageCatalogue
importPacks map[catalogpkg.Provider]upstream.ImportPackResolver
}
// Router binds configured provider instances to their capabilities and applies
// provider selection policy. One Router belongs to one invocation: providers
// own the network cache, logger, and API keys they were constructed with.
type Router struct {
logger *log.Logger
network *cache.Client
providers providerCatalog
mojang *mojang.Provider
forge *forge.Provider
neoforge *neoforge.Provider
loaders map[server.Product]*loadermeta.Provider
}
// New constructs a router over provider instances. network carries HTTP and
// cache configuration for metadata and artifact requests; logger may be nil.
// curseforgeAPIKey is the effective key: an empty key leaves CurseForge
// unregistered. Construction performs no network requests and decodes no key.
func New(
network *cache.Client,
logger *log.Logger,
curseforgeAPIKey string,
) *Router {
modrinthProvider := modrinth.New(network, logger)
hangarProvider := hangar.New(network, logger)
spigetProvider := spiget.New(network, logger)
mcdrProvider := mcdr.New(network, logger)
router := &Router{
logger: logger,
network: network,
mojang: mojang.New(network),
forge: forge.New(network),
neoforge: neoforge.New(network),
}
router.loaders = make(
map[server.Product]*loadermeta.Provider,
len(loaderRuntimes),
)
for product, definition := range loaderRuntimes {
router.loaders[product] = loadermeta.New(network, definition.meta)
}
router.providers = providerCatalog{
searchProviders: map[catalogpkg.Registry]upstream.SearchProvider{
catalogpkg.RegistryModrinth: modrinthProvider,
catalogpkg.RegistryMCDR: mcdrProvider,
catalogpkg.RegistryHangar: hangarProvider,
catalogpkg.RegistrySpiget: spigetProvider,
},
infoProviders: map[catalogpkg.Provider]upstream.InfoProvider{
catalogpkg.ProviderModrinth: modrinthProvider,
catalogpkg.ProviderMCDR: mcdrProvider,
catalogpkg.ProviderHangar: hangarProvider,
catalogpkg.ProviderSpiget: spigetProvider,
},
catalogues: map[catalogpkg.Provider]upstream.PackageCatalogue{
catalogpkg.ProviderModrinth: modrinthProvider,
catalogpkg.ProviderMCDR: mcdrProvider,
catalogpkg.ProviderHangar: hangarProvider,
catalogpkg.ProviderSpiget: spigetProvider,
},
artifactReleases: map[catalogpkg.Provider]upstream.ArtifactReleaseMapper{
catalogpkg.ProviderModrinth: modrinthProvider,
},
importPacks: map[catalogpkg.Provider]upstream.ImportPackResolver{
catalogpkg.ProviderModrinth: modrinthProvider,
},
}
if key := strings.TrimSpace(curseforgeAPIKey); key != "" {
curseforgeProvider := curseforge.New(network, logger, key)
router.providers.searchProviders[catalogpkg.RegistryCurseForge] = curseforgeProvider
router.providers.infoProviders[catalogpkg.ProviderCurseForge] = curseforgeProvider
router.providers.catalogues[catalogpkg.ProviderCurseForge] = curseforgeProvider
router.providers.artifactReleases[catalogpkg.ProviderCurseForge] = curseforgeProvider
router.providers.importPacks[catalogpkg.ProviderCurseForge] = curseforgeProvider
}
return router
}
func (r *Router) curseforgeAvailable() bool {
_, ok := r.providers.catalogues[catalogpkg.ProviderCurseForge]
return ok
}
// GetArtifactReleaseMapper returns the release mapper registered for provider.
func (r *Router) GetArtifactReleaseMapper(
provider catalogpkg.Provider,
) (upstream.ArtifactReleaseMapper, bool, error) {
mapper, ok := r.providers.artifactReleases[provider]
if !ok {
r.logger.Debug(
"routing: no artifact release mapper for provider",
"provider", provider,
"reason", "provider has no artifact release mapper",
)
}
return mapper, ok, nil
}
func (r *Router) artifactReleaseMappers() []upstream.ArtifactReleaseMapper {
providers := modProviders(r.curseforgeAvailable())
mappers := make([]upstream.ArtifactReleaseMapper, 0, len(providers))
for _, provider := range providers {
mapper, ok := r.providers.artifactReleases[provider]
if ok {
mappers = append(mappers, mapper)
}
}
return mappers
}
// ResolveSearchProviders resolves search providers for the platform. With a
// platform filter active, explicit registry selection is validated against
// registry capability data.
func (r *Router) ResolveSearchProviders(
platform catalogpkg.Ecosystem,
registry catalogpkg.Registry,
) ([]upstream.SearchProvider, error) {
if registry == catalogpkg.RegistryUnknown {
return nil, ErrUnknownProvider
}
if registry != catalogpkg.RegistryUnspecified {
if err := validateSearchRegistryEcosystem(registry, platform); err != nil {
r.logger.Debug(
"routing: search registry rejected for platform",
"registry", registry,
"platform", platform,
"reason", "registry does not support platform",
)
return nil, err
}
return r.resolveExplicitRegistry(registry)
}
keys := providersForEcosystem(platform, r.curseforgeAvailable())
if len(keys) == 0 {
r.logger.Debug(
"routing: search providers unavailable for platform",
"platform", platform,
"reason", "no provider supports platform search",
)
return nil, fmt.Errorf("%w: %s", ErrInvalidEcosystem, platform)
}
providers, err := r.searchersFromKeys(keys)
if err != nil {
return nil, err
}
r.logger.Debug(
"routing: search providers selected for platform",
"platform", platform,
"providers", keys,
)
return providers, nil
}
// ResolveInfoProviders resolves info providers for the platform and
// user-specified provider.
func (r *Router) ResolveInfoProviders(
platform catalogpkg.Ecosystem,
provider catalogpkg.Provider,
) ([]upstream.InfoProvider, error) {
if provider == catalogpkg.ProviderUnknown {
return nil, ErrUnknownProvider
}
if provider != catalogpkg.ProviderUnspecified {
return r.resolveExplicitInformer(provider)
}
keys := providersForEcosystem(platform, r.curseforgeAvailable())
if len(keys) == 0 {
r.logger.Debug(
"routing: info providers unavailable for ecosystem",
"platform", platform,
"reason", "unsupported ecosystem",
)
return nil, fmt.Errorf("%w: %s", ErrInvalidEcosystem, platform)
}
providers, err := r.informersFromKeys(keys)
if err != nil {
return nil, err
}
r.logger.Debug(
"routing: info providers selected from ecosystem candidates",
"platform", platform,
"providers", keys,
)
return providers, nil
}
func (r *Router) resolveExplicitInformer(provider catalogpkg.Provider) (
[]upstream.InfoProvider,
error,
) {
informer, ok := r.providers.infoProviders[provider]
if !ok {
r.logger.Debug(
"routing: explicit info provider rejected",
"provider", provider,
"reason", "provider has no info capability",
)
return nil, fmt.Errorf("%w: %s", ErrUnsupportedProvider, provider)
}
r.logger.Debug(
"routing: explicit info provider selected",
"provider", provider,
"capability", informer.Provider(),
)
return []upstream.InfoProvider{informer}, nil
}
func (r *Router) resolveExplicitRegistry(registry catalogpkg.Registry) (
[]upstream.SearchProvider,
error,
) {
searcher, ok := r.providers.searchProviders[registry]
if !ok {
r.logger.Debug(
"routing: explicit search registry rejected",
"registry", registry,
"reason", "registry has no search capability",
)
return nil, fmt.Errorf("%w: %s", ErrUnsupportedProvider, registry)
}
r.logger.Debug(
"routing: explicit search registry selected",
"registry", registry,
"provider", searcher.Provider(),
)
return []upstream.SearchProvider{searcher}, nil
}
func validateSearchRegistryEcosystem(
registry catalogpkg.Registry,
platform catalogpkg.Ecosystem,
) error {
if !platform.IsSearchable() {
return nil
}
provider := registry.Provider()
if EcosystemSupportedBy(provider, platform) {
return nil
}
return fmt.Errorf(
"registry %s does not support platform %s",
registry,
platform,
)
}
func (r *Router) searchersFromKeys(keys []catalogpkg.Provider) (
[]upstream.SearchProvider,
error,
) {
capabilities := make([]upstream.SearchProvider, 0, len(keys))
for _, key := range keys {
registry, ok := key.Registry()
if !ok {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedProvider, key)
}
capability, ok := r.providers.searchProviders[registry]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedProvider, key)
}
capabilities = append(capabilities, capability)
}
return capabilities, nil
}
func (r *Router) informersFromKeys(keys []catalogpkg.Provider) (
[]upstream.InfoProvider,
error,
) {
capabilities := make([]upstream.InfoProvider, 0, len(keys))
for _, key := range keys {
capability, ok := r.providers.infoProviders[key]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedProvider, key)
}
capabilities = append(capabilities, capability)
}
return capabilities, nil
}
// ResolveImportPack resolves a registry project and optional version selector
// to a server pack downloadable from provider. An empty version selects the
// provider's newest suitable release.
func (r *Router) ResolveImportPack(
ctx context.Context,
provider catalogpkg.Provider,
project, version string,
) (upstream.ImportPack, error) {
// ProviderUnspecified has no ecosystem to infer from, so it cannot resolve.
if provider == catalogpkg.ProviderUnknown || provider == catalogpkg.ProviderUnspecified {
return upstream.ImportPack{}, ErrUnknownProvider
}
resolver, ok := r.providers.importPacks[provider]
if !ok {
if provider == catalogpkg.ProviderCurseForge {
return upstream.ImportPack{}, curseforge.ErrNoApiKey
}
r.logger.Debug(
"routing: import pack rejected",
"provider", provider,
"reason", "provider has no import pack capability",
)
return upstream.ImportPack{}, fmt.Errorf("%w: %s", ErrUnsupportedProvider, provider)
}
return resolver.ResolveImportPack(ctx, project, version)
}
package routing
import (
"context"
"fmt"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// Builds lists the published versions of an explicitly identified project.
func (r *Router) Builds(
ctx context.Context,
ref catalog.Ref,
) ([]upstream.Build, error) {
catalogue, ok := r.providers.catalogues[ref.Provider]
if !ok {
if _, repository := ref.Provider.Registry(); repository {
return nil, fmt.Errorf(
"%w: %s",
ErrUnsupportedProvider,
ref.Provider,
)
}
return nil, fmt.Errorf("%s does not list builds", ref.Provider)
}
return catalogue.Builds(ctx, ref.Name.String())
}
package routing
import "github.com/mclucy/lucy/catalog"
var searchCapabilityByProvider = map[catalog.Provider]map[catalog.Ecosystem]bool{
catalog.ProviderModrinth: {
catalog.EcosystemFabric: true,
catalog.EcosystemQuilt: true,
catalog.EcosystemForge: true,
catalog.EcosystemNeoForge: true,
catalog.EcosystemBukkit: true,
catalog.EcosystemPaper: true,
},
catalog.ProviderCurseForge: {
catalog.EcosystemFabric: true,
catalog.EcosystemQuilt: true,
catalog.EcosystemForge: true,
catalog.EcosystemNeoForge: true,
},
catalog.ProviderHangar: {
catalog.EcosystemBukkit: true,
catalog.EcosystemPaper: true,
},
catalog.ProviderSpiget: {
catalog.EcosystemBukkit: true,
catalog.EcosystemPaper: true,
},
catalog.ProviderMCDR: {
catalog.EcosystemMCDR: true,
},
}
// EcosystemSupportedBy reports whether provider serves ecosystem.
func EcosystemSupportedBy(provider catalog.Provider, ecosystem catalog.Ecosystem) bool {
return searchCapabilityByProvider[provider][ecosystem]
}
package routing
import (
"context"
"fmt"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
// Candidates routes explicit project identities, never context aliases.
func (r *Router) Candidates(
ctx context.Context,
registry catalog.Registry,
project, minecraft string,
loader catalog.Ecosystem,
) ([]upstream.Candidate, error) {
r.logger.Debug(
"routing: catalogue candidates requested",
"registry", registry,
"project", project,
"minecraft", minecraft,
"loader", loader,
)
catalogue, ok := r.providers.catalogues[registry.Provider()]
if !ok {
r.logger.Debug(
"routing: catalogue registry rejected",
"registry", registry,
"reason", "registry has no package catalogue",
)
return nil, fmt.Errorf("%w: %q", ErrNoCatalogue, registry)
}
return catalogue.Candidates(ctx, project, minecraft, loader)
}
package routing
import (
"context"
"encoding/json/v2"
"fmt"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
// CoreModules reports the descriptor modules the server core artifact ships.
// A lock may predate module recording, so the artifact is read when the lock
// carries none. Fabric and Quilt loaders ship their own mod descriptors.
func CoreModules(
ctx context.Context,
product server.Product,
core catalog.Artifact,
acquire artifact.Materializer,
) ([]catalog.DescriptorModule, error) {
definition, ok := loaderRuntimeFor(product)
if !ok {
return nil, nil
}
if len(core.Modules) > 0 {
return core.Modules, nil
}
materialized, err := acquire(ctx, &core)
if err != nil {
return nil, err
}
return artifact.ReadModules(ctx, materialized.Path, definition.ecosystem)
}
// Metadata fetches JSON metadata through the router's configured network.
func (r *Router) Metadata(
ctx context.Context,
endpoint string,
target any,
) error {
if err := ctx.Err(); err != nil {
return err
}
r.logger.Debug("routing: metadata request", "endpoint", endpoint)
data, err := r.network.CachedGetBytes(
ctx,
endpoint,
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return err
}
return json.Unmarshal(data, target)
}
// trustMavenChecksum adopts the digest the artifact's Maven repository
// publishes beside it. Acquisition records whatever digest it computes when
// nothing is supplied to compare against, so a core artifact without a trusted
// checksum would pin unverified bytes in the lock. The repository sidecar is
// that source, and an unavailable one fails the resolution rather than
// lowering the guarantee.
func (r *Router) trustMavenChecksum(
ctx context.Context,
a *catalog.Artifact,
) error {
if err := ctx.Err(); err != nil {
return err
}
data, err := r.network.CachedGetBytes(
ctx,
a.URL+".sha256",
cache.BytesRequestOptions{Kind: cache.KindMetadata},
)
if err != nil {
return fmt.Errorf("no trusted checksum for %s: %w", a.Filename, err)
}
sum := strings.TrimSpace(string(data))
if len(sum) != 64 {
return fmt.Errorf("malformed checksum for %s", a.Filename)
}
a.Hashes["sha256"] = sum
r.logger.Debug(
"routing: trusted checksum adopted",
"artifact", a.Filename,
"sha256", sum,
)
return nil
}
// ResolveServerProduct resolves the server product artifact, its bootstrap
// method, its input artifacts, and the Java advisory for the requested
// Minecraft version. The advisory comes from Mojang's per-version metadata. It
// always acquires the selected core because the lock records the bytes it pins.
func (r *Router) ResolveServerProduct(
ctx context.Context,
req upstream.ServerProductRequest,
acquire artifact.Materializer,
) (upstream.ServerProductResolution, error) {
out := upstream.ServerProductResolution{
Minecraft: req.Minecraft,
Product: req.Product,
ProductVersion: req.ProductVersion,
}
advisory, err := r.mojang.JavaAdvisory(ctx, req.Minecraft)
if err != nil {
return out, err
}
out.JavaAdvisory = advisory
vanilla, err := r.mojang.Fetch(
ctx,
catalog.VersionedRef{
Name: "minecraft",
Ecosystem: catalog.EcosystemMinecraft,
Version: req.Minecraft,
},
)
if err != nil {
return out, err
}
minecraft := catalog.Artifact{
Provider: catalog.ProviderMojang,
ProjectID: "minecraft",
Version: req.Minecraft,
Filename: "server.jar",
URL: vanilla.FileURL,
Hashes: map[string]string{"sha1": vanilla.Hash},
}
if req.Product == server.ProductMinecraft {
r.logger.Debug(
"routing: server product route selected",
"product", req.Product,
"provider", catalog.ProviderMojang,
)
out.Artifact = minecraft
out.Bootstrap = server.BootstrapMethodVanilla
out.ProductVersion = req.Minecraft
materialized, err := acquire(ctx, &out.Artifact)
if err != nil {
return out, err
}
out.Artifact.Hashes = materialized.Hashes
return out, nil
}
out.Inputs = []catalog.Artifact{minecraft}
if req.Repository != "" {
r.logger.Debug(
"routing: server product route selected",
"product", req.Product,
"provider", catalog.ProviderGitHub,
"repository", req.Repository,
)
err = r.resolveGithubProduct(ctx, req, &out, acquire)
} else if definition, ok := loaderRuntimeFor(req.Product); ok {
err = r.resolveLoaderProduct(ctx, req, &out, definition)
} else {
switch req.Product {
case server.ProductForge, server.ProductNeoForge:
var (
remote upstream.ResolvedPackage
provider catalog.Provider
)
if req.Product == server.ProductForge {
provider = catalog.ProviderForge
remote, err = r.forge.Fetch(
ctx,
req.Minecraft,
catalog.VersionedRef{
Name: "forge",
Ecosystem: catalog.EcosystemForge,
Version: req.ProductVersion,
},
)
} else {
provider = catalog.ProviderNeoForge
remote, err = r.neoforge.Fetch(
ctx,
req.Minecraft,
catalog.VersionedRef{
Name: "neoforge",
Ecosystem: catalog.EcosystemNeoForge,
Version: req.ProductVersion,
},
)
}
if err != nil {
return out, err
}
out.Artifact = catalog.Artifact{
Provider: provider,
ProjectID: req.Product.String(),
Version: req.ProductVersion,
Filename: remote.Filename,
URL: remote.FileURL,
Hashes: map[string]string{},
}
materialized, e := acquire(ctx, &out.Artifact)
if e != nil {
return out, e
}
out.Artifact.Hashes = materialized.Hashes
if err := r.resolveInstaller(ctx, req, &out, materialized.Path); err != nil {
return out, err
}
r.logger.Debug(
"routing: server product route selected",
"product", req.Product,
"provider", provider,
"version", out.ProductVersion,
)
case server.ProductPaper:
err = r.resolvePaper(ctx, req, &out)
case server.ProductPurpur:
build := req.ProductVersion
if floating(build) {
build = "latest"
}
var info struct {
Build string `json:"build"`
Version string `json:"version"`
MD5 string `json:"md5"`
}
if e := r.Metadata(
ctx,
"https://api.purpurmc.org/v2/purpur/"+
req.Minecraft.String()+"/"+build.String(),
&info,
); e != nil {
return out, e
}
if info.Version != req.Minecraft.String() {
return out, fmt.Errorf(
"purpur release targets Minecraft %s, requested %s",
info.Version,
req.Minecraft,
)
}
out.ProductVersion = version.Version(info.Build)
out.Artifact = catalog.Artifact{
Provider: catalog.ProviderPurpur,
ProjectID: "purpur",
ReleaseID: info.Build,
Version: version.Version(info.Build),
Filename: "purpur-" + req.Minecraft.String() + "-" +
info.Build + ".jar",
URL: "https://api.purpurmc.org/v2/purpur/" +
req.Minecraft.String() + "/" + info.Build + "/download",
Hashes: map[string]string{"md5": info.MD5},
}
out.Bootstrap = server.BootstrapMethodPaperclip
r.logger.Debug(
"routing: server product route selected",
"product", req.Product,
"provider", catalog.ProviderPurpur,
"build", info.Build,
)
default:
r.logger.Debug(
"routing: server product route rejected",
"product", req.Product,
"reason", "unsupported server product",
)
return out, fmt.Errorf("unsupported server product %q", req.Product)
}
}
if err != nil {
return out, err
}
materialized, err := acquire(ctx, &out.Artifact)
if err != nil {
return out, err
}
out.Artifact.Hashes = materialized.Hashes
if definition, ok := loaderRuntimeFor(out.Product); ok {
modules, e := artifact.ReadModules(
ctx,
materialized.Path,
definition.ecosystem,
)
if e != nil {
return out, e
}
out.Artifact.Modules = modules
}
if out.Bootstrap == server.BootstrapMethodPaperclip {
if err := paperclipInput(&out, materialized.Path); err != nil {
return out, err
}
}
if err := acquireInputs(ctx, out.Inputs, acquire); err != nil {
return out, err
}
return out, nil
}
func floating(v version.Version) bool {
switch v {
case "", version.Any, version.Beta, version.Stable, "latest":
return true
default:
return false
}
}
package routing
import (
"context"
"errors"
"fmt"
"sync"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
)
var ErrNoProviderSucceeded = errors.New("no provider succeeded")
// SearchMany executes search on all providers in parallel.
//
// Each provider contributes one upstream.SearchResponse item in the returned
// slice, kept separate from the other providers' results.
func (r *Router) SearchMany(
ctx context.Context,
providers []upstream.SearchProvider,
query upstream.Query,
) ([]upstream.SearchResponse, []upstream.ProviderError) {
if len(providers) == 0 {
return nil, nil
}
type slot struct {
res upstream.SearchResponse
err upstream.ProviderError
ok bool
failed bool
}
slots := make([]slot, len(providers))
var wg sync.WaitGroup
for i, provider := range providers {
wg.Go(func() {
res, err := provider.Search(ctx, query)
if err == nil && len(res.Items) == 0 {
err = fmt.Errorf(
"no projects found for \"%s\"",
query.Keyword,
)
}
if err != nil {
slots[i] = slot{
failed: true,
err: upstream.ProviderError{
Provider: provider.Provider(),
Err: err,
},
}
return
}
if res.Provider == catalog.ProviderUnknown {
res.Provider = provider.Provider()
}
slots[i] = slot{ok: true, res: res}
})
}
wg.Wait()
results := make([]upstream.SearchResponse, 0, len(providers))
providerErrors := make([]upstream.ProviderError, 0)
for _, item := range slots {
if item.ok {
results = append(results, item.res)
}
if item.failed {
providerErrors = append(providerErrors, item.err)
}
}
return results, providerErrors
}
// GetInfoFirstSuccess executes info on all providers in parallel and returns the
// first successful result. Ref.Provider records the provider that answered.
func (r *Router) GetInfoFirstSuccess(
ctx context.Context,
providers []upstream.InfoProvider,
ref catalog.Ref,
) (upstream.Info, []upstream.ProviderError, error) {
if len(providers) == 0 {
return upstream.Info{}, nil, ErrNoProviderSucceeded
}
if err := ctx.Err(); err != nil {
return upstream.Info{}, nil, err
}
resChan := make(chan upstream.Info, len(providers))
errChan := make(chan upstream.ProviderError, len(providers))
for _, provider := range providers {
go func(provider upstream.InfoProvider) {
metadata, err := provider.Info(ctx, ref)
if err != nil {
errChan <- upstream.ProviderError{Provider: provider.Provider(), Err: fmt.Errorf("information failed: %w", err)}
return
}
resChan <- upstream.Info{
Ref: catalog.Ref{Name: ref.Name, Provider: provider.Provider()},
Metadata: metadata,
}
}(provider)
}
providerErrors := make([]upstream.ProviderError, 0, len(providers))
pending := len(providers)
for pending > 0 {
select {
case result := <-resChan:
return result, providerErrors, nil
case providerErr := <-errChan:
providerErrors = append(providerErrors, providerErr)
pending--
case <-ctx.Done():
return upstream.Info{}, providerErrors, ctx.Err()
}
}
return upstream.Info{}, providerErrors, joinProviderErrors(providerErrors)
}
// ResolveArtifactByHash resolves an artifact's canonical upstream release.
// Mappers run in policy order; a failed or missing match does not stop later
// mappers. Provider failures are returned for callers that surface warnings.
func (r *Router) ResolveArtifactByHash(
ctx context.Context,
artifact upstream.ArtifactFingerprint,
) upstream.ArtifactReleaseResolution {
resolutions := upstream.LookupArtifactReleases(
ctx,
[]upstream.ArtifactFingerprint{artifact},
r.artifactReleaseMappers(),
namedRelease,
)
return resolutions[0]
}
// ResolveArtifactsByHash resolves canonical upstream releases for artifacts
// in input order. Only a named release is reported; provider failures stay
// attached to the artifact they affected, including failures from mappers
// that ran before a later one matched.
func (r *Router) ResolveArtifactsByHash(
ctx context.Context,
artifacts []upstream.ArtifactFingerprint,
) []upstream.ArtifactReleaseResolution {
return upstream.LookupArtifactReleases(
ctx,
artifacts,
r.artifactReleaseMappers(),
namedRelease,
)
}
// namedRelease accepts the release a mapper matched only when it names its
// project, which is the identity resolution and adoption can use.
func namedRelease(release upstream.Release) bool {
return release.Ref.Name != ""
}
func joinProviderErrors(providerErrors []upstream.ProviderError) error {
if len(providerErrors) == 0 {
return ErrNoProviderSucceeded
}
joined := make([]error, 0, len(providerErrors))
for _, providerErr := range providerErrors {
joined = append(joined, providerErr)
}
return errors.Join(joined...)
}
package routing
import (
"context"
"net/url"
"sync"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
)
const (
// inputWorkers bounds acquisitions in flight for one server product. The
// set is a few dozen small files, so a wider pool adds contention without
// shortening the wait.
inputWorkers = 8
// hostWorkers bounds requests in flight to one upstream host, so a wide
// input set does not open one connection per file to the same server.
hostWorkers = 4
)
// acquireInputs acquires every input that is not embedded and records the
// digests each acquisition proved. Results keep input order. The first failure
// in input order is returned after every started acquisition ends.
func acquireInputs(
ctx context.Context,
inputs []catalog.Artifact,
acquire artifact.Materializer,
) error {
downloadable := make([]int, 0, len(inputs))
for i := range inputs {
if inputs[i].Embedded == "" {
downloadable = append(downloadable, i)
}
}
errs := runBounded(
ctx,
len(downloadable),
func(position int) string {
return hostFromURL(inputs[downloadable[position]].URL)
},
func(position int) error {
index := downloadable[position]
materialized, err := acquire(ctx, &inputs[index])
if err != nil {
return err
}
inputs[index].Hashes = materialized.Hashes
return nil
},
)
if err := firstError(errs); err != nil {
return err
}
return ctx.Err()
}
// firstError reports the failure with the lowest input index.
func firstError(errs []error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
// runBounded calls visit for every index below count with at most inputWorkers
// visits in flight, each waiting for a slot on the host its index names. A
// failure stops further visits without interrupting those in flight. Every
// visit keeps its result at its index, so a caller reports the first failure in
// input order.
func runBounded(
ctx context.Context,
count int,
host func(int) string,
visit func(int) error,
) []error {
errs := make([]error, count)
workers := min(inputWorkers, count)
if workers == 0 {
return errs
}
gates := newHostGates(hostWorkers)
var (
mu sync.Mutex
next int
failed bool
group sync.WaitGroup
)
worker := func() {
for {
mu.Lock()
if failed || next >= count {
mu.Unlock()
return
}
index := next
next++
mu.Unlock()
gate := host(index)
if err := gates.acquire(ctx, gate); err != nil {
mu.Lock()
errs[index], failed = err, true
mu.Unlock()
return
}
err := visit(index)
gates.release(gate)
if err == nil {
continue
}
mu.Lock()
errs[index], failed = err, true
mu.Unlock()
return
}
}
for range workers {
group.Go(worker)
}
group.Wait()
return errs
}
// hostGates bounds visits in flight per upstream host.
type hostGates struct {
limit int
mu sync.Mutex
slots map[string]chan struct{}
}
func newHostGates(limit int) *hostGates {
return &hostGates{limit: limit, slots: make(map[string]chan struct{})}
}
func (g *hostGates) acquire(ctx context.Context, host string) error {
g.mu.Lock()
slots, ok := g.slots[host]
if !ok {
slots = make(chan struct{}, g.limit)
g.slots[host] = slots
}
g.mu.Unlock()
select {
case slots <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (g *hostGates) release(host string) {
g.mu.Lock()
slots := g.slots[host]
g.mu.Unlock()
<-slots
}
func hostFromURL(raw string) string {
parsed, err := url.Parse(raw)
if err != nil {
return ""
}
return parsed.Host
}
package routing
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json/v2"
"fmt"
"path"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/internal/maven"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/mojang"
versionpkg "github.com/mclucy/lucy/version"
)
type mavenLibrary struct {
Name string `json:"name"`
URL string `json:"url"`
Downloads struct {
Artifact *struct {
Path string `json:"path"`
URL string `json:"url"`
SHA1 string `json:"sha1"`
} `json:"artifact"`
} `json:"downloads"`
}
// libraryInput turns one profile library into a bootstrap input. The library
// coordinate decides its placement, so a download that declares a different
// path fails resolution instead of landing elsewhere. The second result is
// false when the profile explicitly names a library that cannot be downloaded:
// Forge declares the client classifier with an empty artifact URL because the
// jar exists nowhere in a public Maven repository.
func libraryInput(lib mavenLibrary, z *zip.Reader, version versionpkg.Version) (catalog.Artifact, bool, error) {
download := lib.Downloads.Artifact
p, err := maven.Path(lib.Name)
if err != nil {
return catalog.Artifact{}, false, err
}
if download != nil && download.Path != "" && download.Path != p {
return catalog.Artifact{}, false, fmt.Errorf(
"library %s declares download path %s, but its coordinate places it at %s",
lib.Name, download.Path, p,
)
}
a := catalog.Artifact{Provider: catalog.ProviderMaven, ProjectID: lib.Name, Version: version, Filename: path.Base(p), Hashes: map[string]string{}}
if z != nil {
if raw, err := zipBytes(z, "maven/"+p); err != nil {
return catalog.Artifact{}, false, err
} else if raw != nil {
a.Embedded = "maven/" + p
sum := sha256.Sum256(raw)
a.Hashes["sha256"] = hex.EncodeToString(sum[:])
return a, true, nil
}
}
if download != nil && download.URL == "" {
return catalog.Artifact{}, false, nil
}
if download != nil {
a.URL = download.URL
}
if a.URL == "" {
base := lib.URL
if base == "" {
base = "https://libraries.minecraft.net/"
}
a.URL = strings.TrimRight(base, "/") + "/" + p
}
if download != nil && download.SHA1 != "" {
a.Hashes["sha1"] = download.SHA1
}
return a, true, nil
}
func zipBytes(z *zip.Reader, name string) ([]byte, error) {
raw, _, err := fsutil.ReadZipEntry(
z,
name,
fsutil.MaxNestedZipEntryBytes,
)
return raw, err
}
func (r *Router) resolveInstaller(ctx context.Context, req upstream.ServerProductRequest, out *upstream.ServerProductResolution, installer string) error {
z, err := zip.OpenReader(installer)
if err != nil {
return err
}
defer z.Close()
raw, err := zipBytes(&z.Reader, "install_profile.json")
if err != nil {
return err
}
if raw == nil {
return fmt.Errorf("installer has no install_profile.json")
}
var profile struct {
Minecraft string `json:"minecraft"`
Version string `json:"version"`
JSON string `json:"json"`
Libraries []mavenLibrary `json:"libraries"`
}
if err := json.Unmarshal(raw, &profile); err != nil {
return err
}
if profile.Minecraft != req.Minecraft.String() {
return fmt.Errorf("%s installer targets Minecraft %s, requested %s", req.Product, profile.Minecraft, req.Minecraft)
}
out.ProductVersion = req.ProductVersion
if floating(out.ProductVersion) {
out.ProductVersion = versionpkg.Version(strings.TrimSuffix(strings.TrimPrefix(out.Artifact.Filename, req.Product.String()+"-"), "-installer.jar"))
if req.Product == server.ProductForge {
out.ProductVersion = versionpkg.Version(strings.TrimPrefix(out.ProductVersion.String(), req.Minecraft.String()+"-"))
}
}
out.Artifact.Version = out.ProductVersion
out.Bootstrap = server.BootstrapMethodForge
if profile.JSON != "" {
raw, e := zipBytes(&z.Reader, strings.TrimPrefix(profile.JSON, "/"))
if e != nil {
return e
}
var detail struct {
Libraries []mavenLibrary `json:"libraries"`
}
if e := json.Unmarshal(raw, &detail); e != nil {
return e
}
profile.Libraries = append(profile.Libraries, detail.Libraries...)
}
seen := map[string]bool{}
for _, lib := range profile.Libraries {
input, downloadable, e := libraryInput(lib, &z.Reader, out.ProductVersion)
if e != nil {
return e
}
if !downloadable {
r.logger.Debug(
"routing: installer library skipped",
"library", lib.Name,
"reason", "no downloadable artifact",
)
continue
}
if seen[input.ProjectID] {
r.logger.Debug(
"routing: installer library skipped",
"library", lib.Name,
"reason", "duplicate library coordinate",
)
continue
}
seen[input.ProjectID] = true
out.Inputs = append(out.Inputs, input)
}
// Processors may need Mojang server mappings in addition to the server JAR.
var index struct {
Versions []struct {
ID string `json:"id"`
URL string `json:"url"`
} `json:"versions"`
}
if err := r.Metadata(ctx, mojang.VersionManifestURL, &index); err != nil {
return err
}
for _, v := range index.Versions {
if v.ID == req.Minecraft.String() {
var detail struct {
Downloads map[string]struct {
URL string `json:"url"`
SHA1 string `json:"sha1"`
} `json:"downloads"`
}
if err := r.Metadata(ctx, v.URL, &detail); err != nil {
return err
}
if mapping, ok := detail.Downloads["server_mappings"]; ok {
out.Inputs = append(out.Inputs, catalog.Artifact{Provider: catalog.ProviderMojang, ProjectID: "server-mappings", Version: req.Minecraft, Filename: "server-mappings.txt", URL: mapping.URL, Hashes: map[string]string{"sha1": mapping.SHA1}})
}
break
}
}
r.logger.Debug(
"routing: installer inputs resolved",
"product", req.Product,
"version", out.ProductVersion,
"inputs", len(out.Inputs),
)
return nil
}
package routing
import (
"context"
"fmt"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/upstream/internal/providers/loadermeta"
"github.com/mclucy/lucy/version"
)
// loaderRuntime is the routing definition of one Fabric-style loader: its
// meta client definition, ecosystem, and bootstrap method.
type loaderRuntime struct {
meta loadermeta.Definition
ecosystem catalog.Ecosystem
bootstrap server.BootstrapMethod
}
// loaderRuntimes is keyed by the server product the definition resolves.
var loaderRuntimes = map[server.Product]loaderRuntime{
server.ProductFabric: {
meta: loadermeta.Definition{
APIBase: "https://meta.fabricmc.net",
APIVersion: "v2",
MavenBase: "https://maven.fabricmc.net/",
Coordinate: "net.fabricmc:fabric-loader",
Provider: catalog.ProviderFabric,
ProjectID: "fabric-loader",
StableFlag: true,
},
ecosystem: catalog.EcosystemFabric,
bootstrap: server.BootstrapMethodFabric,
},
server.ProductQuilt: {
meta: loadermeta.Definition{
APIBase: "https://meta.quiltmc.org",
APIVersion: "v3",
MavenBase: "https://maven.quiltmc.org/repository/release/",
Coordinate: "org.quiltmc:quilt-loader",
Provider: catalog.ProviderQuilt,
ProjectID: "quilt-loader",
StableFlag: false,
},
ecosystem: catalog.EcosystemQuilt,
bootstrap: server.BootstrapMethodQuilt,
},
}
func loaderRuntimeFor(product server.Product) (loaderRuntime, bool) {
definition, ok := loaderRuntimes[product]
return definition, ok
}
// loaderProfileInputs translates a profile into the library artifacts the lock
// records as inputs. Profile order is preserved and the loader library is
// skipped. The caller applies the hash trust policy.
func loaderProfileInputs(
provider *loadermeta.Provider,
profile loadermeta.Profile,
loader version.Version,
) ([]catalog.Artifact, error) {
inputs := make([]catalog.Artifact, 0, len(profile.Libraries))
for _, lib := range profile.Libraries {
if provider.IsLoaderLibrary(lib.Name) {
continue
}
input, downloadable, err := libraryInput(
mavenLibrary{
Name: lib.Name,
URL: lib.URL,
},
nil,
loader,
)
if err != nil {
return nil, err
}
if !downloadable {
continue
}
inputs = append(inputs, input)
}
return inputs, nil
}
// resolveLoaderProduct resolves a loader product through the shared meta
// flow: select the loader version, read its profile, pin the core artifact,
// and pin every profile library.
func (r *Router) resolveLoaderProduct(
ctx context.Context,
req upstream.ServerProductRequest,
out *upstream.ServerProductResolution,
definition loaderRuntime,
) error {
provider, ok := r.loaders[req.Product]
if !ok {
return fmt.Errorf(
"no loader meta provider for product %q", req.Product,
)
}
selected, err := provider.ResolveLoaderVersion(ctx, req.ProductVersion)
if err != nil {
return err
}
out.ProductVersion = selected.Version
profile, err := provider.ServerProfile(
ctx,
req.Minecraft,
out.ProductVersion,
)
if err != nil {
return err
}
artifact, err := provider.LoaderArtifact(selected)
if err != nil {
return err
}
if err := r.trustMavenChecksum(ctx, &artifact); err != nil {
return err
}
out.Artifact = artifact
out.Bootstrap = definition.bootstrap
inputs, err := loaderProfileInputs(provider, profile, out.ProductVersion)
if err != nil {
return err
}
errs := runBounded(
ctx,
len(inputs),
func(i int) string { return hostFromURL(inputs[i].URL) },
func(i int) error { return r.trustMavenChecksum(ctx, &inputs[i]) },
)
if err := firstError(errs); err != nil {
return err
}
out.Inputs = append(out.Inputs, inputs...)
r.logger.Debug(
"routing: server product route selected",
"product", req.Product,
"provider", definition.meta.Provider,
"version", out.ProductVersion,
"libraries", len(inputs),
)
return nil
}
package routing
import (
"context"
"fmt"
"strings"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/version"
)
const (
paperProjectURL = fillProjectBase + "paper"
purpurProjectURL = "https://api.purpurmc.org/v2/purpur"
)
// LatestMinecraftVersion reports the newest Minecraft version a server product
// serves. It answers a floating Minecraft request: each product names the
// version it builds for, which can lag Mojang's release channel.
func (r *Router) LatestMinecraftVersion(
ctx context.Context,
product server.Product,
) (version.Version, error) {
if _, ok := loaderRuntimeFor(product); ok {
provider, ok := r.loaders[product]
if !ok {
return "", fmt.Errorf(
"server product %q publishes no Minecraft versions",
product,
)
}
return provider.LatestGameVersion(ctx)
}
switch product {
case server.ProductMinecraft:
return r.LatestMojangMinecraft(ctx, false)
case server.ProductForge:
return r.forge.LatestMinecraftVersion(ctx)
case server.ProductNeoForge:
return r.neoforge.LatestMinecraftVersion(ctx)
case server.ProductPaper:
return r.latestPaperMinecraft(ctx)
case server.ProductPurpur:
return r.latestPurpurMinecraft(ctx)
default:
return "", fmt.Errorf(
"server product %q publishes no Minecraft versions",
product,
)
}
}
// LatestMojangMinecraft reports the newest Minecraft version on Mojang's
// release channel, or on the snapshot channel when snapshot is set.
func (r *Router) LatestMojangMinecraft(
ctx context.Context,
snapshot bool,
) (version.Version, error) {
manifest, err := r.mojang.VersionManifest(ctx)
if err != nil {
return "", err
}
if snapshot {
return version.Version(manifest.Latest.Snapshot), nil
}
return version.Version(manifest.Latest.Release), nil
}
// MinecraftReleases reports Mojang's release-channel versions, newest first.
func (r *Router) MinecraftReleases(
ctx context.Context,
) ([]version.Version, error) {
manifest, err := r.mojang.VersionManifest(ctx)
if err != nil {
return nil, err
}
releases := make([]version.Version, 0, len(manifest.Versions))
for _, entry := range manifest.Versions {
if entry.Type != "release" {
continue
}
releases = append(releases, version.Version(entry.ID))
}
return releases, nil
}
// latestPaperMinecraft reports the newest release Paper builds. The project
// endpoint groups versions by major line and lists prereleases beside them.
func (r *Router) latestPaperMinecraft(ctx context.Context) (version.Version, error) {
var project struct {
Versions map[string][]string `json:"versions"`
}
if err := r.fillMetadata(ctx, paperProjectURL, &project); err != nil {
return "", err
}
versions := make([]version.Version, 0, len(project.Versions))
for _, group := range project.Versions {
for _, id := range group {
if isMinecraftRelease(id) {
versions = append(versions, version.Version(id))
}
}
}
return version.NewestMinecraft(versions)
}
func (r *Router) latestPurpurMinecraft(
ctx context.Context,
) (version.Version, error) {
var project struct {
Versions []string `json:"versions"`
}
if err := r.Metadata(ctx, purpurProjectURL, &project); err != nil {
return "", err
}
versions := make([]version.Version, 0, len(project.Versions))
for _, id := range project.Versions {
if isMinecraftRelease(id) {
versions = append(versions, version.Version(id))
}
}
return version.NewestMinecraft(versions)
}
// isMinecraftRelease rejects snapshots, prereleases, and release candidates,
// which carry a suffix the release grammar does not accept.
func isMinecraftRelease(id string) bool {
return !strings.Contains(id, "-")
}
package routing
import (
"archive/zip"
"cmp"
"context"
"encoding/json/v2"
"fmt"
"net/http"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/cache"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
)
const (
fillProjectBase = "https://fill.papermc.io/v3/projects/"
fillUserAgent = "lucy (+https://github.com/mclucy/lucy)"
)
// fillMetadata performs a Fill metadata request. Fill asks clients to identify
// themselves, while the router's generic Metadata helper sends no User-Agent;
// keep this narrowly scoped so other providers' request behavior is unchanged.
func (r *Router) fillMetadata(
ctx context.Context,
endpoint string,
target any,
) error {
res, err := r.fillMetadataResponse(ctx, endpoint)
if err != nil {
return err
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return fmt.Errorf("fetch failed: status %d", res.StatusCode)
}
return json.Unmarshal(res.Data, target)
}
func (r *Router) fillMetadataResponse(
ctx context.Context,
endpoint string,
) (*cache.BytesResponse, error) {
r.logger.Debug("routing: metadata request", "endpoint", endpoint)
headers := http.Header{}
headers.Set("User-Agent", fillUserAgent)
return r.network.CachedGetRequest(
ctx,
endpoint,
cache.BytesRequestOptions{
Kind: cache.KindMetadata,
Headers: headers,
},
)
}
// fillBuildsEndpoint builds a Fill v3 build-list URL. An empty channel keeps
// the unfiltered list; Fill's channel query is repeatable and only accepts its
// own channel enums.
func fillBuildsEndpoint(project, minecraft, channel string) string {
endpoint := fillProjectBase + project + "/versions/" + minecraft + "/builds"
if channel != "" {
endpoint += "?channel=" + channel
}
return endpoint
}
// paperBuild is one build entry from the PaperMC fill API.
type paperBuild struct {
ID int `json:"id"`
Channel string `json:"channel"`
Downloads map[string]struct {
Name string `json:"name"`
URL string `json:"url"`
Checksums map[string]string `json:"checksums"`
} `json:"downloads"`
}
// IdentifyFillBuild matches a server jar digest against the published builds
// of a PaperMC fill project. Init uses it when a renamed jar no longer carries
// its build number.
func (r *Router) IdentifyFillBuild(
ctx context.Context,
project string,
minecraft version.Version,
sha256 string,
) (version.Version, bool, error) {
// Fill has no digest lookup and GraphQL only moves the same build list
// behind an experimental schema, so the version's build list is the
// narrowest documented request for matching a jar's checksum.
var builds []paperBuild
endpoint := fillBuildsEndpoint(project, minecraft.String(), "")
if err := r.fillMetadata(ctx, endpoint, &builds); err != nil {
return "", false, err
}
for _, build := range builds {
asset, ok := build.Downloads["server:default"]
if !ok {
continue
}
if strings.EqualFold(asset.Checksums["sha256"], sha256) {
return version.Version(strconv.Itoa(build.ID)), true, nil
}
}
return "", false, nil
}
// resolvePaper selects a Paper build for one Minecraft version. A pinned build
// uses Fill's single-build document, and a stable floating request filters the
// build list by channel. A channel-agnostic floating request keeps the full
// list: /builds/latest could name a build without a server download and skip an
// older usable one, and the channel rules only apply to the stable sentinel.
func (r *Router) resolvePaper(
ctx context.Context,
req upstream.ServerProductRequest,
out *upstream.ServerProductResolution,
) error {
if !floating(req.ProductVersion) {
requested := req.ProductVersion.String()
id, err := strconv.Atoi(requested)
if err != nil || id < 0 || strconv.Itoa(id) != requested {
return noPaperBuildError(req)
}
build, found, err := r.paperBuildByID(ctx, req.Minecraft.String(), id)
if err != nil {
return err
}
if !found || !r.adoptPaperBuild(req, out, build) {
return noPaperBuildError(req)
}
return nil
}
channel := ""
if req.ProductVersion == version.Stable {
channel = "STABLE"
}
var builds []paperBuild
endpoint := fillBuildsEndpoint("paper", req.Minecraft.String(), channel)
if err := r.fillMetadata(ctx, endpoint, &builds); err != nil {
return err
}
slices.SortFunc(builds, func(a, b paperBuild) int { return cmp.Compare(b.ID, a.ID) })
for _, build := range builds {
if req.ProductVersion == version.Stable && build.Channel != "STABLE" {
r.logger.Debug(
"routing: paper build skipped",
"minecraft", req.Minecraft,
"build", build.ID,
"reason", "unstable build channel",
)
continue
}
if r.adoptPaperBuild(req, out, build) {
return nil
}
}
return noPaperBuildError(req)
}
// paperBuildByID reads one build document. Fill answers 404 for an unknown
// build; reading the status directly keeps that absence distinct from transport
// and cache failures.
func (r *Router) paperBuildByID(
ctx context.Context,
minecraft string,
id int,
) (paperBuild, bool, error) {
endpoint := fillBuildsEndpoint("paper", minecraft, "") + "/" + strconv.Itoa(id)
res, err := r.fillMetadataResponse(ctx, endpoint)
if err != nil {
return paperBuild{}, false, err
}
switch {
case res.StatusCode == http.StatusNotFound:
return paperBuild{}, false, nil
case res.StatusCode < 200 || res.StatusCode >= 300:
return paperBuild{}, false, fmt.Errorf(
"fetch failed: status %d",
res.StatusCode,
)
}
var build paperBuild
if err := json.Unmarshal(res.Data, &build); err != nil {
return paperBuild{}, false, err
}
return build, true, nil
}
// adoptPaperBuild records a candidate whose server download is published. It
// reports whether the build is usable so callers can keep scanning the list.
func (r *Router) adoptPaperBuild(
req upstream.ServerProductRequest,
out *upstream.ServerProductResolution,
build paperBuild,
) bool {
asset, ok := build.Downloads["server:default"]
if !ok {
r.logger.Debug(
"routing: paper build skipped",
"minecraft", req.Minecraft,
"build", build.ID,
"reason", "no server download",
)
return false
}
v := strconv.Itoa(build.ID)
out.ProductVersion, out.Bootstrap = version.Version(v), server.BootstrapMethodPaperclip
out.Artifact = catalog.Artifact{
Provider: catalog.ProviderPaperMC,
ProjectID: "paper",
ReleaseID: req.Minecraft.String() + "/" + v,
FileID: "server:default",
Version: version.Version(v),
Filename: asset.Name,
URL: asset.URL,
Hashes: asset.Checksums,
}
r.logger.Debug(
"routing: paper build selected",
"minecraft", req.Minecraft,
"build", v,
"channel", build.Channel,
"requested", req.ProductVersion,
)
return true
}
func noPaperBuildError(req upstream.ServerProductRequest) error {
return fmt.Errorf("no Paper build %s for Minecraft %s", req.ProductVersion, req.Minecraft)
}
func (r *Router) resolveGithubProduct(
ctx context.Context,
req upstream.ServerProductRequest,
out *upstream.ServerProductResolution,
acquire artifact.Materializer,
) error {
var repo struct {
ID int64 `json:"id"`
}
if err := r.Metadata(ctx, "https://api.github.com/repos/"+req.Repository, &repo); err != nil {
return err
}
var releases []struct {
ID int64 `json:"id"`
Tag string `json:"tag_name"`
Prerelease bool `json:"prerelease"`
Draft bool `json:"draft"`
Assets []struct {
ID int64 `json:"id"`
Name string `json:"name"`
URL string `json:"browser_download_url"`
Digest string `json:"digest"`
} `json:"assets"`
}
if err := r.Metadata(ctx, "https://api.github.com/repos/"+req.Repository+"/releases?per_page=100", &releases); err != nil {
return err
}
for _, rl := range releases {
reason := ""
switch {
case rl.Draft:
reason = "draft release"
case !floating(req.ProductVersion) && rl.Tag != req.ProductVersion.String():
reason = "release tag mismatch"
case req.ProductVersion == version.Stable && rl.Prerelease:
reason = "prerelease excluded"
}
if reason != "" {
r.logger.Debug(
"routing: github release skipped",
"repository", req.Repository,
"release", rl.Tag,
"reason", reason,
)
continue
}
for _, a := range rl.Assets {
reason := ""
if !strings.HasSuffix(a.Name, ".jar") {
reason = "not a jar asset"
} else if req.FilePattern != "" {
matched, e := filepath.Match(req.FilePattern, a.Name)
if e != nil {
return e
}
if !matched {
reason = "file pattern mismatch"
}
}
if reason != "" {
r.logger.Debug(
"routing: github release asset skipped",
"repository", req.Repository,
"release", rl.Tag,
"asset", a.Name,
"reason", reason,
)
continue
}
hashes := map[string]string{}
if h, ok := strings.CutPrefix(a.Digest, "sha256:"); ok {
hashes["sha256"] = h
}
candidate := catalog.Artifact{
Provider: catalog.ProviderGitHub,
ProjectID: strconv.FormatInt(repo.ID, 10),
ReleaseID: strconv.FormatInt(rl.ID, 10),
FileID: strconv.FormatInt(a.ID, 10),
Version: version.Version(rl.Tag),
Filename: a.Name,
URL: a.URL,
Hashes: hashes,
}
trial := *out
trial.ProductVersion = version.Version(rl.Tag)
trial.Bootstrap = server.BootstrapMethodPaperclip
materialized, e := acquire(ctx, &candidate)
if e != nil {
return e
}
candidate.Hashes = materialized.Hashes
trial.Artifact = candidate
if e := paperclipInput(&trial, materialized.Path); e != nil {
r.logger.Debug(
"routing: github fork candidate rejected",
"repository", req.Repository,
"release", rl.Tag,
"asset", a.Name,
"reason", "paperclip download context unusable",
)
continue
}
*out = trial
r.logger.Debug(
"routing: github fork core selected",
"repository", req.Repository,
"release", rl.Tag,
"asset", a.Name,
)
return nil
}
}
return fmt.Errorf("no GitHub Paper fork artifact for Minecraft %s in %s", req.Minecraft, req.Repository)
}
// paperclipInput records the Mojang server jar the Paperclip core downloads.
// Its download context names that jar, while bootstrap places it in the cache
// under the version this input carries, so this verifies the declared name.
func paperclipInput(out *upstream.ServerProductResolution, corePath string) error {
z, err := zip.OpenReader(corePath)
if err != nil {
return err
}
defer z.Close()
data, err := zipBytes(&z.Reader, "META-INF/download-context")
if err != nil {
return err
}
if data == nil {
return fmt.Errorf("paper fork has no supported Paperclip download context")
}
fields := strings.Fields(string(data))
if len(fields) != 3 {
return fmt.Errorf("invalid Paperclip download context")
}
expected := "mojang_" + out.Minecraft.String() + ".jar"
if fields[2] != expected {
return fmt.Errorf("core targets %s, requested Minecraft %s", fields[2], out.Minecraft)
}
out.Inputs = []catalog.Artifact{
{
Provider: catalog.ProviderMojang,
ProjectID: "minecraft",
Version: out.Minecraft,
Filename: fields[2],
URL: fields[1],
Hashes: map[string]string{"sha256": fields[0]},
},
}
return nil
}
package routing
import "github.com/mclucy/lucy/catalog"
// providersInPriorityOrder is the provider preference order shared by
// ecosystem selection and search selection.
var providersInPriorityOrder = []catalog.Provider{
catalog.ProviderModrinth,
catalog.ProviderCurseForge,
catalog.ProviderHangar,
catalog.ProviderSpiget,
catalog.ProviderMCDR,
}
// autoProviders is the default candidate list for an unspecified platform.
// curseforge reports whether the configured provider instances include it.
func autoProviders(curseforge bool) []catalog.Provider {
return append(modProviders(curseforge), catalog.ProviderMCDR)
}
func modProviders(curseforge bool) []catalog.Provider {
providers := []catalog.Provider{catalog.ProviderModrinth}
if curseforge {
providers = append(providers, catalog.ProviderCurseForge)
}
return providers
}
// providersForEcosystem returns the ordered providers that serve ecosystem.
// The result is filtered by configured credentials, so a supported ecosystem
// may still have no providers.
func providersForEcosystem(
ecosystem catalog.Ecosystem,
curseforge bool,
) []catalog.Provider {
if ecosystem == catalog.EcosystemUnspecified {
return autoProviders(curseforge)
}
providers := make(
[]catalog.Provider,
0,
len(providersInPriorityOrder),
)
for _, provider := range providersInPriorityOrder {
if !EcosystemSupportedBy(provider, ecosystem) {
continue
}
if provider == catalog.ProviderCurseForge && !curseforge {
continue
}
providers = append(providers, provider)
}
return providers
}
package routing
import (
"context"
"strings"
"github.com/mclucy/lucy/version"
)
type purpurBuildInfo struct {
Build string `json:"build"`
Version string `json:"version"`
MD5 string `json:"md5"`
}
type purpurVersionInfo struct {
Builds struct {
Latest purpurBuildInfo `json:"latest"`
All []purpurBuildInfo `json:"all"`
} `json:"builds"`
}
// IdentifyPurpurBuild matches a Purpur jar digest against the published builds
// for a Minecraft version. The detailed version document carries every build's
// MD5 in one response, so init walks builds from newest to oldest until one
// matches. Failed builds omit the digest, and an empty digest never matches.
func (r *Router) IdentifyPurpurBuild(
ctx context.Context,
minecraft version.Version,
md5 string,
) (version.Version, bool, error) {
if md5 == "" {
return "", false, nil
}
base := "https://api.purpurmc.org/v2/purpur/" + minecraft.String()
var listed purpurVersionInfo
if err := r.Metadata(ctx, base+"?detailed=true", &listed); err != nil {
return "", false, err
}
builds := listed.Builds.All
if len(builds) == 0 {
builds = []purpurBuildInfo{listed.Builds.Latest}
}
for index := len(builds) - 1; index >= 0; index-- {
build := builds[index]
if build.Build == "" {
continue
}
if build.Version != "" && build.Version != minecraft.String() {
continue
}
if build.MD5 == "" {
continue
}
if strings.EqualFold(build.MD5, md5) {
return version.Version(build.Build), true, nil
}
}
return "", false, nil
}
package upstream
import (
"context"
"fmt"
"github.com/mclucy/lucy/catalog"
)
// ProviderError pairs a provider identity with the failure it reported.
type ProviderError struct {
// Provider identifies the semantic upstream label for user-facing diagnostics.
// The failed runtime executor is a Provider implementation.
Provider catalog.Provider
Err error
}
func (e ProviderError) Error() string {
return fmt.Sprintf("%s: %v", e.Provider.String(), e.Err)
}
func (e ProviderError) Unwrap() error {
return e.Err
}
// ArtifactReleaseResolution records the outcome of identifying one fingerprint.
// A match includes the release and provider so callers can reuse the result.
// Errors records failed attempts even when a later mapper finds a match. An
// unmatched result with errors is an incomplete lookup, not a clean miss.
type ArtifactReleaseResolution struct {
Release Release
Matched bool
Provider catalog.Provider
Errors []ProviderError
}
// Complete reports whether every attempted mapper finished without failure.
func (r ArtifactReleaseResolution) Complete() bool { return len(r.Errors) == 0 }
// LookupArtifactReleases resolves fingerprints to published releases in input
// order. It returns one resolution per input, or nil when there are none.
//
// Mappers run in policy order. After each mapper only the fingerprints it did
// not resolve continue to the next mapper, so a provider is asked about an
// artifact only while no earlier provider has identified it. A mapper failure
// is recorded against just the fingerprints that mapper was asked about, and
// resolution continues with later mappers.
//
// Mappers that implement ArtifactBatchReleaseMapper receive all pending
// fingerprints in one call. Other mappers are asked one fingerprint at a time,
// and a lone pending fingerprint also uses the single-fingerprint path.
//
// A mapper-reported match resolves the fingerprint. When accept is non-nil the
// release also has to satisfy it; a rejected match leaves the fingerprint
// unresolved for later mappers.
func LookupArtifactReleases(
ctx context.Context,
fingerprints []ArtifactFingerprint,
mappers []ArtifactReleaseMapper,
accept func(Release) bool,
) []ArtifactReleaseResolution {
if len(fingerprints) == 0 {
return nil
}
resolutions := make([]ArtifactReleaseResolution, len(fingerprints))
pending := len(fingerprints)
var scratch []ArtifactFingerprint
for _, mapper := range mappers {
if pending == 0 {
break
}
provider := mapper.Provider()
artifacts := fingerprints
if pending != len(fingerprints) {
if scratch == nil {
scratch = make([]ArtifactFingerprint, 0, len(fingerprints))
}
scratch = scratch[:0]
for i := range resolutions {
if !resolutions[i].Matched {
scratch = append(scratch, fingerprints[i])
}
}
artifacts = scratch
}
lookups := mapperReleasesByHash(ctx, mapper, artifacts)
next := 0
for i := range resolutions {
if resolutions[i].Matched {
continue
}
result := lookups[next]
next++
if result.Err != nil {
resolutions[i].Errors = append(
resolutions[i].Errors,
ProviderError{Provider: provider, Err: result.Err},
)
continue
}
if !result.Matched {
continue
}
if accept != nil && !accept(result.Release) {
continue
}
resolutions[i].Release = result.Release
resolutions[i].Matched = true
resolutions[i].Provider = provider
pending--
}
}
return resolutions
}
// mapperReleasesByHash asks one mapper about artifacts in input order.
// Batch-capable mappers answer in a single call; the rest are asked one
// artifact at a time. A lone artifact takes the single-fingerprint path even
// for a batch-capable mapper, where the query is identical and no batching is
// possible.
func mapperReleasesByHash(
ctx context.Context,
mapper ArtifactReleaseMapper,
artifacts []ArtifactFingerprint,
) []ArtifactReleaseLookup {
if len(artifacts) == 1 {
release, matched, err := mapper.ReleaseByHash(ctx, artifacts[0])
return []ArtifactReleaseLookup{{
Release: release,
Matched: matched,
Err: err,
}}
}
if batch, ok := mapper.(ArtifactBatchReleaseMapper); ok {
return batch.ReleasesByHash(ctx, artifacts)
}
lookups := make([]ArtifactReleaseLookup, len(artifacts))
for i, artifact := range artifacts {
lookups[i].Release,
lookups[i].Matched,
lookups[i].Err = mapper.ReleaseByHash(ctx, artifact)
}
return lookups
}
package upstream
import (
"strings"
"unicode"
)
// LooksLikeMarkdown reports whether text carries Markdown-only structure:
// ATX headings, fenced code, list items, blockquotes, or inline code, links,
// and emphasis. Plain prose, including bare URLs, is not Markdown.
//
// Detection is purely lexical: upstream metadata normalization must not depend
// on a presentation renderer.
func LooksLikeMarkdown(text string) bool {
for line := range strings.Lines(text) {
trimmed := strings.TrimSpace(line)
if trimmed == "" {
continue
}
if strings.HasPrefix(trimmed, "```") ||
strings.HasPrefix(trimmed, "~~~") {
return true
}
if isATXHeading(trimmed) ||
isListItem(trimmed) ||
strings.HasPrefix(trimmed, "> ") ||
trimmed == ">" {
return true
}
if hasInlineMarkdown(trimmed) {
return true
}
}
return false
}
func isATXHeading(line string) bool {
level := 0
for level < len(line) && line[level] == '#' {
level++
}
if level == 0 || level > 6 {
return false
}
return level == len(line) || line[level] == ' ' || line[level] == '\t'
}
func isListItem(line string) bool {
for _, marker := range []string{"- ", "* ", "+ "} {
if strings.HasPrefix(line, marker) {
return true
}
}
digits := 0
for digits < len(line) && unicode.IsDigit(rune(line[digits])) {
digits++
}
return digits > 0 &&
digits+1 < len(line) &&
(line[digits] == '.' || line[digits] == ')') &&
line[digits+1] == ' '
}
func hasInlineMarkdown(line string) bool {
if strings.Contains(line, "`") {
return true
}
if strings.Contains(line, "](http://") || strings.Contains(line, "](https://") {
return true
}
if strings.Contains(line, "**") || strings.Contains(line, "__") {
return true
}
// A single asterisk pair around non-space text is emphasis; a lone
// asterisk is ordinary punctuation.
if first := strings.IndexByte(line, '*'); first >= 0 {
rest := line[first+1:]
if second := strings.IndexByte(rest, '*'); second > 0 {
inner := rest[:second]
if strings.TrimSpace(inner) == inner && inner != "" {
return true
}
}
}
return false
}
package upstream
import (
"context"
"slices"
"github.com/mclucy/lucy/catalog"
)
// ProjectServerSide is a provider's answer about one project.
type ProjectServerSide struct {
ServerSide ServerSide
ClientSide string
Title string
}
// IsClientOnly reports whether the project stays off a dedicated server.
func (p ProjectServerSide) IsClientOnly() bool {
return ClientOnly(p.ServerSide, p.ClientSide)
}
// ServerSideResolver reports a project's dedicated-server label by a name the
// artifact descriptor provides. found is false when the provider has no such
// project. Providers that publish no side labels answer found=false.
type ServerSideResolver interface {
ServerSideByName(
ctx context.Context,
name string,
) (ProjectServerSide, bool, error)
}
// ArtifactReleaseMapper resolves an installed artifact to the release it was
// published as, so a caller adopts the file already on disk without listing
// the project's releases.
type ArtifactReleaseMapper interface {
ProviderIdentifier
ReleaseByHash(
ctx context.Context,
artifact ArtifactFingerprint,
) (Release, bool, error)
}
// ArtifactBatchReleaseMapper resolves fingerprints in input order. Results
// distinguish an unknown fingerprint from a failed lookup for each artifact.
type ArtifactBatchReleaseMapper interface {
ArtifactReleaseMapper
ReleasesByHash(context.Context, []ArtifactFingerprint) []ArtifactReleaseLookup
}
type ArtifactReleaseLookup struct {
Release Release
Matched bool
Err error
}
// ServerSide is a project's dedicated-server support label. Providers report
// it when they publish one; an empty value means the provider has no answer.
type ServerSide string
const (
ServerSideRequired ServerSide = "required"
ServerSideOptional ServerSide = "optional"
ServerSideUnsupported ServerSide = "unsupported"
)
// ClientOnly reports whether a project's side labels keep it off a dedicated
// server. A server-unsupported project is client-only. So is a client-required
// project that is merely server-optional: a dedicated server has no use for it.
// A project that is optional on both sides is a shared library.
func ClientOnly(serverSide ServerSide, clientSide string) bool {
return serverSide == ServerSideUnsupported ||
(serverSide == ServerSideOptional && clientSide == "required")
}
// Release is one published artifact as its provider records it. Ref names the
// project and version; Candidate describes the same file for resolution.
// Compatibility labels are advisory: installed bytes prove the server holds the
// artifact, so a release whose labels miss the target stays installable.
type Release struct {
Ref catalog.VersionedRef
Candidate Candidate
MinecraftVersions []string
Loaders []string
ServerSide ServerSide
ClientSide string
}
// ClientOnly reports whether the release belongs on a dedicated server.
func (r Release) ClientOnly() bool {
return ClientOnly(r.ServerSide, r.ClientSide)
}
// Supports reports whether the release labels itself for minecraft and loader.
// An empty minecraft or unspecified loader asks nothing. Labels that name no
// ecosystem this build models answer nothing either.
func (r Release) Supports(minecraft string, loader catalog.Ecosystem) bool {
if minecraft != "" && len(r.MinecraftVersions) > 0 &&
!slices.Contains(r.MinecraftVersions, minecraft) {
return false
}
return r.SupportsLoader(loader)
}
// SupportsLoader reports whether the release names a loader that loader runs.
// An unspecified loader asks nothing. Labels that name no modeled ecosystem
// answer nothing either.
func (r Release) SupportsLoader(loader catalog.Ecosystem) bool {
if loader == catalog.EcosystemUnspecified {
return true
}
recognized := false
for _, label := range r.Loaders {
ecosystem := catalog.Ecosystem(label)
if !knownEcosystem(ecosystem) {
continue
}
recognized = true
if loader.Satisfy(ecosystem) {
return true
}
}
return !recognized
}
func knownEcosystem(ecosystem catalog.Ecosystem) bool {
switch ecosystem {
case catalog.EcosystemFabric,
catalog.EcosystemQuilt,
catalog.EcosystemForge,
catalog.EcosystemNeoForge,
catalog.EcosystemBukkit,
catalog.EcosystemPaper,
catalog.EcosystemSponge,
catalog.EcosystemBungeeCord,
catalog.EcosystemVelocity,
catalog.EcosystemMCDR:
return true
default:
return false
}
}
package upstream
import "strings"
// ReleaseChannel is the stability channel published by a provider.
type ReleaseChannel string
const (
ReleaseChannelUnknown ReleaseChannel = ""
ReleaseChannelRelease ReleaseChannel = "release"
ReleaseChannelBeta ReleaseChannel = "beta"
ReleaseChannelAlpha ReleaseChannel = "alpha"
)
func ParseReleaseChannel(s string) ReleaseChannel {
switch strings.ToLower(strings.TrimSpace(s)) {
case "release", "stable":
return ReleaseChannelRelease
case "beta", "prerelease", "pre-release":
return ReleaseChannelBeta
case "alpha":
return ReleaseChannelAlpha
default:
return ReleaseChannelUnknown
}
}
package version
import (
"fmt"
"strings"
)
// ErrAmbiguousVersion is returned when attempting to parse a non-exact
// version constant.
var ErrAmbiguousVersion = fmt.Errorf("attempting to parse an ambiguous version")
// Engine parses, orders, and matches versions under one grammar.
type Engine struct {
kind Dialect
}
// NewEngine binds operations to a dialect identifier.
func NewEngine(kind Dialect) (Engine, error) {
if !kind.Valid() {
return Engine{}, fmt.Errorf("unsupported version dialect %q", kind)
}
return Engine{kind: kind}, nil
}
// valueDialect returns the dialect of the concrete versions kind parses.
// Quilt descriptors constrain Fabric versions, so their values belong to the
// Fabric dialect and stay comparable with Fabric modules.
func valueDialect(kind Dialect) Dialect {
if kind == DialectQuilt {
return DialectFabric
}
return kind
}
// ParseVersion parses a concrete version. It rejects selectors, versions
// containing wildcards, and input outside the dialect grammar.
func (d Engine) ParseVersion(raw Version) (ResolvableVersion, error) {
switch raw {
case Beta, Stable, None, Any, Unknown:
return nil, fmt.Errorf("%w: %s", ErrAmbiguousVersion, raw)
}
var parsed ResolvableVersion
switch d.kind {
case DialectFabric, DialectQuilt:
parsed = parseFabricVersion(raw)
case DialectMCDR:
parsed = parseMCDRVersion(string(raw), false)
case DialectMaven:
parsed = parseMavenVersion(raw)
case DialectMinecraft:
parsed = parseMinecraftRelease(raw)
if parsed == nil {
parsed = parseMinecraftSnapshot(raw)
}
case DialectOpaque:
parsed = parseOpaqueVersion(raw)
default:
return nil, fmt.Errorf("unsupported version dialect %q", d.kind)
}
if parsed == nil || !parsed.Validate() {
return nil, fmt.Errorf(
"invalid %s version %q",
d.kind,
raw,
)
}
return parsed, nil
}
// ParseConstraint parses a version constraint. A nil expression with a nil
// error means the constraint accepts every version. Invalid input returns an
// error, never an unconstrained expression.
func (d Engine) ParseConstraint(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || raw == "*" {
return nil, nil
}
switch d.kind {
case DialectFabric:
return parseFabricConstraint(raw)
case DialectQuilt:
return parseQuiltConstraint(raw)
case DialectMCDR:
return parseMCDRConstraint(raw)
case DialectMaven:
return parseMavenRange(raw)
case DialectMinecraft:
return parseMinecraftConstraint(raw)
case DialectOpaque:
return parseOpaqueConstraint(raw)
default:
return nil, fmt.Errorf("unsupported version dialect %q", d.kind)
}
}
// ParseConstraints parses each string as an alternative. One unconstrained
// alternative makes the whole expression unconstrained.
func (d Engine) ParseConstraints(raws []string) (Expr, error) {
if len(raws) == 0 {
return nil, nil
}
merged := make(Expr, 0, len(raws))
for _, raw := range raws {
expr, err := d.ParseConstraint(raw)
if err != nil {
return nil, err
}
if len(expr) == 0 {
return nil, nil
}
merged = append(merged, expr...)
}
if len(merged) == 0 {
return nil, nil
}
return merged, nil
}
// Compare orders two versions of this dialect. Different dialects are never
// comparable.
func (d Engine) Compare(
left, right ResolvableVersion,
) (int, bool) {
if left == nil || right == nil {
return 0, false
}
values := valueDialect(d.kind)
if left.Dialect() != values || right.Dialect() != values {
return 0, false
}
if comparison, ok := left.Compare(right); ok {
return comparison, true
}
if comparison, ok := right.Compare(left); ok {
return -comparison, true
}
return 0, false
}
// Match reports whether a parsed version satisfies an expression of this
// dialect. A nil or empty expression accepts every version.
func (d Engine) Match(
expr Expr,
actual ResolvableVersion,
) bool {
if len(expr) == 0 {
return true
}
if actual == nil || actual.Dialect() != valueDialect(d.kind) {
return false
}
for _, conjunction := range expr {
matched := true
for _, term := range conjunction {
if !d.matchTerm(term, actual) {
matched = false
break
}
}
if matched {
return true
}
}
return false
}
// MatchText parses both sides and reports whether the version satisfies the
// constraint.
func (d Engine) MatchText(
raw string,
actual Version,
) (bool, error) {
expr, err := d.ParseConstraint(raw)
if err != nil {
return false, err
}
if len(expr) == 0 {
return true, nil
}
parsed, err := d.ParseVersion(actual)
if err != nil {
return false, err
}
return d.Match(expr, parsed), nil
}
func (d Engine) matchTerm(
term SubExpr,
actual ResolvableVersion,
) bool {
if term.Operator == OpNever || term.Value == nil {
return false
}
values := valueDialect(d.kind)
if term.Value.Dialect() != values {
return false
}
if values == DialectFabric {
_, actualSemantic := actual.(*SemverVersion)
_, boundSemantic := term.Value.(*SemverVersion)
if !actualSemantic || !boundSemantic {
return matchOpaqueOperator(
term.Operator,
term.Inverted,
actual,
term.Value,
)
}
}
comparison, ok := d.Compare(actual, term.Value)
if !ok {
// An incomparable operand makes the parsed predicate false, so its
// complement is true.
return term.Inverted
}
switch term.Operator {
case OpEq:
return comparison == 0
case OpNeq:
return comparison != 0
case OpGt:
return comparison > 0
case OpGte:
return comparison >= 0
case OpLt:
return comparison < 0
case OpLte:
return comparison <= 0
default:
return false
}
}
// matchOpaqueOperator applies Fabric Loader's rule for versions outside its
// semantic grammar: an inclusive predicate requires exact string equality,
// while an exclusive predicate never matches. For a term produced by
// negation, the result is the complement of the original predicate.
func matchOpaqueOperator(
operator Operator,
inverted bool,
left, right ResolvableVersion,
) bool {
leftString, leftOK := left.(fmt.Stringer)
rightString, rightOK := right.(fmt.Stringer)
if !leftOK || !rightOK {
return false
}
equal := leftString.String() == rightString.String()
if inverted {
return !matchOpaqueRaw(operator.Inverse(), equal)
}
return matchOpaqueRaw(operator, equal)
}
func matchOpaqueRaw(operator Operator, equal bool) bool {
switch operator {
case OpEq, OpGte, OpLte:
return equal
default:
return false
}
}
// ParseVersion parses a concrete version under dialect.
func ParseVersion(
raw Version,
dialect Dialect,
) (ResolvableVersion, error) {
bound, err := NewEngine(dialect)
if err != nil {
return nil, err
}
return bound.ParseVersion(raw)
}
// ParseConstraint parses a constraint under dialect.
func ParseConstraint(
raw string,
dialect Dialect,
) (Expr, error) {
bound, err := NewEngine(dialect)
if err != nil {
return nil, err
}
return bound.ParseConstraint(raw)
}
// ParseConstraints parses alternative constraints under dialect.
func ParseConstraints(
raws []string,
dialect Dialect,
) (Expr, error) {
bound, err := NewEngine(dialect)
if err != nil {
return nil, err
}
return bound.ParseConstraints(raws)
}
// Compare orders two versions. Versions from different dialects are
// incomparable.
func Compare(left, right ResolvableVersion) (int, bool) {
if left == nil || right == nil {
return 0, false
}
bound, err := NewEngine(left.Dialect())
if err != nil || left.Dialect() != right.Dialect() {
return 0, false
}
return bound.Compare(left, right)
}
// Match reports whether actual satisfies raw under dialect.
func Match(
raw string,
actual Version,
dialect Dialect,
) (bool, error) {
bound, err := NewEngine(dialect)
if err != nil {
return false, err
}
return bound.MatchText(raw, actual)
}
package version
// Expr is a boolean expression in disjunctive normal form: the outer slice is
// OR, the inner slice is AND. A nil or empty outer slice accepts every version.
type Expr [][]SubExpr
type SubExpr struct {
Value ResolvableVersion
Operator Operator
// Inverted records that Operator is the logical complement of a parsed
// predicate. Dialects with partial ordering use it to keep the complement
// consistent with their own predicate rules.
Inverted bool
}
// Negate returns the logical negation of the expression in disjunctive normal
// form. Negating a disjunction produces a conjunction of negated clauses, so
// the result is distributed back into OR-of-AND form.
func (exps Expr) Negate() Expr {
if len(exps) == 0 {
return Expr{{SubExpr{Operator: OpNever}}}
}
result := Expr{{}}
for _, conjunction := range exps {
if len(conjunction) == 0 {
return Expr{{SubExpr{Operator: OpNever}}}
}
clause := make([]SubExpr, 0, len(conjunction))
trueClause := false
for _, term := range conjunction {
inverted, always := term.negated()
if always {
trueClause = true
break
}
clause = append(clause, inverted)
}
if trueClause {
continue
}
next := make(Expr, 0, len(result)*len(clause))
for _, product := range result {
for _, term := range clause {
distributed := make([]SubExpr, 0, len(product)+1)
distributed = append(distributed, product...)
distributed = append(distributed, term)
next = append(next, distributed)
}
}
result = next
}
if len(result) == 1 && len(result[0]) == 0 {
return nil
}
if len(result) == 0 {
return Expr{{SubExpr{Operator: OpNever}}}
}
return result
}
// negated returns the logical complement of one term. always reports a term
// that is already true, whose negation contributes nothing to a conjunction.
func (term SubExpr) negated() (inverted SubExpr, always bool) {
if term.Operator == OpNever || term.Value == nil {
return SubExpr{}, true
}
return SubExpr{
Value: term.Value,
Operator: term.Operator.Inverse(),
Inverted: !term.Inverted,
}, false
}
type Operator uint8
const (
OpEq Operator = iota
OpNeq
OpGt
OpGte
OpLt
OpLte
// OpNever is the canonical unsatisfiable term produced by negating an
// unconstrained expression.
OpNever
)
func (op Operator) String() string {
switch op {
case OpEq:
return "equal"
case OpNeq:
return "not equal"
case OpGt:
return "greater than"
case OpGte:
return "greater than or equal"
case OpLt:
return "less than"
case OpLte:
return "less than or equal"
case OpNever:
return "never"
default:
return "unknown"
}
}
func (op Operator) ToSign() string {
switch op {
case OpEq:
return "="
case OpNeq:
return "!="
case OpGt:
return ">"
case OpGte:
return ">="
case OpLt:
return "<"
case OpLte:
return "<="
case OpNever:
return "!"
default:
return "unknown"
}
}
func (op Operator) Inverse() Operator {
switch op {
case OpEq:
return OpNeq
case OpNeq:
return OpEq
case OpGt:
return OpLte
case OpGte:
return OpLt
case OpLt:
return OpGte
case OpLte:
return OpGt
default:
return op
}
}
package version
import (
"encoding/json/jsontext"
"strings"
)
// MavenVersion implements Maven-style version ordering for Forge/NeoForge
// mod metadata and Maven version ranges.
type MavenVersion struct {
original string
tokens []mavenToken
}
type mavenToken struct {
separator byte
value string
numeric bool
followedByDigit bool
}
func parseMavenVersion(raw Version) ResolvableVersion {
original := string(raw)
if original == "" || len(original) > 256 {
return nil
}
return &MavenVersion{
original: original,
tokens: tokenizeMavenVersion(original),
}
}
func (v *MavenVersion) Compare(other ResolvableVersion) (int, bool) {
if v == nil || other == nil {
return 0, false
}
var o *MavenVersion
switch other := other.(type) {
case *MavenVersion:
o = other
default:
return 0, false
}
if o == nil {
return 0, false
}
maxLen := max(len(o.tokens), len(v.tokens))
for i := range maxLen {
left := mavenTokenAt(v.tokens, i, mavenTokenSeparatorAt(o.tokens, i))
right := mavenTokenAt(o.tokens, i, mavenTokenSeparatorAt(v.tokens, i))
if cmp := compareMavenToken(left, right); cmp != 0 {
return cmp, true
}
}
return 0, true
}
func (v *MavenVersion) Validate() bool {
return v != nil && v.original != ""
}
func (v *MavenVersion) Dialect() Dialect {
return DialectMaven
}
func (v *MavenVersion) String() string {
if v == nil {
return ""
}
return v.original
}
// MarshalJSONTo renders the version in its original string form. All fields
// are unexported, which encoding/json/v2 refuses to marshal.
func (v *MavenVersion) MarshalJSONTo(enc *jsontext.Encoder) error {
return enc.WriteToken(jsontext.String(v.String()))
}
func tokenizeMavenVersion(raw string) []mavenToken {
tokens := make([]mavenToken, 0)
separator := byte('.')
var buf strings.Builder
previousClass := byte(0)
flush := func(followedByDigit bool) {
if buf.Len() == 0 {
return
}
value := buf.String()
tokens = append(
tokens, mavenToken{
separator: separator,
value: value,
numeric: isMavenNumeric(value),
followedByDigit: followedByDigit,
},
)
buf.Reset()
}
for i := 0; i < len(raw); i++ {
ch := raw[i]
if isMavenSeparator(ch) {
flush(false)
separator = ch
previousClass = 0
continue
}
class := mavenCharClass(ch)
if buf.Len() > 0 && previousClass != 0 && class != previousClass {
flush(class == '0')
separator = '-'
}
buf.WriteByte(ch)
previousClass = class
}
flush(false)
return trimMavenNullTokens(tokens)
}
func isMavenSeparator(ch byte) bool {
return ch == '.' || ch == '-'
}
func mavenCharClass(ch byte) byte {
if ch >= '0' && ch <= '9' {
return '0'
}
return 'a'
}
func isMavenNumeric(value string) bool {
if value == "" {
return false
}
for i := 0; i < len(value); i++ {
if value[i] < '0' || value[i] > '9' {
return false
}
}
return true
}
func trimMavenNullTokens(tokens []mavenToken) []mavenToken {
tokens = trimTrailingMavenNullTokens(tokens)
for i := len(tokens) - 1; i >= 0; i-- {
if tokens[i].separator != '-' {
continue
}
start := i
for start > 0 && isMavenNullToken(tokens[start-1]) {
start--
}
if start == i {
continue
}
tokens = append(tokens[:start], tokens[i:]...)
i = start
}
return trimTrailingMavenNullTokens(tokens)
}
func trimTrailingMavenNullTokens(tokens []mavenToken) []mavenToken {
for len(tokens) > 0 && isMavenNullToken(tokens[len(tokens)-1]) {
tokens = tokens[:len(tokens)-1]
}
return tokens
}
func isMavenNullToken(token mavenToken) bool {
if token.numeric {
return compareMavenInteger(token.value, "0") == 0
}
switch normalizeMavenQualifier(token.value) {
case "", "final", "ga", "release":
return true
default:
return false
}
}
func mavenTokenAt(
tokens []mavenToken,
index int,
otherSeparator byte,
) mavenToken {
if index < len(tokens) {
return tokens[index]
}
if otherSeparator == 0 {
otherSeparator = '.'
}
if otherSeparator == '.' {
return mavenToken{separator: otherSeparator, value: "0", numeric: true}
}
return mavenToken{separator: otherSeparator, value: "", numeric: false}
}
func mavenTokenSeparatorAt(tokens []mavenToken, index int) byte {
if index < len(tokens) {
return tokens[index].separator
}
return 0
}
func compareMavenToken(left, right mavenToken) int {
if left.separator != right.separator {
if cmp := compareInt(
mavenTokenKind(left),
mavenTokenKind(right),
); cmp != 0 {
return cmp
}
}
if left.numeric && right.numeric {
return compareMavenInteger(left.value, right.value)
}
if !left.numeric && !right.numeric {
return compareMavenQualifier(left, right)
}
if left.numeric {
return 1
}
return -1
}
func mavenTokenKind(token mavenToken) int {
if !token.numeric {
return 0
}
if token.separator == '.' {
return 2
}
return 1
}
func compareMavenInteger(left, right string) int {
left = strings.TrimLeft(left, "0")
right = strings.TrimLeft(right, "0")
if left == "" {
left = "0"
}
if right == "" {
right = "0"
}
if cmp := compareInt(len(left), len(right)); cmp != 0 {
return cmp
}
return strings.Compare(left, right)
}
func compareMavenQualifier(left, right mavenToken) int {
leftValue := mavenQualifierValue(left)
rightValue := mavenQualifierValue(right)
leftRank, leftKnown := mavenQualifierRank(leftValue)
rightRank, rightKnown := mavenQualifierRank(rightValue)
if leftKnown || rightKnown {
if cmp := compareInt(leftRank, rightRank); cmp != 0 {
return cmp
}
if leftKnown && rightKnown {
return 0
}
}
return strings.Compare(leftValue, rightValue)
}
func mavenQualifierValue(token mavenToken) string {
value := normalizeMavenQualifier(token.value)
if token.followedByDigit && len(value) == 1 {
switch value {
case "a":
return "alpha"
case "b":
return "beta"
case "m":
return "milestone"
}
}
return value
}
func normalizeMavenQualifier(value string) string {
return strings.ToLower(strings.TrimSpace(value))
}
func mavenQualifierRank(value string) (int, bool) {
switch value {
case "alpha":
return 0, true
case "beta":
return 1, true
case "milestone":
return 2, true
case "rc", "cr":
return 3, true
case "snapshot":
return 4, true
case "", "final", "ga", "release":
return 5, true
case "sp":
return 6, true
default:
return 7, false
}
}
package version
import (
"errors"
"strconv"
"strings"
)
// NewestMinecraft reports the highest version in the list under the Minecraft
// grammar. Entries the grammar cannot parse are skipped.
func NewestMinecraft(versions []Version) (Version, error) {
var newest Version
var parsed ResolvableVersion
for _, candidate := range versions {
if candidate == "" {
continue
}
resolved, err := ParseVersion(candidate, DialectMinecraft)
if err != nil || resolved == nil {
continue
}
if parsed == nil {
newest, parsed = candidate, resolved
continue
}
if newerMinecraft(candidate, resolved, newest, parsed) {
newest, parsed = candidate, resolved
}
}
if parsed == nil {
return "", errors.New("no Minecraft version in the candidate list")
}
return newest, nil
}
// newerMinecraft reports whether candidate is newer than current. The release
// scheme changed at year 26, and versions from different schemes do not
// compare, so a year-based version outranks every 1.x version.
func newerMinecraft(
candidate Version,
candidateParsed ResolvableVersion,
current Version,
currentParsed ResolvableVersion,
) bool {
candidateScheme := minecraftSchemeRank(candidate)
currentScheme := minecraftSchemeRank(current)
if candidateScheme != currentScheme {
return candidateScheme > currentScheme
}
comparison, comparable := Compare(currentParsed, candidateParsed)
return comparable && comparison < 0
}
// minecraftSchemeRank orders the release schemes: 1.x releases rank 0 and
// year-based releases rank 1.
func minecraftSchemeRank(v Version) int {
head, _, _ := strings.Cut(string(v), ".")
year, err := strconv.Atoi(head)
if err != nil {
return 0
}
if year >= minPost26ReleaseYear {
return 1
}
return 0
}
package version
import (
"strconv"
"strings"
)
func parseMinecraftVersion(s Version) ResolvableVersion {
if v := parseMinecraftRelease(s); v != nil {
return v
}
return parseMinecraftSnapshot(s)
}
func parseMinecraftSnapshot(s Version) ResolvableVersion {
if v := parsePre26WeekSnapshot(s); v != nil {
return v
}
return parsePost26MinecraftSnapshot(s)
}
func parsePre26WeekSnapshot(s Version) ResolvableVersion {
if len(s) < 4 {
return nil
}
index := s[len(s)-1]
v := parseSnapshotWorkCycle(s[:len(s)-1])
if v == nil {
return nil
}
if index < minSnapshotIndex || index > maxSnapshotIndex {
return nil
}
v.Index = index
if !v.Validate() {
return nil
}
return v
}
func parseSnapshotWorkCycle(s Version) *Pre26MinecraftSnapshotVersion {
tokens := strings.Split(string(s), "w")
if len(tokens) != 2 {
return nil
}
year, ok := parseUint8(tokens[0])
if !ok {
return nil
}
workCycle, ok := parseUint8(tokens[1])
if !ok {
return nil
}
return &Pre26MinecraftSnapshotVersion{
Year: year,
WorkCycle: workCycle,
Index: 0,
}
}
func parsePost26MinecraftSnapshot(s Version) ResolvableVersion {
str := string(s)
if !strings.Contains(str, "-snapshot-") {
return nil
}
tokens := strings.Split(str, "-snapshot-")
if len(tokens) != 2 {
return nil
}
core := strings.Split(tokens[0], ".")
if len(core) != 2 {
return nil
}
year, ok := parseUint8(core[0])
if !ok {
return nil
}
update, ok := parseUint8(core[1])
if !ok {
return nil
}
snapshotN, ok := parseUint8(tokens[1])
if !ok {
return nil
}
v := &Post26MinecraftSnapshotVersion{
Year: year,
Update: update,
SnapshotN: snapshotN,
}
if !v.Validate() {
return nil
}
return v
}
func parseMinecraftRelease(s Version) ResolvableVersion {
if v := parsePost26MinecraftRelease(s); v != nil {
return v
}
return parsePre26MinecraftRelease(s)
}
func parsePost26MinecraftRelease(s Version) ResolvableVersion {
str := string(s)
if str == "" || strings.Contains(str, "-snapshot-") {
return nil
}
core, suffix := splitCoreAndSuffix(str)
coreTokens := strings.Split(core, ".")
if len(coreTokens) < 2 || len(coreTokens) > 3 {
return nil
}
year, ok := parseUint8(coreTokens[0])
if !ok || year < minPost26ReleaseYear {
return nil
}
update, ok := parseUint8(coreTokens[1])
if !ok {
return nil
}
v := &MinecraftVersion{
Year: year,
Update: update,
Post26: true,
}
if len(coreTokens) == 3 {
hotfix, ok := parseUint8(coreTokens[2])
if !ok {
return nil
}
v.Hotfix = hotfix
}
if suffix != "" {
prerelease, number, ok := parseMinecraftPrereleaseSuffix(suffix)
if !ok {
return nil
}
v.Prerelease = prerelease
v.PrereleaseNumber = number
}
if !v.Validate() {
return nil
}
return v
}
func parsePre26MinecraftRelease(s Version) ResolvableVersion {
str := string(s)
if str == "" {
return nil
}
core, suffix := splitCoreAndSuffix(str)
coreTokens := strings.Split(core, ".")
if len(coreTokens) < 2 || len(coreTokens) > 3 {
return nil
}
year, ok := parseUint8(coreTokens[0])
if !ok || year >= minPost26ReleaseYear {
return nil
}
update, ok := parseUint8(coreTokens[1])
if !ok {
return nil
}
v := &MinecraftVersion{
Year: year,
Update: update,
Post26: false,
}
if len(coreTokens) == 3 {
hotfix, ok := parseUint8(coreTokens[2])
if !ok {
return nil
}
v.Hotfix = hotfix
}
if suffix != "" {
prerelease, number, ok := parseMinecraftPrereleaseSuffix(suffix)
if !ok {
return nil
}
v.Prerelease = prerelease
v.PrereleaseNumber = number
}
if !v.Validate() {
return nil
}
return v
}
func splitCoreAndSuffix(raw string) (core string, suffix string) {
core = raw
if before, after, ok := strings.Cut(raw, "-"); ok {
core = before
suffix = after
}
return core, suffix
}
func parseMinecraftPrereleaseSuffix(suffix string) (
PrereleaseType,
uint8,
bool,
) {
if after, ok := strings.CutPrefix(suffix, "pre"); ok {
number, ok := parsePrereleaseNumber(after)
if !ok {
return "", 0, false
}
return Post26Prerelease, number, true
}
if after, ok := strings.CutPrefix(suffix, "rc"); ok {
number, ok := parsePrereleaseNumber(after)
if !ok {
return "", 0, false
}
return Post26ReleaseCandidate, number, true
}
return "", 0, false
}
func parsePrereleaseNumber(s string) (uint8, bool) {
s = strings.TrimPrefix(s, "-")
if s == "" {
return 0, false
}
n, ok := parseUint8(s)
if !ok || n == 0 {
return 0, false
}
return n, true
}
func parseUint8(s string) (uint8, bool) {
if s == "" {
return 0, false
}
v, err := strconv.Atoi(s)
if err != nil || v < 0 || v > 255 {
return 0, false
}
return uint8(v), true
}
package version
import (
"fmt"
"strings"
)
// parseMinecraftConstraint accepts exact release or snapshot versions as OR
// alternatives. Minecraft metadata defines no range operators.
func parseMinecraftConstraint(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || raw == "*" {
return nil, nil
}
parts := strings.Split(raw, "||")
result := make(Expr, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
return nil, fmt.Errorf("empty alternative in Minecraft range %q", raw)
}
if isWildcardExpression(part) {
return nil, nil
}
version := parseMinecraftVersion(Version(part))
if version == nil {
return nil, fmt.Errorf("invalid Minecraft version %q", part)
}
result = append(result, []SubExpr{
{Value: version, Operator: OpEq},
})
}
if len(result) == 0 {
return nil, nil
}
return result, nil
}
package version
import "strconv"
const (
maxSnapshotWeek = 54
maxSnapshotIndex = uint8('h')
minSnapshotIndex = uint8('a')
minPost26ReleaseYear = 26
)
// docs:
// https://zh.minecraft.wiki/w/%E7%89%88%E6%9C%AC%E6%A0%BC%E5%BC%8F
// https://www.minecraft.net/en-us/article/minecraft-new-version-numbering-system
type Pre26MinecraftSnapshotVersion struct {
Year uint8 // the last two digits of the year, e.g. 24 for 2024
WorkCycle uint8 // the week of the year
Index uint8 // the letter, stored as ASCII values directly
}
func (v1 *Pre26MinecraftSnapshotVersion) Compare(v2 ResolvableVersion) (
int,
bool,
) {
o, ok := v2.(*Pre26MinecraftSnapshotVersion)
if !ok || v1 == nil || o == nil {
return 0, false
}
if cmp := compareUint8(v1.Year, o.Year); cmp != 0 {
return cmp, true
}
if cmp := compareUint8(v1.WorkCycle, o.WorkCycle); cmp != 0 {
return cmp, true
}
return compareUint8(v1.Index, o.Index), true
}
func (v1 *Pre26MinecraftSnapshotVersion) Validate() bool {
if v1 == nil {
return false
}
return v1.Year != 0 &&
v1.WorkCycle > 0 && v1.WorkCycle <= maxSnapshotWeek &&
v1.Index >= minSnapshotIndex && v1.Index <= maxSnapshotIndex
}
func (v1 *Pre26MinecraftSnapshotVersion) Dialect() Dialect {
return DialectMinecraft
}
// Post26MinecraftSnapshotVersion represents snapshots after the new numbering
// scheme (for example 26.1-snapshot-1).
type Post26MinecraftSnapshotVersion struct {
Year uint8
Update uint8
SnapshotN uint8
}
func (v1 *Post26MinecraftSnapshotVersion) Compare(v2 ResolvableVersion) (
int,
bool,
) {
o, ok := v2.(*Post26MinecraftSnapshotVersion)
if !ok || v1 == nil || o == nil {
return 0, false
}
if cmp := compareUint8(v1.Year, o.Year); cmp != 0 {
return cmp, true
}
if cmp := compareUint8(v1.Update, o.Update); cmp != 0 {
return cmp, true
}
return compareUint8(v1.SnapshotN, o.SnapshotN), true
}
func (v1 *Post26MinecraftSnapshotVersion) Validate() bool {
if v1 == nil {
return false
}
return v1.Year >= minPost26ReleaseYear &&
v1.Update > 0 &&
v1.SnapshotN > 0
}
func (v1 *Post26MinecraftSnapshotVersion) Dialect() Dialect {
return DialectMinecraft
}
type MinecraftVersion struct {
Year uint8
Update uint8
Hotfix uint8
Prerelease PrereleaseType
PrereleaseNumber uint8
Post26 bool
}
type PrereleaseType string
const (
Post26Prerelease PrereleaseType = "pre"
Post26ReleaseCandidate PrereleaseType = "rc"
)
func (v *MinecraftVersion) Title() string {
if v == nil {
return ""
}
if v.Post26 {
base := strconv.Itoa(int(v.Year)) + "." + strconv.Itoa(int(v.Update))
if v.Prerelease != "" {
return base + "-" + string(v.Prerelease) + "-" + strconv.Itoa(int(v.PrereleaseNumber))
}
if v.Hotfix > 0 {
return base + "." + strconv.Itoa(int(v.Hotfix))
}
return base
}
base := strconv.Itoa(int(v.Year)) + "." + strconv.Itoa(int(v.Update))
if v.Hotfix > 0 {
base += "." + strconv.Itoa(int(v.Hotfix))
}
if v.Prerelease != "" {
return base + "-" + string(v.Prerelease) + strconv.Itoa(int(v.PrereleaseNumber))
}
return base
}
func (v1 *MinecraftVersion) Compare(v2 ResolvableVersion) (int, bool) {
o, ok := v2.(*MinecraftVersion)
if !ok || v1 == nil || o == nil {
return 0, false
}
if v1.Post26 != o.Post26 {
return 0, false
}
if cmp := compareUint8(v1.Year, o.Year); cmp != 0 {
return cmp, true
}
if cmp := compareUint8(v1.Update, o.Update); cmp != 0 {
return cmp, true
}
if cmp := compareUint8(v1.Hotfix, o.Hotfix); cmp != 0 {
return cmp, true
}
if cmp := compareUint8(
prereleaseRank(v1.Prerelease),
prereleaseRank(o.Prerelease),
); cmp != 0 {
return cmp, true
}
return compareUint8(v1.PrereleaseNumber, o.PrereleaseNumber), true
}
func (v1 *MinecraftVersion) Validate() bool {
if v1 == nil {
return false
}
if v1.Year == 0 || v1.Update == 0 {
return false
}
if v1.Post26 && v1.Year < minPost26ReleaseYear {
return false
}
switch v1.Prerelease {
case "":
return true
case Post26Prerelease, Post26ReleaseCandidate:
if v1.PrereleaseNumber == 0 {
return false
}
if v1.Post26 {
return v1.Hotfix == 0
}
return true
default:
return false
}
}
func (v1 *MinecraftVersion) Dialect() Dialect {
return DialectMinecraft
}
func prereleaseRank(pr PrereleaseType) uint8 {
switch pr {
case Post26Prerelease:
return 0
case Post26ReleaseCandidate:
return 1
default:
return 2
}
}
func compareUint8(a, b uint8) int {
if a < b {
return -1
}
if a > b {
return 1
}
return 0
}
package version
import (
"fmt"
"strings"
)
// parseOpaqueVersion accepts any non-empty identifier. Opaque versions
// compare by exact string.
func parseOpaqueVersion(raw Version) ResolvableVersion {
text := string(raw)
if strings.TrimSpace(text) == "" {
return nil
}
return &StringVersion{
dialect: DialectOpaque,
original: text,
}
}
// parseOpaqueConstraint accepts an unconstrained expression or an exact
// identifier. Descriptors with an opaque version grammar define no range
// operators.
func parseOpaqueConstraint(raw string) (Expr, error) {
text := strings.TrimSpace(raw)
if text == "" || text == "*" {
return nil, nil
}
if strings.ContainsAny(text, " \t\r\n|") {
return nil, fmt.Errorf("opaque constraint %q must be an exact version", raw)
}
switch text[0] {
case '<', '>', '=', '!', '^', '~':
return nil, fmt.Errorf("opaque constraint %q must be an exact version", raw)
}
version := parseOpaqueVersion(Version(text))
if version == nil {
return nil, fmt.Errorf("invalid opaque version %q", raw)
}
return Expr{
{{Value: version, Operator: OpEq}},
}, nil
}
package version
import (
"fmt"
"strings"
)
// parseMavenRange parses Maven version ranges used by Forge and NeoForge.
// A bare version is a recommended version, not a restriction.
//
// References:
// - https://docs.minecraftforge.net/en/latest/gettingstarted/modfiles/
// - https://maven.apache.org/enforcer/enforcer-rules/versionRanges.html
func parseMavenRange(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || raw == "*" || strings.EqualFold(raw, "none") {
return nil, nil
}
parts, err := splitMavenUnions(raw)
if err != nil {
return nil, err
}
result := make(Expr, 0, len(parts))
for _, part := range parts {
constraints, err := parseMavenSingleRange(strings.TrimSpace(part))
if err != nil {
return nil, err
}
if len(constraints) == 0 {
continue
}
result = append(result, constraints)
}
if len(result) == 0 {
return nil, nil
}
return result, nil
}
func splitMavenUnions(raw string) ([]string, error) {
var out []string
depth := 0
start := 0
flush := func(end int) error {
part := strings.TrimSpace(raw[start:end])
if part == "" {
return fmt.Errorf("invalid Maven range %q", raw)
}
out = append(out, part)
return nil
}
for index := range len(raw) {
switch raw[index] {
case '[', '(':
depth++
case ']', ')':
if depth == 0 {
return nil, fmt.Errorf("invalid Maven range %q", raw)
}
depth--
case ',':
if depth == 0 {
if err := flush(index); err != nil {
return nil, err
}
start = index + 1
}
}
}
if depth != 0 {
return nil, fmt.Errorf("invalid Maven range %q", raw)
}
if err := flush(len(raw)); err != nil {
return nil, err
}
return out, nil
}
func parseMavenSingleRange(raw string) ([]SubExpr, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return nil, fmt.Errorf("empty Maven range")
}
if !startsRange(raw) {
if parseMavenVersion(Version(raw)) == nil {
return nil, fmt.Errorf("invalid Maven version %q", raw)
}
return nil, nil
}
if !endsRange(raw) {
return nil, fmt.Errorf("invalid Maven range %q", raw)
}
left := raw[0]
right := raw[len(raw)-1]
if !((left == '[' || left == '(') && (right == ']' || right == ')')) {
return nil, fmt.Errorf("invalid Maven range %q", raw)
}
body := strings.TrimSpace(raw[1 : len(raw)-1])
if !strings.Contains(body, ",") {
if left == '[' && right == ']' && body != "" {
version := parseMavenVersion(Version(body))
if version == nil {
return nil, fmt.Errorf("invalid Maven version %q", body)
}
return []SubExpr{
{Value: version, Operator: OpEq},
}, nil
}
return nil, fmt.Errorf("invalid Maven range %q", raw)
}
bounds := strings.SplitN(body, ",", 2)
lowerToken := strings.TrimSpace(bounds[0])
upperToken := strings.TrimSpace(bounds[1])
var lower, upper *MavenVersion
out := make([]SubExpr, 0, 2)
if lowerToken != "" {
parsed := parseMavenVersion(Version(lowerToken))
if parsed == nil {
return nil, fmt.Errorf("invalid Maven version %q", lowerToken)
}
lower = parsed.(*MavenVersion)
operator := OpGt
if left == '[' {
operator = OpGte
}
out = append(out, SubExpr{Value: lower, Operator: operator})
}
if upperToken != "" {
parsed := parseMavenVersion(Version(upperToken))
if parsed == nil {
return nil, fmt.Errorf("invalid Maven version %q", upperToken)
}
upper = parsed.(*MavenVersion)
operator := OpLt
if right == ']' {
operator = OpLte
}
out = append(out, SubExpr{Value: upper, Operator: operator})
}
if lower != nil && upper != nil {
comparison, comparable := lower.Compare(upper)
if !comparable {
return nil, fmt.Errorf("incomparable Maven bounds in %q", raw)
}
if comparison > 0 {
return nil, fmt.Errorf("descending Maven range %q", raw)
}
if comparison == 0 && (left == '(' || right == ')') {
return nil, fmt.Errorf("empty Maven range %q", raw)
}
}
return out, nil
}
func startsRange(raw string) bool {
return strings.HasPrefix(raw, "[") || strings.HasPrefix(raw, "(")
}
func endsRange(raw string) bool {
return strings.HasSuffix(raw, "]") || strings.HasSuffix(raw, ")")
}
package version
import (
"fmt"
"strings"
)
// parseQuiltConstraint parses quilt.mod.json dependency specifiers. Space and
// comma separated predicates form one conjunction, and || separates
// alternatives.
func parseQuiltConstraint(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
alternatives := strings.Split(raw, "||")
result := make(Expr, 0, len(alternatives))
for _, alternative := range alternatives {
alternative = strings.TrimSpace(alternative)
if alternative == "" {
return nil, fmt.Errorf("empty alternative in Quilt range %q", raw)
}
terms, err := parseQuiltClause(alternative)
if err != nil {
return nil, err
}
if len(terms) == 0 {
return nil, nil
}
result = append(result, terms)
}
if len(result) == 0 {
return nil, nil
}
return result, nil
}
func parseQuiltClause(raw string) ([]SubExpr, error) {
if strings.Contains(raw, " - ") {
return parseFabricHyphenRange(raw)
}
tokens := strings.FieldsFunc(
raw,
func(r rune) bool { return r == ' ' || r == '\t' || r == ',' },
)
terms := make([]SubExpr, 0, len(tokens))
for _, token := range tokens {
parsed, err := parseQuiltToken(token)
if err != nil {
return nil, err
}
terms = append(terms, parsed...)
}
return terms, nil
}
// parseQuiltToken parses one predicate. A bare version is the compatible range
// below the next major version; every other predicate follows Fabric.
func parseQuiltToken(raw string) ([]SubExpr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
if hasQuiltOperator(raw) || hasWildcardComponent(raw) {
return parseFabricToken(raw)
}
lower := parseFabricVersion(Version(raw))
semantic, ok := lower.(*SemverVersion)
if !ok {
return nil, fmt.Errorf("invalid Quilt version %q", raw)
}
upper := parseFabricVersion(
Version(fmt.Sprintf("%d.0.0-", semantic.Major()+1)),
)
if upper == nil {
return nil, fmt.Errorf("invalid Quilt version %q", raw)
}
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
}
func hasQuiltOperator(raw string) bool {
for _, prefix := range []string{
">=", "<=", "!=", "==", ">", "<", "=", "^", "~",
} {
if strings.HasPrefix(raw, prefix) {
return true
}
}
return false
}
package version
import (
"fmt"
"strconv"
"strings"
)
// parseFabricConstraint parses fabric.mod.json dependency predicates. Each
// entry of a VersionRange array is an alternative, which ParseConstraints
// merges into OR clauses.
//
// Reference: https://wiki.fabricmc.net/documentation:fabric_mod_json_spec
func parseFabricConstraint(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
parts := strings.Split(raw, "||")
result := make(Expr, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
return nil, fmt.Errorf("empty alternative in Fabric range %q", raw)
}
terms, err := parseFabricClause(part)
if err != nil {
return nil, err
}
if len(terms) == 0 {
return nil, nil
}
result = append(result, terms)
}
if len(result) == 0 {
return nil, nil
}
return result, nil
}
func parseFabricClause(raw string) ([]SubExpr, error) {
if strings.Contains(raw, " - ") {
return parseFabricHyphenRange(raw)
}
tokens := strings.Fields(raw)
terms := make([]SubExpr, 0, len(tokens))
for _, token := range tokens {
parsed, err := parseFabricToken(token)
if err != nil {
return nil, err
}
terms = append(terms, parsed...)
}
return terms, nil
}
func parseFabricHyphenRange(raw string) ([]SubExpr, error) {
tokens := strings.SplitN(raw, " - ", 2)
if len(tokens) != 2 {
return nil, fmt.Errorf("invalid Fabric range %q", raw)
}
lower := parseFabricVersion(Version(strings.TrimSpace(tokens[0])))
upper := parseFabricVersion(Version(strings.TrimSpace(tokens[1])))
if lower == nil || upper == nil {
return nil, fmt.Errorf("invalid Fabric range %q", raw)
}
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLte},
}, nil
}
func parseFabricToken(raw string) ([]SubExpr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
// Comma-separated comparators are an AND group.
if strings.Contains(raw, ",") {
parts := strings.Split(raw, ",")
terms := make([]SubExpr, 0, len(parts))
for _, part := range parts {
parsed, err := parseFabricToken(part)
if err != nil {
return nil, err
}
terms = append(terms, parsed...)
}
return terms, nil
}
operator := ""
versionToken := raw
for _, candidate := range []string{
">=", "<=", "!=", "==", ">", "<", "=", "^", "~",
} {
if after, ok := strings.CutPrefix(raw, candidate); ok {
operator = candidate
versionToken = strings.TrimSpace(after)
break
}
}
if versionToken == "" {
return nil, fmt.Errorf("invalid Fabric predicate %q", raw)
}
if hasWildcardComponent(versionToken) {
switch operator {
case "", "=", "==":
return parseFabricWildcardRange(versionToken)
default:
return nil, fmt.Errorf(
"Fabric wildcard predicate %q requires equality",
raw,
)
}
}
lower := parseFabricVersion(Version(versionToken))
if lower == nil {
return nil, fmt.Errorf("invalid Fabric version %q", versionToken)
}
if _, semantic := lower.(*SemverVersion); !semantic {
switch operator {
case ">", "<", "!=":
return nil, fmt.Errorf(
"Fabric predicate %q needs a semantic version",
raw,
)
default:
// Fabric reduces inclusive predicates on plain strings to equality.
return []SubExpr{
{Value: lower, Operator: OpEq},
}, nil
}
}
switch operator {
case "", "=", "==":
return []SubExpr{{Value: lower, Operator: OpEq}}, nil
case "!=":
return []SubExpr{{Value: lower, Operator: OpNeq}}, nil
case ">":
return []SubExpr{{Value: lower, Operator: OpGt}}, nil
case ">=":
return []SubExpr{{Value: lower, Operator: OpGte}}, nil
case "<":
return []SubExpr{{Value: lower, Operator: OpLt}}, nil
case "<=":
return []SubExpr{{Value: lower, Operator: OpLte}}, nil
case "^", "~":
upper := semverUpperBound(lower.(*SemverVersion), operator)
if upper == nil {
return nil, fmt.Errorf("invalid Fabric predicate %q", raw)
}
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
default:
return nil, fmt.Errorf("invalid Fabric predicate %q", raw)
}
}
// parseFabricWildcardRange expands a Fabric X-range. Fabric includes
// prereleases at the lower boundary and excludes them at the next component.
func parseFabricWildcardRange(raw string) ([]SubExpr, error) {
core := raw
if index := strings.IndexByte(core, '+'); index >= 0 {
core = core[:index]
}
if strings.Contains(core, "-") {
return nil, fmt.Errorf(
"Fabric wildcard %q cannot carry a prerelease",
raw,
)
}
parts := strings.Split(core, ".")
if len(parts) < 2 {
return nil, fmt.Errorf("invalid Fabric wildcard %q", raw)
}
wildcardIndex := -1
for index, part := range parts {
if isWildcardComponent(part) {
wildcardIndex = index
break
}
}
if wildcardIndex <= 0 {
return nil, fmt.Errorf("invalid Fabric wildcard %q", raw)
}
for _, part := range parts[wildcardIndex:] {
if !isWildcardComponent(part) {
return nil, fmt.Errorf("invalid Fabric wildcard %q", raw)
}
}
parts = parts[:wildcardIndex+1]
numbers := make([]uint64, 0, wildcardIndex)
for _, part := range parts[:wildcardIndex] {
number, err := strconv.ParseUint(part, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid Fabric wildcard %q", raw)
}
numbers = append(numbers, number)
}
switch wildcardIndex {
case 1: // a.x behaves as ^a-
lower := newSemverBoundary(DialectFabric, numbers[0])
upper := newSemverBoundary(DialectFabric, numbers[0]+1)
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
case 2: // a.b.x behaves as ~a.b-
lower := newSemverBoundary(
DialectFabric,
numbers[0],
numbers[1],
)
upper := newSemverBoundary(
DialectFabric,
numbers[0],
numbers[1]+1,
)
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
default: // a.b.c.x increments the last numeric component.
lower := newSemverBoundary(DialectFabric, numbers...)
incremented := append([]uint64(nil), numbers...)
incremented[len(incremented)-1]++
upper := newSemverBoundary(DialectFabric, incremented...)
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
}
}
func semverUpperBound(
lower *SemverVersion,
operator string,
) ResolvableVersion {
switch operator {
case "^":
return newSemverBoundary(
lower.Dialect(),
lower.Major()+1,
)
case "~":
return newSemverBoundary(
lower.Dialect(),
lower.Major(),
lower.Minor()+1,
)
default:
return nil
}
}
// parseMCDRConstraint parses metadata dependency requirements. Criterions are
// space-separated and combined with AND.
//
// References:
// - https://docs.mcdreforged.com/en/latest/plugin_dev/metadata.html
// - https://github.com/MCDReforged/MCDReforged/blob/master/mcdreforged/plugin/meta/version.py
func parseMCDRConstraint(raw string) (Expr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
tokens := strings.Fields(raw)
terms := make([]SubExpr, 0, len(tokens))
for _, token := range tokens {
parsed, err := parseMCDRCriterion(token)
if err != nil {
return nil, err
}
terms = append(terms, parsed...)
}
if len(terms) == 0 {
return nil, nil
}
return Expr{terms}, nil
}
func parseMCDRCriterion(raw string) ([]SubExpr, error) {
raw = strings.TrimSpace(raw)
if raw == "" || isWildcardExpression(raw) {
return nil, nil
}
operator := ""
versionToken := raw
for _, candidate := range []string{
">=", "<=", "==", ">", "<", "=", "^", "~",
} {
if after, ok := strings.CutPrefix(raw, candidate); ok {
operator = candidate
versionToken = strings.TrimSpace(after)
break
}
}
if versionToken == "" {
return nil, fmt.Errorf("invalid MCDR criterion %q", raw)
}
lower := parseMCDRVersion(versionToken, true)
if lower == nil {
return nil, fmt.Errorf("invalid MCDR version %q", versionToken)
}
semantic, ok := lower.(*SemverVersion)
if !ok {
return nil, fmt.Errorf("invalid MCDR version %q", versionToken)
}
switch operator {
case "", "=", "==":
return []SubExpr{{Value: lower, Operator: OpEq}}, nil
case ">":
return []SubExpr{{Value: lower, Operator: OpGt}}, nil
case ">=":
return []SubExpr{{Value: lower, Operator: OpGte}}, nil
case "<":
return []SubExpr{{Value: lower, Operator: OpLt}}, nil
case "<=":
return []SubExpr{{Value: lower, Operator: OpLte}}, nil
case "^":
if semantic.wildcardAt(0) {
return []SubExpr{{Operator: OpNever}}, nil
}
upper := newSemverBoundary(
DialectMCDR,
semantic.Major()+1,
)
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
case "~":
if semantic.wildcardAt(0) || semantic.wildcardAt(1) {
return []SubExpr{{Operator: OpNever}}, nil
}
upper := newSemverBoundary(
DialectMCDR,
semantic.Major(),
semantic.Minor()+1,
)
return []SubExpr{
{Value: lower, Operator: OpGte},
{Value: upper, Operator: OpLt},
}, nil
default:
return nil, fmt.Errorf("invalid MCDR criterion %q", raw)
}
}
func hasWildcardComponent(raw string) bool {
core := raw
if index := strings.IndexByte(core, '+'); index >= 0 {
core = core[:index]
}
if index := strings.IndexByte(core, '-'); index >= 0 {
core = core[:index]
}
for _, part := range strings.Split(core, ".") {
if isWildcardComponent(part) {
return true
}
}
return false
}
func isWildcardExpression(token string) bool {
token = strings.TrimSpace(token)
if token == "" {
return true
}
return isWildcardComponent(token)
}
func isWildcardComponent(token string) bool {
return token == "*" || token == "x" || token == "X"
}
package version
import (
"encoding/json/jsontext"
"strconv"
"strings"
)
// SemverVersion implements the semantic grammar shared by Fabric Loader and
// MCDR: one or more numeric components, an optional prerelease, and build
// metadata. Build metadata never participates in comparison.
type SemverVersion struct {
dialect Dialect
numbers []uint64
wildcards []bool
prerelease string
hasPrerelease bool
original string
}
type semverParseOptions struct {
dialect Dialect
allowWildcard bool
validateBuild bool
}
func parseSemverVersion(
raw string,
options semverParseOptions,
) *SemverVersion {
core := raw
if index := strings.IndexByte(core, '+'); index >= 0 {
build := core[index+1:]
if options.validateBuild && !validExtraIdentifiers(build, true) {
return nil
}
core = core[:index]
}
prerelease := ""
hasPrerelease := false
if index := strings.IndexByte(core, '-'); index >= 0 {
prerelease = core[index+1:]
hasPrerelease = true
core = core[:index]
if !validExtraIdentifiers(prerelease, false) {
return nil
}
}
if core == "" || strings.HasPrefix(core, ".") || strings.HasSuffix(core, ".") {
return nil
}
parts := strings.Split(core, ".")
numbers := make([]uint64, 0, len(parts))
var wildcards []bool
for _, part := range parts {
if isWildcardComponent(part) {
if !options.allowWildcard {
return nil
}
if wildcards == nil {
wildcards = make([]bool, len(parts))
}
wildcards[len(numbers)] = true
numbers = append(numbers, 0)
continue
}
number, err := strconv.ParseUint(part, 10, 64)
if err != nil {
return nil
}
numbers = append(numbers, number)
}
return &SemverVersion{
dialect: options.dialect,
numbers: numbers,
wildcards: wildcards,
prerelease: prerelease,
hasPrerelease: hasPrerelease,
original: raw,
}
}
func parseFabricVersion(raw Version) ResolvableVersion {
text := string(raw)
if text == "" {
return nil
}
if parsed := parseSemverVersion(
text,
semverParseOptions{dialect: DialectFabric},
); parsed != nil {
return parsed
}
return &StringVersion{
dialect: DialectFabric,
original: text,
}
}
func parseMCDRVersion(raw string, allowWildcard bool) ResolvableVersion {
parsed := parseSemverVersion(
raw,
semverParseOptions{
dialect: DialectMCDR,
allowWildcard: allowWildcard,
validateBuild: true,
},
)
if parsed == nil {
return nil
}
return parsed
}
// validExtraIdentifiers accepts prerelease or build identifiers allowed by the
// semantic grammars. An empty value is valid and denotes an empty prerelease.
func validExtraIdentifiers(value string, allowPlus bool) bool {
if value == "" {
return true
}
for identifier := range strings.SplitSeq(value, ".") {
if identifier == "" {
return false
}
for _, ch := range identifier {
if ch == '-' || (allowPlus && ch == '+') ||
(ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') {
continue
}
return false
}
}
return true
}
// newSemverBoundary creates a version directly below every prerelease and
// above every lower core version, matching Fabric's trailing '-' predicate
// boundary.
func newSemverBoundary(
dialect Dialect,
numbers ...uint64,
) *SemverVersion {
return &SemverVersion{
dialect: dialect,
numbers: numbers,
hasPrerelease: true,
original: joinSemverNumbers(numbers) + "-",
}
}
func joinSemverNumbers(numbers []uint64) string {
parts := make([]string, len(numbers))
for index, number := range numbers {
parts[index] = strconv.FormatUint(number, 10)
}
return strings.Join(parts, ".")
}
func (s *SemverVersion) component(index int) (uint64, bool) {
if s == nil || index < 0 {
return 0, false
}
if index < len(s.numbers) {
return s.numbers[index], s.wildcards != nil && s.wildcards[index]
}
if len(s.numbers) > 0 && s.wildcards != nil && s.wildcards[len(s.numbers)-1] {
return 0, true
}
return 0, false
}
func (s *SemverVersion) Major() uint64 {
value, _ := s.component(0)
return value
}
func (s *SemverVersion) Minor() uint64 {
value, _ := s.component(1)
return value
}
func (s *SemverVersion) Patch() uint64 {
value, _ := s.component(2)
return value
}
func (s *SemverVersion) wildcardAt(index int) bool {
_, wildcard := s.component(index)
return wildcard
}
func (s *SemverVersion) hasWildcard() bool {
if s == nil {
return false
}
for _, wildcard := range s.wildcards {
if wildcard {
return true
}
}
return false
}
func (s *SemverVersion) Prerelease() string {
if s == nil {
return ""
}
return s.prerelease
}
func (s *SemverVersion) Dialect() Dialect {
if s == nil {
return DialectUnknown
}
return s.dialect
}
func (s *SemverVersion) Compare(other ResolvableVersion) (int, bool) {
if s == nil || other == nil {
return 0, false
}
switch other := other.(type) {
case *SemverVersion:
if other.dialect != s.dialect {
return 0, false
}
count := max(len(s.numbers), len(other.numbers))
for index := range count {
left, leftWildcard := s.component(index)
right, rightWildcard := other.component(index)
if leftWildcard || rightWildcard {
continue
}
if comparison := compareUint(left, right); comparison != 0 {
return comparison, true
}
}
switch s.dialect {
case DialectFabric:
return compareFabricPrerelease(s, other), true
case DialectMCDR:
return compareMCDRPrerelease(s, other), true
default:
return 0, false
}
case *StringVersion:
if other.dialect != s.dialect {
return 0, false
}
return strings.Compare(s.String(), other.String()), true
default:
return 0, false
}
}
// compareFabricPrerelease follows Fabric Loader: a release outranks its
// prereleases, numeric identifiers rank below alphanumeric ones, numeric
// identifiers compare by length, and a longer identifier list outranks a
// shorter list sharing its prefix.
func compareFabricPrerelease(left, right *SemverVersion) int {
if !left.hasPrerelease && !right.hasPrerelease {
return 0
}
if !left.hasPrerelease {
return 1
}
if !right.hasPrerelease {
return -1
}
leftParts := prereleaseIdentifiers(left.prerelease)
rightParts := prereleaseIdentifiers(right.prerelease)
for index := range min(len(leftParts), len(rightParts)) {
if comparison := comparePrereleaseIdentifier(
leftParts[index],
rightParts[index],
); comparison != 0 {
return comparison
}
}
return compareInt(len(leftParts), len(rightParts))
}
// compareMCDRPrerelease follows MCDReforged's _ExtraElement ordering. The whole
// prerelease is one element split at its final dot into a body and an optional
// numeric suffix.
func compareMCDRPrerelease(left, right *SemverVersion) int {
switch {
case left.hasPrerelease && right.hasPrerelease:
return compareMCDRExtra(left.prerelease, right.prerelease)
case left.hasPrerelease:
if right.hasWildcard() {
return 0
}
return -1
case right.hasPrerelease:
if left.hasWildcard() {
return 0
}
return 1
default:
return 0
}
}
type mcdrExtra struct {
text string
body string
number int64
hasNum bool
}
func parseMCDRExtra(value string) mcdrExtra {
extra := mcdrExtra{text: value, body: value}
if index := strings.LastIndexByte(value, '.'); index >= 0 {
if number, err := strconv.ParseInt(value[index+1:], 10, 64); err == nil {
extra.body = value[:index]
extra.number = number
extra.hasNum = true
}
}
return extra
}
func (e mcdrExtra) String() string {
if e.hasNum {
return e.body + "." + strconv.FormatInt(e.number, 10)
}
return e.text
}
func (e mcdrExtra) less(other mcdrExtra) bool {
if !e.hasNum || !other.hasNum {
return e.String() < other.String()
}
if e.body != other.body {
return e.body < other.body
}
return e.number < other.number
}
func compareMCDRExtra(left, right string) int {
leftExtra := parseMCDRExtra(left)
rightExtra := parseMCDRExtra(right)
if leftExtra.less(rightExtra) {
return -1
}
if rightExtra.less(leftExtra) {
return 1
}
return 0
}
func prereleaseIdentifiers(prerelease string) []string {
if prerelease == "" {
return nil
}
return strings.Split(prerelease, ".")
}
func comparePrereleaseIdentifier(left, right string) int {
leftNumeric := isUnsignedInteger(left)
rightNumeric := isUnsignedInteger(right)
switch {
case leftNumeric && rightNumeric:
if comparison := compareInt(len(left), len(right)); comparison != 0 {
return comparison
}
return strings.Compare(left, right)
case leftNumeric:
return -1
case rightNumeric:
return 1
default:
return strings.Compare(left, right)
}
}
func isUnsignedInteger(value string) bool {
if value == "0" {
return true
}
if value == "" || value[0] == '0' {
return false
}
for _, ch := range value {
if ch < '0' || ch > '9' {
return false
}
}
return true
}
func compareUint(left, right uint64) int {
switch {
case left < right:
return -1
case left > right:
return 1
default:
return 0
}
}
func compareInt(left, right int) int {
if left < right {
return -1
}
if left > right {
return 1
}
return 0
}
func (s *SemverVersion) Validate() bool {
return s != nil && len(s.numbers) > 0
}
func (s *SemverVersion) String() string {
if s == nil {
return ""
}
return s.original
}
// MarshalJSONTo renders the version in its original string form. The parsed
// components are unexported, which encoding/json/v2 refuses to marshal.
func (s *SemverVersion) MarshalJSONTo(enc *jsontext.Encoder) error {
return enc.WriteToken(jsontext.String(s.String()))
}
package version
import (
"encoding/json/jsontext"
"strings"
)
// StringVersion is a version outside the semantic grammar. Fabric Loader
// compares it as a plain string; the opaque dialect uses it for identifiers.
type StringVersion struct {
dialect Dialect
original string
}
func (v *StringVersion) Dialect() Dialect {
if v == nil {
return DialectUnknown
}
return v.dialect
}
func (v *StringVersion) Compare(other ResolvableVersion) (int, bool) {
if v == nil || other == nil || other.Dialect() != v.dialect {
return 0, false
}
switch other := other.(type) {
case *StringVersion:
if v.dialect == DialectOpaque {
if v.original != other.original {
return 0, false
}
return 0, true
}
return strings.Compare(v.original, other.original), true
case *SemverVersion:
return strings.Compare(v.original, other.String()), true
default:
return 0, false
}
}
func (v *StringVersion) Validate() bool {
return v != nil && v.original != ""
}
func (v *StringVersion) String() string {
if v == nil {
return ""
}
return v.original
}
// MarshalJSONTo renders the version verbatim for the same reason as
// SemverVersion.
func (v *StringVersion) MarshalJSONTo(enc *jsontext.Encoder) error {
return enc.WriteToken(jsontext.String(v.String()))
}
// Package version owns version vocabulary, parsing, ordering, and constraint
// matching for every package dialect that lucy resolves.
package version
// Version is a package version. It may hold a selector during resolution or
// an exact version after resolution.
type Version string
func (v Version) String() string {
switch v {
case Any, "":
return "any"
case None:
return "none"
case Unknown:
return "unknown"
case Beta:
return "beta"
case Stable:
return "stable"
}
return string(v)
}
func (v Version) CanInfer() bool {
switch v {
case Any, Beta, Stable:
return true
}
return false
}
func (v Version) IsInvalid() bool {
switch v {
case None, Unknown:
return true
}
return false
}
var (
Any Version = "any"
Beta Version = "beta"
Stable Version = "stable"
None Version = "none"
Unknown Version = "unknown"
)
// Dialect identifies a version grammar together with the ordering and
// constraint semantics that grammar defines.
type Dialect string
const (
DialectUnknown Dialect = ""
// DialectFabric is the version grammar of fabric.mod.json metadata.
// Reference: https://wiki.fabricmc.net/documentation:fabric_mod_json_spec
DialectFabric Dialect = "fabric"
// DialectQuilt is the constraint grammar of quilt.mod.json metadata. Its
// concrete versions are Fabric version values.
// Reference: https://github.com/QuiltMC/rfcs/blob/main/specification/0002-quilt.mod.json.md
DialectQuilt Dialect = "quilt"
// DialectMCDR is the version grammar of mcdreforged.plugin.json metadata.
// Reference: https://docs.mcdreforged.com/en/latest/plugin_dev/metadata.html
DialectMCDR Dialect = "mcdr"
// DialectMaven is Maven version ordering, used by Forge and NeoForge
// mods.toml metadata. Reference:
// https://maven.apache.org/enforcer/enforcer-rules/versionRanges.html
DialectMaven Dialect = "maven"
// DialectMinecraft is the Minecraft release and snapshot grammar.
// Reference: https://zh.minecraft.wiki/w/%E7%89%88%E6%9C%AC%E6%A0%BC%E5%BC%8F
DialectMinecraft Dialect = "minecraft"
// DialectOpaque treats versions as unordered identifiers. It serves
// descriptors whose grammar defines no version ranges, such as plugin.yml.
DialectOpaque Dialect = "opaque"
)
// Valid reports whether d is a dialect defined by this package.
func (d Dialect) Valid() bool {
switch d {
case DialectFabric,
DialectQuilt,
DialectMCDR,
DialectMaven,
DialectMinecraft,
DialectOpaque:
return true
default:
return false
}
}
// ResolvableVersion is a parsed version that belongs to exactly one dialect.
//
// A nil ResolvableVersion represents an invalid or unparseable version.
// Implementations reject comparisons against a different dialect.
type ResolvableVersion interface {
Compare(v2 ResolvableVersion) (int, bool)
Validate() bool
Dialect() Dialect
}
package discovery
import (
"bufio"
"encoding/json/v2"
"path/filepath"
"regexp"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
versionpkg "github.com/mclucy/lucy/version"
)
var arclightJarNamePattern = regexp.MustCompile(
`^arclight-(?:forge|neoforge|fabric)-(\d+\.\d+(?:\.\d+)?)(?:[-.].*)?\.jar$`,
)
// discoverArclight recognizes Arclight hybrid server jars. Loader evidence is
// kept as a concrete runtime component; the jar itself is the sole entry
// point of the installation.
func discoverArclight(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
installation, err := inspectArclightInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
if installation != nil {
installations = append(installations, *installation)
}
}
return installations, findings
}
// Sources:
// - https://arclight.izzel.io/
// - https://deepwiki.com/IzzelAliz/Arclight/1-overview
func inspectArclightInstallation(
s *scan,
primary *artifact,
) (*Installation, error) {
manifest, ok, err := readProductEntry(s, primary, bukkitManifestPath)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
manifestSignals := parseArclightManifest(manifest)
if !manifestSignals.valid() {
return nil, nil
}
launchProps, hasLaunchProps, err := readProductEntry(
s,
primary,
"arclight-server-launch.properties",
)
if err != nil {
return nil, err
}
hasCommonJar, err := productEntryExists(s, primary, "common.jar")
if err != nil {
return nil, err
}
if !hasLaunchProps && !hasCommonJar {
return nil, nil
}
gameVersion := manifestSignals.gameVersion
if !hasConcreteVersion(gameVersion) {
gameVersion = parseArclightGameVersionFromPath(primary.Path())
}
components := []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemMinecraft,
Name: input.ToProjectName("minecraft"),
Version: gameVersion,
},
}
if loader, ok := arclightLoaderEcosystem(launchProps); ok {
component := arclightLoaderComponent(loader)
installerJSON, found, err := readProductEntry(
s,
primary,
"META-INF/installer.json",
)
if err != nil {
return nil, err
}
if found {
if loaderVersion, ok := parseArclightLoaderVersion(
installerJSON,
loader,
); ok {
component.Version = loaderVersion
}
}
components = append(components, component)
}
identity := Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemUnspecified,
Name: input.ToProjectName("arclight"),
Version: observedVersion(manifestSignals.implementationVersion),
},
Components: components,
}
installation := NewInstallation(identity, primary.Path())
return &installation, nil
}
type arclightManifestSignals struct {
mainClass string
implementation string
implementationVersion versionpkg.Version
gameVersion versionpkg.Version
}
func (s arclightManifestSignals) valid() bool {
return s.mainClass == "io.izzel.arclight.server.Launcher" &&
s.implementation == "Arclight"
}
func parseArclightManifest(data []byte) arclightManifestSignals {
var signals arclightManifestSignals
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "Main-Class: "):
signals.mainClass = strings.TrimSpace(
strings.TrimPrefix(
line,
"Main-Class: ",
),
)
case strings.HasPrefix(line, "Implementation-Title: "):
signals.implementation = strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Title: ",
),
)
case strings.HasPrefix(line, "Implementation-Version: "):
version := strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Version: ",
),
)
signals.implementationVersion = versionpkg.Version(version)
if parsedGameVersion := parseArclightGameVersionFromImplementation(version); hasConcreteVersion(parsedGameVersion) {
signals.gameVersion = parsedGameVersion
}
}
}
return signals
}
func parseArclightGameVersionFromImplementation(version string) versionpkg.Version {
if !strings.HasPrefix(version, "arclight-") {
return versionpkg.Unknown
}
trimmed := strings.TrimPrefix(version, "arclight-")
parts := strings.Split(trimmed, "-")
if len(parts) == 0 || !isMinecraftReleaseVersion(parts[0]) {
return versionpkg.Unknown
}
return versionpkg.Version(parts[0])
}
func parseArclightGameVersionFromPath(filePath string) versionpkg.Version {
match := arclightJarNamePattern.FindStringSubmatch(filepath.Base(filePath))
if match == nil {
return versionpkg.Unknown
}
return versionpkg.Version(match[1])
}
func arclightLoaderEcosystem(launchProps []byte) (catalog.Ecosystem, bool) {
scanner := bufio.NewScanner(strings.NewReader(string(launchProps)))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok || strings.TrimSpace(key) != "launch.mainClass" {
continue
}
switch strings.TrimSpace(value) {
case "io.izzel.arclight.boot.fabric.application.Main_Fabric":
return catalog.EcosystemFabric, true
case "io.izzel.arclight.boot.neoforge.application.Main_Neoforge":
return catalog.EcosystemNeoForge, true
case "io.izzel.arclight.boot.forge.application.Main_Forge":
return catalog.EcosystemForge, true
default:
return catalog.EcosystemUnspecified, false
}
}
return catalog.EcosystemUnspecified, false
}
type arclightInstallerMetadata struct {
Installer struct {
Forge string `json:"forge"`
NeoForge string `json:"neoforge"`
FabricLoader string `json:"fabricLoader"`
} `json:"installer"`
}
func arclightLoaderComponent(
loader catalog.Ecosystem,
) catalog.VersionedRef {
var name catalog.Name
switch loader {
case catalog.EcosystemFabric:
name = "fabric-loader"
case catalog.EcosystemNeoForge:
name = "neoforge"
case catalog.EcosystemForge:
name = "forge"
}
return catalog.VersionedRef{
Ecosystem: loader,
Name: name,
Version: versionpkg.Unknown,
}
}
func parseArclightLoaderVersion(
data []byte,
loader catalog.Ecosystem,
) (versionpkg.Version, bool) {
var metadata arclightInstallerMetadata
if err := json.Unmarshal(data, &metadata); err != nil {
return versionpkg.Unknown, false
}
var version string
switch loader {
case catalog.EcosystemFabric:
version = metadata.Installer.FabricLoader
case catalog.EcosystemNeoForge:
version = metadata.Installer.NeoForge
case catalog.EcosystemForge:
version = metadata.Installer.Forge
}
loaderVersion := versionpkg.Version(strings.TrimSpace(version))
if !hasConcreteVersion(loaderVersion) {
return versionpkg.Unknown, false
}
return loaderVersion, true
}
package discovery
import (
"bufio"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
"github.com/mclucy/lucy/version"
)
const (
bukkitManifestPath = "META-INF/MANIFEST.MF"
bukkitManifestMainClass = "org.bukkit.craftbukkit.Main"
bukkitImplementationCraftBukkit = "CraftBukkit"
bukkitPaperClassPrefix = "io/papermc/paper/"
bukkitLegacyPaperClassPrefix = "com/destroystokyo/paper/"
)
var bukkitVersionPrefixPattern = regexp.MustCompile(`^(\d+\.\d+(?:\.\d+)?)`)
type bukkitManifestSignals struct {
mainClass string
specificationTitle string
specificationVendor string
implementationTitle string
implementationVendor string
implementationVer string
}
// discoverBukkit recognizes CraftBukkit-derived server layouts. A single
// confirmed artifact is one installation; contradictory paper-lineage claims
// are returned as separate installations so the engine can report typed
// ambiguity instead of inventing a runtime.
func discoverBukkit(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
detected, err := inspectBukkitInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
installations = append(installations, detected...)
}
return installations, findings
}
func inspectBukkitInstallation(
s *scan,
primary *artifact,
) ([]Installation, error) {
var judgment paperJudgment
manifest, ok, err := readBukkitManifest(s, primary)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
signals := parseBukkitManifest(manifest)
metaMainClass, err := readBukkitSidecarString(
s,
primary,
paperMetaMainClassPath,
)
if err != nil {
return nil, err
}
reaperPatchProperties, err := readBukkitPatchProperties(s, primary)
if err != nil {
return nil, err
}
// Stage 1: Bukkit Confirmation
// CraftBukkit-derived servers consistently launch through
// org.bukkit.craftbukkit.Main, while Implementation-Title: CraftBukkit is the
// fallback family marker seen in repackaged jars that keep the canonical
// implementation title. Extracted modern Paper fixtures keep the decisive
// Bukkit entrypoint in META-INF/main-class, while strict launcher-heavy Reaper
// and Youer fixtures only expose definitive Paper-fork proof via patch or
// manifest identity. Without one of these strict signals, we should not claim
// a Bukkit-lineage server executable.
judgment.bukkitConfirmed = signals.mainClass == bukkitManifestMainClass ||
strings.EqualFold(
signals.implementationTitle,
bukkitImplementationCraftBukkit,
) ||
metaMainClass == bukkitManifestMainClass ||
hasStrictReaperBukkitConfirmation(reaperPatchProperties) ||
hasStrictYouerBukkitConfirmation(signals)
if !judgment.bukkitConfirmed {
return nil, nil
}
// Stage 2: Observation Extraction
judgment.observations, err = extractPaperObservations(s, primary)
if err != nil {
return nil, err
}
// Stage 3: Family Reasoning
reasonPaperFamily(&judgment)
// Stage 4: Lineage Attribution
attributePaperLineage(&judgment)
// Stage 5: Contradiction Resolution
resolvePaperContradictions(&judgment)
// Stage 6: Runtime Projection
gameVersion := judgment.observations.gameVersion
if !hasConcreteVersion(gameVersion) {
gameVersion = version.Unknown
}
return projectPaperInstallations(primary.Path(), gameVersion, judgment), nil
}
func reasonPaperFamily(judgment *paperJudgment) {
if judgment == nil {
return
}
switch {
case judgment.observations.hasPaperClasses:
judgment.familyResult = familyStrong
case hasModernPaperclipMetadataCluster(judgment.observations):
judgment.familyResult = familyStrong
case hasConcreteVersion(judgment.observations.versionJSONID):
judgment.familyResult = familyWeak
case len(judgment.observations.patchProperties) > 0 || judgment.observations.hasPaperMCPatch:
judgment.familyResult = familyWeak
case judgment.observations.hasPaperclipNamespace || judgment.observations.hasLegacyPaperclipNamespace:
judgment.familyResult = familyWeak
default:
judgment.familyResult = familyMiss
}
}
func hasModernPaperclipMetadataCluster(obs paperObservations) bool {
return strings.TrimSpace(obs.downloadContext) != "" &&
len(obs.librariesListEntries) > 0 &&
strings.TrimSpace(obs.metaMainClass) != ""
}
func attributePaperLineage(judgment *paperJudgment) {
if judgment == nil {
return
}
lineages := inferPaperObservationLineages(judgment.observations)
judgment.lineages = lineages
switch {
case len(lineages) > 1:
judgment.lineageResult = lineageContradiction
judgment.lineageName = strings.Join(lineages, ",")
case len(lineages) == 1 && lineages[0] == "paper":
judgment.lineageResult = lineagePaper
judgment.lineageName = "paper"
case len(lineages) == 1:
judgment.lineageResult = lineageFork
judgment.lineageName = lineages[0]
default:
judgment.lineageResult = lineageUnknown
}
}
func inferPaperObservationLineages(obs paperObservations) []string {
lineages := make([]string, 0, 8)
seen := make(map[string]struct{}, 8)
add := func(name string) {
normalized := normalizePaperLineageName(name)
if normalized == "" {
return
}
if _, ok := seen[normalized]; ok {
return
}
seen[normalized] = struct{}{}
lineages = append(lineages, normalized)
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_paper/paper/META-INF/libraries.list
if observationLinesContain(
obs.librariesListEntries,
paperLibraryPaperToken,
) || observationLinesContain(
obs.librariesListEntries,
paperLibraryMojangAPIToken,
) {
add("paper")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_folia/folia/META-INF/libraries.list
if observationLinesContain(
obs.librariesListEntries,
paperLibraryFoliaToken,
) {
add("folia")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_divine/divine/META-INF/libraries.list
if observationLinesContain(
obs.librariesListEntries,
paperLibraryDivineToken,
) {
add("divine")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_purpur/purpur/META-INF/libraries.list
if observationLinesContain(
obs.librariesListEntries,
paperLibraryPurpurToken,
) {
add("purpur")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_leaf/leaf/META-INF/libraries.list and cn/dreeam/leaper/*
if observationLinesContain(
obs.librariesListEntries,
paperLibraryLeafToken,
) || obs.hasLeaperNamespace {
add("leaf")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_leaves/leaves/META-INF/libraries.list, META-INF/build-info, META-INF/leavesclip-version
if observationLinesContain(
obs.librariesListEntries,
paperLibraryLeavesToken,
) || obs.hasLeavesclipNamespace || obs.leavesclipVersion != "" || strings.HasPrefix(
obs.buildInfo,
"Leaves\t",
) {
add("leaves")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_reaper/reaper/patch.properties
if hasStrictReaperObservationLineage(obs) {
add("reaper")
}
// Fixture citation: workspace/discovery/testdata/paper_family/test_youer/youer/META-INF/MANIFEST.MF
if obs.hasYouerNamespace ||
strings.EqualFold(
obs.manifestSpecificationTitle,
paperManifestYouerToken,
) ||
strings.EqualFold(
obs.manifestImplementationTitle,
paperManifestYouerToken,
) ||
strings.Contains(
strings.ToLower(obs.manifestMainClass),
paperMainClassYouerToken,
) {
add("youer")
}
slices.Sort(lineages)
return lineages
}
func readBukkitManifest(s *scan, primary *artifact) ([]byte, bool, error) {
return readProductEntry(s, primary, bukkitManifestPath)
}
func readBukkitSidecarString(
s *scan,
primary *artifact,
entryPath string,
) (string, error) {
data, ok, err := readProductEntry(s, primary, entryPath)
if err != nil || !ok {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
func readBukkitPatchProperties(
s *scan,
primary *artifact,
) (map[string]string, error) {
data, ok, err := readProductEntry(s, primary, paperPatchPropertiesPath)
if err != nil || !ok {
return nil, err
}
return parsePaperPatchProperties(data), nil
}
func hasStrictReaperBukkitConfirmation(properties map[string]string) bool {
return strings.Contains(properties["patch"], paperPatchReaperToken)
}
func hasStrictYouerBukkitConfirmation(signals bukkitManifestSignals) bool {
return strings.EqualFold(
signals.specificationTitle,
paperManifestYouerToken,
) ||
strings.EqualFold(signals.implementationTitle, paperManifestYouerToken) ||
strings.Contains(
strings.ToLower(signals.mainClass),
paperMainClassYouerToken,
)
}
func hasStrictReaperObservationLineage(obs paperObservations) bool {
return strings.Contains(obs.patchProperties["patch"], paperPatchReaperToken)
}
func observationLinesContain(lines []string, want string) bool {
for _, line := range lines {
if strings.Contains(line, want) {
return true
}
}
return false
}
func resolvePaperContradictions(judgment *paperJudgment) {
if judgment == nil {
return
}
if judgment.lineageResult == lineageContradiction {
judgment.familyResult = familyContradiction
}
judgment.contradicted = judgment.familyResult == familyContradiction
}
// projectPaperInstallations emits one installation per attributable lineage.
// Contradictory claims are never merged into one fabricated identity; the
// engine reports the ambiguity and strict selection refuses it.
func projectPaperInstallations(
filePath string,
gameVersion version.Version,
judgment paperJudgment,
) []Installation {
if !judgment.bukkitConfirmed {
return nil
}
components := []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemMinecraft,
Name: input.ToProjectName("minecraft"),
Version: gameVersion,
},
}
if judgment.contradicted {
installations := make([]Installation, 0, len(judgment.lineages))
for _, lineage := range judgment.lineages {
name := normalizePaperLineageName(lineage)
if name == "" {
continue
}
installations = append(
installations,
newPaperInstallation(name, components, filePath),
)
}
if len(installations) > 0 {
return installations
}
}
lineage := "bukkit"
switch judgment.lineageResult {
case lineagePaper:
lineage = "paper"
case lineageFork:
if detected := normalizePaperLineageName(judgment.lineageName); detected != "" {
lineage = detected
}
case lineageUnknown, lineageContradiction:
// No attributable lineage retains the confirmed bukkit baseline.
}
return []Installation{newPaperInstallation(lineage, components, filePath)}
}
func newPaperInstallation(
lineage string,
components []catalog.VersionedRef,
filePath string,
) Installation {
installation := NewInstallation(
Identity{
Primary: catalog.VersionedRef{
Ecosystem: paperLineageEcosystem(lineage),
Name: input.ToProjectName(lineage),
Version: paperBuildFromFilename(filePath, lineage, components),
},
Components: cloneComponents(components),
},
filePath,
)
installation.SetCore(filePath)
return installation
}
// paperBuildFromFilename recovers the build number that the paperclip jar
// itself does not carry. The convention is <lineage>-<minecraft>-<build>.jar;
// a renamed jar falls back to the published-build digest in init.
func paperBuildFromFilename(
filePath string,
lineage string,
components []catalog.VersionedRef,
) version.Version {
gameVersion := version.Unknown
for _, component := range components {
if component.Ecosystem == catalog.EcosystemMinecraft {
gameVersion = component.Version
break
}
}
if gameVersion == version.Unknown {
return version.Unknown
}
pattern := regexp.MustCompile(
`^` + regexp.QuoteMeta(lineage) +
`-(\d+(?:\.\d+)*)-(\d+)(?:[-+].*)?\.jar$`,
)
match := pattern.FindStringSubmatch(filepath.Base(filePath))
if len(match) != 3 || match[1] != gameVersion.String() {
return version.Unknown
}
return version.Version(match[2])
}
func paperLineageEcosystem(lineage string) catalog.Ecosystem {
switch lineage {
case "bukkit":
return catalog.EcosystemBukkit
case "youer":
// Youer is a NeoForge hybrid; its primary product is not a Paper
// ecosystem, and served-package policy handles it by name.
return catalog.EcosystemUnspecified
default:
return catalog.EcosystemPaper
}
}
func cloneComponents(
components []catalog.VersionedRef,
) []catalog.VersionedRef {
if len(components) == 0 {
return nil
}
return append([]catalog.VersionedRef(nil), components...)
}
// observedVersion keeps an unparseable or absent artifact version observable
// as version.Unknown instead of producing an invalid identity.
func observedVersion(value version.Version) version.Version {
if !hasConcreteVersion(value) {
return version.Unknown
}
return value
}
func normalizePaperLineageName(name string) string {
normalized := strings.ToLower(strings.TrimSpace(name))
if normalized == "" {
return ""
}
switch normalized {
case "craftbukkit", "bukkit":
return ""
default:
return normalized
}
}
func parseBukkitManifest(data []byte) bukkitManifestSignals {
var signals bukkitManifestSignals
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "Main-Class: "):
signals.mainClass = strings.TrimSpace(
strings.TrimPrefix(
line,
"Main-Class: ",
),
)
case strings.HasPrefix(line, "Implementation-Title: "):
signals.implementationTitle = strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Title: ",
),
)
case strings.HasPrefix(line, "Specification-Title: "):
signals.specificationTitle = strings.TrimSpace(
strings.TrimPrefix(
line,
"Specification-Title: ",
),
)
case strings.HasPrefix(line, "Specification-Vendor: "):
signals.specificationVendor = strings.TrimSpace(
strings.TrimPrefix(
line,
"Specification-Vendor: ",
),
)
case strings.HasPrefix(line, "Implementation-Version: "):
signals.implementationVer = strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Version: ",
),
)
case strings.HasPrefix(line, "Implementation-Vendor: "):
signals.implementationVendor = strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Vendor: ",
),
)
}
}
return signals
}
func parseBukkitGameVersion(implementationVersion string) version.Version {
match := bukkitVersionPrefixPattern.FindStringSubmatch(strings.TrimSpace(implementationVersion))
if len(match) < 2 || !isMinecraftReleaseVersion(match[1]) {
return version.Unknown
}
return version.Version(match[1])
}
// productCandidate reports whether a root artifact can carry an executable
// server layout. Directory layouts are only considered when they expose the
// manifest every recognized server product ships.
func productCandidate(s *scan, primary *artifact) bool {
if primary == nil {
return false
}
if !primary.IsDirectory() {
return strings.HasSuffix(
strings.ToLower(primary.Path()),
".jar",
)
}
manifest, ok := s.File(
filepath.Join(
primary.Path(),
filepath.FromSlash(bukkitManifestPath),
),
)
return ok && !manifest.IsDirectory()
}
// readProductEntry reads one entry from a jar artifact or from an unpacked
// directory layout artifact. Directory reads stay root-confined through the
// scan; archives use the scan-owned ReaderAt handle.
func readProductEntry(
s *scan,
primary *artifact,
entryPath string,
) ([]byte, bool, error) {
if primary == nil {
return nil, false, nil
}
if primary.IsDirectory() {
nested, ok := s.File(
filepath.Join(
primary.Path(),
filepath.FromSlash(entryPath),
),
)
if !ok || nested.IsDirectory() {
return nil, false, nil
}
data, err := nested.Read()
if err != nil {
return nil, false, err
}
return data, true, nil
}
archive, err := primary.Archive()
if err != nil {
return nil, false, err
}
if archive == nil {
return nil, false, nil
}
return readArchiveEntry(archive, entryPath)
}
// productEntryExists reports whether one entry is present without loading its
// bytes. Large payload jars are never read just to test for a marker.
func productEntryExists(
s *scan,
primary *artifact,
entryPath string,
) (bool, error) {
if primary == nil {
return false, nil
}
if primary.IsDirectory() {
nested, ok := s.File(
filepath.Join(
primary.Path(),
filepath.FromSlash(entryPath),
),
)
return ok && !nested.IsDirectory(), nil
}
archive, err := primary.Archive()
if err != nil {
return false, err
}
if archive == nil {
return false, nil
}
for _, file := range archive.File {
if file.Name == entryPath {
return true, nil
}
}
return false, nil
}
package discovery
import (
"bufio"
"regexp"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
versionpkg "github.com/mclucy/lucy/version"
)
var catServerVersionPattern = regexp.MustCompile(
`^(?:git-CatServer-)?(\d+\.\d+(?:\.\d+)?)-`,
)
// discoverCatServer recognizes CatServer hybrid jars and keeps the Minecraft
// version the manifest declares.
func discoverCatServer(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
installation, err := inspectCatServerInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
if installation != nil {
installations = append(installations, *installation)
}
}
return installations, findings
}
func inspectCatServerInstallation(
s *scan,
primary *artifact,
) (*Installation, error) {
manifest, ok, err := readProductEntry(s, primary, bukkitManifestPath)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
signals := parseCatServerManifest(manifest)
if !signals.valid() {
return nil, nil
}
identity := Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemUnspecified,
Name: input.ToProjectName("catserver"),
Version: signals.version,
},
Components: []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemMinecraft,
Name: input.ToProjectName("minecraft"),
Version: signals.gameVersion,
},
},
}
installation := NewInstallation(identity, primary.Path())
return &installation, nil
}
type catServerManifestSignals struct {
mainClass string
title string
version versionpkg.Version
gameVersion versionpkg.Version
}
func (s catServerManifestSignals) valid() bool {
return s.title == "CatServer" &&
s.mainClass == "catserver.server.CatServerLaunch" &&
hasConcreteVersion(s.gameVersion)
}
func parseCatServerManifest(data []byte) catServerManifestSignals {
var signals catServerManifestSignals
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "Main-Class: "):
signals.mainClass = strings.TrimSpace(
strings.TrimPrefix(
line,
"Main-Class: ",
),
)
case strings.HasPrefix(line, "Implementation-Title: "):
signals.title = strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Title: ",
),
)
case strings.HasPrefix(line, "Implementation-Version: "):
version := strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Version: ",
),
)
signals.version = versionpkg.Version(version)
signals.gameVersion = parseCatServerGameVersion(version)
}
}
return signals
}
func parseCatServerGameVersion(version string) versionpkg.Version {
match := catServerVersionPattern.FindStringSubmatch(version)
if match == nil {
return versionpkg.Unknown
}
return versionpkg.Version(match[1])
}
package discovery
import (
"path/filepath"
"slices"
"sort"
"strings"
"github.com/mclucy/lucy/server"
)
// Discover scans one server directory through the static directory recognizer
// registry and reconciles every recognizer output into a single observation.
// It does not read workspace declarations and does not choose a runtime; call
// Select afterwards.
func Discover(serverDir string) (result Result) {
result.Selection = Selection{State: SelectionNone}
scan, err := newScan(serverDir)
if err != nil {
result.Diagnostics = append(result.Diagnostics, Finding{
Kind: FindingUnreadableFile,
Path: serverDir,
Cause: err,
})
return result
}
defer func() {
if closeErr := scan.Close(); closeErr != nil {
result.Diagnostics = append(result.Diagnostics, Finding{
Kind: FindingUnreadableFile,
Path: scan.root,
Cause: closeErr,
})
}
}()
raw := make([]Installation, 0, len(recognizerRegistry))
for _, entry := range recognizerRegistry {
installations, findings := entry.discover(scan)
raw = append(raw, installations...)
result.Diagnostics = append(result.Diagnostics, findings...)
}
installations, findings := reconcileInstallations(raw, scan)
result.Installations = installations
result.Diagnostics = append(result.Diagnostics, findings...)
return result
}
func reconcileInstallations(
raw []Installation,
scan *scan,
) ([]Installation, []Finding) {
var findings []Finding
installations := make([]Installation, 0, len(raw))
for index := range raw {
installation := raw[index]
if len(installation.Files) == 0 {
continue
}
if err := installation.Identity.Normalize(); err != nil {
path := firstEntryPointPath(&installation)
if path == "" {
path = firstFilePath(installation)
}
findings = append(findings, Finding{
Kind: FindingInvalidIdentity,
Path: path,
Identity: installation.Identity,
Cause: err,
})
}
installations = append(installations, installation)
}
installations = shadowVanillaClaims(installations)
installations = mergeIdenticalInstallations(installations)
installations = absorbVanillaPayloads(installations)
installations = dropEmptyInstallations(installations)
findings = append(findings, conflictingClaims(installations)...)
findings = append(findings, unknownArtifacts(installations, scan)...)
sort.Slice(installations, func(i, j int) bool {
return compareInstallations(installations[i], installations[j]) < 0
})
return installations, findings
}
// shadowVanillaClaims drops a generic vanilla entry-point claim when a
// specific installation claims the same artifact. Other vanilla entry points
// on the same installation remain observable.
func shadowVanillaClaims(installations []Installation) []Installation {
claims := make(map[string][]int, len(installations))
for index := range installations {
if !installations[index].Identity.IsValid() {
continue
}
for file := range installations[index].EntryPoints() {
claims[file.Path] = append(claims[file.Path], index)
}
}
shadowed := make(map[int]map[string]bool)
for path, indexes := range claims {
specific := false
for _, index := range indexes {
identity := installations[index].Identity
if !isVanillaIdentity(identity) && identity.IsValid() {
specific = true
break
}
}
if !specific {
continue
}
for _, index := range indexes {
if !isVanillaIdentity(installations[index].Identity) {
continue
}
if shadowed[index] == nil {
shadowed[index] = make(map[string]bool)
}
shadowed[index][path] = true
}
}
out := installations[:0]
for index := range installations {
for path := range shadowed[index] {
installations[index].removeFile(path)
}
if len(installations[index].Files) == 0 {
continue
}
out = append(out, installations[index])
}
clear(installations[len(out):])
return out
}
// mergeIdenticalInstallations unions members and entry points of equal
// concrete identities. Unknown or contradictory identities never merge.
func mergeIdenticalInstallations(installations []Installation) []Installation {
out := make([]Installation, 0, len(installations))
indexes := make(map[string]int, len(installations))
for index := range installations {
candidate := installations[index]
if candidate.Identity.IsValid() && candidate.Identity.IsConcrete() {
key := identityKey(candidate.Identity)
if existing, ok := indexes[key]; ok &&
out[existing].Identity.Equal(candidate.Identity) {
if out[existing].CorePath == "" {
out[existing].CorePath = candidate.CorePath
}
for _, file := range candidate.Files {
out[existing].addFile(file)
}
continue
}
indexes[key] = len(out)
}
out = append(out, candidate)
}
return out
}
// absorbVanillaPayloads treats a vanilla entry point referenced as a member by
// a matching-Minecraft non-vanilla installation as payload, not as a second
// standalone installation.
func absorbVanillaPayloads(installations []Installation) []Installation {
type reference struct {
installation int
path string
}
drop := make([]bool, len(installations))
for vanillaIndex := range installations {
vanilla := &installations[vanillaIndex]
if !vanilla.Identity.IsValid() || !isVanillaIdentity(vanilla.Identity) {
continue
}
minecraft := vanilla.Identity.MinecraftVersion()
if !concreteVersion(minecraft) {
continue
}
referenced := make(map[string]bool)
var references []reference
for file := range vanilla.EntryPoints() {
for installerIndex := range installations {
if installerIndex == vanillaIndex {
continue
}
installer := &installations[installerIndex]
if !installer.Identity.IsValid() ||
isVanillaIdentity(installer.Identity) ||
firstEntryPoint(installer) == nil {
continue
}
installerMinecraft := installer.Identity.MinecraftVersion()
if !concreteVersion(installerMinecraft) ||
installerMinecraft != minecraft ||
!hasFile(installer, file.Path) {
continue
}
references = append(references, reference{
installation: installerIndex,
path: file.Path,
})
referenced[file.Path] = true
}
}
if len(references) == 0 {
continue
}
for _, found := range references {
member := fileAt(vanilla, found.path)
if member == nil {
continue
}
installations[found.installation].addFile(File{
Path: member.Path,
Role: RolePayload,
Ownership: member.Ownership,
})
}
allReferenced := true
for file := range vanilla.EntryPoints() {
if !referenced[file.Path] {
allReferenced = false
break
}
}
if allReferenced {
for _, found := range references {
for _, file := range vanilla.Files {
role := file.Role
if role == RoleEntryPoint {
role = RolePayload
}
installations[found.installation].addFile(File{
Path: file.Path,
Role: role,
Ownership: file.Ownership,
})
}
}
drop[vanillaIndex] = true
continue
}
for path := range referenced {
vanilla.removeFile(path)
}
}
out := installations[:0]
for index := range installations {
if drop[index] {
continue
}
out = append(out, installations[index])
}
clear(installations[len(out):])
return out
}
func conflictingClaims(installations []Installation) []Finding {
claims := make(map[string][]*Installation, len(installations))
for index := range installations {
installation := &installations[index]
if !installation.Identity.IsValid() {
continue
}
for file := range installation.EntryPoints() {
claims[file.Path] = append(claims[file.Path], installation)
}
}
paths := make([]string, 0, len(claims))
for path := range claims {
paths = append(paths, path)
}
slices.Sort(paths)
findings := make([]Finding, 0)
for _, path := range paths {
found := claims[path]
if len(found) <= 1 || sameConcreteIdentity(found) {
continue
}
identities := make([]Identity, 0, len(found))
entryPoints := make([]string, 0, len(found))
for _, installation := range found {
identities = append(identities, installation.Identity)
for file := range installation.EntryPoints() {
entryPoints = append(entryPoints, file.Path)
}
}
findings = append(findings, Finding{
Kind: FindingConflictingIdentities,
Path: path,
Paths: sortedUnique(entryPoints),
Identities: uniqueIdentities(identities),
})
}
return findings
}
func sameConcreteIdentity(installations []*Installation) bool {
if len(installations) == 0 {
return true
}
first := installations[0].Identity
if !first.IsConcrete() {
return false
}
for _, installation := range installations[1:] {
if !installation.Identity.IsConcrete() ||
!first.Equal(installation.Identity) {
return false
}
}
return true
}
func unknownArtifacts(installations []Installation, scan *scan) []Finding {
if scan == nil {
return nil
}
claimed := make(map[string]bool)
for index := range installations {
for _, file := range installations[index].Files {
claimed[filepath.Clean(file.Path)] = true
}
}
var findings []Finding
for _, artifact := range scan.RootFiles() {
if artifact.IsDirectory() ||
!strings.HasSuffix(strings.ToLower(artifact.Path()), ".jar") ||
claimed[filepath.Clean(artifact.Path())] {
continue
}
findings = append(findings, Finding{
Kind: FindingUnknownArtifact,
Path: artifact.Path(),
})
}
return findings
}
func dropEmptyInstallations(installations []Installation) []Installation {
out := installations[:0]
for index := range installations {
if len(installations[index].Files) == 0 {
continue
}
out = append(out, installations[index])
}
clear(installations[len(out):])
return out
}
func compareInstallations(left, right Installation) int {
if result := compareIdentities(left.Identity, right.Identity); result != 0 {
return result
}
if result := strings.Compare(firstEntryPointPath(&left), firstEntryPointPath(&right)); result != 0 {
return result
}
return strings.Compare(firstFilePath(left), firstFilePath(right))
}
func firstFilePath(installation Installation) string {
if len(installation.Files) == 0 {
return ""
}
path := installation.Files[0].Path
for _, file := range installation.Files[1:] {
if file.Path < path {
path = file.Path
}
}
return path
}
func isVanillaIdentity(identity Identity) bool {
if !identity.IsValid() {
return false
}
return identity.Product() == server.ProductMinecraft
}
func hasFile(installation *Installation, path string) bool {
return fileAt(installation, path) != nil
}
func fileAt(installation *Installation, path string) *File {
if installation == nil {
return nil
}
path = filepath.Clean(path)
for index := range installation.Files {
if installation.Files[index].Path == path {
return &installation.Files[index]
}
}
return nil
}
package discovery
import "errors"
var errNotRegularFile = errors.New("discovery: artifact is not a regular file")
// SelectionError is the typed failure of a selection request. It carries the
// domain state and the available installations so the presentation boundary
// can derive its own guidance; no CLI command or severity strings live here.
type SelectionError struct {
State SelectionState
Installations []Installation
}
func (e *SelectionError) Error() string {
if e == nil {
return "server selection failed"
}
switch e.State {
case SelectionNone:
return "no server installation was found"
case SelectionAmbiguous:
return "multiple server installations satisfy the selection"
case SelectionMissingDeclared:
return "the declared server installation is not installed"
case SelectionUnmatched:
return "no installed server matches the requested filters"
case SelectionInvalid:
return "no launchable server installation was found"
default:
return "server selection failed"
}
}
package discovery
import (
"archive/zip"
"bufio"
"encoding/json/v2"
"path/filepath"
"strings"
"github.com/mclucy/lucy/internal/fileschema"
versionpkg "github.com/mclucy/lucy/version"
)
const (
fabricInstallPropertiesPath = "install.properties"
fabricLaunchPropertiesPath = "fabric-server-launch.properties"
fabricMetaLauncherMainClass = "net.fabricmc.installer.ServerLauncher"
fabricServerDataDir = ".fabric/server"
fabricGeneratedLauncherPrefix = "fabric-loader-server-"
fabricVersionSidecarPath = "version.json"
// fabricLauncherPropertiesPath is the sidecar file FabricServerLauncher
// keeps beside the shim; note the extra "r" versus
// fabricLaunchPropertiesPath, which sits inside the jar.
fabricLauncherPropertiesPath = "fabric-server-launcher.properties"
fabricServerJarProperty = "serverJar"
minecraftServerJarName = "server.jar"
fabricModernKnotServer = "net.fabricmc.loader.impl.launch.knot.KnotServer"
fabricLegacyKnotServer = "net.fabricmc.loader.launch.knot.KnotServer"
)
// parseFabricInstallProperties reads the unattended install.properties entry
// that a Fabric meta launcher embeds. Only a complete loader and game version
// pair counts as a runtime identity.
func parseFabricInstallProperties(zipReader *zip.Reader) (
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
ok bool,
) {
loaderVersion = versionpkg.Unknown
gameVersion = versionpkg.Unknown
for _, f := range zipReader.File {
if f.Name != fabricInstallPropertiesPath {
continue
}
r, err := f.Open()
if err != nil {
continue
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if after, found := strings.CutPrefix(
line,
"fabric-loader-version=",
); found {
loaderVersion = versionpkg.Version(strings.TrimSpace(after))
} else if after, found := strings.CutPrefix(
line,
"game-version=",
); found {
gameVersion = versionpkg.Version(strings.TrimSpace(after))
}
}
scanErr := scanner.Err()
_ = r.Close()
if scanErr == nil && loaderVersion != versionpkg.Unknown &&
gameVersion != versionpkg.Unknown {
return loaderVersion, gameVersion, true
}
}
return loaderVersion, gameVersion, false
}
func fabricLauncherPropertiesAreServer(data []byte) bool {
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimRight(line, "\r")
if after, found := strings.CutPrefix(line, "launch.mainClass="); found {
return after == fabricModernKnotServer || after == fabricLegacyKnotServer
}
}
return false
}
// parseFabricLauncherManifest returns the loader and game versions named by
// the Class-Path entries of a Fabric launch jar manifest, together with the
// raw classpath. Installer shims keep library paths relative to the root;
// generated .fabric/server launchers walk back with "./../..".
func parseFabricLauncherManifest(zipReader *zip.Reader) (
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
classPath []string,
) {
loaderVersion = versionpkg.Unknown
gameVersion = versionpkg.Unknown
classPath = parseArchiveClassPath(zipReader)
for _, entry := range classPath {
if parsed, found := fabricClassPathVersion(entry, "fabric-loader"); found {
loaderVersion = parsed
} else if parsed, found := fabricClassPathVersion(entry, "intermediary"); found {
gameVersion = parsed
}
}
return loaderVersion, gameVersion, classPath
}
// fabricClassPathVersion extracts the version segment after
// libraries/net/fabricmc/<artifact>/ in a manifest Class-Path entry.
func fabricClassPathVersion(classPath, artifact string) (versionpkg.Version, bool) {
segments := strings.Split(filepath.ToSlash(classPath), "/")
for i := 0; i+4 < len(segments); i++ {
if segments[i] != "libraries" || segments[i+1] != "net" ||
segments[i+2] != "fabricmc" || segments[i+3] != artifact {
continue
}
candidate := segments[i+4]
if candidate == "" || candidate == "." || candidate == ".." {
return versionpkg.Unknown, false
}
return versionpkg.Version(candidate), true
}
return versionpkg.Unknown, false
}
// readArchiveManifestMainClass returns the Main-Class attribute of a jar
// manifest, unfolding its continuation lines first.
func readArchiveManifestMainClass(zipReader *zip.Reader) (string, bool) {
data, ok, err := readArchiveEntry(zipReader, "META-INF/MANIFEST.MF")
if err != nil || !ok {
return "", false
}
for _, line := range unfoldManifestLines(data) {
if value, found := strings.CutPrefix(line, "Main-Class: "); found {
return strings.TrimSpace(value), true
}
}
return "", false
}
// parseArchiveClassPath returns the entries of the first Class-Path
// attribute in a jar manifest.
func parseArchiveClassPath(zipReader *zip.Reader) []string {
data, ok, err := readArchiveEntry(zipReader, "META-INF/MANIFEST.MF")
if err != nil || !ok {
return nil
}
for _, line := range unfoldManifestLines(data) {
value, found := strings.CutPrefix(line, "Class-Path: ")
if !found {
continue
}
return strings.Fields(value)
}
return nil
}
// unfoldManifestLines joins the continuation lines of a JAR manifest. A
// continuation line starts with a single space that is not part of the value.
func unfoldManifestLines(data []byte) []string {
raw := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n")
lines := make([]string, 0, len(raw))
for _, line := range raw {
line = strings.TrimSuffix(line, "\r")
if strings.HasPrefix(line, " ") && len(lines) > 0 {
lines[len(lines)-1] += line[1:]
continue
}
lines = append(lines, line)
}
return lines
}
func parseFabricLauncherBundledLoaderVersion(zipReader *zip.Reader) versionpkg.Version {
data, ok, err := readArchiveEntry(zipReader, "fabric.mod.json")
if err != nil || !ok {
return versionpkg.Unknown
}
var metadata fileschema.FileFabricModIdentifier
if err := json.Unmarshal(data, &metadata); err != nil {
return versionpkg.Unknown
}
if metadata.ID != "fabricloader" || strings.TrimSpace(metadata.Version) == "" {
return versionpkg.Unknown
}
return versionpkg.Version(metadata.Version)
}
func parseFabricLauncherSidecarGameVersion(
s *scan,
primaryFile *artifact,
) versionpkg.Version {
sidecar, ok := s.Sibling(primaryFile, fabricVersionSidecarPath)
if !ok || sidecar.IsDirectory() {
return versionpkg.Unknown
}
data, err := sidecar.Read()
if err != nil {
return versionpkg.Unknown
}
var metadata struct {
Name string `json:"name"`
ReleaseTarget string `json:"release_target"`
}
if err := json.Unmarshal(data, &metadata); err != nil {
return versionpkg.Unknown
}
if strings.TrimSpace(metadata.Name) != "" {
return versionpkg.Version(metadata.Name)
}
if strings.TrimSpace(metadata.ReleaseTarget) != "" {
return versionpkg.Version(metadata.ReleaseTarget)
}
return versionpkg.Unknown
}
// parseServerJarGameVersion reads the game version from the version.json of a
// server jar on disk. Legacy ids embed a build hash after " / "; the name and
// release_target fields carry the clean release id. Any problem yields
// VersionUnknown: this source is the last resort for launch shims with no
// embedded version evidence.
func parseServerJarGameVersion(file *artifact) versionpkg.Version {
zipReader, err := file.Archive()
if err != nil {
return versionpkg.Unknown
}
data, ok, err := readArchiveEntry(zipReader, mojangVersionJSONEntry)
if err != nil || !ok {
return versionpkg.Unknown
}
version, guarded, err := mojangVersionFromJSON(data)
if err != nil || guarded {
return versionpkg.Unknown
}
if isMinecraftReleaseVersion(string(version)) {
return version
}
var metadata struct {
Name string `json:"name"`
ReleaseTarget string `json:"release_target"`
}
if err := json.Unmarshal(data, &metadata); err != nil {
return versionpkg.Unknown
}
for _, candidate := range []string{
strings.TrimSpace(metadata.Name),
strings.TrimSpace(metadata.ReleaseTarget),
} {
if isMinecraftReleaseVersion(candidate) {
return versionpkg.Version(candidate)
}
}
return versionpkg.Unknown
}
// fabricLauncherServerJarPath returns the server jar that the launch shim at
// primaryPath boots. FabricServerLauncher reads serverJar from
// fabric-server-launcher.properties beside the shim and falls back to
// server.jar when the file or the entry is missing.
func fabricLauncherServerJarPath(
primaryPath string,
properties []byte,
) string {
name := minecraftServerJarName
if value := propertiesValue(properties, fabricServerJarProperty); value != "" {
name = value
}
if filepath.IsAbs(name) {
return filepath.Clean(name)
}
return filepath.Join(filepath.Dir(primaryPath), name)
}
// propertiesValue returns the value of key in a Java properties payload, or
// "" when the key is absent.
func propertiesValue(data []byte, key string) string {
var value string
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(strings.TrimRight(line, "\r"))
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "!") {
continue
}
separator := strings.IndexAny(line, "=:\t ")
if separator < 0 {
continue
}
propertyKey := strings.TrimSpace(line[:separator])
if propertyKey != key {
continue
}
propertyValue := strings.TrimLeft(line[separator:], "=:\t ")
value = strings.TrimSpace(propertyValue)
}
return value
}
package discovery
import (
"encoding/json/v2"
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
// discoverFabric recognizes Fabric server distributions. Two layouts are
// legitimate:
//
// - an installer shim (fabric-server-launch.jar) beside the vanilla jar
// its fabric-server-launcher.properties names, with libraries referenced
// from the shim manifest;
// - an unattended meta launcher (fabric-server-mc.<mc>-loader.<loader>-
// launcher.<installer>.jar) which, after its first run, keeps a payload
// and generated launch jar under the hidden .fabric/server directory.
//
// The meta launcher is recognized before .fabric/server is materialized.
// Hidden files are claimed only when their content matches the identity the
// meta launcher embedded; stale files from another version stay unclaimed.
// A generated launcher without its meta launcher is still a real installed
// layout and is recognized from its own content.
func discoverFabric(s *scan) ([]Installation, []Finding) {
if s == nil {
return nil, nil
}
installations := make([]Installation, 0)
metaLauncherSeen := false
for _, file := range s.RootFiles() {
if file.IsDirectory() || !isJarArtifact(file) {
continue
}
if installation, ok := fabricMetaLauncherInstallation(s, file); ok {
installations = append(installations, installation)
metaLauncherSeen = true
continue
}
if installation, ok := fabricShimInstallation(s, file); ok {
installations = append(installations, installation)
}
}
if !metaLauncherSeen {
installations = append(
installations,
fabricGeneratedLauncherInstallations(s)...,
)
}
return installations, nil
}
// fabricMetaLauncherInstallation recognizes the unattended launcher by its
// embedded install.properties and claims the hidden files the launcher
// generates on first run when their content agrees with that identity.
func fabricMetaLauncherInstallation(
s *scan,
file *artifact,
) (Installation, bool) {
archive, err := file.Archive()
if err != nil {
return Installation{}, false
}
mainClass, ok := readArchiveManifestMainClass(archive)
if !ok || mainClass != fabricMetaLauncherMainClass {
return Installation{}, false
}
loaderVersion, gameVersion, ok := parseFabricInstallProperties(archive)
if !ok {
return Installation{}, false
}
installation := NewInstallation(
fabricIdentity(loaderVersion, gameVersion),
file.Path(),
)
dataDir := filepath.Join(s.root, filepath.FromSlash(fabricServerDataDir))
generatedPath := filepath.Join(
dataDir,
fabricGeneratedLauncherPrefix+string(loaderVersion)+
"-minecraft-"+string(gameVersion)+".jar",
)
if generated, ok := s.File(generatedPath); ok && !generated.IsDirectory() {
generatedLoader, generatedGame, classPath, ok := fabricLaunchJarIdentity(generated)
if ok && generatedLoader == loaderVersion && generatedGame == gameVersion {
installation.AddFile(generated.Path(), RoleEntryPoint)
addLocalClassPathFiles(s, &installation, generated, classPath)
addFabricSidecars(s, &installation, generated)
}
}
payloadPath := filepath.Join(dataDir, string(gameVersion)+"-server.jar")
if payload, ok := s.File(payloadPath); ok && !payload.IsDirectory() &&
fabricServerPayloadMatches(payload, gameVersion) {
installation.AddFile(payload.Path(), RolePayload)
}
return installation, true
}
// fabricShimInstallation enriches a launch shim with the sidecars, payload
// and classpath files the shim needs at run time.
func fabricShimInstallation(s *scan, file *artifact) (Installation, bool) {
archive, err := file.Archive()
if err != nil {
return Installation{}, false
}
properties, ok, err := readArchiveEntry(archive, fabricLaunchPropertiesPath)
if err != nil || !ok || !fabricLauncherPropertiesAreServer(properties) {
return Installation{}, false
}
loaderVersion, gameVersion, classPath := parseFabricLauncherManifest(archive)
if loaderVersion == versionpkg.Unknown {
loaderVersion = parseFabricLauncherBundledLoaderVersion(archive)
}
launcherProperties := []byte(nil)
propertiesFile, hasProperties := s.Sibling(file, fabricLauncherPropertiesPath)
if hasProperties && !propertiesFile.IsDirectory() {
launcherProperties, _ = propertiesFile.Read()
}
if gameVersion == versionpkg.Unknown {
gameVersion = parseFabricLauncherSidecarGameVersion(s, file)
}
// Installer 1.1+ shims embed no version evidence, so the last resort is
// the vanilla jar the shim boots: FabricServerLauncher reads serverJar
// from fabric-server-launcher.properties and defaults to server.jar.
serverJarPath := fabricLauncherServerJarPath(file.Path(), launcherProperties)
serverJar, hasServerJar := s.File(serverJarPath)
if hasServerJar && serverJar.IsDirectory() {
hasServerJar = false
}
if gameVersion == versionpkg.Unknown && hasServerJar {
gameVersion = parseServerJarGameVersion(serverJar)
}
if loaderVersion == versionpkg.Unknown || gameVersion == versionpkg.Unknown {
return Installation{}, false
}
installation := NewInstallation(
fabricIdentity(loaderVersion, gameVersion),
file.Path(),
)
if hasServerJar {
installation.AddFile(serverJar.Path(), RolePayload)
}
if hasProperties {
installation.AddFile(propertiesFile.Path(), RoleConfiguration)
}
if sidecar, ok := s.Sibling(file, fabricVersionSidecarPath); ok &&
!sidecar.IsDirectory() {
installation.AddFile(sidecar.Path(), RoleConfiguration)
}
addLocalClassPathFiles(s, &installation, file, classPath)
return installation, true
}
// fabricGeneratedLauncherInstallations recognizes a generated launch jar in
// the hidden server data directory when no meta launcher remains.
func fabricGeneratedLauncherInstallations(s *scan) []Installation {
dataDir := filepath.Join(s.root, filepath.FromSlash(fabricServerDataDir))
entries, err := s.ReadDir(dataDir)
if err != nil {
return nil
}
installations := make([]Installation, 0)
for _, entry := range entries {
if entry.IsDir() ||
!strings.HasPrefix(entry.Name(), fabricGeneratedLauncherPrefix) ||
!strings.HasSuffix(strings.ToLower(entry.Name()), ".jar") {
continue
}
file, ok := s.File(filepath.Join(dataDir, entry.Name()))
if !ok || file.IsDirectory() {
continue
}
loaderVersion, gameVersion, classPath, ok := fabricLaunchJarIdentity(file)
if !ok {
continue
}
installation := NewInstallation(
fabricIdentity(loaderVersion, gameVersion),
file.Path(),
)
addLocalClassPathFiles(s, &installation, file, classPath)
addFabricSidecars(s, &installation, file)
payloadPath := filepath.Join(dataDir, string(gameVersion)+"-server.jar")
if payload, ok := s.File(payloadPath); ok && !payload.IsDirectory() &&
fabricServerPayloadMatches(payload, gameVersion) {
installation.AddFile(payload.Path(), RolePayload)
}
installations = append(installations, installation)
}
return installations
}
// addFabricSidecars claims the launcher properties and version metadata that
// sit beside a generated launch jar.
func addFabricSidecars(s *scan, installation *Installation, launcher *artifact) {
if properties, ok := s.Sibling(launcher, fabricLauncherPropertiesPath); ok &&
!properties.IsDirectory() {
installation.AddFile(properties.Path(), RoleConfiguration)
}
if sidecar, ok := s.Sibling(launcher, fabricVersionSidecarPath); ok &&
!sidecar.IsDirectory() {
installation.AddFile(sidecar.Path(), RoleConfiguration)
}
}
// fabricServerPayloadMatches verifies that a downloaded server jar carries
// the game version the meta launcher embedded. The id field is authoritative
// for modern servers; name and release_target cover older ids that append a
// build hash.
func fabricServerPayloadMatches(
file *artifact,
gameVersion versionpkg.Version,
) bool {
archive, err := file.Archive()
if err != nil {
return false
}
data, ok, err := readArchiveEntry(archive, mojangVersionJSONEntry)
if err != nil || !ok {
return false
}
version, guarded, err := mojangVersionFromJSON(data)
if err != nil || guarded {
return false
}
if version == gameVersion {
return true
}
var metadata struct {
Name string `json:"name"`
ReleaseTarget string `json:"release_target"`
}
if err := json.Unmarshal(data, &metadata); err != nil {
return false
}
return versionpkg.Version(strings.TrimSpace(metadata.Name)) == gameVersion ||
versionpkg.Version(strings.TrimSpace(metadata.ReleaseTarget)) == gameVersion
}
// fabricLaunchJarIdentity validates a generated Fabric launch jar from its
// content. The filename alone is never sufficient.
func fabricLaunchJarIdentity(file *artifact) (
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
classPath []string,
ok bool,
) {
archive, err := file.Archive()
if err != nil {
return versionpkg.Unknown, versionpkg.Unknown, nil, false
}
loaderVersion, gameVersion, classPath = parseFabricLauncherManifest(archive)
if loaderVersion == versionpkg.Unknown || gameVersion == versionpkg.Unknown {
return versionpkg.Unknown, versionpkg.Unknown, nil, false
}
properties, found, err := readArchiveEntry(archive, fabricLaunchPropertiesPath)
if err != nil || !found || !fabricLauncherPropertiesAreServer(properties) {
return versionpkg.Unknown, versionpkg.Unknown, nil, false
}
return loaderVersion, gameVersion, classPath, true
}
// addMatchingMinecraftPayload claims the root Minecraft server jar as the
// installation payload when its content names the same game version. The
// engine then treats the matching vanilla installation as payload rather
// than a second server.
func addMatchingMinecraftPayload(
s *scan,
installation *Installation,
gameVersion versionpkg.Version,
) {
if s == nil || installation == nil || !hasConcreteVersion(gameVersion) {
return
}
serverJar, ok := s.File(filepath.Join(s.root, minecraftServerJarName))
if !ok || serverJar.IsDirectory() {
return
}
if parseServerJarGameVersion(serverJar) != gameVersion {
return
}
installation.AddFile(serverJar.Path(), RolePayload)
}
// addMinecraftServerLibraryPayload claims the Minecraft server jar that
// installers keep under libraries/net/minecraft/server/<mc>/. The path names
// the game version; a version.json inside the jar must agree when present.
func addMinecraftServerLibraryPayload(
s *scan,
installation *Installation,
gameVersion versionpkg.Version,
) {
if s == nil || installation == nil || !hasConcreteVersion(gameVersion) {
return
}
version := string(gameVersion)
for _, name := range []string{
"server-" + version + ".jar",
"server-" + version + "-bundled.jar",
} {
path := filepath.Join(
s.root,
"libraries",
"net",
"minecraft",
"server",
version,
name,
)
file, ok := s.File(path)
if !ok || file.IsDirectory() {
continue
}
if recorded := parseServerJarGameVersion(file); recorded != versionpkg.Unknown &&
recorded != gameVersion {
continue
}
installation.AddFile(file.Path(), RolePayload)
}
}
// addLocalClassPathFiles resolves manifest Class-Path entries against the jar
// that declares them and claims the local files that exist. Class-Path
// entries must stay inside the scanned directory.
func addLocalClassPathFiles(
s *scan,
installation *Installation,
jar *artifact,
classPath []string,
) {
for _, entry := range classPath {
entry = strings.Trim(strings.TrimSpace(entry), `"`)
if entry == "" || strings.Contains(entry, "://") ||
strings.HasPrefix(entry, "file:") {
continue
}
path := filepath.FromSlash(entry)
if !filepath.IsAbs(path) {
path = filepath.Join(filepath.Dir(jar.Path()), path)
}
if file, ok := s.File(path); ok && !file.IsDirectory() {
installation.AddFile(file.Path(), RoleLibrary)
}
}
}
func fabricIdentity(
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
) Identity {
return Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemFabric,
Name: "fabric",
Version: loaderVersion,
},
Components: []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemFabric,
Name: "fabric-loader",
Version: loaderVersion,
},
{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: gameVersion,
},
},
}
}
// isJarArtifact reports whether a scanned file is a jar by name. Content
// inspection decides whether it is a real installation; the name only avoids
// opening unrelated files.
func isJarArtifact(file *artifact) bool {
return strings.HasSuffix(strings.ToLower(file.Path()), ".jar")
}
package discovery
import (
"iter"
"path/filepath"
"slices"
"sort"
"strings"
)
// FindingKind is a typed observation condition. Presentation severity and CLI
// suggestions belong to the presentation boundary.
type FindingKind string
const (
FindingUnknown FindingKind = ""
FindingUnknownArtifact FindingKind = "unknown_artifact"
FindingConflictingIdentities FindingKind = "conflicting_identities"
FindingInvalidIdentity FindingKind = "invalid_identity"
FindingUnreadableFile FindingKind = "unreadable_file"
FindingReceiptError FindingKind = "receipt_error"
FindingOwnershipError FindingKind = "ownership_error"
FindingModifiedFile FindingKind = "modified_file"
FindingUnmanagedInstallation FindingKind = "unmanaged_installation"
FindingMissingDeclaredInstallation FindingKind = "missing_declared_installation"
FindingUnmatchedInstallations FindingKind = "unmatched_installations"
FindingAmbiguousInstallations FindingKind = "ambiguous_installations"
FindingAutomaticSelection FindingKind = "automatic_selection"
)
// Finding is one typed observation condition. Path is the primary affected
// path; Paths carries related evidence when a condition spans several files.
// Installation conditions carry Identity or Identities instead of entry-point
// paths.
type Finding struct {
Kind FindingKind
Path string
Paths []string
Identity Identity
Identities []Identity
Ownership Ownership
Cause error
}
// Result is one discovery observation. Installations are immutable after
// Discover except for ownership labels applied by ObserveOwnership. Selection
// is the explicit read-only choice made by Select.
type Result struct {
Installations []Installation
Diagnostics []Finding
Selection Selection
}
// Selected returns the current selection only when it names a launchable
// installation.
func (r *Result) Selected() *Selection {
if r == nil || !r.Selection.IsValid() {
return nil
}
return &r.Selection
}
// FindInstallation returns the installation whose member paths and roles
// exactly match the given evidence. It returns nil when no installation
// matches.
func (r *Result) FindInstallation(members map[string]FileRole) *Installation {
if r == nil || len(members) == 0 {
return nil
}
for index := range r.Installations {
installation := &r.Installations[index]
if installationMatchesMembers(installation, members) {
return installation
}
}
return nil
}
// RebasePaths returns the observation with every absolute path under from
// repointed to to. A caller that observes a staged tree and then publishes it
// at another path reports the published paths instead of the staging paths.
func (r Result) RebasePaths(from, to string) Result {
from, to = filepath.Clean(from), filepath.Clean(to)
if from == to || from == "." || !filepath.IsAbs(from) {
return r
}
rebase := func(path string) string {
if path == "" {
return ""
}
relative, err := filepath.Rel(from, path)
if err != nil || relative == ".." ||
strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return path
}
return filepath.Join(to, relative)
}
selected := -1
if r.Selection.Installation != nil {
for index := range r.Installations {
if &r.Installations[index] == r.Selection.Installation {
selected = index
break
}
}
}
installations := make([]Installation, len(r.Installations))
for index := range r.Installations {
installations[index] = r.Installations[index].rebasePaths(rebase)
}
r.Installations = installations
diagnostics := make([]Finding, len(r.Diagnostics))
for index := range r.Diagnostics {
diagnostics[index] = r.Diagnostics[index].rebasePaths(rebase)
}
r.Diagnostics = diagnostics
switch {
case selected >= 0:
r.Selection.Installation = &r.Installations[selected]
case r.Selection.Installation != nil:
installation := r.Selection.Installation.rebasePaths(rebase)
r.Selection.Installation = &installation
}
return r
}
func (i Installation) rebasePaths(rebase func(string) string) Installation {
i.CorePath = rebase(i.CorePath)
if i.Files == nil {
return i
}
files := make([]File, len(i.Files))
for index := range i.Files {
files[index] = i.Files[index]
files[index].Path = rebase(files[index].Path)
}
i.Files = files
return i
}
func (f Finding) rebasePaths(rebase func(string) string) Finding {
f.Path = rebase(f.Path)
if f.Paths == nil {
return f
}
paths := make([]string, len(f.Paths))
for index := range f.Paths {
paths[index] = rebase(f.Paths[index])
}
f.Paths = paths
return f
}
func installationMatchesMembers(
installation *Installation,
members map[string]FileRole,
) bool {
if installation == nil || len(installation.Files) != len(members) {
return false
}
for _, file := range installation.Files {
role, ok := members[file.Path]
if !ok || role != file.Role {
return false
}
}
return true
}
// Findings yields the immutable diagnostics followed by selection conditions
// derived from the current selection. Nothing is cached between calls, so a
// changed selection never leaves stale finding arrays behind.
func (r *Result) Findings() iter.Seq[Finding] {
return func(yield func(Finding) bool) {
if r == nil {
return
}
for _, finding := range r.Diagnostics {
if !yield(finding) {
return
}
}
r.yieldSelectionFindings(yield)
}
}
func (r *Result) yieldSelectionFindings(yield func(Finding) bool) bool {
switch r.Selection.State {
case SelectionSelected:
return r.yieldSelectedFindings(yield)
case SelectionAmbiguous:
return yield(Finding{
Kind: FindingAmbiguousInstallations,
Identities: r.candidateIdentities(),
})
case SelectionUnmatched:
return yield(Finding{
Kind: FindingUnmatchedInstallations,
Identities: r.observedIdentities(),
})
case SelectionMissingDeclared:
return yield(Finding{
Kind: FindingMissingDeclaredInstallation,
})
default:
return true
}
}
func (r *Result) yieldSelectedFindings(yield func(Finding) bool) bool {
selected := r.Selection
if !selected.IsValid() {
return true
}
if selected.Source == SourcePreferred || selected.Source == SourceCoverage {
if !yield(Finding{
Kind: FindingAutomaticSelection,
Identity: selected.Installation.Identity,
Identities: r.competingIdentities(),
}) {
return false
}
}
for index := range r.Installations {
installation := &r.Installations[index]
if installation == selected.Installation ||
!launchableInstallation(installation) {
continue
}
entry := chooseEntryPoint(installation)
if entry == nil || entry.Ownership == OwnershipManaged {
continue
}
if !yield(Finding{
Kind: FindingUnmanagedInstallation,
Identity: installation.Identity,
Ownership: entry.Ownership,
}) {
return false
}
}
return true
}
// observedIdentities lists every valid identity a filter could have matched.
func (r *Result) observedIdentities() []Identity {
identities := make([]Identity, 0, len(r.Installations))
for index := range r.Installations {
installation := &r.Installations[index]
if !installation.Identity.IsValid() {
continue
}
identities = append(identities, installation.Identity)
}
return uniqueIdentities(identities)
}
func (r *Result) candidateIdentities() []Identity {
identities := make([]Identity, 0, len(r.Installations))
for index := range r.Installations {
installation := &r.Installations[index]
if !launchableInstallation(installation) {
continue
}
identities = append(identities, installation.Identity)
}
return uniqueIdentities(identities)
}
func (r *Result) competingIdentities() []Identity {
if r == nil || r.Selection.Installation == nil {
return nil
}
identities := make([]Identity, 0, len(r.Installations))
for index := range r.Installations {
installation := &r.Installations[index]
if installation == r.Selection.Installation ||
!launchableInstallation(installation) {
continue
}
identities = append(identities, installation.Identity)
}
return uniqueIdentities(identities)
}
// uniqueIdentities sorts the caller-owned slice and compacts equal canonical
// identities in place.
func uniqueIdentities(identities []Identity) []Identity {
sort.SliceStable(identities, func(i, j int) bool {
return compareIdentities(identities[i], identities[j]) < 0
})
unique := identities[:0]
last := ""
for _, identity := range identities {
key := identityKey(identity)
if len(unique) > 0 && key == last {
continue
}
last = key
unique = append(unique, identity)
}
clear(identities[len(unique):])
return unique
}
func sortedUnique(paths []string) []string {
if len(paths) == 0 {
return nil
}
slices.Sort(paths)
unique := paths[:0]
for _, path := range paths {
if len(unique) > 0 && unique[len(unique)-1] == path {
continue
}
unique = append(unique, path)
}
return unique
}
package discovery
import (
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
const forgeLibraryRoot = "libraries/net/minecraftforge/forge"
// discoverForge recognizes installed Forge servers under the Forge Maven
// library directory. One directory holds at most one Forge installation:
// modern layouts keep the runtime in a universal library and launch it
// through a generated argument file or a bootstrap shim; legacy layouts use
// the universal jar directly. The installer jar itself is a provisioning
// tool and is never a runtime.
func discoverForge(s *scan) ([]Installation, []Finding) {
if s == nil {
return nil, nil
}
root := filepath.Join(s.root, filepath.FromSlash(forgeLibraryRoot))
installations := make([]Installation, 0)
if entries, err := s.ReadDir(root); err == nil {
for _, entry := range entries {
if !entry.IsDir() {
continue
}
installation, ok := forgeInstallation(
s,
filepath.Join(root, entry.Name()),
)
if ok {
installations = append(installations, installation)
}
}
}
installations = append(
installations,
discoverRootForgeInstallations(s)...,
)
return installations, nil
}
// discoverRootForgeInstallations recognizes standalone Forge launchers kept
// directly in the server directory. These are the legacy universal and server
// jars that predate the Maven-shaped installed layout. Installers and shims
// are provisioning/launch fragments, not standalone installations.
func discoverRootForgeInstallations(s *scan) []Installation {
installations := make([]Installation, 0)
for _, file := range s.RootFiles() {
if file.IsDirectory() || !isJarArtifact(file) {
continue
}
installation, ok := rootForgeInstallation(s, file)
if ok {
installations = append(installations, installation)
}
}
return installations
}
// rootForgeInstallation builds one installation from a root-level Forge
// launcher. Identity comes from manifest metadata, the Maven-shaped filename,
// or validated argument sidecars. A jar without positive Forge content is
// never claimed, even when it has a Main-Class.
func rootForgeInstallation(
s *scan,
file *artifact,
) (Installation, bool) {
archive, err := file.Archive()
if err != nil {
return Installation{}, false
}
if verifyForgeShimArtifact(file) {
return Installation{}, false
}
if installerArtifact(archive) {
return Installation{}, false
}
manifestForge, manifestGame := parseForgeManifest(archive)
tupleGame, tupleForge, _ := parseForgeVersionTupleFromPath(file.Path())
unixArgs, hasUnixArgs := s.Sibling(file, "unix_args.txt")
winArgs, hasWinArgs := s.Sibling(file, "win_args.txt")
argsLoader, argsGame := versionpkg.Unknown, versionpkg.Unknown
if hasUnixArgs {
if data, err := unixArgs.Read(); err == nil {
argsLoader, argsGame = parseLoaderArgs(data)
}
}
if !hasConcreteVersion(argsGame) && hasWinArgs {
if data, err := winArgs.Read(); err == nil {
argsLoader, argsGame = parseLoaderArgs(data)
}
}
gameVersion := firstConcreteVersion(manifestGame, tupleGame, argsGame)
forgeVersion := firstConcreteVersion(manifestForge, tupleForge, argsLoader)
if !hasConcreteVersion(gameVersion) || !hasConcreteVersion(forgeVersion) {
return Installation{}, false
}
unixArgsValid := hasUnixArgs &&
loaderArgsLaunchValid(unixArgs, forgeVersion, gameVersion)
winArgsValid := hasWinArgs &&
loaderArgsLaunchValid(winArgs, forgeVersion, gameVersion)
base := filepath.Base(file.Path())
kind := forgeArtifactKindFromName(base)
universalSibling, hasUniversalSibling := forgeRootSibling(s, file, base, "universal")
serverSibling, hasServerSibling := forgeRootSibling(s, file, base, "server")
shim, hasShim := forgeRootSibling(s, file, base, "shim")
universalValid := kind == "universal" &&
verifyForgeUniversalArtifact(file, forgeVersion, gameVersion)
if !universalValid && hasUniversalSibling {
universalValid = verifyForgeUniversalArtifact(
universalSibling,
forgeVersion,
gameVersion,
)
}
serverReadable := (kind == "server" && forgeArtifactReadable(file)) ||
(hasServerSibling && forgeArtifactReadable(serverSibling))
fileReadable := forgeArtifactReadable(file)
shimValid := hasShim && verifyForgeShimArtifact(shim)
runnable := artifactHasLaunchMainClass(file)
manifestMatches := hasConcreteVersion(manifestForge) &&
manifestForge == forgeVersion &&
(!hasConcreteVersion(manifestGame) || manifestGame == gameVersion)
productContent := manifestMatches || forgeProductContent(archive)
runtimePresent := universalValid || serverReadable || fileReadable
entries := make([]*artifact, 0, 3)
switch {
case shimValid && runtimePresent:
entries = append(entries, shim)
if unixArgsValid {
entries = append(entries, unixArgs)
}
if winArgsValid {
entries = append(entries, winArgs)
}
case (unixArgsValid || winArgsValid) && runtimePresent:
if unixArgsValid {
entries = append(entries, unixArgs)
}
if winArgsValid {
entries = append(entries, winArgs)
}
case runnable && productContent:
entries = append(entries, file)
default:
return Installation{}, false
}
installation := NewInstallation(
forgeIdentity(gameVersion, forgeVersion),
entries[0].Path(),
)
for _, entry := range entries[1:] {
installation.AddFile(entry.Path(), RoleEntryPoint)
}
universalArtifact := universalSibling
if kind == "universal" {
universalArtifact = file
}
serverArtifact := serverSibling
if kind == "server" {
serverArtifact = file
}
if universalValid && universalArtifact != nil &&
!containsArtifact(entries, universalArtifact) {
installation.AddFile(universalArtifact.Path(), RoleLibrary)
}
if serverReadable && serverArtifact != nil &&
!containsArtifact(entries, serverArtifact) {
installation.AddFile(serverArtifact.Path(), RolePayload)
}
if !containsArtifact(entries, file) && kind == "" && fileReadable {
installation.AddFile(file.Path(), RolePayload)
}
if hasUnixArgs && !unixArgsValid {
installation.AddFile(unixArgs.Path(), RoleConfiguration)
}
if hasWinArgs && !winArgsValid {
installation.AddFile(winArgs.Path(), RoleConfiguration)
}
if shimValid {
addForgeClassPathFiles(s, &installation, shim)
}
addForgeRootClassPathFiles(s, &installation, file, gameVersion)
addMatchingMinecraftPayload(s, &installation, gameVersion)
addMinecraftServerLibraryPayload(s, &installation, gameVersion)
return installation, true
}
// addForgeRootClassPathFiles claims the local libraries and Minecraft server
// payload named by a root Forge launcher manifest. Legacy universals list the
// Minecraft server jar directly in Class-Path.
func addForgeRootClassPathFiles(
s *scan,
installation *Installation,
jar *artifact,
gameVersion versionpkg.Version,
) {
for _, entry := range parseArchiveClassPathFromArtifact(jar) {
entry = strings.Trim(strings.TrimSpace(entry), `"`)
if entry == "" || strings.Contains(entry, "://") ||
strings.HasPrefix(entry, "file:") {
continue
}
path := filepath.FromSlash(entry)
candidates := []string{filepath.Join(s.root, path)}
if filepath.IsAbs(path) {
candidates = []string{path}
} else {
candidates = append(
candidates,
filepath.Join(filepath.Dir(jar.Path()), path),
)
}
for _, candidate := range candidates {
file, ok := s.File(candidate)
if !ok || file.IsDirectory() {
continue
}
role := RoleLibrary
base := strings.ToLower(filepath.Base(file.Path()))
if strings.Contains(base, "minecraft_server") ||
(strings.HasPrefix(base, "server-") &&
strings.HasSuffix(base, ".jar")) {
if recorded := parseServerJarGameVersion(file); recorded == versionpkg.Unknown ||
recorded == gameVersion {
role = RolePayload
}
}
installation.AddFile(file.Path(), role)
break
}
}
}
func forgeRootSibling(
s *scan,
file *artifact,
base string,
kind string,
) (*artifact, bool) {
prefix := forgeArtifactNamePrefix(base)
if prefix == "" {
return nil, false
}
sibling, ok := s.Sibling(file, prefix+"-"+kind+".jar")
if !ok || sibling.IsDirectory() {
return nil, false
}
return sibling, true
}
func forgeArtifactNamePrefix(base string) string {
for _, kind := range []string{"server", "universal", "shim"} {
suffix := "-" + kind + ".jar"
if strings.HasSuffix(base, suffix) {
return strings.TrimSuffix(base, suffix)
}
}
return ""
}
func forgeArtifactKindFromName(base string) string {
for _, kind := range []string{"server", "universal", "shim"} {
if strings.HasSuffix(base, "-"+kind+".jar") {
return kind
}
}
return ""
}
func firstConcreteVersion(values ...versionpkg.Version) versionpkg.Version {
for _, value := range values {
if hasConcreteVersion(value) {
return value
}
}
return versionpkg.Unknown
}
// forgeInstallation builds one installation from a
// libraries/net/minecraftforge/forge/<minecraft>-<forge>/ directory. A shim
// is the real entry point when it is complete; a server jar with generated
// arguments is the next choice; the universal jar is the entry point only
// for layouts that predate both, and is otherwise a runtime library.
func forgeInstallation(s *scan, versionDir string) (Installation, bool) {
version := filepath.Base(versionDir)
match := forgeRuntimeVersionDirPattern.FindStringSubmatch(version)
if match == nil {
return Installation{}, false
}
gameVersion := versionpkg.Version(match[1])
forgeVersion := versionpkg.Version(match[2])
universal, hasUniversal := forgeArtifact(
s,
versionDir,
"forge-"+version+"-universal.jar",
)
server, hasServer := forgeArtifact(
s,
versionDir,
"forge-"+version+"-server.jar",
)
shim, hasShim := forgeArtifact(
s,
versionDir,
"forge-"+version+"-shim.jar",
)
unixArgs, hasUnixArgs := forgeArtifact(s, versionDir, "unix_args.txt")
winArgs, hasWinArgs := forgeArtifact(s, versionDir, "win_args.txt")
shimValid := hasShim && verifyForgeShimArtifact(shim)
serverReadable := hasServer && forgeArtifactReadable(server)
universalValid := hasUniversal &&
verifyForgeUniversalArtifact(universal, forgeVersion, gameVersion)
unixArgsValid := hasUnixArgs &&
loaderArgsLaunchValid(unixArgs, forgeVersion, gameVersion)
winArgsValid := hasWinArgs &&
loaderArgsLaunchValid(winArgs, forgeVersion, gameVersion)
serverRunnable := serverReadable && artifactHasLaunchMainClass(server) &&
verifyForgeServerArtifact(server, forgeVersion, gameVersion)
universalRunnable := universalValid && artifactHasLaunchMainClass(universal)
entries := make([]*artifact, 0, 3)
switch {
case shimValid && (universalValid || serverReadable):
// The shim is the direct java -jar launch target, but it only
// bootstraps a complete layout. Generated arguments remain launch
// targets as well when they validate.
entries = append(entries, shim)
if unixArgsValid {
entries = append(entries, unixArgs)
}
if winArgsValid {
entries = append(entries, winArgs)
}
case (unixArgsValid || winArgsValid) && (universalValid || serverReadable):
if unixArgsValid {
entries = append(entries, unixArgs)
}
if winArgsValid {
entries = append(entries, winArgs)
}
case serverRunnable:
entries = append(entries, server)
case universalRunnable:
// Only genuine legacy universal jars with their own launch entry
// class are bootable; otherwise the universal is a runtime library.
entries = append(entries, universal)
default:
// An installer, a library-only universal, or a bare argument file
// is not a runnable layout.
return Installation{}, false
}
installation := NewInstallation(
forgeIdentity(gameVersion, forgeVersion),
entries[0].Path(),
)
for _, entry := range entries[1:] {
installation.AddFile(entry.Path(), RoleEntryPoint)
}
if universalValid && !containsArtifact(entries, universal) {
installation.AddFile(universal.Path(), RoleLibrary)
}
if serverReadable && !containsArtifact(entries, server) {
installation.AddFile(server.Path(), RolePayload)
}
if hasUnixArgs && !unixArgsValid {
installation.AddFile(unixArgs.Path(), RoleConfiguration)
}
if hasWinArgs && !winArgsValid {
installation.AddFile(winArgs.Path(), RoleConfiguration)
}
if shimValid {
addForgeClassPathFiles(s, &installation, shim)
}
addMatchingMinecraftPayload(s, &installation, gameVersion)
addMinecraftServerLibraryPayload(s, &installation, gameVersion)
return installation, true
}
func containsArtifact(artifacts []*artifact, target *artifact) bool {
for _, artifact := range artifacts {
if artifact == target {
return true
}
}
return false
}
// addForgeClassPathFiles claims the libraries named by a Forge shim
// manifest. Forge writes those entries relative to the server root, so the
// root is tried before the shim's own directory.
func addForgeClassPathFiles(
s *scan,
installation *Installation,
shim *artifact,
) {
for _, entry := range parseArchiveClassPathFromArtifact(shim) {
entry = strings.Trim(strings.TrimSpace(entry), `"`)
if entry == "" || strings.Contains(entry, "://") ||
strings.HasPrefix(entry, "file:") {
continue
}
path := filepath.FromSlash(entry)
candidates := []string{filepath.Join(s.root, path)}
if filepath.IsAbs(path) {
candidates = []string{path}
} else {
candidates = append(
candidates,
filepath.Join(filepath.Dir(shim.Path()), path),
)
}
for _, candidate := range candidates {
file, ok := s.File(candidate)
if !ok || file.IsDirectory() {
continue
}
installation.AddFile(file.Path(), RoleLibrary)
break
}
}
}
func forgeArtifact(
s *scan,
versionDir string,
name string,
) (*artifact, bool) {
file, ok := s.File(filepath.Join(versionDir, name))
if !ok || file.IsDirectory() {
return nil, false
}
return file, true
}
// forgeArtifactReadable reports whether the artifact is a readable archive.
func forgeArtifactReadable(file *artifact) bool {
_, err := file.Archive()
return err == nil
}
func parseArchiveClassPathFromArtifact(file *artifact) []string {
archive, err := file.Archive()
if err != nil {
return nil
}
return parseArchiveClassPath(archive)
}
func forgeIdentity(
gameVersion versionpkg.Version,
forgeVersion versionpkg.Version,
) Identity {
return Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemForge,
Name: "forge",
Version: forgeVersion,
},
Components: []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemForge,
Name: "forge",
Version: forgeVersion,
},
{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: gameVersion,
},
},
}
}
package discovery
import (
"archive/zip"
"strings"
versionpkg "github.com/mclucy/lucy/version"
)
// loaderArgsLaunchValid reports whether a generated argument sidecar is a
// positively identified launch target for this loader layout: it names the
// same loader and Minecraft versions and either a server launch target or a
// server main class. NeoForge 26.2 dropped --launchTarget in favor of
// net.neoforged.fml.startup.Server.
func loaderArgsLaunchValid(
file *artifact,
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
) bool {
if file == nil || !hasConcreteVersion(gameVersion) {
return false
}
data, err := file.Read()
if err != nil {
return false
}
argsLoader, argsGame := parseLoaderArgs(data)
if hasConcreteVersion(argsLoader) && argsLoader != loaderVersion {
return false
}
if !hasConcreteVersion(argsGame) || argsGame != gameVersion {
return false
}
target := strings.ToLower(parseLaunchTarget(data))
if target != "" && strings.Contains(target, "server") {
return true
}
mainClass := strings.ToLower(parseLaunchMainClass(data))
return mainClass != "" && strings.Contains(mainClass, "server")
}
// parseLaunchMainClass returns the first fully qualified Java class token in a
// generated argument sidecar. Flags, JVM properties, and classpath entries are
// not class tokens.
func parseLaunchMainClass(data []byte) string {
for line := range strings.SplitSeq(string(data), "\n") {
candidate := strings.TrimSpace(line)
if candidate == "" || strings.HasPrefix(candidate, "-") ||
strings.ContainsAny(candidate, " \t=/:") {
continue
}
if isJavaClassName(candidate) {
return candidate
}
}
return ""
}
func isJavaClassName(value string) bool {
parts := strings.Split(value, ".")
if len(parts) < 2 {
return false
}
for _, part := range parts {
if part == "" {
return false
}
for index, r := range part {
switch {
case r == '_' || r == '$':
case r >= 'a' && r <= 'z':
case r >= 'A' && r <= 'Z':
case index > 0 && r >= '0' && r <= '9':
default:
return false
}
}
}
last := parts[len(parts)-1]
return last[0] >= 'A' && last[0] <= 'Z'
}
// artifactHasLaunchMainClass reports whether a jar declares a Main-Class and
// is therefore independently java -jar runnable.
func artifactHasLaunchMainClass(file *artifact) bool {
if file == nil {
return false
}
archive, err := file.Archive()
if err != nil {
return false
}
mainClass, ok := readArchiveManifestMainClass(archive)
return ok && strings.TrimSpace(mainClass) != ""
}
// forgeProductContent reports whether a jar carries positive Forge content.
// Legacy universal jars have no implementation versions in their manifest;
// they identify themselves through Tweak-Class, a Forge main class, or FML
// classes.
func forgeProductContent(zipReader *zip.Reader) bool {
switch {
case archiveManifestContains(zipReader, "FML-System-Mods: forge"):
return true
case archiveManifestContains(zipReader, "Tweak-Class: net.minecraftforge."):
return true
case archiveManifestContains(zipReader, "Main-Class: net.minecraftforge."):
return true
case archiveContains(
zipReader,
"net/minecraftforge/fml/relauncher/ServerLaunchWrapper.class",
):
return true
case archiveContains(
zipReader,
"net/minecraftforge/fml/common/launcher/FMLTweaker.class",
):
return true
default:
return false
}
}
// verifyForgeUniversalArtifact validates a universal jar by the Forge and
// Minecraft versions recorded in its manifest. The directory name supplies
// the Minecraft version when the manifest does not repeat it. Legacy
// universals without implementation versions are accepted only with positive
// Forge content in the archive.
func verifyForgeUniversalArtifact(
file *artifact,
forgeVersion versionpkg.Version,
gameVersion versionpkg.Version,
) bool {
archive, err := file.Archive()
if err != nil {
return false
}
if installerArtifact(archive) {
return false
}
manifestForge, manifestGame := parseForgeManifest(archive)
if hasConcreteVersion(manifestForge) {
if manifestForge != forgeVersion {
return false
}
if !hasConcreteVersion(manifestGame) {
manifestGame = gameVersion
}
return manifestGame == gameVersion
}
return forgeProductContent(archive)
}
// verifyForgeServerArtifact reports whether a server jar is positively a
// Forge artifact for this layout. A vanilla server jar placed in a
// Maven-shaped Forge directory must not become a Forge runtime merely because
// its name and Main-Class are present.
func verifyForgeServerArtifact(
file *artifact,
forgeVersion versionpkg.Version,
gameVersion versionpkg.Version,
) bool {
archive, err := file.Archive()
if err != nil {
return false
}
if installerArtifact(archive) {
return false
}
manifestForge, manifestGame := parseForgeManifest(archive)
if hasConcreteVersion(manifestForge) {
if manifestForge != forgeVersion {
return false
}
if hasConcreteVersion(manifestGame) && manifestGame != gameVersion {
return false
}
return true
}
return forgeProductContent(archive)
}
// installerArtifact reports whether a jar is a loader installer rather than
// a runtime artifact.
func installerArtifact(zipReader *zip.Reader) bool {
if archiveContains(zipReader, "install_profile.json") {
return true
}
data, ok, err := readArchiveEntry(zipReader, "version.json")
if err != nil || !ok {
return false
}
_, guarded, err := mojangVersionFromJSON(data)
return err == nil && guarded
}
// archiveContains reports whether a ZIP archive has an entry with this exact
// name.
func archiveContains(zipReader *zip.Reader, name string) bool {
for _, entry := range zipReader.File {
if entry.Name == name {
return true
}
}
return false
}
// archiveManifestContains reports whether the jar manifest contains needle.
func archiveManifestContains(zipReader *zip.Reader, needle string) bool {
data, ok, err := readArchiveEntry(zipReader, "META-INF/MANIFEST.MF")
return err == nil && ok && strings.Contains(string(data), needle)
}
// verifyForgeShimArtifact requires the two bootstrap descriptors that make a
// Forge shim a launch target rather than an arbitrary jar named *-shim.jar.
func verifyForgeShimArtifact(file *artifact) bool {
archive, err := file.Archive()
if err != nil {
return false
}
hasProperties := false
hasList := false
for _, entry := range archive.File {
switch entry.Name {
case "bootstrap-shim.properties":
hasProperties = true
case "bootstrap-shim.list":
hasList = true
}
}
return hasProperties && hasList
}
package discovery
import (
"archive/zip"
"bufio"
"path/filepath"
"regexp"
"strconv"
"strings"
versionpkg "github.com/mclucy/lucy/version"
)
var forgeRuntimeVersionDirPattern = regexp.MustCompile(
`^(\d+\.\d+(?:\.\d+)?)-(\d+(?:\.\d+)+)$`,
)
var forgeJarNameVersionPattern = regexp.MustCompile(
`^forge-(\d+\.\d+(?:\.\d+)?)-(\d+(?:\.\d+)+)(?:-[a-z]+)?\.jar$`,
)
// parseForgeManifest reads the Forge and Minecraft versions from the
// per-section attributes of a Forge universal jar manifest. The manifest may
// list the implementation version before the implementation title, so the
// parser keeps one pending version and adopts it when the Forge section
// starts.
func parseForgeManifest(
zipReader *zip.Reader,
) (forgeVersion versionpkg.Version, gameVersion versionpkg.Version) {
for _, f := range zipReader.File {
if f.Name != "META-INF/MANIFEST.MF" {
continue
}
r, err := f.Open()
if err != nil {
continue
}
var inForgeSection bool
var pendingImplVersion string
var specTitle string
minecraftGameVersion := versionpkg.Unknown
var gameVersionCandidates []versionpkg.Version
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
switch {
case strings.HasPrefix(line, "Name: "):
inForgeSection = false
specTitle = ""
case strings.HasPrefix(line, "Specification-Title: "):
if after, found := strings.CutPrefix(
line,
"Specification-Title: ",
); found {
specTitle = strings.TrimSpace(after)
}
case line == "Implementation-Title: net.minecraftforge":
inForgeSection = true
if pendingImplVersion != "" {
forgeVersion = versionpkg.Version(pendingImplVersion)
pendingImplVersion = ""
}
case strings.HasPrefix(line, "Implementation-Version: "):
if after, found := strings.CutPrefix(
line,
"Implementation-Version: ",
); found {
switch {
case inForgeSection:
forgeVersion = versionpkg.Version(after)
case !inForgeSection && forgeVersion == "" && pendingImplVersion == "":
pendingImplVersion = after
}
}
case strings.HasPrefix(line, "Specification-Version: "):
if after, found := strings.CutPrefix(
line,
"Specification-Version: ",
); found && isMinecraftReleaseVersion(after) {
candidate := versionpkg.Version(after)
gameVersionCandidates = append(
gameVersionCandidates,
candidate,
)
if specTitle == "Minecraft" {
minecraftGameVersion = candidate
}
}
}
}
_ = r.Close()
switch {
case minecraftGameVersion != versionpkg.Unknown:
gameVersion = minecraftGameVersion
default:
// Without a Minecraft specification section, a manifest may
// still repeat the game version. Skip the loader's own
// specification, which shares the Forge version prefix.
for index := len(gameVersionCandidates) - 1; index >= 0; index-- {
candidate := gameVersionCandidates[index]
if versionSharesPrefix(candidate, forgeVersion) {
continue
}
gameVersion = candidate
break
}
}
break
}
return forgeVersion, gameVersion
}
// isMinecraftReleaseVersion reports whether value is a positively identified
// Minecraft release id. Minecraft uses dotted numeric ids: the classic 1.x
// line and the year-based 26.x line. Arbitrary plugin versions such as 2.5.0
// are not release ids.
func isMinecraftReleaseVersion(value string) bool {
parts := strings.Split(value, ".")
if len(parts) < 2 {
return false
}
for _, part := range parts {
if part == "" {
return false
}
for _, r := range part {
if r < '0' || r > '9' {
return false
}
}
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return false
}
return major == 1 || major >= 26
}
func parseForgeVersionTupleFromPath(
filePath string,
) (gameVersion versionpkg.Version, forgeVersion versionpkg.Version, ok bool) {
parts := strings.Split(filepath.ToSlash(filePath), "/")
for i := 0; i < len(parts)-1; i++ {
if parts[i] != "forge" {
continue
}
match := forgeRuntimeVersionDirPattern.FindStringSubmatch(parts[i+1])
if match == nil {
continue
}
return versionpkg.Version(match[1]), versionpkg.Version(match[2]), true
}
if match := forgeJarNameVersionPattern.FindStringSubmatch(filepath.Base(filePath)); match != nil {
return versionpkg.Version(match[1]), versionpkg.Version(match[2]), true
}
return versionpkg.Unknown, versionpkg.Unknown, false
}
// versionSharesPrefix reports whether candidate is the loader version or one
// of its prefixes. Forge manifests repeat the loader specification version,
// which must not be mistaken for a Minecraft release id.
func versionSharesPrefix(candidate versionpkg.Version, loader versionpkg.Version) bool {
if candidate == "" || loader == "" {
return false
}
return candidate == loader ||
strings.HasPrefix(string(loader), string(candidate)+".")
}
func hasConcreteVersion(version versionpkg.Version) bool {
return version != "" && !version.IsInvalid() && !version.CanInfer()
}
// parseLoaderArgs extracts the loader and Minecraft versions from the
// generated Forge/NeoForge argument sidecar. Both `--fml.forgeVersion` and
// `--fml.neoForgeVersion` are accepted because the installer uses the same
// argument shape for both products.
func parseLoaderArgs(data []byte) (
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
) {
loaderVersion = versionpkg.Unknown
gameVersion = versionpkg.Unknown
for line := range strings.SplitSeq(string(data), "\n") {
fields := strings.Fields(strings.TrimSpace(line))
for i := 0; i+1 < len(fields); i++ {
switch fields[i] {
case "--fml.forgeVersion", "--fml.neoForgeVersion":
loaderVersion = versionpkg.Version(fields[i+1])
case "--fml.mcVersion":
gameVersion = versionpkg.Version(fields[i+1])
}
}
}
return loaderVersion, gameVersion
}
// parseLaunchTarget returns the value of --launchTarget in a generated loader
// argument sidecar. Server layouts name a server target; the client installer
// spec names a client target.
func parseLaunchTarget(data []byte) string {
for line := range strings.SplitSeq(string(data), "\n") {
fields := strings.Fields(strings.TrimSpace(line))
for i := 0; i+1 < len(fields); i++ {
if fields[i] == "--launchTarget" {
return fields[i+1]
}
}
}
return ""
}
package discovery
import (
"bufio"
"path/filepath"
"regexp"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
versionpkg "github.com/mclucy/lucy/version"
)
const geyserStandaloneBootstrapClass = "org/geysermc/geyser/platform/standalone/GeyserStandaloneBootstrap.class"
// discoverGeyser recognizes the standalone Geyser proxy jar. The embedded
// bootstrap class is a hard gate: a manifest alone is not enough.
func discoverGeyser(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
installation, err := inspectGeyserInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
if installation != nil {
installations = append(installations, *installation)
}
}
return installations, findings
}
// Sources:
// - https://geysermc.org/wiki/geyser/setup/self/standalone
// - https://geysermc.org/wiki/geyser/setup/self/proxy-servers
// - https://geysermc.org/wiki/geyser/faq/
func inspectGeyserInstallation(
s *scan,
primary *artifact,
) (*Installation, error) {
manifest, ok, err := readProductEntry(s, primary, bukkitManifestPath)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
signals := parseGeyserStandaloneManifest(manifest)
if !signals.valid() {
return nil, nil
}
hasStandaloneBootstrap, err := productEntryExists(
s,
primary,
geyserStandaloneBootstrapClass,
)
if err != nil {
return nil, err
}
if !hasStandaloneBootstrap {
return nil, nil
}
version := signals.version
if !hasConcreteVersion(version) {
version = parseGeyserStandaloneVersionFromPath(primary.Path())
}
identity := Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemUnspecified,
Name: input.ToProjectName("geyser"),
Version: version,
},
}
installation := NewInstallation(identity, primary.Path())
return &installation, nil
}
type geyserStandaloneManifestSignals struct {
mainClass string
version versionpkg.Version
}
func (s geyserStandaloneManifestSignals) valid() bool {
return s.mainClass == "org.geysermc.geyser.platform.standalone.GeyserStandaloneBootstrap"
}
func parseGeyserStandaloneManifest(data []byte) geyserStandaloneManifestSignals {
var signals geyserStandaloneManifestSignals
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(line, "Main-Class: "):
signals.mainClass = strings.TrimSpace(
strings.TrimPrefix(
line,
"Main-Class: ",
),
)
case strings.HasPrefix(line, "Implementation-Version: "):
signals.version = versionpkg.Version(
strings.TrimSpace(
strings.TrimPrefix(
line,
"Implementation-Version: ",
),
),
)
}
}
return signals
}
var geyserStandaloneVersionPattern = regexp.MustCompile(
`geyser-standalone-(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)\.jar`,
)
func parseGeyserStandaloneVersionFromPath(filePath string) versionpkg.Version {
match := geyserStandaloneVersionPattern.FindStringSubmatch(
strings.ToLower(filepath.Base(filePath)),
)
if match == nil {
return versionpkg.Unknown
}
return versionpkg.Version(match[1])
}
package discovery
import (
"errors"
"fmt"
"iter"
"path/filepath"
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// FileRole describes how a member participates in an installation.
type FileRole string
const (
RoleUnknown FileRole = ""
RoleEntryPoint FileRole = "entry_point"
RolePayload FileRole = "payload"
RoleLibrary FileRole = "library"
RoleConfiguration FileRole = "configuration"
)
// Ownership describes whether a member is tracked by the local installation
// receipt and whether its content still matches the recorded hash.
type Ownership string
const (
OwnershipUnknown Ownership = ""
OwnershipUnmanaged Ownership = "unmanaged"
OwnershipManaged Ownership = "managed"
OwnershipModified Ownership = "modified"
OwnershipUnreadable Ownership = "unreadable"
)
// File is one member of an installation. It is data, not an open handle.
// Path is absolute and canonical.
type File struct {
Path string
Role FileRole
Ownership Ownership
}
// Identity is the observed runtime identity of an installation. Primary is a
// value; Components carry the additional runtime components that detectors
// proved. Normalize canonicalizes both in place before any comparison.
type Identity struct {
Primary catalog.VersionedRef
Components []catalog.VersionedRef
}
// Normalize canonicalizes names and ecosystems, removes exact duplicates, and
// upgrades an unknown component version to a concrete one when both occur for
// the same base identity. Conflicting concrete versions for one base identity
// are kept and reported as an error so the caller can emit a typed diagnostic;
// they are never silently erased.
func (i *Identity) Normalize() error {
if i == nil {
return errors.New("discovery: nil identity")
}
var problems []error
primary, ok := canonicalPrimary(i.Primary)
if !ok {
problems = append(problems, fmt.Errorf(
"invalid primary runtime %q",
i.Primary.StringQualified(),
))
} else {
i.Primary = primary
}
primaryKey := ""
if ok {
primaryKey = componentKey(i.Primary)
}
components := make([]catalog.VersionedRef, 0, len(i.Components))
indexes := make(map[string]int, len(i.Components))
seen := make(map[string]bool, len(i.Components))
for _, raw := range i.Components {
component, ok := canonicalComponent(raw)
if !ok {
problems = append(problems, fmt.Errorf(
"invalid runtime component %q",
raw.StringQualified(),
))
continue
}
if primaryKey != "" && componentKey(component) == primaryKey &&
!concreteVersion(i.Primary.Version) &&
concreteVersion(component.Version) {
// The component carries exact evidence for the same base
// identity; project it onto the primary value.
i.Primary.Version = component.Version
}
key := componentKey(component)
full := key + "@" + component.Version.String()
if seen[full] {
continue
}
seen[full] = true
index, exists := indexes[key]
if !exists {
indexes[key] = len(components)
components = append(components, component)
continue
}
existing := components[index]
switch {
case existing.Version == component.Version:
continue
case !concreteVersion(existing.Version) && concreteVersion(component.Version):
components[index] = component
case concreteVersion(existing.Version) && !concreteVersion(component.Version):
continue
default:
// Both versions are concrete and different. Keep both so the
// contradiction remains observable.
components = append(components, component)
}
}
slices.SortFunc(components, compareComponent)
i.Components = components
if ok && i.Primary.Ecosystem == catalog.EcosystemMinecraft {
i.Components = ensureMinecraftComponent(i.Components, i.Primary)
}
if err := i.contradiction(); err != nil {
problems = append(problems, err)
}
return errors.Join(problems...)
}
// IsValid reports whether the identity has a canonical primary and only
// canonical, non-contradictory components. Unknown versions remain valid.
func (i Identity) IsValid() bool {
primary, ok := canonicalPrimary(i.Primary)
if !ok || primary != i.Primary {
return false
}
if i.contradiction() != nil {
return false
}
for _, component := range i.Components {
canonical, ok := canonicalComponent(component)
if !ok || canonical != component {
return false
}
}
return true
}
// IsConcrete reports whether every version the identity carries is an exact
// observed version. Only concrete identities may prove equality for merging.
func (i Identity) IsConcrete() bool {
if !i.IsValid() || !concreteVersion(i.Primary.Version) {
return false
}
for _, component := range i.Components {
if redundantPrimaryComponent(i.Primary, component) {
continue
}
if !concreteVersion(component.Version) {
return false
}
}
return true
}
// Equal compares the canonical complete structure of two identities. A
// component that merely repeats the primary identity adds no structure and is
// ignored.
func (i Identity) Equal(other Identity) bool {
return identityKey(i) == identityKey(other)
}
// Product returns the executable server product named by the primary runtime.
func (i Identity) Product() server.Product {
if i.Primary.Name == "" {
return server.ProductUnknown
}
match, ok := server.NormalizeProduct(i.Primary)
if !ok {
return server.ProductUnknown
}
return match.Product
}
// MinecraftVersion returns the concrete Minecraft version carried by the
// identity, or version.Unknown when no single concrete version is known.
func (i Identity) MinecraftVersion() versionpkg.Version {
if i.contradictsKey(componentKey(catalog.VersionedRef{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
})) {
return versionpkg.Unknown
}
for _, component := range i.Components {
if component.Ecosystem != catalog.EcosystemMinecraft ||
component.Name != "minecraft" {
continue
}
if concreteVersion(component.Version) {
return component.Version
}
}
if i.Primary.Ecosystem == catalog.EcosystemMinecraft &&
concreteVersion(i.Primary.Version) {
return i.Primary.Version
}
return versionpkg.Unknown
}
// Ecosystem reports the mod-loader ecosystem of the identity. It falls back to
// Minecraft when no loader component applies.
func (i Identity) Ecosystem() catalog.Ecosystem {
if !i.IsValid() {
return catalog.EcosystemUnspecified
}
ecosystem := server.LoaderEcosystem(i.Primary.Name.String())
if ecosystem != catalog.EcosystemUnspecified &&
(i.Primary.Ecosystem == ecosystem ||
i.Primary.Ecosystem == catalog.EcosystemUnspecified) {
return ecosystem
}
for _, component := range i.Components {
if _, ok := server.LoaderComponentName(
component.Ecosystem,
component.Name.String(),
); ok {
return component.Ecosystem
}
}
return catalog.EcosystemMinecraft
}
func (i Identity) canonical() Identity {
copied := Identity{
Primary: i.Primary,
Components: slices.Clone(i.Components),
}
_ = copied.Normalize()
return copied
}
func (i Identity) contradiction() error {
versions := make(map[string]map[versionpkg.Version]struct{})
record := func(ref catalog.VersionedRef) {
if !concreteVersion(ref.Version) {
return
}
key := componentKey(ref)
if versions[key] == nil {
versions[key] = make(map[versionpkg.Version]struct{})
}
versions[key][ref.Version] = struct{}{}
}
if primary, ok := canonicalPrimary(i.Primary); ok {
record(primary)
}
for _, component := range i.Components {
record(component)
}
var problems []error
keys := make([]string, 0, len(versions))
for key := range versions {
keys = append(keys, key)
}
slices.Sort(keys)
for _, key := range keys {
found := versions[key]
if len(found) <= 1 {
continue
}
concrete := make([]versionpkg.Version, 0, len(found))
for value := range found {
concrete = append(concrete, value)
}
slices.Sort(concrete)
problems = append(problems, fmt.Errorf(
"conflicting concrete versions for %s: %s",
key,
strings.Join(versionStrings(concrete), " and "),
))
}
return errors.Join(problems...)
}
func (i Identity) contradictsKey(key string) bool {
versions := make(map[versionpkg.Version]struct{})
if primary, ok := canonicalPrimary(i.Primary); ok &&
componentKey(primary) == key &&
concreteVersion(primary.Version) {
versions[primary.Version] = struct{}{}
}
for _, component := range i.Components {
if componentKey(component) == key && concreteVersion(component.Version) {
versions[component.Version] = struct{}{}
}
}
return len(versions) > 1
}
func canonicalPrimary(ref catalog.VersionedRef) (catalog.VersionedRef, bool) {
name := strings.ToLower(strings.TrimSpace(ref.Name.String()))
if ref.Version == "" {
ref.Version = versionpkg.Unknown
}
if name == "" || !ref.Ecosystem.Valid() ||
(!concreteVersion(ref.Version) && ref.Version != versionpkg.Unknown) {
return catalog.VersionedRef{}, false
}
ref.Provider = catalog.ProviderUnspecified
ref.Name = catalog.Name(name)
return ref, true
}
func canonicalComponent(ref catalog.VersionedRef) (catalog.VersionedRef, bool) {
name := strings.ToLower(strings.TrimSpace(ref.Name.String()))
if ref.Version == "" {
ref.Version = versionpkg.Unknown
}
if name == "" || (!concreteVersion(ref.Version) && ref.Version != versionpkg.Unknown) {
return catalog.VersionedRef{}, false
}
component := catalog.Name(name)
switch {
case ref.Ecosystem == catalog.EcosystemMinecraft && name == "minecraft":
// The game is not a loader component.
case ref.Ecosystem == catalog.EcosystemFabric && name == "fabric-api":
// Fabric API is a mod that every Fabric runtime carries.
default:
loader, ok := server.LoaderComponentName(ref.Ecosystem, name)
if !ok {
return catalog.VersionedRef{}, false
}
component = loader
}
ref.Provider = catalog.ProviderUnspecified
ref.Name = component
return ref, true
}
func componentKey(ref catalog.VersionedRef) string {
return ref.Ecosystem.String() + "/" + ref.Name.String()
}
func ensureMinecraftComponent(
components []catalog.VersionedRef,
primary catalog.VersionedRef,
) []catalog.VersionedRef {
for index := range components {
if components[index].Ecosystem != catalog.EcosystemMinecraft ||
components[index].Name != "minecraft" {
continue
}
if !concreteVersion(components[index].Version) &&
concreteVersion(primary.Version) {
components[index].Version = primary.Version
slices.SortFunc(components, compareComponent)
}
return components
}
return append(components, catalog.VersionedRef{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: primary.Version,
})
}
func compareComponent(left, right catalog.VersionedRef) int {
if result := strings.Compare(left.Ecosystem.String(), right.Ecosystem.String()); result != 0 {
return result
}
if result := strings.Compare(left.Name.String(), right.Name.String()); result != 0 {
return result
}
return strings.Compare(left.Version.String(), right.Version.String())
}
func versionStrings(versions []versionpkg.Version) []string {
out := make([]string, 0, len(versions))
for _, value := range versions {
out = append(out, value.String())
}
return out
}
func concreteVersion(value versionpkg.Version) bool {
switch value {
case "", versionpkg.None, versionpkg.Unknown, versionpkg.Any,
versionpkg.Stable, versionpkg.Beta:
return false
default:
return true
}
}
// Installation is one observed runtime together with every member the
// recognizer proved belongs to it. All entry points, payloads, libraries, and
// configuration sidecars live in the single Files collection. CorePath names
// the server core artifact when the recognizer proved one; it is evidence for
// identifying the installed build, not a selection target.
type Installation struct {
Identity Identity
CorePath string
Files []File
}
// NewInstallation creates an unmanaged entry-point installation. Central
// reconciliation normalizes the identity.
func NewInstallation(identity Identity, entryPoint string) Installation {
installation := Installation{Identity: identity}
if entryPoint != "" {
installation.AddFile(entryPoint, RoleEntryPoint)
}
return installation
}
// SetCore records the server core artifact the recognizer proved. The same
// file may also be an entry-point member.
func (i *Installation) SetCore(path string) {
if i == nil || path == "" {
return
}
i.CorePath = filepath.Clean(path)
}
// AddFile unions a member by path. A dependency member upgrades to an entry
// point when the same identity explicitly launches it; an existing entry point
// never downgrades.
func (i *Installation) AddFile(path string, role FileRole) {
i.addFile(File{
Path: path,
Role: role,
Ownership: OwnershipUnmanaged,
})
}
// EntryPoints iterates the entry-point members of the single Files collection.
func (i *Installation) EntryPoints() iter.Seq[*File] {
return func(yield func(*File) bool) {
if i == nil {
return
}
for index := range i.Files {
if i.Files[index].Role != RoleEntryPoint {
continue
}
if !yield(&i.Files[index]) {
return
}
}
}
}
func (i *Installation) addFile(file File) {
if i == nil || file.Path == "" {
return
}
file.Path = filepath.Clean(file.Path)
if file.Ownership == OwnershipUnknown {
file.Ownership = OwnershipUnmanaged
}
for index := range i.Files {
existing := &i.Files[index]
if existing.Path != file.Path {
continue
}
if file.Role == RoleEntryPoint {
existing.Role = RoleEntryPoint
}
existing.Ownership = strongerOwnership(existing.Ownership, file.Ownership)
return
}
i.Files = append(i.Files, file)
}
func (i *Installation) removeFile(path string) {
if i == nil {
return
}
path = filepath.Clean(path)
files := i.Files[:0]
for _, file := range i.Files {
if file.Path == path {
continue
}
files = append(files, file)
}
clear(i.Files[len(files):])
i.Files = files
}
func strongerOwnership(left, right Ownership) Ownership {
rank := func(value Ownership) int {
switch value {
case OwnershipManaged:
return 4
case OwnershipModified:
return 3
case OwnershipUnreadable:
return 2
case OwnershipUnmanaged:
return 1
default:
return 0
}
}
if rank(left) >= rank(right) {
return left
}
return right
}
// identityKey is the stable canonical key used for ordering and grouping.
func identityKey(identity Identity) string {
canonical := identity.canonical()
primaryKey := componentKey(canonical.Primary)
parts := make([]string, 0, 1+len(canonical.Components))
parts = append(parts, primaryKey+"@"+canonical.Primary.Version.String())
for _, component := range canonical.Components {
if redundantPrimaryComponent(canonical.Primary, component) {
continue
}
parts = append(parts, componentKey(component)+"@"+component.Version.String())
}
return strings.Join(parts, "|")
}
func redundantPrimaryComponent(
primary catalog.VersionedRef,
component catalog.VersionedRef,
) bool {
if componentKey(primary) != componentKey(component) {
return false
}
if component.Version == primary.Version {
return true
}
return !concreteVersion(component.Version) && concreteVersion(primary.Version)
}
func compareIdentities(left, right Identity) int {
return strings.Compare(identityKey(left), identityKey(right))
}
package discovery
import (
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
var neoforgeVersionDirPattern = regexp.MustCompile(`^(\d+)\.(\d+)(?:\.\d+)*(?:-[a-zA-Z0-9.]+)*$`)
// parseModLoaderVersionTuple derives the Minecraft and loader versions from a
// Maven version directory name. NeoForge used to drop the Minecraft "1."
// prefix (20.2.x -> 1.20.2, 21.1.x -> 1.21.1); the year scheme keeps the
// Minecraft triple and appends a build (26.2.0.67 -> 26.2). Only the
// directory name is considered; content evidence refines the result where
// the loader publishes it.
func parseModLoaderVersionTuple(
versionDir string,
platform catalog.Ecosystem,
) (gameVersion, loaderVersion versionpkg.Version, ok bool) {
name := filepath.Base(versionDir)
switch platform {
case catalog.EcosystemForge:
match := forgeRuntimeVersionDirPattern.FindStringSubmatch(name)
if match == nil {
return versionpkg.Unknown, versionpkg.Unknown, false
}
return versionpkg.Version(match[1]), versionpkg.Version(match[2]), true
case catalog.EcosystemNeoForge:
if neoforgeVersionDirPattern.FindStringSubmatch(name) == nil {
return versionpkg.Unknown, versionpkg.Unknown, false
}
gameVersion = neoforgeGameVersionFromTuple(name)
if gameVersion == versionpkg.Unknown {
return versionpkg.Unknown, versionpkg.Unknown, false
}
return gameVersion, versionpkg.Version(name), true
default:
return versionpkg.Unknown, versionpkg.Unknown, false
}
}
// neoforgeGameVersionFromTuple maps a NeoForge loader version to the
// Minecraft release it targets. Classic lines drop the leading 1; year-scheme
// lines keep the Minecraft triple and add a build segment, where a zero patch
// is not part of the release id (26.2.0.67 -> 26.2, 26.2.1.5 -> 26.2.1).
func neoforgeGameVersionFromTuple(name string) versionpkg.Version {
segments := strings.Split(strings.SplitN(name, "-", 2)[0], ".")
if len(segments) < 2 {
return versionpkg.Unknown
}
major, err := strconv.Atoi(segments[0])
if err != nil {
return versionpkg.Unknown
}
if major < 26 {
return versionpkg.Version("1." + segments[0] + "." + segments[1])
}
gameVersion := segments[0] + "." + segments[1]
if len(segments) >= 4 && segments[2] != "0" {
gameVersion += "." + segments[2]
}
return versionpkg.Version(gameVersion)
}
package discovery
import (
"archive/zip"
"encoding/json/v2"
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
const (
neoForgeLibraryRoot = "libraries/net/neoforged/neoforge"
neoForgePatchedServerRoot = "libraries/net/neoforged/minecraft-server-patched"
neoForgeVersionPropertiesPath = "net/neoforged/neoforge/common/version.properties"
neoForgeModsTomlPath = "META-INF/neoforge.mods.toml"
)
// discoverNeoForge recognizes installed NeoForge servers under the NeoForge
// Maven library directory. The installer only provisions the layout; the
// runtime identity and its members are proven from local archives and the
// generated argument sidecars. The universal jar is the entry point when no
// server jar is present; otherwise it is a runtime library.
func discoverNeoForge(s *scan) ([]Installation, []Finding) {
if s == nil {
return nil, nil
}
root := filepath.Join(s.root, filepath.FromSlash(neoForgeLibraryRoot))
entries, err := s.ReadDir(root)
if err != nil {
return nil, nil
}
installations := make([]Installation, 0)
for _, entry := range entries {
if !entry.IsDir() {
continue
}
installation, ok := neoForgeInstallation(
s,
filepath.Join(root, entry.Name()),
)
if ok {
installations = append(installations, installation)
}
}
return installations, nil
}
// neoForgeInstallation builds one installation from a
// libraries/net/neoforged/neoforge/<version>/ directory.
func neoForgeInstallation(s *scan, versionDir string) (Installation, bool) {
loaderVersion := versionpkg.Version(filepath.Base(versionDir))
tupleGameVersion, _, ok := parseModLoaderVersionTuple(
versionDir,
catalog.EcosystemNeoForge,
)
if !ok {
return Installation{}, false
}
universal, hasUniversal := neoForgeArtifact(
s,
versionDir,
"neoforge-"+string(loaderVersion)+"-universal.jar",
)
server, hasServer := neoForgeArtifact(
s,
versionDir,
"neoforge-"+string(loaderVersion)+"-server.jar",
)
unixArgs, hasUnixArgs := neoForgeArtifact(s, versionDir, "unix_args.txt")
winArgs, hasWinArgs := neoForgeArtifact(s, versionDir, "win_args.txt")
universalGameVersion, universalValid := versionpkg.Unknown, false
if hasUniversal {
universalGameVersion, universalValid = neoForgeUniversalEvidence(
universal,
loaderVersion,
)
}
serverGameVersion, serverReadable := versionpkg.Unknown, false
if hasServer {
serverGameVersion, serverReadable = neoForgeServerEvidence(server)
}
patched, hasPatched := neoForgePatchedServerArtifact(s, loaderVersion)
patchedGameVersion, patchedReadable := versionpkg.Unknown, false
if hasPatched {
patchedGameVersion, patchedReadable = neoForgeServerEvidence(patched)
}
gameVersion := tupleGameVersion
switch {
case universalValid && hasConcreteVersion(universalGameVersion):
gameVersion = universalGameVersion
default:
if argsGameVersion := neoForgeArgsGameVersion(
s,
versionDir,
loaderVersion,
hasUnixArgs,
hasWinArgs,
); hasConcreteVersion(argsGameVersion) {
gameVersion = argsGameVersion
} else if installerGameVersion := neoForgeInstallerGameVersion(
s,
loaderVersion,
); hasConcreteVersion(installerGameVersion) {
gameVersion = installerGameVersion
} else if hasConcreteVersion(serverGameVersion) {
gameVersion = serverGameVersion
} else if hasConcreteVersion(patchedGameVersion) {
gameVersion = patchedGameVersion
}
}
unixArgsValid := hasUnixArgs &&
loaderArgsLaunchValid(unixArgs, loaderVersion, gameVersion)
winArgsValid := hasWinArgs &&
loaderArgsLaunchValid(winArgs, loaderVersion, gameVersion)
serverRunnable := serverReadable && artifactHasLaunchMainClass(server) &&
verifyNeoForgeServerArtifact(server, loaderVersion)
universalRunnable := universalValid && artifactHasLaunchMainClass(universal)
entries := make([]*artifact, 0, 2)
switch {
case (unixArgsValid || winArgsValid) &&
(universalValid || serverReadable || patchedReadable):
// The generated argument sidecar is the Java launch target for an
// installed NeoForge server.
if unixArgsValid {
entries = append(entries, unixArgs)
}
if winArgsValid {
entries = append(entries, winArgs)
}
case serverRunnable:
entries = append(entries, server)
case universalRunnable:
// A universal jar is bootable only when it declares its own launch
// entry class; otherwise it is a runtime library.
entries = append(entries, universal)
default:
return Installation{}, false
}
installation := NewInstallation(
neoForgeIdentity(gameVersion, loaderVersion),
entries[0].Path(),
)
for _, entry := range entries[1:] {
installation.AddFile(entry.Path(), RoleEntryPoint)
}
if universalValid && !containsArtifact(entries, universal) {
installation.AddFile(universal.Path(), RoleLibrary)
}
if serverReadable && !containsArtifact(entries, server) {
installation.AddFile(server.Path(), RolePayload)
}
if patchedReadable && !containsArtifact(entries, patched) {
installation.AddFile(patched.Path(), RolePayload)
}
if hasUnixArgs && !unixArgsValid {
installation.AddFile(unixArgs.Path(), RoleConfiguration)
}
if hasWinArgs && !winArgsValid {
installation.AddFile(winArgs.Path(), RoleConfiguration)
}
addMatchingMinecraftPayload(s, &installation, gameVersion)
addMinecraftServerLibraryPayload(s, &installation, gameVersion)
return installation, true
}
func neoForgeArtifact(
s *scan,
versionDir string,
name string,
) (*artifact, bool) {
file, ok := s.File(filepath.Join(versionDir, name))
if !ok || file.IsDirectory() {
return nil, false
}
return file, true
}
// neoForgePatchedServerArtifact resolves the patched Minecraft server jar
// that current NeoForge installers place under their own Maven coordinate.
func neoForgePatchedServerArtifact(
s *scan,
loaderVersion versionpkg.Version,
) (*artifact, bool) {
version := string(loaderVersion)
path := filepath.Join(
s.root,
filepath.FromSlash(neoForgePatchedServerRoot),
version,
"minecraft-server-patched-"+version+".jar",
)
file, ok := s.File(path)
if !ok || file.IsDirectory() {
return nil, false
}
return file, true
}
// verifyNeoForgeServerArtifact reports whether a server jar is positively a
// NeoForge artifact for this layout. A vanilla server jar placed in a
// Maven-shaped NeoForge directory must not become a NeoForge runtime merely
// because its name and Main-Class are present.
func verifyNeoForgeServerArtifact(
file *artifact,
loaderVersion versionpkg.Version,
) bool {
archive, err := file.Archive()
if err != nil {
return false
}
if installerArtifact(archive) {
return false
}
if data, ok, err := readArchiveEntry(
archive,
neoForgeVersionPropertiesPath,
); err == nil && ok {
recorded := versionpkg.Version(
propertiesValue(data, "neoforge_version"),
)
return recorded == loaderVersion
}
if data, ok, err := readArchiveEntry(
archive,
neoForgeModsTomlPath,
); err == nil && ok {
if modVersion, found := parseTomlModVersion(data, "neoforge"); found {
return versionpkg.Version(modVersion) == loaderVersion
}
}
return archiveManifestContains(archive, "FML-System-Mods: neoforge")
}
// neoForgeUniversalEvidence validates a NeoForge universal jar and returns
// the Minecraft version the archive records locally, when it records one.
func neoForgeUniversalEvidence(
file *artifact,
loaderVersion versionpkg.Version,
) (versionpkg.Version, bool) {
archive, err := file.Archive()
if err != nil {
return versionpkg.Unknown, false
}
if installerArtifact(archive) {
return versionpkg.Unknown, false
}
if data, ok, err := readArchiveEntry(
archive,
neoForgeVersionPropertiesPath,
); err == nil && ok {
recordedLoader := versionpkg.Version(
propertiesValue(data, "neoforge_version"),
)
if recordedLoader != loaderVersion {
return versionpkg.Unknown, false
}
gameVersion := versionpkg.Version(
propertiesValue(data, "minecraft_version"),
)
if hasConcreteVersion(gameVersion) &&
isMinecraftReleaseVersion(string(gameVersion)) {
return gameVersion, true
}
return versionpkg.Unknown, true
}
if data, ok, err := readArchiveEntry(
archive,
neoForgeModsTomlPath,
); err == nil && ok {
if modVersion, found := parseTomlModVersion(data, "neoforge"); found {
if versionpkg.Version(modVersion) != loaderVersion {
return versionpkg.Unknown, false
}
return versionpkg.Unknown, true
}
}
ok, err := verifyNeoForgeUniversalManifest(archive, loaderVersion)
if err != nil || !ok {
return versionpkg.Unknown, false
}
return versionpkg.Unknown, true
}
// neoForgeServerEvidence validates a NeoForge server jar and reads the
// Minecraft version from its embedded version spec when present.
func neoForgeServerEvidence(
file *artifact,
) (versionpkg.Version, bool) {
archive, err := file.Archive()
if err != nil {
return versionpkg.Unknown, false
}
if installerArtifact(archive) {
return versionpkg.Unknown, false
}
data, ok, err := readArchiveEntry(archive, mojangVersionJSONEntry)
if err != nil || !ok {
return versionpkg.Unknown, true
}
gameVersion, guarded, err := mojangVersionFromJSON(data)
if err != nil || guarded || !hasConcreteVersion(gameVersion) ||
!isMinecraftReleaseVersion(string(gameVersion)) {
return versionpkg.Unknown, true
}
return gameVersion, true
}
// neoForgeArgsGameVersion reads the Minecraft version from the generated
// argument sidecar, which is authoritative for the installed layout.
func neoForgeArgsGameVersion(
s *scan,
versionDir string,
loaderVersion versionpkg.Version,
hasUnixArgs bool,
hasWinArgs bool,
) versionpkg.Version {
names := make([]string, 0, 2)
if hasUnixArgs {
names = append(names, "unix_args.txt")
}
if hasWinArgs {
names = append(names, "win_args.txt")
}
for _, name := range names {
file, ok := neoForgeArtifact(s, versionDir, name)
if !ok {
continue
}
data, err := file.Read()
if err != nil {
continue
}
argsLoader, argsGame := parseLoaderArgs(data)
if hasConcreteVersion(argsLoader) && argsLoader != loaderVersion {
continue
}
if hasConcreteVersion(argsGame) &&
isMinecraftReleaseVersion(string(argsGame)) {
return argsGame
}
}
return versionpkg.Unknown
}
// neoForgeInstallerGameVersion reads the Minecraft version from the installer
// metadata kept beside the installed layout. The installer is provisioning
// metadata, not a runtime; its version spec still names the exact game
// release the loader targets.
func neoForgeInstallerGameVersion(
s *scan,
loaderVersion versionpkg.Version,
) versionpkg.Version {
installerPath := filepath.Join(
s.root,
"neoforge-"+string(loaderVersion)+"-installer.jar",
)
installer, ok := s.File(installerPath)
if !ok || installer.IsDirectory() {
return versionpkg.Unknown
}
archive, err := installer.Archive()
if err != nil {
return versionpkg.Unknown
}
data, ok, err := readArchiveEntry(archive, "version.json")
if err != nil || !ok {
return versionpkg.Unknown
}
var spec struct {
InheritsFrom string `json:"inheritsFrom"`
Arguments struct {
Game []string `json:"game"`
} `json:"arguments"`
}
if err := json.Unmarshal(data, &spec); err != nil {
return versionpkg.Unknown
}
argsLoader, argsGame := parseLoaderArgs(
[]byte(strings.Join(spec.Arguments.Game, " ")),
)
if hasConcreteVersion(argsLoader) && argsLoader != loaderVersion {
return versionpkg.Unknown
}
if hasConcreteVersion(argsGame) &&
isMinecraftReleaseVersion(string(argsGame)) {
return argsGame
}
inherited := versionpkg.Version(strings.TrimSpace(spec.InheritsFrom))
if hasConcreteVersion(inherited) &&
isMinecraftReleaseVersion(string(inherited)) {
return inherited
}
return versionpkg.Unknown
}
// parseTomlModVersion returns the version declared by one [[mods]] block in a
// NeoForge mods TOML file.
func parseTomlModVersion(data []byte, modID string) (string, bool) {
currentID := ""
currentVersion := ""
flush := func() (string, bool) {
matched := currentID == modID && currentVersion != ""
version := currentVersion
currentID = ""
currentVersion = ""
return version, matched
}
for line := range strings.SplitSeq(string(data), "\n") {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "[[") {
if version, matched := flush(); matched {
return version, true
}
continue
}
key, value, found := strings.Cut(trimmed, "=")
if !found {
continue
}
switch strings.TrimSpace(key) {
case "modId":
currentID = strings.Trim(strings.TrimSpace(value), `"'`)
case "version":
currentVersion = strings.Trim(strings.TrimSpace(value), `"'`)
}
}
return flush()
}
// verifyNeoForgeUniversalManifest checks the two manifest markers NeoForge
// universal jars carry: the system-mod declaration and the loader classpath
// entry.
func verifyNeoForgeUniversalManifest(
reader *zip.Reader,
loaderVersion versionpkg.Version,
) (bool, error) {
manifest, ok, err := readArchiveEntry(reader, "META-INF/MANIFEST.MF")
if err != nil || !ok {
return false, err
}
if strings.Contains(string(manifest), "FML-System-Mods: neoforge") {
return true, nil
}
classpathEntry := "libraries/net/neoforged/neoforge/" +
string(loaderVersion) + "/"
return strings.Contains(string(manifest), classpathEntry), nil
}
func neoForgeIdentity(
gameVersion versionpkg.Version,
loaderVersion versionpkg.Version,
) Identity {
return Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemNeoForge,
Name: "neoforge",
Version: loaderVersion,
},
Components: []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemNeoForge,
Name: "neoforge",
Version: loaderVersion,
},
{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: gameVersion,
},
},
}
}
package discovery
import (
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"os"
"path/filepath"
"strings"
"github.com/mclucy/lucy/receipt"
)
// ObserveOwnership verifies the local installation receipt against every
// observed member using the shared receipt reader. Receipt paths are
// workspace-anchor-relative even when the server directory is nested. A
// recorded path establishes ownership granted by install commit or explicit
// adoption; ownership is never inferred through symlink aliases. Content
// hashes in the receipt serve as conflict baselines: matching content confirms
// an unmodified managed member (OwnershipManaged), while differing content
// identifies an owned member that was modified locally (OwnershipModified).
// Ownership remains independent of observed condition: content changes never
// erase ownership history, unrecorded paths remain OwnershipUnmanaged, and
// members that cannot be read are marked OwnershipUnreadable without losing
// their owned status. The method never writes files.
func (r *Result) ObserveOwnership(workspaceRoot string) {
if r == nil {
return
}
r.clearOwnershipDiagnostics()
for index := range r.Installations {
for fileIndex := range r.Installations[index].Files {
r.Installations[index].Files[fileIndex].Ownership = OwnershipUnmanaged
}
}
current, err := receipt.Read(workspaceRoot)
if errors.Is(err, os.ErrNotExist) {
return
}
if err != nil {
r.appendReceiptError(filepath.Join(workspaceRoot, receipt.Filename), err)
return
}
recorded := make(map[string]string, len(current.Entries))
for _, entry := range current.Entries {
relative := filepath.Clean(filepath.FromSlash(entry.Path))
if !filepath.IsLocal(relative) || relative == "." {
continue
}
recorded[relative] = normalizeHash(entry.SHA256)
}
absoluteRoot, err := filepath.Abs(workspaceRoot)
if err != nil {
r.appendReceiptError(workspaceRoot, err)
return
}
root, err := os.OpenRoot(absoluteRoot)
if err != nil {
r.appendReceiptError(absoluteRoot, err)
return
}
defer root.Close()
verified := make(map[string]verifiedHash, len(recorded))
for index := range r.Installations {
installation := &r.Installations[index]
for fileIndex := range installation.Files {
file := &installation.Files[fileIndex]
relative, ok := relativeWithinRoot(absoluteRoot, file.Path)
if !ok {
continue
}
expectedHash, listed := recorded[relative]
if !listed {
continue
}
observed, ok := verified[relative]
if !ok {
hash, hashErr := hashRootFile(root, relative)
observed = verifiedHash{hash: hash, err: hashErr}
verified[relative] = observed
}
if observed.err != nil {
file.Ownership = OwnershipUnreadable
r.Diagnostics = append(r.Diagnostics, Finding{
Kind: FindingOwnershipError,
Path: file.Path,
Identity: installation.Identity,
Cause: observed.err,
})
continue
}
if observed.hash != "" && observed.hash == expectedHash {
file.Ownership = OwnershipManaged
continue
}
file.Ownership = OwnershipModified
r.Diagnostics = append(r.Diagnostics, Finding{
Kind: FindingModifiedFile,
Path: file.Path,
Identity: installation.Identity,
})
}
}
}
type verifiedHash struct {
hash string
err error
}
// relativeWithinRoot resolves a member path against the workspace anchor even
// when one side uses a symlinked spelling. It returns a path relative to the
// anchor spelling first, then to the resolved anchor.
func relativeWithinRoot(root, path string) (string, bool) {
roots := []string{root}
if resolved, err := filepath.EvalSymlinks(root); err == nil && resolved != root {
roots = append(roots, resolved)
}
paths := []string{path}
if resolved, err := filepath.EvalSymlinks(path); err == nil && resolved != path {
paths = append(paths, resolved)
}
for _, candidateRoot := range roots {
for _, candidatePath := range paths {
rel, err := filepath.Rel(candidateRoot, candidatePath)
if err == nil && rel != "." && filepath.IsLocal(rel) {
return rel, true
}
}
}
return "", false
}
func hashRootFile(root *os.Root, relative string) (string, error) {
info, err := root.Stat(relative)
if err != nil {
return "", err
}
if !info.Mode().IsRegular() {
return "", errNotRegularFile
}
file, err := root.Open(relative)
if err != nil {
return "", err
}
hash := sha256.New()
_, copyErr := io.Copy(hash, file)
closeErr := file.Close()
if copyErr != nil {
return "", copyErr
}
if closeErr != nil {
return "", closeErr
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func normalizeHash(hash string) string {
return strings.ToLower(strings.TrimSpace(hash))
}
func (r *Result) appendReceiptError(path string, err error) {
if r == nil {
return
}
r.Diagnostics = append(r.Diagnostics, Finding{
Kind: FindingReceiptError,
Path: path,
Cause: err,
})
}
func (r *Result) clearOwnershipDiagnostics() {
if r == nil || len(r.Diagnostics) == 0 {
return
}
kept := r.Diagnostics[:0]
for _, finding := range r.Diagnostics {
switch finding.Kind {
case FindingReceiptError, FindingOwnershipError, FindingModifiedFile:
continue
}
kept = append(kept, finding)
}
clear(r.Diagnostics[len(kept):])
r.Diagnostics = kept
}
package discovery
import (
"archive/zip"
"encoding/json/v2"
"fmt"
"io/fs"
"path/filepath"
"strings"
"github.com/mclucy/lucy/internal/fsutil"
versionpkg "github.com/mclucy/lucy/version"
)
const (
paperMetaMainClassPath = "META-INF/main-class"
paperLibrariesListPath = "META-INF/libraries.list"
paperVersionsListPath = "META-INF/versions.list"
paperPatchesListPath = "META-INF/patches.list"
paperDownloadContextPath = "META-INF/download-context"
paperVersionJSONPath = "version.json"
paperPatchPropertiesPath = "patch.properties"
paperPatchReaperToken = "paperMC.patch"
paperPatchFilePath = paperPatchReaperToken
paperBuildInfoPath = "META-INF/build-info"
paperLeavesclipVersionPath = "META-INF/leavesclip-version"
paperLeaperNamespacePrefix = "cn/dreeam/leaper/"
paperLeavesclipNamespace = "org/leavesmc/leavesclip/"
paperPaperclipNamespace = "io/papermc/paperclip/"
paperLegacyPaperclipPrefix = "paperclip/"
paperYouerNamespace = "com/mohistmc/launcher/youer/"
paperManifestYouerToken = "Youer"
paperMainClassYouerToken = "youer"
paperLibraryPaperToken = "io.papermc.paper:paper-api:"
paperLibraryMojangAPIToken = "com.destroystokyo.paper:paper-mojangapi:"
paperLibraryFoliaToken = "dev.folia:folia-api:"
paperLibraryDivineToken = "org.bxteam.divinemc:divinemc-api:"
paperLibraryPurpurToken = "org.purpurmc.purpur:purpur-api:"
paperLibraryLeafToken = "cn.dreeam.leaf:leaf-api:"
paperLibraryLeavesToken = "org.leavesmc.leaves:leaves-api:"
)
type paperObservationEntry struct {
name string
read func() ([]byte, error)
}
type paperObservationSource interface {
Walk(func(paperObservationEntry) error) error
}
func extractPaperObservations(
s *scan,
primary *artifact,
) (paperObservations, error) {
obs := paperObservations{
patchProperties: make(map[string]string),
}
source, err := newPaperObservationSource(s, primary)
if err != nil {
return paperObservations{}, err
}
err = source.Walk(
func(entry paperObservationEntry) error {
name := entry.name
switch {
case strings.HasPrefix(
name,
bukkitPaperClassPrefix,
), strings.HasPrefix(name, bukkitLegacyPaperClassPrefix):
obs.hasPaperClasses = true
case strings.HasPrefix(name, paperLeaperNamespacePrefix):
obs.hasLeaperNamespace = true
case strings.HasPrefix(name, paperLeavesclipNamespace):
obs.hasLeavesclipNamespace = true
case strings.HasPrefix(name, paperPaperclipNamespace):
obs.hasPaperclipNamespace = true
case strings.HasPrefix(name, paperLegacyPaperclipPrefix):
obs.hasLegacyPaperclipNamespace = true
case strings.HasPrefix(name, paperYouerNamespace):
obs.hasYouerNamespace = true
}
switch name {
case bukkitManifestPath:
data, err := entry.read()
if err != nil {
return err
}
signals := parseBukkitManifest(data)
obs.manifestMainClass = signals.mainClass
obs.manifestSpecificationTitle = signals.specificationTitle
obs.manifestSpecificationVendor = signals.specificationVendor
obs.manifestImplementationTitle = signals.implementationTitle
obs.manifestImplementationVendor = signals.implementationVendor
obs.manifestImplementationVer = signals.implementationVer
case paperMetaMainClassPath:
data, err := entry.read()
if err != nil {
return err
}
obs.metaMainClass = strings.TrimSpace(string(data))
case paperLibrariesListPath:
data, err := entry.read()
if err != nil {
return err
}
obs.librariesListEntries = readObservationLines(data)
case paperVersionsListPath:
data, err := entry.read()
if err != nil {
return err
}
obs.versionsListEntries = readObservationLines(data)
case paperPatchesListPath:
data, err := entry.read()
if err != nil {
return err
}
obs.patchesListEntries = readObservationLines(data)
case paperDownloadContextPath:
data, err := entry.read()
if err != nil {
return err
}
obs.downloadContext = strings.TrimSpace(string(data))
case paperVersionJSONPath:
data, err := entry.read()
if err != nil {
return err
}
obs.versionJSONID = parsePaperVersionJSONID(data)
case paperPatchPropertiesPath:
data, err := entry.read()
if err != nil {
return err
}
obs.patchProperties = parsePaperPatchProperties(data)
obs.hasPaperMCPatch = obs.hasPaperMCPatch || strings.EqualFold(
obs.patchProperties["patch"],
paperPatchFilePath,
)
case paperPatchFilePath:
obs.hasPaperMCPatch = true
case paperBuildInfoPath:
data, err := entry.read()
if err != nil {
return err
}
obs.buildInfo = strings.TrimSpace(string(data))
case paperLeavesclipVersionPath:
data, err := entry.read()
if err != nil {
return err
}
obs.leavesclipVersion = strings.TrimSpace(string(data))
}
return nil
},
)
if err != nil {
return paperObservations{}, err
}
obs.gameVersion = inferPaperObservationGameVersion(obs)
return obs, nil
}
func newPaperObservationSource(
s *scan,
primary *artifact,
) (paperObservationSource, error) {
if primary == nil {
return nil, fmt.Errorf("paper observation artifact is missing")
}
if primary.IsDirectory() {
return paperObservationDirSource{
scan: s,
root: primary.Path(),
}, nil
}
archive, err := primary.Archive()
if err != nil {
return nil, err
}
if archive == nil {
return nil, fmt.Errorf(
"paper observation path is not an archive: %s",
primary.Path(),
)
}
return paperObservationZipSource{reader: archive}, nil
}
type paperObservationZipSource struct {
reader *zip.Reader
}
func (s paperObservationZipSource) Walk(fn func(paperObservationEntry) error) error {
for _, file := range s.reader.File {
if file.FileInfo().IsDir() {
continue
}
zipFile := file
if err := fn(
paperObservationEntry{
name: filepath.ToSlash(zipFile.Name),
read: func() ([]byte, error) {
r, err := zipFile.Open()
if err != nil {
return nil, err
}
defer r.Close()
return fsutil.CopyBytes(r, fsutil.MaxZipEntryBytes)
},
},
); err != nil {
return err
}
}
return nil
}
type paperObservationDirSource struct {
scan *scan
root string
}
func (s paperObservationDirSource) Walk(fn func(paperObservationEntry) error) error {
return filepath.WalkDir(
s.root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
rel, err := filepath.Rel(s.root, path)
if err != nil {
return err
}
file, ok := s.scan.File(path)
if !ok || file.IsDirectory() {
return nil
}
return fn(
paperObservationEntry{
name: filepath.ToSlash(rel),
read: file.Read,
},
)
},
)
}
func readObservationLines(data []byte) []string {
trimmed := strings.TrimSpace(string(data))
if trimmed == "" {
return nil
}
return strings.Split(trimmed, "\n")
}
func parsePaperVersionJSONID(data []byte) versionpkg.Version {
var payload struct {
ID string `json:"id"`
}
if err := json.Unmarshal(data, &payload); err != nil {
return versionpkg.Unknown
}
if !isMinecraftReleaseVersion(payload.ID) {
return versionpkg.Unknown
}
return versionpkg.Version(payload.ID)
}
func parsePaperPatchProperties(data []byte) map[string]string {
properties := make(map[string]string)
for _, line := range readObservationLines(data) {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
properties[strings.TrimSpace(key)] = strings.TrimSpace(value)
}
return properties
}
func inferPaperObservationGameVersion(obs paperObservations) versionpkg.Version {
if hasConcreteVersion(obs.versionJSONID) {
return obs.versionJSONID
}
if version := parseBukkitGameVersion(obs.manifestImplementationVer); hasConcreteVersion(version) {
return version
}
if version := parsePaperVersionList(obs.versionsListEntries); hasConcreteVersion(version) {
return version
}
if version := parsePaperPatchPropertiesVersion(obs.patchProperties); hasConcreteVersion(version) {
return version
}
return versionpkg.Unknown
}
func parsePaperVersionList(entries []string) versionpkg.Version {
for _, entry := range entries {
fields := strings.Split(entry, "\t")
if len(fields) < 2 {
continue
}
candidate := strings.TrimSpace(fields[1])
if isMinecraftReleaseVersion(candidate) {
return versionpkg.Version(candidate)
}
}
return versionpkg.Unknown
}
func parsePaperPatchPropertiesVersion(properties map[string]string) versionpkg.Version {
version := strings.TrimSpace(properties["version"])
if !isMinecraftReleaseVersion(version) {
return versionpkg.Unknown
}
return versionpkg.Version(version)
}
package discovery
import "strings"
type productPreferenceGroup struct {
names []string
tier int
order int
}
// productPreferences is the fixed live-status preference order: lower tiers,
// then lower orders, win. Names match case-insensitively, and the primary
// runtime name is consulted before the catalogued product string.
var productPreferences = [...]productPreferenceGroup{
// Tier 0: hybrid server platforms.
{names: []string{"youer"}, tier: 0, order: 0},
{names: []string{"arclight", "arclight-forge", "arclight-neoforge", "arclight-fabric"}, tier: 0, order: 1},
{names: []string{"catserver"}, tier: 0, order: 2},
{names: []string{"spongeneo"}, tier: 0, order: 3},
{names: []string{"spongeforge"}, tier: 0, order: 4},
// Tier 1: mod loaders.
{names: []string{"neoforge"}, tier: 1, order: 0},
{names: []string{"forge"}, tier: 1, order: 1},
{names: []string{"fabric"}, tier: 1, order: 2},
{names: []string{"quilt"}, tier: 1, order: 3},
// Tier 2: Paper-family forks.
{names: []string{"reaper"}, tier: 2, order: 0},
{names: []string{"leaf"}, tier: 2, order: 1},
{names: []string{"divine"}, tier: 2, order: 2},
{names: []string{"pufferfish"}, tier: 2, order: 3},
{names: []string{"purpur"}, tier: 2, order: 4},
{names: []string{"folia"}, tier: 2, order: 5},
{names: []string{"leaves"}, tier: 2, order: 6},
// Tier 3: general-purpose server implementations.
{names: []string{"paper"}, tier: 3, order: 0},
{names: []string{"spigot"}, tier: 3, order: 1},
{names: []string{"craftbukkit", "bukkit"}, tier: 3, order: 2},
{names: []string{"spongevanilla"}, tier: 3, order: 3},
// Tier 4: vanilla Minecraft.
{names: []string{"minecraft", "vanilla", "mc"}, tier: 4, order: 0},
// Tier 5: proxies.
{names: []string{"bungeecord", "velocity", "waterfall"}, tier: 5, order: 0},
}
const (
productRankFallbackTier = 5
productRankFallbackOrder = 1
)
func productRankByName(name string) (int, int, bool) {
name = strings.TrimSpace(name)
for _, group := range productPreferences {
for _, candidate := range group.names {
if strings.EqualFold(name, candidate) {
return group.tier, group.order, true
}
}
}
return 0, 0, false
}
func productRank(identity Identity) (int, int) {
if tier, order, ok := productRankByName(identity.Primary.Name.String()); ok {
return tier, order
}
if tier, order, ok := productRankByName(identity.Product().String()); ok {
return tier, order
}
return productRankFallbackTier, productRankFallbackOrder
}
package discovery
import (
"archive/zip"
"path/filepath"
"strings"
"github.com/mclucy/lucy/catalog"
versionpkg "github.com/mclucy/lucy/version"
)
// Quilt's server layout mirrors Fabric's launch shim: a manifest-only
// quilt-server-launch.jar boots the vanilla server jar named by
// quilt-server-launcher.properties. The launcher's Main-Class and manifest
// Class-Path name the loader and libraries; the first run extracts the vanilla
// bundler into versions/<game>/server-<game>.jar and writes a transform cache
// under .cache/quilt_loader.
const (
quiltLauncherMainClass = "org.quiltmc.loader.impl.launch.server.QuiltServerLauncher"
quiltKnotServerMainClass = "org.quiltmc.loader.impl.launch.knot.KnotServer"
quiltLaunchPropertiesPath = "quilt-server-launch.properties"
quiltLauncherPropertiesPath = "quilt-server-launcher.properties"
quiltServerJarProperty = "serverJar"
quiltFirstRunVersionsDir = "versions"
quiltLoaderLibraryGroup = "org/quiltmc/quilt-loader"
quiltHashedLibraryGroup = "org/quiltmc/hashed"
quiltIntermediaryLibraryGroup = "net/fabricmc/intermediary"
)
// discoverQuilt recognizes an installed Quilt server from the launcher JAR.
// Identity comes from the manifest Class-Path, never from the filename: a
// Fabric launcher declares a different Main-Class and is rejected here.
func discoverQuilt(s *scan) ([]Installation, []Finding) {
if s == nil {
return nil, nil
}
installations := make([]Installation, 0)
for _, file := range s.RootFiles() {
if file.IsDirectory() || !isJarArtifact(file) {
continue
}
if installation, ok := quiltLauncherInstallation(s, file); ok {
installations = append(installations, installation)
}
}
return installations, nil
}
// quiltLauncherInstallation proves the launcher identity and claims the
// sidecars, payload, first-run extraction, and classpath files it uses.
func quiltLauncherInstallation(s *scan, file *artifact) (Installation, bool) {
archive, err := file.Archive()
if err != nil {
return Installation{}, false
}
mainClass, ok := readArchiveManifestMainClass(archive)
if !ok || mainClass != quiltLauncherMainClass {
return Installation{}, false
}
if !quiltLaunchPropertiesMatch(archive) {
return Installation{}, false
}
loaderVersion, gameVersion, classPath := parseQuiltLauncherManifest(archive)
if loaderVersion == versionpkg.Unknown || gameVersion == versionpkg.Unknown {
return Installation{}, false
}
installation := NewInstallation(
quiltIdentity(loaderVersion, gameVersion),
file.Path(),
)
addLocalClassPathFiles(s, &installation, file, classPath)
addQuiltLauncherSidecar(s, &installation, file)
addQuiltServerPayload(s, &installation, file, gameVersion)
addQuiltFirstRunPayloads(s, &installation, gameVersion)
return installation, true
}
// quiltLaunchPropertiesMatch validates the launch properties a generated
// launcher embeds. The official installer embeds none, so only a present entry
// must name Quilt's KnotServer main class.
func quiltLaunchPropertiesMatch(archive *zip.Reader) bool {
data, found, err := readArchiveEntry(archive, quiltLaunchPropertiesPath)
if err != nil {
return false
}
if !found {
return true
}
return propertiesValue(data, "launch.mainClass") == quiltKnotServerMainClass
}
// parseQuiltLauncherManifest returns the loader and game versions named by the
// Class-Path entries of a Quilt launcher. The hashed artifact carries the game
// version; intermediary is the fallback for layouts without it.
func parseQuiltLauncherManifest(zipReader *zip.Reader) (
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
classPath []string,
) {
loaderVersion = versionpkg.Unknown
classPath = parseArchiveClassPath(zipReader)
hashedGameVersion := versionpkg.Unknown
intermediaryGameVersion := versionpkg.Unknown
for _, entry := range classPath {
if parsed, found := quiltClassPathVersion(entry, quiltLoaderLibraryGroup); found {
loaderVersion = parsed
}
if parsed, found := quiltClassPathVersion(entry, quiltHashedLibraryGroup); found {
hashedGameVersion = parsed
}
if parsed, found := quiltClassPathVersion(entry, quiltIntermediaryLibraryGroup); found {
intermediaryGameVersion = parsed
}
}
if hashedGameVersion != versionpkg.Unknown {
gameVersion = hashedGameVersion
} else {
gameVersion = intermediaryGameVersion
}
return loaderVersion, gameVersion, classPath
}
// quiltClassPathVersion extracts the version segment after groupPath in a
// manifest Class-Path entry, for example
// libraries/org/quiltmc/quilt-loader/0.27.1/quilt-loader-0.27.1.jar.
func quiltClassPathVersion(
classPath string,
groupPath string,
) (versionpkg.Version, bool) {
segments := strings.Split(filepath.ToSlash(classPath), "/")
group := strings.Split(groupPath, "/")
for i := 0; i+len(group)+1 < len(segments); i++ {
if segments[i] != "libraries" {
continue
}
matched := true
for offset, part := range group {
if segments[i+1+offset] != part {
matched = false
break
}
}
if !matched {
continue
}
candidate := segments[i+len(group)+1]
if candidate == "" || candidate == "." || candidate == ".." {
continue
}
return versionpkg.Version(candidate), true
}
return versionpkg.Unknown, false
}
// addQuiltLauncherSidecar claims the properties file the launcher reads for
// the server jar location. It is configuration, not payload evidence.
func addQuiltLauncherSidecar(
s *scan,
installation *Installation,
launcher *artifact,
) {
properties, ok := s.Sibling(launcher, quiltLauncherPropertiesPath)
if !ok || properties.IsDirectory() {
return
}
installation.AddFile(properties.Path(), RoleConfiguration)
}
// addQuiltServerPayload claims the jar the launcher boots when its content
// names the observed game version. The sidecar may name another location;
// the launcher defaults to server.jar in its own directory.
func addQuiltServerPayload(
s *scan,
installation *Installation,
launcher *artifact,
gameVersion versionpkg.Version,
) {
serverJarPath := filepath.Join(filepath.Dir(launcher.Path()), minecraftServerJarName)
if properties, ok := s.Sibling(launcher, quiltLauncherPropertiesPath); ok &&
!properties.IsDirectory() {
if data, err := properties.Read(); err == nil {
serverJarPath = quiltLauncherServerJarPath(launcher.Path(), data)
}
}
payload, ok := s.File(serverJarPath)
if !ok || payload.IsDirectory() ||
!quiltServerPayloadMatches(payload, gameVersion) {
return
}
installation.AddFile(payload.Path(), RolePayload)
}
// addQuiltFirstRunPayloads claims the vanilla jar the bundler extracts on first
// run. The path names the game version, and version.json must agree; cache
// entries carry no identity evidence and stay unclaimed.
func addQuiltFirstRunPayloads(
s *scan,
installation *Installation,
gameVersion versionpkg.Version,
) {
if s == nil || installation == nil || !hasConcreteVersion(gameVersion) {
return
}
version := string(gameVersion)
dir := filepath.Join(s.root, quiltFirstRunVersionsDir, version)
for _, name := range []string{
"server-" + version + ".jar",
version + ".jar",
} {
payload, ok := s.File(filepath.Join(dir, name))
if !ok || payload.IsDirectory() ||
!quiltServerPayloadMatches(payload, gameVersion) {
continue
}
installation.AddFile(payload.Path(), RolePayload)
}
}
// quiltServerPayloadMatches reports whether a server jar carries the observed
// game version. A missing or guarded version.json proves nothing.
func quiltServerPayloadMatches(
file *artifact,
gameVersion versionpkg.Version,
) bool {
if !hasConcreteVersion(gameVersion) {
return false
}
return parseServerJarGameVersion(file) == gameVersion
}
// quiltLauncherServerJarPath returns the server jar that the Quilt launch
// launcher boots. QuiltServerLauncher reads serverJar from
// quilt-server-launcher.properties beside the launcher and falls back to
// server.jar when the file or the entry is missing.
func quiltLauncherServerJarPath(
launcherPath string,
properties []byte,
) string {
name := minecraftServerJarName
if value := propertiesValue(properties, quiltServerJarProperty); value != "" {
name = value
}
if filepath.IsAbs(name) {
return filepath.Clean(name)
}
return filepath.Join(filepath.Dir(launcherPath), name)
}
func quiltIdentity(
loaderVersion versionpkg.Version,
gameVersion versionpkg.Version,
) Identity {
return Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemQuilt,
Name: "quilt",
Version: loaderVersion,
},
Components: []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemQuilt,
Name: "quilt-loader",
Version: loaderVersion,
},
{
Ecosystem: catalog.EcosystemMinecraft,
Name: "minecraft",
Version: gameVersion,
},
},
}
}
package discovery
import (
"archive/zip"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/mclucy/lucy/internal/fsutil"
)
// scan owns one canonical root, the root-confined filesystem view, and the
// artifact metadata cache for a single Discover call. It is private: no
// resource-bearing value escapes into Result.
type scan struct {
root string
displayRoot string
fs *os.Root
mu sync.Mutex
files map[string]*artifact
physical []physicalArtifact
rootFiles []*artifact
readers []*os.File
closed bool
}
type physicalArtifact struct {
info os.FileInfo
file *artifact
}
// artifact is one cached filesystem entry. Sidecar bytes and ZIP metadata are
// cached lazily; a JAR is never cached as a whole byte slice.
type artifact struct {
scan *scan
path string
relPath string
isDir bool
size int64
dataOnce sync.Once
data []byte
dataErr error
archiveOnce sync.Once
archive *zip.Reader
archiveErr error
}
func newScan(root string) (*scan, error) {
absolute, err := filepath.Abs(root)
if err != nil {
return nil, err
}
resolved, err := filepath.EvalSymlinks(absolute)
if err != nil {
return nil, err
}
info, err := os.Stat(resolved)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fmt.Errorf("scan root %s is not a directory", resolved)
}
fs, err := os.OpenRoot(resolved)
if err != nil {
return nil, err
}
entries, err := os.ReadDir(resolved)
if err != nil {
_ = fs.Close()
return nil, err
}
s := &scan{
root: resolved,
displayRoot: absolute,
fs: fs,
files: make(map[string]*artifact, len(entries)),
rootFiles: make([]*artifact, 0, len(entries)),
}
rootSeen := make(map[*artifact]bool, len(entries))
for _, entry := range entries {
file, ok := s.fileLocked(entry.Name())
if !ok || rootSeen[file] {
continue
}
rootSeen[file] = true
s.rootFiles = append(s.rootFiles, file)
}
return s, nil
}
// RootFiles returns the cached top-level artifacts. The slice is the scan's
// internal read-only view; callers must not mutate or retain it past the scan.
func (s *scan) RootFiles() []*artifact {
if s == nil {
return nil
}
return s.rootFiles
}
// File resolves an absolute or root-relative path inside the root. Nested
// paths and symlinks are accepted only when their resolved target stays inside
// the root.
func (s *scan) File(path string) (*artifact, bool) {
if s == nil {
return nil, false
}
rel, ok := s.relative(path)
if !ok {
return nil, false
}
s.mu.Lock()
defer s.mu.Unlock()
return s.fileLocked(rel)
}
// fileLocked resolves one path to the single cached artifact that represents
// its physical file. Aliases, hard links, and symlinks that resolve inside the
// root share one artifact, one metadata cache, and one ReaderAt descriptor.
func (s *scan) fileLocked(rel string) (*artifact, bool) {
if file, exists := s.files[rel]; exists {
return file, true
}
if s.closed {
return nil, false
}
linkInfo, err := s.fs.Lstat(rel)
if err != nil {
return nil, false
}
info, statErr := s.fs.Stat(rel)
canonicalRel := rel
if statErr != nil {
// A symlink that escapes the root is not followed. It remains its own
// unreadable artifact so a later read fails instead of leaking data.
info = linkInfo
} else if linkInfo.Mode()&os.ModeSymlink != 0 {
if resolved, resolveErr := filepath.EvalSymlinks(
filepath.Join(s.displayRoot, rel),
); resolveErr == nil {
if target, ok := relativeWithin(s.root, resolved); ok {
canonicalRel = target
} else if target, ok := relativeWithin(s.displayRoot, resolved); ok {
canonicalRel = target
}
}
}
for _, physical := range s.physical {
if !os.SameFile(physical.info, info) {
continue
}
s.files[rel] = physical.file
if canonicalRel != rel {
s.files[canonicalRel] = physical.file
}
return physical.file, true
}
file := &artifact{
scan: s,
path: filepath.Join(s.displayRoot, canonicalRel),
relPath: canonicalRel,
isDir: info.IsDir(),
}
if !info.IsDir() {
file.size = info.Size()
}
s.physical = append(s.physical, physicalArtifact{info: info, file: file})
s.files[rel] = file
if canonicalRel != rel {
s.files[canonicalRel] = file
}
return file, true
}
// Sibling resolves a named sibling of primary inside the root.
func (s *scan) Sibling(primary *artifact, name string) (*artifact, bool) {
if s == nil || primary == nil || name == "" {
return nil, false
}
return s.File(filepath.Join(filepath.Dir(primary.RelPath()), name))
}
// ReadDir lists a root-confined directory in lexical order.
func (s *scan) ReadDir(path string) ([]os.DirEntry, error) {
if s == nil {
return nil, os.ErrInvalid
}
rel, ok := s.relative(path)
if !ok {
return nil, fmt.Errorf("path %q is outside the scan root", path)
}
s.mu.Lock()
closed := s.closed
s.mu.Unlock()
if closed {
return nil, os.ErrClosed
}
file, err := s.fs.Open(rel)
if err != nil {
return nil, err
}
defer file.Close()
entries, err := file.ReadDir(-1)
if err != nil {
return nil, err
}
slices.SortFunc(entries, func(left, right os.DirEntry) int {
return strings.Compare(left.Name(), right.Name())
})
return entries, nil
}
// Close releases every ReaderAt descriptor and the root handle.
func (s *scan) Close() error {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.closed = true
var problems []error
for _, reader := range s.readers {
if err := reader.Close(); err != nil {
problems = append(problems, err)
}
}
s.readers = nil
if s.fs != nil {
if err := s.fs.Close(); err != nil {
problems = append(problems, err)
}
s.fs = nil
}
return errors.Join(problems...)
}
func (s *scan) relative(path string) (string, bool) {
if path == "" {
return "", false
}
clean := filepath.Clean(path)
if filepath.IsAbs(clean) {
if rel, ok := relativeWithin(s.displayRoot, clean); ok {
return rel, true
}
if rel, ok := relativeWithin(s.root, clean); ok {
return rel, true
}
resolved, err := filepath.EvalSymlinks(clean)
if err == nil {
if rel, ok := relativeWithin(s.root, resolved); ok {
return rel, true
}
}
return "", false
}
if clean == "." || !filepath.IsLocal(clean) {
return "", false
}
return clean, true
}
func relativeWithin(root, path string) (string, bool) {
rel, err := filepath.Rel(root, path)
if err != nil || rel == "." || !filepath.IsLocal(rel) {
return "", false
}
return rel, true
}
func (s *scan) openReader(file *artifact) (*os.File, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, os.ErrClosed
}
reader, err := s.fs.Open(file.relPath)
if err != nil {
return nil, err
}
s.readers = append(s.readers, reader)
return reader, nil
}
// Path returns the absolute canonical path.
func (a *artifact) Path() string {
if a == nil {
return ""
}
return a.path
}
// RelPath returns the path relative to the scan root using slashes.
func (a *artifact) RelPath() string {
if a == nil {
return ""
}
return filepath.ToSlash(a.relPath)
}
// IsDirectory reports whether the artifact is a directory.
func (a *artifact) IsDirectory() bool {
return a != nil && a.isDir
}
// Read returns bounded sidecar bytes. JAR/ZIP payloads must be opened through
// Archive so a large server JAR is never cached as a whole byte slice.
func (a *artifact) Read() ([]byte, error) {
if a == nil {
return nil, os.ErrInvalid
}
a.dataOnce.Do(func() {
if a.isDir {
a.dataErr = errNotRegularFile
return
}
if isArchivePath(a.relPath) {
a.dataErr = fmt.Errorf(
"artifact %s is an archive; open it through Archive",
a.RelPath(),
)
return
}
if a.size > fsutil.MaxZipEntryBytes {
a.dataErr = fmt.Errorf(
"artifact %s exceeds the sidecar read limit",
a.RelPath(),
)
return
}
if a.scan == nil || a.scan.fs == nil {
a.dataErr = os.ErrClosed
return
}
reader, err := a.scan.fs.Open(a.relPath)
if err != nil {
a.dataErr = err
return
}
defer func() {
if err := reader.Close(); err != nil {
a.dataErr = err
}
}()
a.data, a.dataErr = fsutil.CopyBytes(reader, fsutil.MaxZipEntryBytes)
})
return a.data, a.dataErr
}
// Archive opens the artifact as a ZIP reader backed by a scan-owned ReaderAt
// descriptor. The descriptor stays open until scan.Close.
func (a *artifact) Archive() (*zip.Reader, error) {
if a == nil {
return nil, os.ErrInvalid
}
a.archiveOnce.Do(func() {
if a.isDir {
a.archiveErr = fmt.Errorf("artifact %s is a directory", a.RelPath())
return
}
if a.scan == nil {
a.archiveErr = os.ErrInvalid
return
}
reader, err := a.scan.openReader(a)
if err != nil {
a.archiveErr = err
return
}
info, err := reader.Stat()
if err != nil {
a.archiveErr = err
return
}
a.archive, a.archiveErr = zip.NewReader(reader, info.Size())
})
return a.archive, a.archiveErr
}
func isArchivePath(path string) bool {
lower := strings.ToLower(path)
return strings.HasSuffix(lower, ".jar") || strings.HasSuffix(lower, ".zip")
}
package discovery
import (
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/server"
versionpkg "github.com/mclucy/lucy/version"
)
// SelectionState distinguishes the explicit outcomes of a selection request.
type SelectionState string
const (
SelectionUnknown SelectionState = ""
SelectionNone SelectionState = "none"
SelectionSelected SelectionState = "selected"
SelectionAmbiguous SelectionState = "ambiguous"
SelectionMissingDeclared SelectionState = "missing_declared"
SelectionUnmatched SelectionState = "unmatched"
SelectionInvalid SelectionState = "invalid"
)
// SelectionSource records why an installation was selected.
type SelectionSource string
const (
SourceUnknown SelectionSource = ""
SourceInferred SelectionSource = "inferred"
SourceDeclared SelectionSource = "declared"
SourceExplicit SelectionSource = "explicit"
// SourceCoverage selects the installation whose recognized members
// account for strictly more files than any other candidate's.
SourceCoverage SelectionSource = "coverage"
SourcePreferred SelectionSource = "preferred"
)
// SelectionPolicy controls whether an ambiguous observation may be resolved
// by the read-only preference order.
type SelectionPolicy string
const (
PolicyUnknown SelectionPolicy = ""
PolicyStrict SelectionPolicy = "strict"
PolicyPreferModified SelectionPolicy = "prefer_modified"
)
// Declaration is the applicable persisted installation identity.
type Declaration struct {
Product server.Product
Minecraft versionpkg.Version
CoreVersion versionpkg.Version
}
// Expectation narrows candidate installations by identity. Empty fields match
// any value; a concrete version must equal an observed concrete version.
// Expectation is an invocation filter, not a persisted declaration.
type Expectation struct {
Product server.Product
Minecraft versionpkg.Version
CoreVersion versionpkg.Version
}
// Request is one selection attempt. Installation selects a result member
// directly. Expectation narrows the candidates and takes precedence over the
// persisted declaration because it describes this invocation. Policy
// PreferModified is opted into only by live status.
type Request struct {
Installation *Installation
Expectation *Expectation
Declared *Declaration
Policy SelectionPolicy
}
// Selection is the read-only result of a selection attempt. It references the
// chosen installation; member roles remain discovery evidence.
type Selection struct {
State SelectionState
Source SelectionSource
Installation *Installation
}
// IsValid reports whether the selection names a launchable installation with a
// usable identity.
func (s Selection) IsValid() bool {
return s.State == SelectionSelected &&
launchableInstallation(s.Installation)
}
// Product returns the selected installation product.
func (s Selection) Product() server.Product {
if !s.IsValid() {
return server.ProductUnknown
}
return s.Installation.Identity.Product()
}
// MinecraftVersion returns the selected installation Minecraft version.
func (s Selection) MinecraftVersion() versionpkg.Version {
if !s.IsValid() {
return versionpkg.Unknown
}
return s.Installation.Identity.MinecraftVersion()
}
// Ecosystem returns the selected installation loader ecosystem.
func (s Selection) Ecosystem() catalog.Ecosystem {
if !s.IsValid() {
return catalog.EcosystemUnspecified
}
return s.Installation.Identity.Ecosystem()
}
// Select updates the result selection without mutating or reordering members.
// It never writes files. Every non-selected outcome returns *SelectionError.
func (r *Result) Select(request Request) error {
if r == nil {
return &SelectionError{State: SelectionNone}
}
r.Selection = Selection{State: SelectionNone}
selectable := r.selectableInstallations()
switch {
case request.Installation != nil:
return r.selectDirect(request.Installation, selectable)
case request.Expectation != nil:
return r.selectExpectation(request.Expectation, selectable)
case request.Declared != nil:
return r.selectDeclared(request.Declared, selectable)
default:
return r.selectInferred(request.Policy, selectable)
}
}
// selectDirect applies a caller's direct installation choice. The installation
// must belong to this result and satisfy the launchability evidence.
func (r *Result) selectDirect(
installation *Installation,
selectable []*Installation,
) error {
for _, candidate := range selectable {
if candidate == installation {
r.selectCandidate(candidate, SourceExplicit)
return nil
}
}
r.Selection.State = SelectionInvalid
return &SelectionError{
State: SelectionInvalid,
Installations: copyInstallations(r.Installations),
}
}
// selectExpectation filters the launchable installations by identity. It never
// supplies a fact that discovery did not observe.
func (r *Result) selectExpectation(
expectation *Expectation,
selectable []*Installation,
) error {
matches := installationsMatchingExpectation(selectable, expectation)
switch len(matches) {
case 1:
r.selectCandidate(matches[0], SourceExplicit)
return nil
case 0:
r.Selection.State = SelectionUnmatched
return &SelectionError{
State: SelectionUnmatched,
Installations: copyInstallations(r.Installations),
}
default:
r.Selection.State = SelectionAmbiguous
return &SelectionError{
State: SelectionAmbiguous,
Installations: cloneInstallations(matches),
}
}
}
func (r *Result) selectDeclared(
declaration *Declaration,
selectable []*Installation,
) error {
matches := installationsMatchingDeclaration(selectable, declaration)
switch len(matches) {
case 1:
r.selectCandidate(matches[0], SourceDeclared)
return nil
case 0:
default:
r.Selection.State = SelectionAmbiguous
return &SelectionError{
State: SelectionAmbiguous,
Installations: cloneInstallations(matches),
}
}
r.Selection.State = SelectionMissingDeclared
return &SelectionError{
State: SelectionMissingDeclared,
Installations: cloneInstallations(selectable),
}
}
func (r *Result) selectInferred(
policy SelectionPolicy,
selectable []*Installation,
) error {
switch len(selectable) {
case 0:
if len(r.Installations) > 0 {
r.Selection.State = SelectionInvalid
return &SelectionError{
State: SelectionInvalid,
Installations: copyInstallations(r.Installations),
}
}
r.Selection.State = SelectionNone
return &SelectionError{State: SelectionNone}
case 1:
r.selectCandidate(selectable[0], SourceInferred)
return nil
default:
if leading := coverageLeader(selectable); leading != nil {
r.selectCandidate(leading, SourceCoverage)
return nil
}
if policy == PolicyPreferModified {
if preferred := preferredInstallation(selectable); preferred != nil {
r.selectCandidate(preferred, SourcePreferred)
return nil
}
}
}
r.Selection.State = SelectionAmbiguous
return &SelectionError{
State: SelectionAmbiguous,
Installations: cloneInstallations(selectable),
}
}
// coverageLeader returns the only candidate whose member coverage is strictly
// higher than every other candidate's. It returns nil for a tie at the top, so
// the caller keeps the existing preference or ambiguity behavior.
func coverageLeader(selectable []*Installation) *Installation {
var leader *Installation
highest := 0
tied := false
for _, installation := range selectable {
coverage := memberCoverage(installation)
switch {
case coverage > highest:
highest = coverage
leader = installation
tied = false
case coverage == highest && leader != nil:
tied = true
}
}
if tied {
return nil
}
return leader
}
// memberCoverage counts the members that prove this runtime owns the
// directory. Entry points, payloads, and libraries are files the recognizer
// proved belong to the runtime, so the runtime the directory was built around
// owns the most of them. Configuration sidecars do not show which runtime was
// installed, and unreadable members prove nothing.
func memberCoverage(installation *Installation) int {
if installation == nil {
return 0
}
coverage := 0
for _, file := range installation.Files {
if file.Role == RoleConfiguration ||
file.Ownership == OwnershipUnreadable {
continue
}
coverage++
}
return coverage
}
func (r *Result) selectCandidate(
installation *Installation,
source SelectionSource,
) {
r.Selection.State = SelectionSelected
r.Selection.Source = source
r.Selection.Installation = installation
}
func (r *Result) selectableInstallations() []*Installation {
selectable := make([]*Installation, 0, len(r.Installations))
for index := range r.Installations {
installation := &r.Installations[index]
if !launchableInstallation(installation) {
continue
}
selectable = append(selectable, installation)
}
return selectable
}
// launchableInstallation reports whether discovery has layout evidence that the
// installation can start. Entry-point members prove launchability; they never
// enter Selection.
func launchableInstallation(installation *Installation) bool {
if installation == nil || !installation.Identity.IsValid() ||
firstEntryPoint(installation) == nil {
return false
}
entry := chooseEntryPoint(installation)
return entry != nil && entry.Ownership != OwnershipUnreadable
}
// A known version conflict excludes an installation. Missing metadata does not
// establish a conflict or prove equality between candidates; selection still
// requires one matching installation.
func installationsMatchingDeclaration(
installations []*Installation,
declaration *Declaration,
) []*Installation {
if declaration == nil || declaration.Product == server.ProductUnknown {
return nil
}
matches := make([]*Installation, 0, len(installations))
for _, installation := range installations {
if !installation.Identity.IsValid() {
continue
}
if !installationMatchesProduct(installation, declaration.Product) {
continue
}
if concreteVersion(declaration.Minecraft) {
observed := installation.Identity.MinecraftVersion()
if concreteVersion(observed) && observed != declaration.Minecraft {
continue
}
}
if concreteVersion(declaration.CoreVersion) {
observed := installation.Identity.Primary.Version
if concreteVersion(observed) && observed != declaration.CoreVersion {
continue
}
}
matches = append(matches, installation)
}
return matches
}
// installationMatchesProduct matches the catalogued product first. Products
// outside the server catalog, such as a Paper fork named only by its primary
// identity, match by canonical primary name.
func installationMatchesProduct(
installation *Installation,
product server.Product,
) bool {
if installation == nil || product == server.ProductUnknown {
return false
}
if installation.Identity.Product() == product {
return true
}
return strings.EqualFold(
installation.Identity.Primary.Name.String(),
string(product),
)
}
// installationsMatchingExpectation applies an invocation filter. Empty fields
// match any observed value; concrete expectation versions must equal an
// observed concrete version. Unknown observed metadata never proves a conflict.
func installationsMatchingExpectation(
installations []*Installation,
expectation *Expectation,
) []*Installation {
if expectation == nil {
return nil
}
matches := make([]*Installation, 0, len(installations))
for _, installation := range installations {
if !installation.Identity.IsValid() {
continue
}
if expectation.Product != server.ProductUnknown &&
!installationMatchesProduct(installation, expectation.Product) {
continue
}
if concreteVersion(expectation.Minecraft) {
observed := installation.Identity.MinecraftVersion()
if concreteVersion(observed) && observed != expectation.Minecraft {
continue
}
}
if concreteVersion(expectation.CoreVersion) {
observed := installation.Identity.Primary.Version
if concreteVersion(observed) && observed != expectation.CoreVersion {
continue
}
}
matches = append(matches, installation)
}
return matches
}
func firstEntryPoint(installation *Installation) *File {
if installation == nil {
return nil
}
for file := range installation.EntryPoints() {
return file
}
return nil
}
// chooseEntryPoint prefers a receipt-managed entry point, then a locally
// modified owned entry point, then a readable unmanaged entry point, and
// finally any remaining unreadable entry point. Filesystem timestamps never participate.
func chooseEntryPoint(installation *Installation) *File {
if installation == nil {
return nil
}
var firstReadable, unreadable, modified, managed *File
for file := range installation.EntryPoints() {
if file.Ownership == OwnershipUnreadable {
if unreadable == nil || file.Path < unreadable.Path {
unreadable = file
}
continue
}
if firstReadable == nil || file.Path < firstReadable.Path {
firstReadable = file
}
if file.Ownership == OwnershipModified &&
(modified == nil || file.Path < modified.Path) {
modified = file
}
if file.Ownership == OwnershipManaged &&
(managed == nil || file.Path < managed.Path) {
managed = file
}
}
if managed != nil {
return managed
}
if modified != nil {
return modified
}
if firstReadable != nil {
return firstReadable
}
return unreadable
}
func entryPointOwnershipRank(installation *Installation) int {
best := 0
for file := range installation.EntryPoints() {
rank := 0
switch file.Ownership {
case OwnershipManaged:
rank = 4
case OwnershipModified:
rank = 3
case OwnershipUnreadable:
rank = 2
case OwnershipUnmanaged:
rank = 1
default:
rank = 0
}
if rank > best {
best = rank
}
}
return best
}
func preferredInstallation(candidates []*Installation) *Installation {
if len(candidates) == 0 {
return nil
}
best := candidates[0]
for _, candidate := range candidates[1:] {
if preferInstallation(candidate, best) < 0 {
best = candidate
}
}
return best
}
func preferInstallation(left, right *Installation) int {
leftTier, leftOrder := productRank(left.Identity)
rightTier, rightOrder := productRank(right.Identity)
if leftTier != rightTier {
return leftTier - rightTier
}
if leftOrder != rightOrder {
return leftOrder - rightOrder
}
leftRank := entryPointOwnershipRank(left)
rightRank := entryPointOwnershipRank(right)
if leftRank != rightRank {
return rightRank - leftRank
}
if result := strings.Compare(identityKey(left.Identity), identityKey(right.Identity)); result != 0 {
return result
}
return strings.Compare(firstEntryPointPath(left), firstEntryPointPath(right))
}
func firstEntryPointPath(installation *Installation) string {
if installation == nil {
return ""
}
path := ""
for file := range installation.EntryPoints() {
if path == "" || file.Path < path {
path = file.Path
}
}
return path
}
func cloneInstallations(installations []*Installation) []Installation {
cloned := make([]Installation, 0, len(installations))
for _, installation := range installations {
if installation == nil {
continue
}
cloned = append(cloned, *installation)
}
return cloned
}
func copyInstallations(installations []Installation) []Installation {
return slices.Clone(installations)
}
package discovery
import (
"bufio"
"path/filepath"
"regexp"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/input"
versionpkg "github.com/mclucy/lucy/version"
)
var (
spongeVanillaVersionPattern = regexp.MustCompile(
`^(\d+\.\d+(?:\.\d+)?)-(\d+(?:\.\d+)+)$`,
)
spongeHybridVersionPattern = regexp.MustCompile(
`^(\d+\.\d+(?:\.\d+)?)-(\d+(?:\.\d+)+)-(\d+(?:\.\d+)+)$`,
)
spongeUniversalJarPattern = regexp.MustCompile(
`(?i)^sponge(?:vanilla|forge|neo)-.+\.jar$`,
)
)
type spongeFlavor int
const (
spongeFlavorUnknown spongeFlavor = iota
spongeFlavorVanilla
spongeFlavorForge
spongeFlavorNeo
)
// discoverSponge recognizes SpongeVanilla/SpongeForge/SpongeNeo universal
// jars. The specification title decides the flavor; the implementation title
// only fills in when no specification title is present.
func discoverSponge(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
installation, err := inspectSpongeInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
if installation != nil {
installations = append(installations, *installation)
}
}
return installations, findings
}
func inspectSpongeInstallation(
s *scan,
primary *artifact,
) (*Installation, error) {
if !spongeUniversalJarPattern.MatchString(
strings.ToLower(filepath.Base(primary.Path())),
) {
return nil, nil
}
manifest, ok, err := readProductEntry(s, primary, bukkitManifestPath)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
signals := parseSpongeManifest(manifest)
if !signals.valid() {
return nil, nil
}
identity := buildSpongeIdentity(signals)
installation := NewInstallation(identity, primary.Path())
return &installation, nil
}
type spongeManifestSignals struct {
title string
vendor string
version string
flavor spongeFlavor
gameVersion versionpkg.Version
loaderVersion versionpkg.Version
spongeVersion versionpkg.Version
}
func (s spongeManifestSignals) valid() bool {
if !strings.EqualFold(strings.TrimSpace(s.vendor), "SpongePowered") {
return false
}
if s.flavor == spongeFlavorUnknown {
return false
}
if !hasConcreteVersion(s.gameVersion) {
return false
}
if !hasConcreteVersion(s.spongeVersion) {
return false
}
if s.flavor != spongeFlavorVanilla && !hasConcreteVersion(s.loaderVersion) {
return false
}
return true
}
func parseSpongeManifest(data []byte) spongeManifestSignals {
var signals spongeManifestSignals
scanner := bufio.NewScanner(strings.NewReader(string(data)))
inNamedSection := false
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "Name: ") {
inNamedSection = true
continue
}
if strings.TrimSpace(line) == "" {
inNamedSection = false
continue
}
if inNamedSection {
continue
}
switch {
case strings.HasPrefix(line, "Specification-Title: "):
signals.title = strings.TrimSpace(
strings.TrimPrefix(line, "Specification-Title: "),
)
case strings.HasPrefix(line, "Specification-Vendor: "):
if signals.vendor == "" {
signals.vendor = strings.TrimSpace(
strings.TrimPrefix(line, "Specification-Vendor: "),
)
}
case strings.HasPrefix(line, "Implementation-Title: "):
if signals.title == "" {
signals.title = strings.TrimSpace(
strings.TrimPrefix(line, "Implementation-Title: "),
)
}
case strings.HasPrefix(line, "Implementation-Vendor: "):
if signals.vendor == "" {
signals.vendor = strings.TrimSpace(
strings.TrimPrefix(line, "Implementation-Vendor: "),
)
}
case strings.HasPrefix(line, "Implementation-Version: "):
if signals.version == "" {
signals.version = strings.TrimSpace(
strings.TrimPrefix(line, "Implementation-Version: "),
)
}
}
}
signals.flavor, signals.gameVersion, signals.loaderVersion, signals.spongeVersion = parseSpongeImplementationVersion(
signals.title,
signals.version,
)
return signals
}
func parseSpongeImplementationVersion(
title string,
version string,
) (
flavor spongeFlavor,
gameVersion versionpkg.Version,
loaderVersion versionpkg.Version,
spongeVersion versionpkg.Version,
) {
version = strings.TrimSpace(version)
switch strings.TrimSpace(title) {
case "SpongeVanilla":
match := spongeVanillaVersionPattern.FindStringSubmatch(version)
if match == nil {
return spongeFlavorUnknown, versionpkg.Unknown, versionpkg.Unknown, versionpkg.Unknown
}
return spongeFlavorVanilla,
versionpkg.Version(match[1]),
versionpkg.Unknown,
versionpkg.Version(match[2])
case "SpongeForge":
match := spongeHybridVersionPattern.FindStringSubmatch(version)
if match == nil {
return spongeFlavorUnknown, versionpkg.Unknown, versionpkg.Unknown, versionpkg.Unknown
}
return spongeFlavorForge,
versionpkg.Version(match[1]),
versionpkg.Version(match[2]),
versionpkg.Version(match[3])
case "SpongeNeo":
match := spongeHybridVersionPattern.FindStringSubmatch(version)
if match == nil {
return spongeFlavorUnknown, versionpkg.Unknown, versionpkg.Unknown, versionpkg.Unknown
}
return spongeFlavorNeo,
versionpkg.Version(match[1]),
versionpkg.Version(match[2]),
versionpkg.Version(match[3])
default:
return spongeFlavorUnknown, versionpkg.Unknown, versionpkg.Unknown, versionpkg.Unknown
}
}
func buildSpongeIdentity(signals spongeManifestSignals) Identity {
primaryName := "spongevanilla"
switch signals.flavor {
case spongeFlavorForge:
primaryName = "spongeforge"
case spongeFlavorNeo:
primaryName = "spongeneo"
}
components := []catalog.VersionedRef{
{
Ecosystem: catalog.EcosystemMinecraft,
Name: input.ToProjectName("minecraft"),
Version: signals.gameVersion,
},
}
switch signals.flavor {
case spongeFlavorForge:
components = append(
components, catalog.VersionedRef{
Ecosystem: catalog.EcosystemForge,
Name: input.ToProjectName("forge"),
Version: signals.loaderVersion,
},
)
case spongeFlavorNeo:
components = append(
components, catalog.VersionedRef{
Ecosystem: catalog.EcosystemNeoForge,
Name: input.ToProjectName("neoforge"),
Version: signals.loaderVersion,
},
)
}
return Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemSponge,
Name: input.ToProjectName(primaryName),
Version: signals.spongeVersion,
},
Components: components,
}
}
package discovery
import (
"archive/zip"
"encoding/json/v2"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/internal/fsutil"
"github.com/mclucy/lucy/version"
)
// mojangVersionJSONEntry is the version spec entry inside a Mojang server jar.
const mojangVersionJSONEntry = "version.json"
// mojangVersionFromJSON extracts the game version from a Mojang version.json
// payload. guarded reports a Forge installer jar, which also carries a
// version.json but with _comment and/or mainClass control fields a real spec
// never has. encoding/json ignores unknown fields, so the guard fields must
// be checked explicitly.
func mojangVersionFromJSON(data []byte) (version.Version, bool, error) {
guard := &struct {
Comment []string `json:"_comment"`
MainClass string `json:"mainClass"`
}{}
if err := json.Unmarshal(data, guard); err == nil &&
(len(guard.Comment) > 0 || guard.MainClass != "") {
return version.Unknown, true, nil
}
var spec fileschema.FileMinecraftVersionSpec
if err := json.Unmarshal(data, &spec); err != nil {
return version.Unknown, false, err
}
return version.Version(spec.ID), false, nil
}
func readArchiveEntry(zipReader *zip.Reader, name string) ([]byte, bool, error) {
return fsutil.ReadZipEntry(zipReader, name, fsutil.MaxZipEntryBytes)
}
package discovery
import (
"github.com/mclucy/lucy/catalog"
)
// discoverVanilla recognizes Mojang server jars. A Fabric meta launcher also
// embeds version.json; it is rejected here because the loader installation
// owns that artifact, not plain Minecraft.
func discoverVanilla(s *scan) ([]Installation, []Finding) {
var installations []Installation
var findings []Finding
for _, primary := range s.RootFiles() {
if !productCandidate(s, primary) {
continue
}
installation, err := inspectVanillaInstallation(s, primary)
if err != nil {
findings = append(findings, Finding{
Kind: FindingUnreadableFile,
Path: primary.Path(),
Cause: err,
})
continue
}
if installation != nil {
installations = append(installations, *installation)
}
}
return installations, findings
}
func inspectVanillaInstallation(
s *scan,
primary *artifact,
) (*Installation, error) {
launchProperties, hasLaunchProperties, err := readProductEntry(
s,
primary,
fabricLaunchPropertiesPath,
)
if err != nil {
return nil, err
}
if hasLaunchProperties && fabricLauncherPropertiesAreServer(launchProperties) {
return nil, nil
}
versionJSON, ok, err := readProductEntry(s, primary, mojangVersionJSONEntry)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
gameVersion, guarded, err := mojangVersionFromJSON(versionJSON)
if err != nil {
return nil, err
}
if guarded {
return nil, nil
}
identity := Identity{
Primary: catalog.VersionedRef{
Ecosystem: catalog.EcosystemMinecraft,
Name: catalog.Name("minecraft"),
Version: observedVersion(gameVersion),
},
}
installation := NewInstallation(identity, primary.Path())
return &installation, nil
}
// Package identify associates local package files with their upstream identities.
package identify
import (
"context"
"errors"
"fmt"
"strings"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/upstream"
"github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace"
)
// HashLookup resolves artifact fingerprints through the configured upstream
// catalogue, returning one resolution per fingerprint in input order. Callers
// inject the routing capability they own.
type HashLookup func(
ctx context.Context,
artifacts []upstream.ArtifactFingerprint,
) []upstream.ArtifactReleaseResolution
// Packages adds upstream identities for observed.UnidentifiedPackageFiles.
// A non-nil resolutions map supplies and retains lookup outcomes by path,
// including misses and provider errors. Unmatched paths remain unidentified.
func Packages(
ctx context.Context,
observed *workspace.Workspace,
lookup HashLookup,
resolutions map[string]upstream.ArtifactReleaseResolution,
) []error {
if observed == nil || len(observed.UnidentifiedPackageFiles) == 0 {
return nil
}
candidates := observed.UnidentifiedPackageFiles
var fingerprints []upstream.ArtifactFingerprint
for _, path := range candidates {
if _, resolved := resolutions[path]; !resolved {
fingerprints = append(fingerprints, observed.PackageAnalysis(path))
}
}
if len(fingerprints) > 0 && lookup == nil {
return []error{errors.New("package identification requires a hash lookup")}
}
var lookups []upstream.ArtifactReleaseResolution
if len(fingerprints) > 0 {
lookups = lookup(ctx, fingerprints)
}
var (
idx *workspace.PackageIndex
unidentified []string
errs []error
)
next := 0
for _, path := range candidates {
resolution, resolved := resolutions[path]
if !resolved {
resolution = lookups[next]
next++
if resolutions != nil {
resolutions[path] = resolution
}
}
if resolution.Matched && resolution.Release.Ref.Name != "" {
if idx == nil {
idx = workspace.NewPackageIndex()
idx.Merge(observed.Packages)
}
idx.Add(identifiedPackage(path, resolution.Release.Ref))
} else {
unidentified = append(unidentified, path)
}
for _, providerErr := range resolution.Errors {
errs = append(errs, fmt.Errorf("%s: %w", path, providerErr))
}
}
if idx != nil {
observed.Packages = idx.Packages()
}
observed.UnidentifiedPackageFiles = unidentified
return errs
}
func identifiedPackage(
path string,
ref catalog.VersionedRef,
) workspace.DiscoveredPackage {
ecosystem := ref.Ecosystem
if ecosystem == catalog.EcosystemUnspecified {
ecosystem = catalog.EcosystemForge
}
resolved := ref.Version
if resolved == "" {
resolved = version.Unknown
}
name := ref.Name
if ref.Provider == catalog.ProviderMCDR {
name = catalog.Name(
strings.ReplaceAll(string(ref.Name), "_", "-"),
)
}
return workspace.DiscoveredPackage{
ID: catalog.VersionedRef{
Name: name,
Provider: ref.Provider,
Ecosystem: ecosystem,
Version: resolved,
},
Path: path,
}
}
// Package workspace observes a Minecraft server directory (i.e., a workspace).
//
// The package collects the following information:
//
// - the server runtime that runs in the directory
// - the directories that hold content packages
// - the content packages that are installed
// - the running state of the server process
//
// Observe returns a Workspace pointer. A Workspace is one local observation:
// ServerDir, Wrappers, Discovery, Packages, UnidentifiedPackageFiles, and
// Warnings store the facts, and every other member is a method over them.
//
// Observation is local-only: the package reads the server directory and the
// installed artifacts, and never contacts upstream services. Resolving the
// upstream identity of a package is a separate step.
package workspace
import (
"errors"
"path/filepath"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/document"
versionpkg "github.com/mclucy/lucy/version"
"github.com/mclucy/lucy/workspace/discovery"
)
const sessionLockName = "session.lock"
// Workspace is one consistent observation of a server directory.
type Workspace struct {
// ServerDir is the server directory that the observation describes.
// If MCDR manages the anchor, then ServerDir is the MCDR working
// directory.
ServerDir string `json:"root"`
Wrappers WrapperInfo `json:"wrappers"`
// Warnings records the recoverable problems seen while observing the
// directory, such as MCDR version-detection failures. It stays out of
// the JSON wire format; CLI presentation reports the entries once per
// consumed observation.
Warnings []error `json:"-"`
// Discovery holds the observed installations, ownership diagnostics,
// and the runtime selected from the request and the applicable
// declaration. Presentation projects this result explicitly.
Discovery discovery.Result `json:"-"`
// Packages contains identities associated with installed package files.
// Observation fills it from descriptors; identification can add hash matches.
Packages []DiscoveredPackage `json:"packages"`
// UnidentifiedPackageFiles lists JAR paths without a known package identity.
// A missing or unreadable descriptor does not establish that a file is a
// valid package.
UnidentifiedPackageFiles []string `json:"-"`
analyses *artifact.Analyses
// declared is the applicable declaration derived from the manifest and
// lock, if any. Later selections keep its authority.
declared *discovery.Declaration
// selectionErr records why the current selection is not valid. A nil
// error means the observation selected a runtime.
selectionErr error
}
// Observe builds one observation of root. The request carries an explicit
// entry point and the selection policy. Observe derives the applicable
// declaration from the local manifest and lock itself, discovers
// installations, verifies receipt ownership, selects a runtime, and then
// observes the package directories of the selected runtime.
//
// Selection happens before package observation so package directories always
// belong to the runtime that the observation reports.
func Observe(root string, request discovery.Request) *Workspace {
return ObserveWithAnalyses(root, request, nil)
}
// ObserveWithAnalyses reuses package evidence from an enclosing operation.
func ObserveWithAnalyses(root string, request discovery.Request, analyses *artifact.Analyses) *Workspace {
ws := ObserveRuntime(root, request)
ws.analyses = analyses
ws.observePackages()
return ws
}
// PackageAnalysis returns local evidence for a path in this observation.
func (ws *Workspace) PackageAnalysis(path string) *artifact.Analysis {
return ws.analyses.File(path)
}
// ObserveRuntime observes the runtime without opening the package files.
func ObserveRuntime(root string, request discovery.Request) *Workspace {
anchor, err := filepath.Abs(root)
if err != nil {
return &Workspace{}
}
wrappers, warnings := detectWrappers(anchor)
declaration, locked := applicableDeclaration(anchor)
ws := &Workspace{
ServerDir: resolveServerDir(anchor, wrappers),
Wrappers: wrappers,
Warnings: warnings,
declared: declaration,
}
if locked != nil {
ws.ServerDir = filepath.Join(anchor, filepath.FromSlash(locked.Server.Directory))
}
ws.Discovery = discovery.Discover(ws.ServerDir)
ws.Discovery.ObserveOwnership(anchor)
request.Declared = declaration
ws.selectionErr = ws.Discovery.Select(request)
return ws
}
// Select changes the runtime selection of this observation and replaces the
// package observation with the directories that the resulting selection names.
// Package data therefore never describes another selection, including when the
// attempt selects no runtime. Select preserves the declaration derived during
// observation and never rescans installations.
func (ws *Workspace) Select(request discovery.Request) error {
if ws == nil {
return errors.New("workspace: no observation")
}
if request.Declared == nil {
request.Declared = ws.declared
}
ws.selectionErr = ws.Discovery.Select(request)
ws.observePackages()
return ws.selectionErr
}
// SelectionError reports why this observation has no valid runtime selection.
// It is nil when a runtime was selected.
func (ws *Workspace) SelectionError() error {
if ws == nil {
return nil
}
return ws.selectionErr
}
// observePackages observes the package directories of the current selection
// and replaces Packages and UnidentifiedPackageFiles. An unresolved selection
// leaves only the wrapper-owned package directories.
func (ws *Workspace) observePackages() {
if ws == nil {
return
}
runtime := catalog.EcosystemUnspecified
if selection := ws.Runtime(); selection != nil {
runtime = selection.Ecosystem()
}
packages, unidentified, warnings := discoverPackages(
ws.PackageDirs(),
mcdrPluginDirs(ws.Wrappers),
runtime,
ws.analyses,
)
ws.Packages, ws.UnidentifiedPackageFiles = packages, unidentified
ws.Warnings = append(ws.Warnings, warnings...)
}
// applicableDeclaration builds the runtime declaration from a readable
// manifest and a valid lock whose runtime identity agrees with the manifest.
// Package-only intent changes do not invalidate runtime authority.
func applicableDeclaration(
root string,
) (*discovery.Declaration, *document.Lock) {
declared, err := document.ManifestFile(root).Read()
if err != nil {
return nil, nil
}
locked, err := document.LockFile(root).Read()
if err != nil {
return nil, nil
}
if declared.Server.Directory != locked.Server.Directory ||
declared.Server.Minecraft != locked.Server.Minecraft ||
declared.Server.Core.Product != locked.Server.Product ||
(concreteRuntimeVersion(declared.Server.Core.ProductVersion) &&
declared.Server.Core.ProductVersion != locked.Server.CoreVersion) {
return nil, nil
}
return &discovery.Declaration{
Product: locked.Server.Product,
Minecraft: locked.Server.Minecraft,
CoreVersion: locked.Server.CoreVersion,
}, locked
}
// resolveServerDir returns the directory that holds the server. Only MCDR
// moves the server away from the anchor. MCDR uses its configured working
// directory.
func resolveServerDir(anchor string, wrappers WrapperInfo) string {
if wrappers.MCDR != nil {
return wrappers.MCDR.Config.workingDirectory(anchor)
}
return anchor
}
func concreteRuntimeVersion(version versionpkg.Version) bool {
switch version {
case "", versionpkg.None, versionpkg.Unknown, versionpkg.Any,
versionpkg.Stable, versionpkg.Beta:
return false
default:
return true
}
}
func mcdrPluginDirs(wrappers WrapperInfo) []string {
if wrappers.MCDR == nil {
return nil
}
return wrappers.MCDR.Config.PluginDirectories
}
// Runtime returns the selected runtime, or nil when the observation did not
// settle on one. Every non-nil result satisfies IsValid.
func (ws *Workspace) Runtime() *discovery.Selection {
if ws == nil {
return nil
}
return ws.Discovery.Selected()
}
// Running reports whether the server runs at this moment. The check probes
// an exclusive lock on the session file. Running performs I/O on every call,
// because activity changes over time. Running returns false when no single
// runtime exists, or when the save location is unknown.
func (ws *Workspace) Running() bool {
if ws == nil || ws.Runtime() == nil {
return false
}
saveDir := ws.SaveDir()
if saveDir == "" {
return false
}
return checkSessionLock(filepath.Join(saveDir, sessionLockName))
}
package workspace
import (
"github.com/mclucy/lucy/workspace/discovery"
)
// RunningAt checks the native world session lock without catalogue or app lookup.
func RunningAt(anchor string) bool {
root := readMCDRWorkingDirectory(anchor)
ws := &Workspace{ServerDir: root}
ws.Discovery = discovery.Discover(root)
ws.selectionErr = ws.Discovery.Select(discovery.Request{})
return ws.Running()
}
package workspace
import (
"slices"
"strings"
"github.com/mclucy/lucy/catalog"
serverpkg "github.com/mclucy/lucy/server"
"github.com/mclucy/lucy/workspace/discovery"
)
// ServedEcosystem is one ecosystem that a runtime can serve with a
// compatibility note.
type ServedEcosystem struct {
Ecosystem catalog.Ecosystem `json:"ecosystem"`
Compatibility Compatibility `json:"compatibility"`
}
// ServedEcosystems lists the package ecosystems an observed workspace
// can serve. The list contains:
//
// - direct ecosystems from the detected runtime
// - bridged ecosystems through installed packages. Example: Sinytra
// Connector
//
// Consumers should call this method. selectionServedEcosystems gives only the
// direct ecosystems.
func (ws *Workspace) ServedEcosystems() []ServedEcosystem {
if ws == nil {
return nil
}
offers := selectionServedEcosystems(ws.Runtime())
if hasDirectOffer(offers, catalog.EcosystemForge) ||
hasDirectOffer(offers, catalog.EcosystemNeoForge) {
for _, pkg := range ws.Packages {
if !isConnectorBridgePackage(pkg) {
continue
}
offers = appendServedEcosystem(
offers,
catalog.EcosystemFabric,
CompatDegraded,
)
break
}
}
return offers
}
// ProductServedEcosystems derives native offers from a server product and its
// loader components, independent of installed packages.
func ProductServedEcosystems(
product catalog.VersionedRef,
components []catalog.VersionedRef,
) []ServedEcosystem {
return productServedEcosystems(product.Name.String(), product, components)
}
// selectionServedEcosystems derives offers from the selected installation
// identity only; installed packages never contribute.
func selectionServedEcosystems(
selection *discovery.Selection,
) []ServedEcosystem {
if selection == nil || !selection.IsValid() || selection.Installation == nil {
return nil
}
identity := selection.Installation.Identity
return productServedEcosystems(
identity.Primary.Name.String(),
identity.Primary,
identity.Components,
)
}
func productServedEcosystems(
name string,
primary catalog.VersionedRef,
components []catalog.VersionedRef,
) []ServedEcosystem {
offers := make([]ServedEcosystem, 0, 3)
name = strings.ToLower(strings.TrimSpace(name))
// Hybrid products bridge ecosystems that no loader table row expresses,
// such as Arclight serving both Forge and Bukkit.
switch name {
case "arclight", "arclight-forge", "arclight-neoforge", "arclight-fabric":
switch name {
case "arclight-forge":
offers = appendServedEcosystem(offers, catalog.EcosystemForge, CompatFull)
case "arclight-neoforge":
offers = appendServedEcosystem(offers, catalog.EcosystemNeoForge, CompatFull)
case "arclight-fabric":
offers = appendServedEcosystem(offers, catalog.EcosystemFabric, CompatFull)
default:
for _, ecosystem := range selectedLoaderEcosystems(components) {
offers = appendServedEcosystem(offers, ecosystem, CompatFull)
}
}
if len(offers) > 0 {
offers = appendServedEcosystem(
offers,
catalog.EcosystemBukkit,
CompatFull,
)
}
case "catserver":
offers = appendServedEcosystem(
offers,
catalog.EcosystemForge,
CompatFull,
)
offers = appendServedEcosystem(
offers,
catalog.EcosystemBukkit,
CompatFull,
)
case "youer":
offers = appendServedEcosystem(
offers,
catalog.EcosystemNeoForge,
CompatFull,
)
offers = appendServedEcosystem(
offers,
catalog.EcosystemPaper,
CompatFull,
)
offers = appendServedEcosystem(
offers,
catalog.EcosystemBukkit,
CompatFull,
)
case "spongevanilla", "spongeforge", "spongeneo":
offers = appendServedEcosystem(
offers,
catalog.EcosystemSponge,
CompatFull,
)
for _, ecosystem := range selectedLoaderEcosystems(
components,
) {
if ecosystem == catalog.EcosystemFabric {
continue
}
offers = appendServedEcosystem(
offers,
ecosystem,
CompatFull,
)
}
case "velocity":
offers = appendServedEcosystem(
offers,
catalog.EcosystemVelocity,
CompatFull,
)
case "bungeecord", "waterfall":
offers = appendServedEcosystem(
offers,
catalog.EcosystemBungeeCord,
CompatFull,
)
default:
offers = appendProductOffers(offers, primary, name)
}
return offers
}
// appendProductOffers adds the ecosystems a product serves on its own. A
// product without a package family serves no packages, unless its name
// resolves to one that does.
func appendProductOffers(
offers []ServedEcosystem,
primary catalog.VersionedRef,
name string,
) []ServedEcosystem {
ecosystem := primary.Ecosystem
if ecosystem.IsUnspecified() {
if product, ok := serverpkg.ParseProduct(name); ok {
ecosystem = product.Ecosystem()
}
}
if ecosystem.Family() == catalog.FamilyNone {
return offers
}
for _, served := range ecosystem.Loads() {
offers = appendServedEcosystem(offers, served, CompatFull)
}
return offers
}
func appendServedEcosystem(
offers []ServedEcosystem,
ecosystem catalog.Ecosystem,
compatibility Compatibility,
) []ServedEcosystem {
if ecosystem == catalog.EcosystemUnspecified {
return offers
}
for i := range offers {
if offers[i].Ecosystem != ecosystem {
continue
}
if compatibility == CompatFull {
offers[i].Compatibility = compatibility
}
return offers
}
return append(offers, ServedEcosystem{
Compatibility: compatibility,
Ecosystem: ecosystem,
})
}
func selectedLoaderEcosystems(
components []catalog.VersionedRef,
) []catalog.Ecosystem {
var ecosystems []catalog.Ecosystem
for _, component := range components {
if _, ok := serverpkg.LoaderComponentName(
component.Ecosystem,
component.Name.String(),
); !ok {
continue
}
ecosystems = appendUniqueEcosystem(ecosystems, component.Ecosystem)
}
return ecosystems
}
func appendUniqueEcosystem(
ecosystems []catalog.Ecosystem,
ecosystem catalog.Ecosystem,
) []catalog.Ecosystem {
if slices.Contains(ecosystems, ecosystem) {
return ecosystems
}
return append(ecosystems, ecosystem)
}
func hasDirectOffer(
offers []ServedEcosystem,
ecosystem catalog.Ecosystem,
) bool {
for _, offer := range offers {
if offer.Ecosystem == ecosystem &&
offer.Compatibility == CompatFull {
return true
}
}
return false
}
// isConnectorBridgePackage reports whether pkg is Sinytra Connector. The
// mod id varied over time:
//
// - "connectormod": FML modId of releases up to 1.20.1
// - "connector": FML modId since 1.21 (renamed per
// https://github.com/Sinytra/Connector/discussions/1293) and the
// Modrinth project slug
// - "sinytra-connector": the CurseForge project slug
func isConnectorBridgePackage(pkg DiscoveredPackage) bool {
if pkg.ID.Ecosystem != catalog.EcosystemForge &&
pkg.ID.Ecosystem != catalog.EcosystemNeoForge {
return false
}
switch strings.ToLower(strings.TrimSpace(pkg.ID.Name.String())) {
case "sinytra-connector", "connector", "connectormod":
return true
default:
return false
}
}
package workspace
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
versionpkg "github.com/mclucy/lucy/version"
)
const mcdrConfigFileName = "config.yml"
// detectWrappers reads the wrappers of a server directory and the
// recoverable warnings seen while reading them. These wrappers do not come
// from jars. An MCDR installation manages a server directory from outside
// the directory.
func detectWrappers(dir string) (WrapperInfo, []error) {
var wrappers WrapperInfo
warnings := detectMCDRWrapper(dir, &wrappers)
return wrappers, warnings
}
// detectMCDRWrapper detects an MCDR managed directory and returns the MCDR
// version-detection warnings. The marker is the config.yml file. It records
// the wrapper version. The version comes from the mcdreforged command on
// PATH. Relative plugin directories resolve against dir.
//
// MCDR changes the server directory, so later consumers will not depend on
// pwd. Warnings are diagnostics for CLI presentation; the wrapper detection
// itself only logs them.
func detectMCDRWrapper(dir string, wrappers *WrapperInfo) []error {
var warnings []error
configPath := filepath.Join(dir, mcdrConfigFileName)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil
}
config, err := readMCDRConfig(configPath)
if err != nil {
return []error{err}
}
for i, pluginDir := range config.PluginDirectories {
if !filepath.IsAbs(pluginDir) {
config.PluginDirectories[i] = filepath.Join(dir, pluginDir)
}
}
// A hung mcdreforged must not block workspace observation.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
version := versionpkg.Unknown
// MCDReforged is provisioned by install, so absence from PATH is normal.
if output, err := exec.CommandContext(ctx, "mcdreforged", "--version").Output(); err == nil {
if fields := strings.Fields(string(output)); len(fields) > 1 {
version = versionpkg.Version(fields[1])
} else {
warnErr := fmt.Errorf("cannot parse mcdr version output")
warnings = append(warnings, warnErr)
}
}
wrappers.MCDR = &MCDREnv{
Version: version,
Config: config,
}
return warnings
}
package workspace
import (
"fmt"
"os"
"path/filepath"
"github.com/mclucy/lucy/version"
"go.yaml.in/yaml/v4"
)
// WrapperInfo describes non-jar wrappers around a server directory.
type WrapperInfo struct {
MCDR *MCDREnv `json:"mcdr,omitempty"`
}
type MCDREnv struct {
Version version.Version `json:"version"`
Config *MCDRConfig `json:"config,omitempty"`
}
// MCDRConfig is the subset of an MCDR config.yml file that Lucy consumes.
// Unknown keys stay ignored so an MCDR upgrade does not break observation.
type MCDRConfig struct {
WorkingDirectory string `yaml:"working_directory"`
PluginDirectories []string `yaml:"plugin_directories"`
}
func readMCDRConfig(path string) (*MCDRConfig, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("cannot open %s: %w", path, err)
}
defer file.Close()
config := &MCDRConfig{}
if err := yaml.NewDecoder(file).Decode(config); err != nil {
return nil, fmt.Errorf("cannot decode %s: %w", path, err)
}
return config, nil
}
// ServerDirectory returns the directory that holds the server at anchor. Only
// MCDR moves the server away from the anchor, and it uses its configured
// working directory. A missing or unreadable configuration leaves the anchor.
func ServerDirectory(anchor string) string {
return readMCDRWorkingDirectory(anchor)
}
// readMCDRWorkingDirectory resolves the server directory of an MCDR anchor
// while decoding only working_directory. Activity checks must stay tolerant of
// unrelated malformed configuration fields.
func readMCDRWorkingDirectory(anchor string) string {
file, err := os.Open(filepath.Join(anchor, mcdrConfigFileName))
if err != nil {
return anchor
}
defer file.Close()
var config struct {
WorkingDirectory string `yaml:"working_directory"`
}
if err := yaml.NewDecoder(file).Decode(&config); err != nil {
return anchor
}
return resolveMCDRWorkingDirectory(anchor, config.WorkingDirectory)
}
func (c *MCDRConfig) workingDirectory(anchor string) string {
if c == nil {
return anchor
}
return resolveMCDRWorkingDirectory(anchor, c.WorkingDirectory)
}
// resolveMCDRWorkingDirectory resolves a configured working directory against
// the MCDR anchor.
func resolveMCDRWorkingDirectory(anchor, workingDirectory string) string {
if workingDirectory == "" {
return anchor
}
if filepath.IsAbs(workingDirectory) {
return workingDirectory
}
return filepath.Join(anchor, workingDirectory)
}
package workspace
import (
"cmp"
"sort"
)
// PackageIndex collects identities while keeping distinct installed paths.
// Adoption needs every conflicting file, not one representative by identity.
type PackageIndex struct {
pkgs map[string]DiscoveredPackage
extras map[[2]string]DiscoveredPackage
}
func NewPackageIndex() *PackageIndex {
return &PackageIndex{
pkgs: make(map[string]DiscoveredPackage),
}
}
// Add keeps the first observation of a package at a path. An observation with
// a path replaces a pathless one for the same identity.
func (idx *PackageIndex) Add(pkg DiscoveredPackage) {
key := pkg.ID.StringQualified()
if existing, exists := idx.pkgs[key]; exists {
if pkg.Path == "" || existing.Path == pkg.Path {
return
}
if existing.Path != "" {
if idx.extras == nil {
idx.extras = make(map[[2]string]DiscoveredPackage)
}
file := [2]string{key, pkg.Path}
if _, ok := idx.extras[file]; !ok {
idx.extras[file] = pkg
}
return
}
}
idx.pkgs[key] = pkg
}
// Merge bulk-adds a slice of packages into the index. Each package is subject
// to the same dedupe policy as Add.
func (idx *PackageIndex) Merge(pkgs []DiscoveredPackage) {
for _, pkg := range pkgs {
idx.Add(pkg)
}
}
// Packages returns the index in identity and path order.
func (idx *PackageIndex) Packages() []DiscoveredPackage {
result := make([]DiscoveredPackage, 0, len(idx.pkgs)+len(idx.extras))
for _, pkg := range idx.pkgs {
result = append(result, pkg)
}
for _, pkg := range idx.extras {
result = append(result, pkg)
}
sort.Slice(result, func(i, j int) bool {
pi, pj := result[i].ID, result[j].ID
if c := cmp.Compare(pi.Ecosystem.String(), pj.Ecosystem.String()); c != 0 {
return c < 0
}
if c := cmp.Compare(pi.Name.String(), pj.Name.String()); c != 0 {
return c < 0
}
if c := cmp.Compare(pi.Version.String(), pj.Version.String()); c != 0 {
return c < 0
}
if c := cmp.Compare(pi.Provider, pj.Provider); c != 0 {
return c < 0
}
return result[i].Path < result[j].Path
})
return result
}
package workspace
import (
"fmt"
"os"
"path/filepath"
"slices"
"sync"
"github.com/mclucy/lucy/artifact"
"github.com/mclucy/lucy/catalog"
)
// discoverPackages inventories the packages under searchPaths and
// mcdrPluginDirs, when the MCDR wrapper exists. Deduplication and
// local-path enrichment follow the PackageIndex.Add policy.
//
// The scan is local-only. Each artifact keeps the descriptor of the runtime
// the server selects. It returns the discovered packages together with the
// sorted, deduplicated paths of jar files whose descriptor could not be read.
// Identifying those packages is a separate step.
func discoverPackages(
searchPaths []string,
mcdrPluginDirs []string,
runtime catalog.Ecosystem,
analyses *artifact.Analyses,
) ([]DiscoveredPackage, []string, []error) {
idx := NewPackageIndex()
var unidentified []string
var warnings []error
readInfo := func(path string) (infos []artifact.PackageInfo, err error) {
if analyses == nil {
return artifact.ReadInfo(path)
}
return analyses.File(path).Info()
}
for _, searchPath := range searchPaths {
jarFiles, err := findJar(searchPath)
if err != nil {
warnings = append(warnings, fmt.Errorf("cannot read the mod directory: %w", err))
continue
}
packages := make([][]artifact.PackageInfo, len(jarFiles))
workers := min(8, len(jarFiles))
var wg sync.WaitGroup
for worker := range workers {
wg.Go(func() {
for i := worker; i < len(jarFiles); i += workers {
infos, err := readInfo(jarFiles[i])
if err == nil {
packages[i] = artifact.PreferredPackageInfos(infos, runtime)
}
}
})
}
wg.Wait()
for i, infos := range packages {
if len(infos) == 0 {
unidentified = append(unidentified, jarFiles[i])
continue
}
idx.Merge(artifactInfoToDiscoveredPackage(infos))
}
}
for _, dir := range mcdrPluginDirs {
pluginFiles, err := findFileWithExt([]string{dir}, ".pyz", ".mcdr")
if err != nil {
warnings = append(warnings, fmt.Errorf("cannot read the MCDR plugin directory: %w", err))
continue
}
for _, pluginFile := range pluginFiles {
analyzed, err := readInfo(pluginFile)
analyzed = artifact.PreferredPackageInfos(
analyzed,
catalog.EcosystemMCDR,
)
if err == nil && len(analyzed) > 0 {
pkgs := artifactInfoToDiscoveredPackage(analyzed)
idx.Merge(pkgs)
}
}
}
return idx.Packages(), sortUniquePaths(unidentified), warnings
}
// sortUniquePaths returns paths in ascending order without duplicates. A
// nil or single-element input is returned as is.
func sortUniquePaths(paths []string) []string {
if len(paths) < 2 {
return paths
}
slices.Sort(paths)
return slices.Compact(paths)
}
// findJar lists regular files with a .jar extension directly inside each
// given directory. It does not walk subdirectories. Servers keep their
// runtime jars at shallow locations with known names.
func findJar(dir ...string) ([]string, error) {
return findFileWithExt(dir, ".jar")
}
func findFileWithExt(dirs []string, ext ...string) ([]string, error) {
var files []string
for _, dir := range dirs {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if slices.Contains(ext, filepath.Ext(entry.Name())) {
files = append(files, filepath.Join(dir, entry.Name()))
}
}
}
return files, nil
}
func artifactInfoToDiscoveredPackage(infos []artifact.PackageInfo) []DiscoveredPackage {
if len(infos) == 0 {
return nil
}
pkgs := make([]DiscoveredPackage, 0, len(infos))
for _, info := range infos {
pkg := DiscoveredPackage{
ID: catalog.VersionedRef{
Ref: info.Ref.Ref,
Ecosystem: info.Ref.Ecosystem,
Version: info.Ref.Version,
},
Path: info.FilePath,
}
if len(info.Dependencies) > 0 {
deps := make([]catalog.Dependency, 0, len(info.Dependencies))
for _, dep := range info.Dependencies {
deps = append(deps, catalog.Dependency{
ID: catalog.VersionedRef{
Ref: dep.Ref.Ref,
Ecosystem: dep.Ref.Ecosystem,
},
Constraint: dep.Constraint,
Mandatory: dep.Mandatory,
Origin: catalog.NormalizeDependencyOrigin(dep.Origin),
})
}
pkg.Dependencies = deps
}
pkgs = append(pkgs, pkg)
}
return pkgs
}
package workspace
import (
"path/filepath"
"slices"
"github.com/mclucy/lucy/catalog"
"github.com/mclucy/lucy/internal/fileschema"
"github.com/mclucy/lucy/workspace/discovery"
"unknwon.dev/ini/v2"
)
// PackageDirs lists the directories that hold content packages for this
// observation. Loader runtimes use mods/. Bukkit family servers use
// plugins/. The list is empty when no runtime was identified.
func (ws *Workspace) PackageDirs() []string {
if ws == nil {
return nil
}
return packageSearchPaths(ws.Runtime(), ws.ServerDir)
}
// packageSearchPaths maps full-support ecosystem offers onto conventional
// directory names. Duplicate names appear once, in offer order.
func packageSearchPaths(
selection *discovery.Selection,
root string,
) []string {
if selection == nil || !selection.IsValid() {
return nil
}
var paths []string
for _, offer := range selectionServedEcosystems(selection) {
if offer.Compatibility != CompatFull {
continue
}
var path string
switch offer.Ecosystem.Family() {
case catalog.FamilyMod:
path = filepath.Join(root, "mods")
case catalog.FamilyPlugin:
path = filepath.Join(root, "plugins")
default:
continue
}
duplicate := slices.Contains(paths, path)
if !duplicate {
paths = append(paths, path)
}
}
return paths
}
// SaveDir returns the world save directory from server.properties. The path
// is ServerDir joined with the level-name property. SaveDir returns an empty
// string when no usable properties file exists. A missing level-name
// degrades to ServerDir. This matches the runtime default of storing the
// world beside the server.
func (ws *Workspace) SaveDir() string {
if ws == nil {
return ""
}
properties := parseServerProperties(ws.ServerDir)
if properties == nil {
return ""
}
return filepath.Join(ws.ServerDir, properties["level-name"])
}
// parseServerProperties reads root/server.properties into a flat map of key
// and value pairs. It returns nil after any read error or parse error. A
// missing file is normal for new server directories.
func parseServerProperties(
root string,
) fileschema.FileMinecraftServerProperties {
file, err := ini.Load(filepath.Join(root, "server.properties"))
if err != nil {
return nil
}
properties := make(map[string]string, len(file.Sections())*8)
for _, section := range file.Sections() {
for _, key := range section.Keys() {
properties[key.Name()] = key.String()
}
}
return properties
}
//go:build unix || darwin || linux
package workspace
import (
"bytes"
"errors"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
)
// checkSessionLock reports whether another process holds session.lock. A
// result of false covers every failure mode. An unreadable or unlocked file
// says nothing about a running server.
//
// lsof runs first. Plain flock probes were unstable on some Linux kernels.
// lsof gives a definite answer when a java process holds the file open.
func checkSessionLock(lockPath string) bool {
if sessionLockHeldByLsof(lockPath) {
return true
}
file, err := os.OpenFile(lockPath, os.O_RDWR|os.O_APPEND, 0o666)
if err != nil {
return false
}
defer file.Close()
err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err != nil && errors.Is(err, syscall.EWOULDBLOCK) {
return true
} else if err != nil {
return false
}
_ = syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
return false
}
// sessionLockHeldByLsof asks the lsof tool whether any process holds
// filePath open.
func sessionLockHeldByLsof(filePath string) bool {
cmd := exec.Command("lsof", filePath)
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return false
}
lines := strings.Split(out.String(), "\n")
outputBegin := 0
for i, line := range lines {
if strings.Contains(line, "COMMAND") {
outputBegin = i + 1
break
}
}
for _, line := range lines[outputBegin:] {
fields := strings.Fields(line)
if len(fields) >= 2 &&
fields[0] == "java" &&
pidLike(fields[1]) {
return true
}
}
return false
}
func pidLike(field string) bool {
_, err := strconv.Atoi(field)
return err == nil
}