GitHubCommencer

La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.

package refs

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

Vue d’ensemble

Package refs keeps the references between a game project's files working when files are renamed or moved: it finds every reference, rewrites the ones a move breaks, and finds a file again after it was moved without the tools.

References

Scan reads a project and lists every reference one of its files makes to another, with the file, line and column that holds it:

  • game.yaml (project.FileName): every path project.PathRefs lists, the autoloaded scenes and resources and the assets section's inputs, outputs and cache, some of which name folders (Ref.Dir) or what game assets writes (Ref.Output), which need not exist; a game.yaml that project.Parse refuses is a Problem, and none of its paths are read;
  • scenes (sceneformat), the files named *.scene.yaml or *.scene.yml and every other YAML file a reference names as a scene: the scene a scene inherits, the navigation mesh file a scene names (navMesh, which game navmesh writes and so need not exist, Ref.Output), the scene an object instances, path-valued prefab references (FieldPrefab, while bare prefab names stay resolver names), an object's material, model and gridMap and an override's prefab, material, model and gridMap, and a tilemap's source and the YAML tileset a layered tilemap names (tilesetFile);
  • prefabs, the files named *.prefab.yaml or *.prefab.yml (KindPrefab): the prefab they inherit (FieldInherits), scene/prefab/material/model/gridMap/particle/animator/skeletal references, and nested layers if scene-shaped;
  • data tables (KindDataTable), YAML files whose row sequences hold path references to project files (FieldDataTable);
  • YAML tilesets (tilemap.TilesetDoc), the files named *.tileset.yaml or *.tileset.yml: the grid image their tiles are cut from;
  • 3D grid maps (world3d), the files named *.gridmap.yaml or *.gridmap.yml and every other YAML file a scene names in gridMap: the glTF mesh library named in meshLibrary;
  • cutscenes (cutscene), the files named *.cutscene.yaml or *.cutscene.yml: the scene a timeline cutscene plays against, a video cutscene's project-relative source path, and the audio source paths on sound and music tracks;
  • screens (gameui), the files named *.screen.yaml or *.screen.yml: each node's sprite path (FieldScreenSprite) and localization textKey (FieldTextKey in Project.TextKeys);
  • localization string tables (l10n), versioned YAML string tables holding locale and strings/plurals maps: each message key definition (FieldStringKey and FieldPluralKey in Project.TextKeys);
  • resource files (resource), YAML files whose header has a resource type: a material's texture;
  • Tiled maps (.tmj) and tilesets (.tsj, and .json files a map names as its external tileset): external tilesets, tileset and tile images and image layers;
  • sprite atlases, JSON files with top-level frames and meta objects: the page image in meta.image;
  • LDtk projects (.ldtk): tileset images, level backgrounds and levels saved in separate files;
  • glTF models in JSON form (.gltf): buffers and images kept in separate files rather than in data URIs or a .glb.

A path in game.yaml, a scene, a YAML tileset or a resource file is relative to the project root, the nearest directory above the file that holds game.yaml, nsgo.yaml or go.mod, or the scanned directory when none does. A path in a Tiled, LDtk or glTF file is relative to that file's directory, as those tools write it. Atlas, tileset and prefab names in scenes are names an AssetResolver looks up, not paths, and are not references to a file; nor is an object's mesh, which names a built-in primitive, or the node or mesh of its model, which name parts inside the model file. The shader and texture paths of a hot-reloaded shader material (hotreload.MaterialDef) are not read either: they are relative to the asset directory a game gives its reloaders at run time, not to the project root.

Stable IDs and the Index

Every scene and resource file carries a stable ID in its header, a uid field (sceneformat.SceneDoc.UID, resource.Header.UID) that a tool writes once with resource.NewUID and that never changes, so it travels with the file through any rename or move. An empty or null uid is read as none, as the loaders read it. A uid is unique within one project root; separate projects, such as two games made from one template, may share one. The project index, IndexFileName at the project root, records where each file was the last time a tool looked: each scene and resource file's path with its uid, and each other file a reference names, such as an image or a Tiled map, with the SHA-256 of its contents. It is a YAML file the tools keep (Index), written in a fixed order so that it changes only when files do, and it belongs in version control with the files it describes.

