File: path.go

package info (click to toggle)
golang-github-vektah-gqlparser 2.5.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,748 kB
  • sloc: javascript: 164; sh: 46; makefile: 10
file content (72 lines) | stat: -rw-r--r-- 1,214 bytes parent folder | download
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
package ast

import (
	"bytes"
	"encoding/json"
	"fmt"
)

var _ json.Unmarshaler = (*Path)(nil)

type Path []PathElement

type PathElement interface {
	isPathElement()
}

var (
	_ PathElement = PathIndex(0)
	_ PathElement = PathName("")
)

func (path Path) String() string {
	if path == nil {
		return ""
	}
	var str bytes.Buffer
	for i, v := range path {
		switch v := v.(type) {
		case PathIndex:
			str.WriteString(fmt.Sprintf("[%d]", v))
		case PathName:
			if i != 0 {
				str.WriteByte('.')
			}
			str.WriteString(string(v))
		default:
			panic(fmt.Sprintf("unknown type: %T", v))
		}
	}
	return str.String()
}

func (path *Path) UnmarshalJSON(b []byte) error {
	var vs []interface{}
	err := json.Unmarshal(b, &vs)
	if err != nil {
		return err
	}

	*path = make([]PathElement, 0, len(vs))
	for _, v := range vs {
		switch v := v.(type) {
		case string:
			*path = append(*path, PathName(v))
		case int:
			*path = append(*path, PathIndex(v))
		case float64:
			*path = append(*path, PathIndex(int(v)))
		default:
			return fmt.Errorf("unknown path element type: %T", v)
		}
	}
	return nil
}

type PathIndex int

func (PathIndex) isPathElement() {}

type PathName string

func (PathName) isPathElement() {}