GitHub快速開始

API 參考取自原始碼中的 Go 文件註解,以英文撰寫。

package datatable

import "github.com/nsgo-dev/game/pkg/datatable"

概覽

Package datatable is experimental: its API and documented formats may change in a minor release. See the API stability policy. loads typed game data tables (enemies, items, levels, quests) from CSV, JSON, and YAML with rich per-cell error reporting and live hot reload.

YAML is the table format this repository defines: a mapping with a version field (FormatVersion) and a rows list, in which every key of a row names a field of the row type. Unknown fields, duplicate fields, missing or unsupported versions are refused. MarshalYAML and SaveYAML write the same format deterministically (fields in struct order, two-space indentation), so a table loaded and saved again is unchanged. CSV and JSON tables are read as their tools export them.

索引

常數

const FormatVersion = 1

FormatVersion is the schema version of a YAML data table: LoadYAML accepts only this version and MarshalYAML writes it.

變數

var ErrDanglingReference = errors.New("unknown referenced key")

ErrDanglingReference is the error a CellError wraps when a referenced key is missing from the candidate snapshot.

var ErrDuplicateField = errors.New("duplicate field")

ErrDuplicateField is the error a CellError wraps when a YAML row sets the same field twice, for example as "hp" and "HP".

var ErrDuplicateKey = errors.New("duplicate primary key")

ErrDuplicateKey is the error a CellError wraps when two rows share a primary key.

var ErrUnknownField = errors.New("unknown field")

ErrUnknownField is the error a CellError wraps when a YAML row has a key that names no field of the row type.

函式

func LoadCSV[T any](filename string, data []byte) ([]T, error)

LoadCSV parses UTF-8 CSV data with a header row into []T. Slice fields in CSV cells may be delimited by ';', '|', or ','.

func LoadFile[T any](path string) ([]T, error)

LoadFile reads path from disk and decodes it into []T based on its file extension (.csv, .json, .yaml, or .yml).

func LoadJSON[T any](filename string, data []byte) ([]T, error)

LoadJSON parses a JSON array of objects into []T.

func LoadYAML[T any](filename string, data []byte) ([]T, error)

LoadYAML parses a versioned YAML data table into []T. Its errors about the document are *loaderr.Error values that name filename, the line and a fix; one about a cell wraps the *CellError.

The document is a mapping with two keys: version, which must equal FormatVersion, and rows, a list of mappings whose keys name fields of T by their table tag, json tag or Go field name (matched exactly first, then case-insensitively). A missing or empty rows key is an empty table. Any other top-level key, a missing or unsupported version, a row key that names no field (ErrUnknownField) and a field set twice in one row (ErrDuplicateField) are refused, as are a merge key (<<), a second YAML document in the same file, and a row type in which two fields share a column name; errors inside a row are a *CellError naming the 1-based row and the field.

func Lookup[T any, K comparable](s *Snapshot, name string, key K) (T, bool)

Lookup returns the indexed row from name in this generation. K must be the primary key column's Go type. Treat any nested row data as read-only.

func MarshalYAML[T any](rows []T) ([]byte, error)

MarshalYAML encodes rows as a versioned YAML data table that LoadYAML reads back.

The output is deterministic: version first, then rows, each row writing every field of T in struct declaration order under its table tag, json tag or Go field name, with two-space indentation. Lists are written inline ([a, b]), a nil pointer as null, and a time.Duration as its String form (such as 1.5s). A nil list and an empty list are both written as [], which loads back as an empty list. Non-finite floats, field types LoadYAML cannot read (maps, structs, interfaces) and a row type in which two fields share a column name are an error.

func MatchPattern(pattern, filePath string) (bool, error)

MatchPattern reports whether filePath matches pattern. Both paths are normalized to forward slashes with leading "./" removed. A pattern with no '/' matches path.Base(filePath). A "**" path segment matches zero or more segments.

func RegisterRowType[T any](r *Registry, pattern string) error

RegisterRowType registers Go struct row type T for files matching pattern in r.

func RegisterTable[T any](s *Set, name, path string) error

RegisterTable adds a file and its row type under name for the next Reload.

func Rows[T any](s *Snapshot, name string) []T

Rows returns the shared slice for name, or nil if the table has a different row type or is absent. Treat the slice, its rows and any nested values as read-only. A later reload leaves the slice reachable through this snapshot.

func SaveYAML[T any](path string, rows []T) error

SaveYAML writes rows to path as a versioned YAML data table in the form MarshalYAML produces.

func Schema[T any](opts jsonschema.Options) (*jsonschema.Schema, error)

Schema returns the JSON Schema of a YAML data table of T rows, the format LoadYAML reads and MarshalYAML writes, for an editor or AI tool to validate and complete a table file while it is written.

