-
Notifications
You must be signed in to change notification settings - Fork 15
/
loading.go
102 lines (81 loc) · 1.96 KB
/
loading.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package rivescript
// Loading and Parsing Methods
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
/*
LoadFile loads a single RiveScript source file from disk.
Parameters
path: Path to a RiveScript source file.
*/
func (rs *RiveScript) LoadFile(path string) error {
rs.say("Load RiveScript file: %s", path)
fh, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open file %s: %s", path, err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
scanner.Split(bufio.ScanLines)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return rs.parse(path, lines)
}
/*
LoadDirectory loads multiple RiveScript documents from a folder on disk.
Parameters
path: Path to the directory on disk
extensions...: List of file extensions to filter on, default is
'.rive' and '.rs'
*/
func (rs *RiveScript) LoadDirectory(path string, extensions ...string) error {
if len(extensions) == 0 {
extensions = []string{".rive", ".rs"}
}
files, err := filepath.Glob(fmt.Sprintf("%s/*", path))
if err != nil {
return fmt.Errorf("failed to open folder %s: %s", path, err)
}
// No files matched?
if len(files) == 0 {
return fmt.Errorf("no RiveScript source files were found in %s", path)
}
var anyValid bool
for _, f := range files {
// Restrict file extensions.
validExtension := false
for _, exten := range extensions {
if strings.HasSuffix(f, exten) {
validExtension = true
break
}
}
if validExtension {
anyValid = true
err := rs.LoadFile(f)
if err != nil {
return err
}
}
}
if !anyValid {
return fmt.Errorf("no RiveScript source files were found in %s", path)
}
return nil
}
/*
Stream loads RiveScript code from a text buffer.
Parameters
code: Raw source code of a RiveScript document, with line breaks after
each line.
*/
func (rs *RiveScript) Stream(code string) error {
lines := strings.Split(code, "\n")
return rs.parse("Stream()", lines)
}