Skip to content

Commit 5a956e1

Browse files
committed
adding recursive method to retrieve all paths from a yaml file, plus test case
1 parent 116d8e5 commit 5a956e1

2 files changed

Lines changed: 72 additions & 1 deletion

File tree

simpleyaml.go

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,15 @@ package simpleyaml
3131

3232
import (
3333
"errors"
34+
"strconv"
3435
"gopkg.in/yaml.v2"
36+
"bytes"
3537
)
3638

3739
type Yaml struct {
3840
data interface{}
3941
}
40-
42+
var array_of_paths = make([]string, 0)
4143
// NewYaml returns a pointer to a new `Yaml` object after unmarshaling `body` bytes
4244
func NewYaml(body []byte) (*Yaml, error) {
4345
var val interface{}
@@ -180,3 +182,55 @@ func (y *Yaml) GetMapKeys() ([]string, error) {
180182
}
181183
return keys, nil
182184
}
185+
186+
// GetAllPaths retrieves all possible paths in the YAML file
187+
//
188+
// Example:
189+
// y.GetAllPaths(yaml_file, array_of_strings)
190+
func GetAllExistingPaths(y *Yaml, path_slice []string) []string {
191+
if y.IsMap() {
192+
keys, err := y.GetMapKeys()
193+
if err != nil {
194+
panic(err)
195+
}
196+
for k, _ := range keys {
197+
if k != 0 {
198+
path_slice = path_slice[:len(path_slice)-1]
199+
}
200+
path_slice = append(path_slice, keys[k])
201+
GetAllExistingPaths(y.Get(keys[k]), path_slice)
202+
}
203+
} else if y.IsArray() {
204+
arr, err := y.Array()
205+
if err != nil {
206+
panic(err)
207+
}
208+
for k, _ := range arr {
209+
if k != 0 {
210+
path_slice = path_slice[:len(path_slice)-1]
211+
}
212+
path_slice = append(path_slice, strconv.Itoa(k))
213+
GetAllExistingPaths(y.GetIndex(k), path_slice)
214+
}
215+
} else {
216+
var buffer bytes.Buffer
217+
for k, _ := range path_slice {
218+
if k == len(path_slice)-1 {
219+
buffer.WriteString(path_slice[k])
220+
}else{
221+
buffer.WriteString(path_slice[k]+".")
222+
}
223+
}
224+
array_of_paths = append(array_of_paths, buffer.String())
225+
}
226+
return array_of_paths
227+
}
228+
229+
// Helper function to invoke GetAllExistingPaths
230+
func (y *Yaml) GetAllPaths() []string {
231+
yin := y
232+
all_paths := make([]string, 0)
233+
initial_path := make([]string, 0)
234+
all_paths = GetAllExistingPaths(yin, initial_path)
235+
return all_paths
236+
}

simpleyaml_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,23 @@ func TestGetPath(t *testing.T) {
141141
}
142142
}
143143

144+
func TestGetAllPaths(t *testing.T) {
145+
y, err := NewYaml(data)
146+
if err != nil {
147+
t.Fatal("init yaml failed")
148+
}
149+
150+
v := y.GetAllPaths()
151+
if err != nil {
152+
t.Fatal("get yaml failed")
153+
}
154+
155+
t.Log(v)
156+
if len(v) != 10 {
157+
t.Fatal("Number of paths do not match number or real paths.")
158+
}
159+
}
160+
144161
func TestArray(t *testing.T) {
145162
y, err := NewYaml(data)
146163
if err != nil {

0 commit comments

Comments
 (0)