The schema is a mapping with a required version, which must equal FormatVersion, and rows, a list of T's rows that may be left out or null for a table with no rows; any other top-level key is refused. Each row is an object keyed by the column names LoadYAML matches, from a field's `table` tag, else its `json` tag, else its Go name, spelled as MarshalYAML writes them, with embedded structs that have neither tag merged in, as the loaders do. A row type in which two fields share a column name is an error, as it is for LoadYAML. A time.Duration is a string such as "1.5s" or an integer of nanoseconds.

The schema describes a table's canonical spelling, which is as strict as LoadYAML about unknown columns and stricter about the rest: it refuses other capitalizations of a column name (LoadYAML also matches a column name in another case), and wants each cell as its own type rather than a string LoadYAML would convert, and a list as a YAML sequence rather than a delimited string. LoadYAML also refuses merge keys (<<), which a YAML language server resolves before validating, so the schema cannot flag them.

opts sets the $id, title and descriptions; Schema fills in FieldName and the time.Duration form unless opts sets them, so a game can pass jsonschema.PackageDocs of its own package as opts.Docs to describe each column. The row schema is at #/definitions/<T's name>.

型別

type Cell struct {
	Key   string
	Value Value
}

Cell is a key-value entry in an ordered Row.

type CellError struct {
	File  string
	Row   int
	Field string
	Value string
	Err   error
}

CellError identifies the exact file, 1-based data row, and column/field name where parsing or type conversion failed.

The loaders return it inside a *loaderr.Error, which adds the cell's line and column in the file and a fix; errors.As finds either.

func (e *CellError) Error() string

Error returns the file name, row, field, value, and underlying parsing or conversion problem.

func (e *CellError) Unwrap() error

Unwrap returns the underlying parsing or conversion error.

type ColumnSpec struct {
	Name     string
	Kind     ValueKind
	ElemKind ValueKind
	Nullable bool
	Type     reflect.Type
}

ColumnSpec describes one column of a Go struct row type.

type Document struct {
	// contains filtered or unexported fields
}

Document is an untyped, round-trip editable YAML data table.

Each row keeps its own key order. Opening a table and calling Marshal without edits returns the exact input bytes; editing a single scalar or inline-list cell changes only that cell's line; structural edits (adding, deleting, or reordering rows, or adding a new key to a row) encode deterministically from the preserved YAML AST so untouched rows keep their key order, formatting, and comments.

func LoadDocument(path string) (*Document, error)

LoadDocument reads path from disk and parses it as an untyped YAML data table.

func NewDocument() *Document

NewDocument constructs an empty version 1 YAML data table document.

func ParseDocument(filename string, data []byte) (*Document, error)

ParseDocument parses a versioned YAML data table into an untyped Document. It enforces the same envelope rules as LoadYAML (version: 1, no unknown top-level keys, no merge keys, no duplicate keys, no trailing second document) without requiring a Go row type.

func (d *Document) AddRow(index int, cells ...Cell) error

AddRow inserts a new row at index (0 <= index <= RowCount()) with the given ordered cells.

func (d *Document) AppendRow(cells ...Cell) (int, error)

AppendRow appends a new row at the end of d and returns its 0-based index.

func (d *Document) Cell(row int, col string) (Value, bool)

Cell returns the value of col in row, and whether that cell is present.

func (d *Document) CellLine(row int, col string) int

CellLine returns the 1-based YAML line number of column col in row, or 0 if the cell or its line metadata is unavailable.

func (d *Document) Clone() *Document

Clone returns a deep copy of d, including its preserved bytes and YAML AST.

func (d *Document) ColumnKind(col string) ValueKind

ColumnKind infers the ValueKind of col from the non-null values present in d. It returns KindNull if no row has a non-null value for col, the shared kind if all non-null values agree, or KindString if values have mixed kinds.

func (d *Document) Columns() []string

Columns returns the union of all rows' keys in deterministic first-appearance order.

func (d *Document) DeleteCell(row int, col string) error

DeleteCell removes col from row if present.

func (d *Document) DeleteRow(index int) error

DeleteRow removes the row at index.

func (d *Document) Marshal() ([]byte, error)

Marshal encodes d back to YAML. If no edits have invalidated the preserved bytes, Marshal returns the exact preserved bytes (unchanged for an unedited file, or patched on only the edited lines); otherwise it encodes deterministically from the AST with two-space indentation.

func (d *Document) MoveRow(from, to int) error

MoveRow moves the row at index from to index to, preserving its key order, comments, and formatting.

func (d *Document) Row(index int) Row

Row returns a copy of row index.

func (d *Document) RowCount() int

RowCount returns the number of rows in d.

func (d *Document) RowLine(row int) int