When a reference names a file that is gone, Project.Moved looks the old path up in the index and finds the file again: the scene or resource file that now holds the same uid, or the one file elsewhere in the project with the same extension and contents that the index does not list. game check reports the broken reference with its file and line and where the file went.

Moving Files

PlanMove plans the move of a file or directory and the rewrite of every reference to what it moves, the moved files' own relative references included, and PlanIndex plans what game index does: point every broken reference whose file Moved finds at the file's new path, give every scene and resource file without a uid a new one, give a copied file that shares its original's uid a new one, and bring each index up to date. A Plan only describes the changes, so a caller can show them first; Plan.Apply makes them in a directory on disk. A reference is rewritten in place, keeping the rest of its file byte for byte, comments and formatting included, and a uid is added as one line after the file's version, so a move shows in review as the lines it changes. The game mv and game index commands and the editor's MoveFile, which its file browser calls and Undo takes back, run these.

Index

Constantes

const (
	FieldAutoloadScene    = project.FieldAutoloadScene
	FieldAutoloadResource = project.FieldAutoloadResource
	FieldInherits         = "inherits"
	FieldNavMesh          = "navigation mesh"
	FieldScene            = "scene"
	FieldPrefab           = "prefab"
	FieldDataTable        = "data table"
	FieldMaterial         = "material"
	FieldModel            = "model"
	FieldGridMap          = "grid map"
	FieldMeshLibrary      = "mesh library"
	FieldStates           = "states"
	FieldClip             = "clip"
	FieldParticles        = "particles"
	FieldSkyHDR           = "sky hdr"
	FieldReflectionProbe  = "reflection probe cubemap"
	FieldLightProbeGrid   = "light probe grid"
	FieldTilemapSource    = "tilemap source"
	FieldTilesetFile      = "tileset file"
	FieldTexture          = "texture"
	FieldExternalTileset  = "external tileset"
	FieldTilesetImage     = "tileset image"
	FieldTileImage        = "tile image"
	FieldImageLayer       = "image layer"
	FieldLevelBackground  = "level background"
	FieldExternalLevel    = "external level"
	FieldAtlasImage       = "atlas image"
	FieldModelBuffer      = "model buffer"
	FieldModelImage       = "model image"
	FieldCutsceneSource   = "cutscene source"
	FieldCutsceneAudio    = "cutscene audio"
	// FieldSkeletalRig is a .skel.yaml rig path referenced by an object's "skeletal" component.
	FieldSkeletalRig = "skeletal rig"
	// FieldScreenSprite is a sprite image or atlas path referenced by a *.screen.yaml node.
	FieldScreenSprite = "sprite"
	// FieldTextKey is a localization text key referenced by a *.screen.yaml node.
	FieldTextKey = "text key"
	// FieldStringKey is a localization string entry key in a YAML string table.
	FieldStringKey = "string key"
	// FieldPluralKey is a localization plural entry key in a YAML string table.
	FieldPluralKey        = "plural key"
	FieldTerrainHeightmap = "terrain heightmap"
	FieldTerrainSplatMap  = "terrain splat map"
	FieldTerrainWeightMap = "terrain weight map"
	FieldTerrainTexture   = "terrain texture"
	FieldTerrainMesh      = "terrain foliage mesh"
	FieldTerrainDensity   = "terrain density map"
)

Fields name what a reference is, in Ref.Field and in messages. A reference in game.yaml has the Field project.PathRefs gives it, such as project.FieldAtlasIn; the two autoload ones are repeated here.

const IndexFileName = "game.index.yaml"

IndexFileName is the project index's name at a project's root, beside game.yaml.

const IndexVersion = 1

IndexVersion is the index schema version this package reads and writes.

Fonctions

func EncodeIndex(ix *Index) ([]byte, error)

EncodeIndex validates ix and writes it as deterministic 2-space YAML after a one-line comment saying what the file is, which ParseIndex reads back unchanged.

func IsAssetPath(p string) bool

