~nromdotcom/gemif

ref: 3c3cfafab93e35e669c16702dd63c9ca558fe44b gemif/pkg/gamemanager/storybook.go -rw-r--r-- 1.9 KiB
3c3cfafaNorm MacLennan Add additional story metadata and intro page 1 year, 1 month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package gamemanager

import (
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

// ErrInvalidStoryDirectory occurs when the config specifies a nonexistent story directory.
var ErrInvalidStoryDirectory = errors.New("story directory does not exist")

// StoryBook contains information on all of the stories loaded from disk.
type StoryBook struct {
	Stories map[string]Story `yaml:"stories" json:"stories"`
}

// Story contains all information about a loaded story.
type Story struct {
	Metadata StoryMetadata `yaml:"metadata" json:"metadata"`
	Rooms    []Room        `yaml:"rooms" json:"rooms"`
}

// StoryMetadata contains story metadata - authorship information, etc.
type StoryMetadata struct {
	ID              string   `yaml:"id"`
	Name            string   `yaml:"name"`
	Description     string   `yaml:"description"`
	ContentWarnings []string `yaml:"cw"`
	StartingScene   string   `yaml:"starting_scene"`
	Author          string   `yaml:"author"`
}

// NewStoryBook makes a new Config object and loads in all of the stories from the given path.
func NewStoryBook(root string) (StoryBook, error) {
	var files []string

	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if info == nil {
			return fmt.Errorf("%w: %s", ErrInvalidStoryDirectory, root)
		}
		if info.IsDir() {
			return nil
		}
		files = append(files, path)

		return nil
	})
	if err != nil {
		log.Fatalf("Couldn't load stories from disk: %s", err)
	}

	c := StoryBook{
		Stories: map[string]Story{},
	}

	for _, file := range files {
		yamlFile, err := ioutil.ReadFile(file)
		if err != nil {
			return c, fmt.Errorf("couldn't load story: %w", err)
		}

		var thisStory *Story
		if err := yaml.Unmarshal(yamlFile, &thisStory); err != nil {
			fmt.Println(err.Error())

			return c, fmt.Errorf("couldn't load story: %w", err)
		}

		c.Stories[thisStory.Metadata.ID] = *thisStory
	}

	return c, nil
}