RowLine returns the 1-based YAML line number where row begins in the parsed document, or 0 if line metadata is unavailable (for example on a newly added row).

func (d *Document) Rows() []Row

Rows returns copies of all rows in document order.

func (d *Document) Save(path string) error

Save marshals d and writes it to path.

func (d *Document) SetCell(row int, col string, val Value) error

SetCell updates or inserts col in row with val. Updating an existing scalar or inline-list cell on a block-style row patches only that line in the preserved YAML bytes; inserting a new key appends it to that row and encodes deterministically from the AST.

func (d *Document) Version() int

Version returns the table's format version (FormatVersion).

type Problem struct {
	// File is the slash-separated path relative to the checked filesystem root.
	File string
	// Line and Column are 1-based, or zero if the location is unknown.
	Line, Column int
	// Message describes the problem without the file position.
	Message string
}

Problem describes a file read or validation error from Registry.CheckFS.

type Registry struct {
	// contains filtered or unexported fields
}

Registry maps slash-separated file patterns (or basename patterns without '/') to Go row types so editors and tools can validate untyped YAML data tables with LoadYAML's rules.

func NewRegistry() *Registry

NewRegistry returns an empty Registry.

func (r *Registry) CheckFS(fsys fs.FS) []Problem

CheckFS checks the .yaml and .yml data tables matched by r, returning problems in filesystem walk order. It reports the first problem per matching file and any errors walking fsys. It skips directories whose names start with a dot or an underscore, and directories named testdata. A nil or empty registry does no work.

func (r *Registry) Clone() *Registry

Clone copies r's bindings, so registrations on the copy do not change r.

func (r *Registry) Lookup(pattern string) (*RowType, bool)

Lookup returns the RowType registered for pattern (after path normalization) and reports whether pattern is registered.

func (r *Registry) Match(filePath string) *RowType

Match returns the first registered RowType whose pattern matches filePath, or nil.

func (r *Registry) Register(pattern string, rt *RowType) error

Register binds pattern to rt. If pattern is already registered, its binding is replaced. Patterns are matched in registration order; a pattern without '/' matches the file's basename, and "**" matches zero or more path segments.

type Row struct {
	Cells []Cell
}

Row is an ordered mapping of column keys to cell values, preserving the YAML key order.

func (r Row) Clone() Row

Clone returns a deep copy of r.

func (r Row) Get(key string) (Value, bool)

Get returns the value of key in r and whether key is present.

func (r Row) Index(key string) int

Index returns the 0-based index of key in r, or -1 if absent.

func (r Row) Keys() []string

Keys returns the row's keys in their stored order.

type RowType struct {
	// contains filtered or unexported fields
}

RowType describes a Go struct row type so an untyped Document or editor grid can validate cells and rows with the exact same rules LoadYAML applies.

func RowTypeFor[T any]() (*RowType, error)

RowTypeFor builds a RowType for Go struct type T. It applies the same structural checks as LoadYAML[T] (must be a struct with no two fields sharing a column name).

func RowTypeOf(t reflect.Type) (*RowType, error)

RowTypeOf builds a RowType for Go struct type t.

func (rt *RowType) Column(col string) (ColumnSpec, bool)

Column looks up col by exact name first and then case-insensitively, as LoadYAML does.

func (rt *RowType) Columns() []ColumnSpec

Columns returns the row type's columns in struct declaration order.

func (rt *RowType) Name() string

Name returns the Go type name of rt.

func (rt *RowType) ParseCellText(filename string, row int, field, raw string) (Value, error)

ParseCellText parses raw grid text for field according to rt and validates it with LoadYAML's rules, returning the typed Value or a *CellError.

func (rt *RowType) Type() reflect.Type

Type returns the underlying Go reflect.Type of rt.

func (rt *RowType) ValidateCell(filename string, row int, field string, val Value) error

ValidateCell validates a single cell value against rt using LoadYAML's conversion rules. row is 0-based; CellError reports 1-based Row.

func (rt *RowType) ValidateDocument(filename string, doc *Document) error

ValidateDocument validates every row of doc and checks primary key uniqueness.

func (rt *RowType) ValidateRow(filename string, row int, r Row) error

ValidateRow checks every cell in r against rt, refusing unknown fields, duplicate fields (including case-insensitive duplicates such as "hp" and "HP"), and values LoadYAML refuses.

type Set struct {
	// contains filtered or unexported fields
}

Set publishes named, typed tables together. Its zero value is an empty set. A Set must not be copied after first use.

func NewSet(validate func(*Snapshot) error) *Set

NewSet creates an empty set. If validate is given, it checks a candidate snapshot before publication. It can read both the candidate and Current, but must not register tables or call Reload on the same set.

func (s *Set) Current() *Snapshot

