Files
radiantwave-legacy/internal/assets/assets.go
T

70 lines
2.3 KiB
Go

// Package assets provisions the static assets bundled into the binary
// (fonts, shaders, and terms-of-service pages) into a per-user assets
// directory at application startup.
package assets
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
// embeddedRoot is the directory in the source tree (and therefore in the
// embedded FS) where the bundled assets live. It mirrors the nix store
// layout, but consumers expect the assets directly under the assets dir,
// so this root is stripped during provisioning.
const embeddedRoot = "share/radiantwave"
// ProvisionAssets provisions the bundled static assets (fonts, shaders, and
// terms-of-service pages) into destDir, stripping the embedded
// share/radiantwave root so the files land directly in destDir rather than
// in a nested share/radiantwave/ subdirectory. Existing files are
// overwritten so the deployed assets always match the running binary.
func ProvisionAssets(bundled fs.FS, destDir string) error {
root, err := fs.Sub(bundled, embeddedRoot)
if err != nil {
return fmt.Errorf("bundled assets missing %s root: %w", embeddedRoot, err)
}
return Provision(root, destDir)
}
// Provision copies every file from the embedded filesystem into destDir,
// preserving the relative directory structure. Existing files are
// overwritten so the deployed assets always match the running binary.
func Provision(bundled fs.FS, destDir string) error {
return fs.WalkDir(bundled, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
src, err := bundled.Open(path)
if err != nil {
return fmt.Errorf("opening bundled asset %s: %w", path, err)
}
defer src.Close()
dst := filepath.Join(destDir, filepath.FromSlash(path))
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return fmt.Errorf("creating asset directory for %s: %w", path, err)
}
out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("creating asset file %s: %w", dst, err)
}
if _, err := io.Copy(out, src); err != nil {
out.Close()
return fmt.Errorf("writing asset file %s: %w", dst, err)
}
if err := out.Close(); err != nil {
return fmt.Errorf("closing asset file %s: %w", dst, err)
}
return nil
})
}