IsAssetPath reports whether p, a slash-separated project path, names a game asset file (image/sprite, tileset, audio, font, or 3D model) rather than a scene, script, project manifest, or import/source sidecar.

func RelPath(dir, target string) string

RelPath returns how a file in dir, or at the project root dir, writes the path of target: target relative to dir, with ".." for each directory up, both slash-separated paths in the same file system.

Types

type File struct {
	// Path is the file's slash-separated path.
	Path string
	// Kind is what the file was read as.
	Kind FileKind
	// UID is the stable ID in the header of a scene or resource file, or "".
	UID string
	// Root is the project root the file's root-relative paths start from, "." for the scanned directory itself.
	Root string
	// contains filtered or unexported fields
}

File is one file Scan read references or a uid from.

type FileKind string

FileKind is what Scan read a file as.

const (
	// KindProject is a game.yaml project file.
	KindProject FileKind = "project"
	// KindScene is a sceneformat scene document.
	KindScene FileKind = "scene"
	// KindPrefab is a prefab YAML document (*.prefab.yaml or *.prefab.yml).
	KindPrefab FileKind = "prefab"
	// KindDataTable is a YAML data table whose rows reference project files.
	KindDataTable FileKind = "data_table"
	// KindScreen is a gameui *.screen.yaml HUD or menu screen document.
	KindScreen FileKind = "screen"
	// KindStringTable is a versioned YAML localization string table (l10n.StringTable).
	KindStringTable FileKind = "string_table"
	// KindResource is a resource file.
	KindResource FileKind = "resource"
	// KindTiled is a Tiled map (.tmj) or tileset (.tsj).
	KindTiled FileKind = "tiled"
	// KindLDtk is an LDtk project (.ldtk).
	KindLDtk FileKind = "ldtk"
	// KindTileset is a YAML tileset (*.tileset.yaml, tilemap.TilesetDoc).
	KindTileset FileKind = "tileset"
	// KindTerrain is a YAML 3D terrain definition (*.terrain.yaml, world3d.TerrainDoc).
	KindTerrain FileKind = "terrain"
	// KindAtlas is a sprite atlas: a JSON file with top-level frames and meta objects, as TexturePacker and Aseprite write it.
	KindAtlas FileKind = "atlas"
	// KindGLTF is a glTF 2.0 model in JSON form (.gltf), whose buffers and images may be separate files.
	KindGLTF FileKind = "gltf"
	// KindCutscene is a cutscene file (*.cutscene.yaml or *.cutscene.yml).
	KindCutscene FileKind = "cutscene"
	// KindGridMap is a world3d GridMap YAML file (*.gridmap.yaml or *.gridmap.yml), which references a glTF mesh library.
	KindGridMap FileKind = "gridmap"
	// KindStates is a *.states.yaml sprite animation state machine file.
	KindStates FileKind = "states"
)
type Index struct {
	// Version is the schema version; it must equal IndexVersion (1).
	Version int `yaml:"version"`
	// Files are the indexed files in path order.
	Files []IndexEntry `yaml:"files,omitempty"`
}

Index is the project index: where each file a reference may name was the last time a tool looked. Its files are sorted by path, and each has either a UID or a SHA256.

func ParseIndex(data []byte) (*Index, error)

ParseIndex decodes a YAML project index and validates it. Unknown fields and trailing YAML documents are refused.

func (ix *Index) Lookup(path string) (IndexEntry, bool)

Lookup returns the entry for path, a slash-separated path from the project root.

func (ix *Index) Validate() error

Validate checks that ix conforms to the version 1 schema: valid relative paths in strictly increasing order, and for each exactly one of a valid UID and a SHA-256 of 64 lower-case hexadecimal digits, with no UID used twice.

type IndexEntry struct {
	// Path is the file's slash-separated path from the project root.
	Path string `yaml:"path"`
	// UID is the stable ID in the header of a scene or resource file.
	UID string `yaml:"uid,omitempty"`
	// SHA256 is the lower-case hexadecimal SHA-256 of the contents of any other file, such as an image.
	SHA256 string `yaml:"sha256,omitempty"`
}