Current reads the last successful publication, or nil before the first.

func (s *Set) Reload() error

Reload reads all registered tables, checks their references and optional validation function, and publishes them at the next version. Any error leaves Current unchanged.

type Snapshot struct {
	// contains filtered or unexported fields
}

Snapshot holds the rows of a Set from one successful reload.

func (s *Snapshot) Version() uint64

Version returns the generation of the snapshot, or zero before a set has loaded.

type Table[T any] struct {
	// contains filtered or unexported fields
}

Table holds a typed game data table loaded from disk. datatablewatch adds hot reloading via tooling/hotreload for game clients; headless builds such as a dedicated server load tables without it.

If a reload fails (for example due to a typo in a cell during editing), Table preserves the last valid rows and records the error in LastError.

func NewTable[T any](path string) (*Table[T], error)

NewTable loads the typed table at path immediately and initializes Version to 1.

func (t *Table[T]) Get(key any) (T, bool)

Get returns the current row with key. Use View.Get when several reads must use the same load generation.

func (t *Table[T]) LastError() error

LastError returns the error from the most recent reload attempt, or nil if it succeeded.

func (t *Table[T]) Path() string

Path returns the table's file path.

func (t *Table[T]) Reload() error

Reload re-reads the file from disk. On success, it atomically replaces Rows and increments Version. On failure, existing Rows are preserved and LastError is updated.

func (t *Table[T]) ReloadBytes(data []byte) error

ReloadBytes parses raw file bytes using the table's file extension. On success, it atomically replaces Rows and increments Version.

func (t *Table[T]) Rows() []T

Rows returns a copy of the currently loaded rows.

func (t *Table[T]) Version() uint64

Version returns the monotonically increasing load generation (starting at 1).

func (t *Table[T]) View() View[T]

View returns an immutable snapshot of the current rows and version without copying the row slice. The snapshot remains stable across Reload calls.

type Value struct {
	Kind ValueKind
	Text string
	List []Value
}

Value holds a single cell's value in an untyped YAML data table.

Scalar values keep their exact text representation in Text (so large int64/uint64 values and integer-vs-float distinctions survive round-trips without float64 precision loss); KindList values store their elements in List.

func BoolValue(b bool) Value

BoolValue returns a KindBool Value.

func DurationValue(d time.Duration) Value

DurationValue returns a KindDuration Value formatted with time.Duration.String.

func FloatValue(f float64) Value

FloatValue returns a KindNumber Value holding a float64.

func InferValue(raw string) Value

InferValue infers a Value and its ValueKind from raw user text.

func IntValue(n int64) Value

IntValue returns a KindNumber Value holding a signed integer.

func ListValue(items ...Value) Value

ListValue returns a KindList Value containing a copy of items.

func NullValue() Value

NullValue returns a KindNull Value.

func ParseValue(kind ValueKind, raw string) (Value, error)

ParseValue parses raw user text as a Value of kind.

func StringValue(s string) Value

StringValue returns a KindString Value.

func UintValue(n uint64) Value

UintValue returns a KindNumber Value holding an unsigned integer.

func ZeroValue(kind ValueKind) Value

ZeroValue returns the deterministic zero value for kind.

func (v Value) Bool() (bool, bool)

Bool returns the boolean value when v is KindBool.

func (v Value) Clone() Value

Clone returns a deep copy of v.

func (v Value) Display() string

Display returns the human-readable grid text for v.

func (v Value) Duration() (time.Duration, bool)

Duration returns the parsed duration when v is KindDuration.

func (v Value) Equal(other Value) bool

Equal reports whether v and other have the same kind and content.

func (v Value) Float64() (float64, bool)

Float64 parses v as a finite float64 when v is KindNumber.

func (v Value) Int64() (int64, bool)

Int64 parses v as a signed 64-bit integer when v is KindNumber.

func (v Value) Uint64() (uint64, bool)

Uint64 parses v as an unsigned 64-bit integer when v is KindNumber.

type ValueKind int

ValueKind classifies a cell value in an untyped YAML data table.

const (
	KindString ValueKind = iota
	KindNumber
	KindBool
	KindDuration
	KindList
	KindNull
)
func (k ValueKind) String() string

String returns the human-readable name of k.

type View[T any] struct {
	// contains filtered or unexported fields
}

View is an immutable, zero-copy read view of a Table at one version. Callers must not modify Rows. A later reload publishes a new view and does not change an existing View.

func (v View[T]) Get(key any) (T, bool)

Get returns the row with key. The key must have the primary key field's Go type. Mutable values referenced by the returned row are shared with the view.

func (v View[T]) Rows() []T

Rows returns the shared rows in this view. The slice must be treated as read-only.

func (v View[T]) Version() uint64

Version returns the table generation captured by this view.