-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
211 lines (184 loc) · 6.67 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import "C"
import (
"context"
"errors"
"fmt"
"log"
"net/url"
"os"
"strings"
v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
"github.com/authzed/spicedb/pkg/development"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
devinterface "github.com/authzed/spicedb/pkg/proto/developer/v1"
"github.com/authzed/spicedb/pkg/spiceerrors"
"github.com/authzed/spicedb/pkg/tuple"
"github.com/authzed/spicedb/pkg/validationfile"
"github.com/charmbracelet/lipgloss"
"github.com/leetrout/python-spicedb-validation/pkg/console"
"github.com/leetrout/python-spicedb-validation/pkg/decode"
"github.com/leetrout/python-spicedb-validation/pkg/printers"
)
func main() {}
//export helloWorld
func helloWorld() {
log.Println("Hello World")
}
//export validateURL
func validateURL(someURLPtr *C.char) {
someURL := C.GoString(someURLPtr)
log.Printf("Should validate some url: %s", someURL)
err := validateCmdFunc(someURL)
if err != nil {
log.Printf("ERROR: %s", err)
}
}
var (
success = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("10")).Render("Success!")
errorPrefix = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("9")).Render("error: ")
errorMessageStyle = lipgloss.NewStyle().Bold(true).Width(80)
linePrefixStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
highlightedSourceStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
highlightedLineStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
codeStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
highlightedCodeStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("15"))
traceStyle = lipgloss.NewStyle().Bold(true)
)
func validateCmdFunc(someURL string) error {
// Parse the URL of the validation document to import.
u, err := url.Parse(someURL)
if err != nil {
return err
}
decoder, err := decode.DecoderForURL(u)
if err != nil {
return err
}
// Decode the validation document.
var parsed validationfile.ValidationFile
validateContents, err := decoder(&parsed)
if err != nil {
var errWithSource spiceerrors.ErrorWithSource
if errors.As(err, &errWithSource) {
ouputErrorWithSource(validateContents, errWithSource)
}
return err
}
// Create the development context.
ctx := context.Background()
tuples := make([]*core.RelationTuple, 0, len(parsed.Relationships.Relationships))
for _, rel := range parsed.Relationships.Relationships {
tuples = append(tuples, tuple.MustFromRelationship[*v1.ObjectReference, *v1.SubjectReference, *v1.ContextualizedCaveat](rel))
}
devCtx, devErrs, err := development.NewDevContext(ctx, &devinterface.RequestContext{
Schema: parsed.Schema.Schema,
Relationships: tuples,
})
if err != nil {
return err
}
if devErrs != nil {
outputDeveloperErrorsWithLineOffset(validateContents, devErrs.InputErrors, 1 /* for the 'schema:' */)
}
// Run assertions.
adevErrs, aerr := development.RunAllAssertions(devCtx, &parsed.Assertions)
if aerr != nil {
return aerr
}
if adevErrs != nil {
outputDeveloperErrors(validateContents, adevErrs)
}
// Run expected relations.
_, erDevErrs, rerr := development.RunValidation(devCtx, &parsed.ExpectedRelations)
if rerr != nil {
return rerr
}
if erDevErrs != nil {
outputDeveloperErrors(validateContents, erDevErrs)
}
fmt.Print(success)
console.Printf(" - %d relationships loaded, %d assertions run, %d expected relations validated\n",
len(tuples),
len(parsed.Assertions.AssertTrue)+len(parsed.Assertions.AssertFalse),
len(parsed.ExpectedRelations.ValidationMap),
)
return nil
}
func ouputErrorWithSource(validateContents []byte, errWithSource spiceerrors.ErrorWithSource) {
lines := strings.Split(string(validateContents), "\n")
console.Printf("%s%s\n", errorPrefix, errorMessageStyle.Render(errWithSource.Error()))
errorLineNumber := int(errWithSource.LineNumber) - 1 // errWithSource.LineNumber is 1-indexed
for i := errorLineNumber - 3; i < errorLineNumber+3; i++ {
if i == errorLineNumber {
renderLine(lines, i, errWithSource.SourceCodeString, errorLineNumber)
} else {
renderLine(lines, i, "", errorLineNumber)
}
}
os.Exit(1)
}
func outputDeveloperErrors(validateContents []byte, devErrors []*devinterface.DeveloperError) {
outputDeveloperErrorsWithLineOffset(validateContents, devErrors, 0)
}
func outputDeveloperErrorsWithLineOffset(validateContents []byte, devErrors []*devinterface.DeveloperError, lineOffset int) {
lines := strings.Split(string(validateContents), "\n")
for _, devErr := range devErrors {
outputDeveloperError(devErr, lines, lineOffset)
}
os.Exit(1)
}
func outputDeveloperError(devError *devinterface.DeveloperError, lines []string, lineOffset int) {
console.Printf("%s %s\n", errorPrefix, errorMessageStyle.Render(devError.Message))
errorLineNumber := int(devError.Line) - 1 + lineOffset // devError.Line is 1-indexed
for i := errorLineNumber - 3; i < errorLineNumber+3; i++ {
if i == errorLineNumber {
renderLine(lines, i, devError.Context, errorLineNumber)
} else {
renderLine(lines, i, "", errorLineNumber)
}
}
if devError.CheckResolvedDebugInformation != nil && devError.CheckResolvedDebugInformation.Check != nil {
console.Printf("\n %s\n", traceStyle.Render("Explanation:"))
tp := printers.NewTreePrinter()
printers.DisplayCheckTrace(devError.CheckResolvedDebugInformation.Check, tp, true)
tp.PrintIndented()
}
console.Printf("\n\n")
}
func renderLine(lines []string, index int, highlight string, highlightLineIndex int) {
if index < 0 || index >= len(lines) {
return
}
lineNumberLength := len(fmt.Sprintf("%d", len(lines)))
lineContents := lines[index]
lineDelimiter := "|"
highlightIndex := strings.Index(lineContents, highlight)
lineNumberStr := fmt.Sprintf("%d", index+1)
spacer := strings.Repeat(" ", lineNumberLength)
lineNumberStyle := linePrefixStyle
lineContentsStyle := codeStyle
if index == highlightLineIndex {
lineNumberStyle = highlightedLineStyle
lineContentsStyle = highlightedCodeStyle
lineDelimiter = ">"
}
if highlightIndex < 0 || len(highlight) == 0 {
console.Printf(" %s %s %s\n", lineNumberStyle.Render(lineNumberStr), lineDelimiter, lineContentsStyle.Render(lineContents))
} else {
console.Printf(" %s %s %s%s%s\n",
lineNumberStyle.Render(lineNumberStr),
lineDelimiter,
lineContentsStyle.Render(lineContents[0:highlightIndex]),
highlightedSourceStyle.Render(highlight),
lineContentsStyle.Render(lineContents[highlightIndex+len(highlight):]),
)
console.Printf(" %s %s %s%s%s\n",
lineNumberStyle.Render(spacer),
lineDelimiter,
strings.Repeat(" ", highlightIndex),
highlightedSourceStyle.Render("^"),
highlightedSourceStyle.Render(strings.Repeat("~", len(highlight)-1)),
)
}
}