IndexEntry is one indexed file.

type IndexOptions struct {
	// Rand is where new uids come from (resource.NewUID); nil is crypto/rand.
	Rand io.Reader
}

IndexOptions configures PlanIndex.

type Move struct {
	From, To string
}

Move moves the file or directory From to To, both slash-separated paths in the project.

type Plan struct {
	// Moves are the files and directories to move, in order.
	Moves []Move
	// Writes are the files to write after the moves, at their paths after the moves, in path order.
	Writes []Write
	// Updated are the references the writes change, as they were before the plan.
	Updated []Ref
	// UpdatedTextKeys are the localization text key references and definitions the writes change, as they were before the plan.
	UpdatedTextKeys []TextKeyRef
	// Assigned are the scene, screen and resource files the writes give a new uid, at their paths after the moves.
	Assigned []string
}

Plan is a set of changes to a project's files that keeps its references working: files to move, then files to write. A Plan only describes them; Apply makes them.

func PlanIndex(fsys fs.FS, opts IndexOptions) (*Plan, error)

PlanIndex plans what game index does to the project in fsys: rewrite every reference to a file that is gone and that Project.Moved finds, give each scene and resource file without a uid a new one, give a new uid to each file sharing its uid with the file the index lists for it (or, when the index lists neither, with the first in path order), and bring the index at every project root up to date. A file that holds a uid that is not valid is refused, since its uid cannot be kept.

func PlanMove(fsys fs.FS, from, to string) (*Plan, error)

PlanMove plans moving the file or directory from to to, both slash-separated paths in fsys such as os.DirFS of a game's directory, and rewriting every reference Scan finds to what it moves: references from other files, and the references a moved Tiled or LDtk file makes relative to itself. It also brings the project index at the root up to date. It refuses a move that would leave a reference it cannot rewrite: one out of the project root, one written in a way it cannot rewrite in place, or one in a file that should name from but does not parse. It refuses to move game.yaml, an index, or a directory holding a project root of its own.

func PlanRenameTextKey(fsys fs.FS, from, to string) (*Plan, error)

PlanRenameTextKey plans renaming the localization text key from to to across every *.screen.yaml file (textKey fields) and YAML localization string table (strings and plurals keys) in fsys. It rewrites each occurrence in place, preserving comments and formatting, and refuses empty keys, no-op renames, unknown keys, or a target key that already exists in a string table holding from.

func (pl *Plan) Apply(dir string) error

Apply makes the plan's changes in dir, the directory the plan's paths are relative to, which must be the one the planning function scanned: each move, creating the directories it moves into, and then each write, through a temporary file renamed over the old one so a failed write never leaves a file half written. It works inside an os.Root, so no path leads outside dir. A move comes first so that when Apply stops part way, the project index still lists the moved files where they were, and game index finds them and finishes the rewrite.

func (pl *Plan) Empty() bool

Empty reports whether the plan changes nothing.

type Problem struct {
	// File is the slash-separated path of the file at fault.
	File string
	// Line is the 1-based line that holds the problem, or 0 when it is about the whole file.
	Line int
	// Message says what is wrong.
	Message string
}

Problem is one thing wrong that Scan found or Project.Check reports.

func (p Problem) String() string

String formats p as "file:line: message", or "file: message" without a line.

type Project struct {
	// Files are the files read, in path order.
	Files []*File
	// Refs are the references found, in file order and then in the order each file writes them.
	Refs []Ref
	// TextKeys are the localization text key references and definitions found in *.screen.yaml files and YAML string tables, in file order and then document order.
	TextKeys []TextKeyRef
	// Problems are what makes the references unsafe to follow or rewrite: a game.yaml or an index that does not parse, and a uid two files of one project share. A reference to a file that is gone is not one of them; Check reports those.
	Problems []Problem
	// contains filtered or unexported fields
}

Project is what Scan found in a directory.

func Scan(fsys fs.FS) (*Project, error)

Scan walks fsys, such as os.DirFS of a game's directory, and reads every file the package comment lists for its references, uids and project indexes. Directories whose names start with "." or "_", and those named testdata, are skipped, as the go command skips them. A file that does not parse is skipped; game check reports it. Scan returns an error only when fsys's root cannot be read.

func (p *Project) Check() []Problem

Check returns the problems Scan found and every reference to a file that is not there, at the file and line that holds the reference, saying where the file went when Moved finds it. Problems are sorted by file, then line, then message.

func (p *Project) Exists(name string) bool

Exists reports whether the scanned directory held a file at name when Scan walked it.

func (p *Project) Found(r Ref) bool

Found reports whether r names something that was there when Scan walked the directory: a file, or a folder when r.Dir is set.

func (p *Project) Index(root string) *Index

Index returns the parsed index at the project root root, or nil when it has none or it does not parse.

func (p *Project) MissingAssets() []string

MissingAssets returns the sorted, deduplicated slash-separated paths of asset files (IsAssetPath) referenced by non-output file references in p that do not exist on disk.

func (p *Project) Moved(target string) (string, bool)

Moved returns where the file at target, a path the scan found no file at, is now, as the project index at its root says: the scene or resource file holding the uid the index lists for target, or else the only file in the project with target's extension and the contents the index lists for it that the index does not list itself. It returns false when the index does not list target or the file cannot be found again.

func (p *Project) MovedHint(r Ref) string

MovedHint returns what to tell a person about r when its target is gone and Moved finds it, such as `it moved to "materials/rock.material.yaml"; run game index to update the reference`, or "" when Moved does not find it.

func (p *Project) Paths() []string

Paths returns every file path Scan found in the directory, in sorted path order.

func (p *Project) Root(name string) string

Root returns the project root of the file at name: the nearest directory above it that holds game.yaml, nsgo.yaml or go.mod, or "." when none does.

func (p *Project) TextKeyUsages(key string) []TextKeyRef

TextKeyUsages returns every occurrence of key in the scanned project across screen files and string tables, in file and line order.

func (p *Project) UnreferencedAssets() []string

UnreferencedAssets returns the sorted slash-separated paths of asset files (IsAssetPath) present in p that are neither generated output targets (Ref.Output) nor referenced by any file in p (UsedBy).

func (p *Project) UsedBy(target string) []Ref

UsedBy returns every non-output reference in p that targets target, in the order Scan recorded them. A directory reference (Ref.Dir) matches every file inside that directory.

type Ref struct {
	// File is the slash-separated path of the file that holds the reference.
	File string
	// Line and Column are where its value is written in File, both counting from 1 and Column in characters.
	Line, Column int
	// Field says what the reference is, one of the Field constants, such as FieldMaterial, or in game.yaml one of package project's.
	Field string
	// Value is the path as File writes it.
	Value string
	// Target is the slash-separated path of the file Value names, or "" when Value cannot name a file in the scanned directory: an absolute path, a URI, a path with backslashes or one leading outside it.
	Target string
	// FromFile reports whether Value is relative to File's directory, as Tiled and LDtk write paths, rather than to the project root.
	FromFile bool
	// Dir reports whether Value names a folder rather than a file, as an assets target's in may in game.yaml.
	Dir bool
	// Output reports whether Value names what a tool writes, such as an assets target's out in game.yaml, which need not exist yet.
	Output bool
	// contains filtered or unexported fields
}

Ref is one reference from a file to another.

type TextKeyRef struct {
	// File is the slash-separated path of the file that holds the key.
	File string
	// Line and Column are where the key is written in File (both 1-based).
	Line, Column int
	// Field says what the occurrence is: FieldTextKey, FieldStringKey, or FieldPluralKey.
	Field string
	// Key is the localization key string (for example "hud.hint.lever").
	Key string
	// NodeID is the screen node ID when the occurrence is in a screen file, or empty in a string table.
	NodeID string
	// contains filtered or unexported fields
}

TextKeyRef is one occurrence of a localization text key in a project file: either a screen node's textKey reference or a string table's key definition.

type Write struct {
	Path string
	Data []byte
}

Write replaces the contents of the file at Path, or creates it, with Data.