Skip to content

Commit 25dc5e3

Browse files
committed
feat: support ParserConfig, use a handle
1 parent f8fe1fd commit 25dc5e3

File tree

6 files changed

+424
-353
lines changed

6 files changed

+424
-353
lines changed

go-src/publiccode-parser-wrapper.go

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
package main
22

33
/*
4+
#include <stdint.h>
45
#include <stdlib.h>
56
#include <stdbool.h>
67
7-
struct ParseOptions {
8+
struct ParserConfig {
89
bool DisableNetwork;
910
char *Branch;
1011
char *BaseURL;
@@ -16,33 +17,54 @@ struct ParseResult {
1617
int ErrorCount;
1718
char **Errors;
1819
};
20+
21+
typedef uintptr_t ParserHandle;
1922
*/
2023
import "C"
2124
import (
2225
"encoding/json"
26+
"errors"
27+
"runtime/cgo"
2328
"strings"
2429
"unsafe"
2530

2631
"github.com/italia/publiccode-parser-go/v4"
2732
)
2833

29-
//export ParseString
30-
func ParseString(content *C.char) *C.struct_ParseResult {
31-
parser, err := publiccode.NewDefaultParser()
32-
if err != nil {
33-
// TODO: proper return
34-
panic("err on NewDefaultParser()")
34+
//export NewParser
35+
func NewParser(disableNetwork C.bool, branch *C.char, baseURL *C.char) C.ParserHandle {
36+
config := publiccode.ParserConfig{
37+
DisableNetwork: bool(disableNetwork),
38+
Branch: C.GoString(branch),
39+
BaseURL: C.GoString(baseURL),
3540
}
3641

37-
goString := C.GoString(content)
42+
p, err := publiccode.NewParser(config)
43+
if err != nil {
44+
return 0
45+
}
3846

39-
pc, err := parser.ParseStream(strings.NewReader(goString))
47+
return C.ParserHandle(cgo.NewHandle(p))
48+
}
4049

50+
//export ParseString
51+
func ParseString(handle C.ParserHandle, content *C.char) *C.struct_ParseResult {
4152
result := (*C.struct_ParseResult)(C.calloc(1, C.size_t(C.sizeof_struct_ParseResult)))
4253
result.Error = nil
4354
result.Errors = nil
4455
result.ErrorCount = 0
4556

57+
parser, err := toGoParser(handle)
58+
if err != nil {
59+
result.Error = C.CString("Failed create a Parser: " + err.Error())
60+
61+
return result
62+
}
63+
64+
goString := C.GoString(content)
65+
66+
pc, err := parser.ParseStream(strings.NewReader(goString))
67+
4668
if err != nil {
4769
if validationRes, ok := err.(publiccode.ValidationResults); ok {
4870
var ve []publiccode.ValidationError
@@ -112,6 +134,20 @@ func FreeResult(result *C.struct_ParseResult) {
112134
}
113135
}
114136

137+
func toGoParser(handle C.ParserHandle) (*publiccode.Parser, error) {
138+
if handle == 0 {
139+
return nil, errors.New("nil handle")
140+
}
141+
142+
v := cgo.Handle(handle).Value()
143+
p, ok := v.(*publiccode.Parser)
144+
if !ok || p == nil {
145+
return nil, errors.New("invalid handle")
146+
}
147+
148+
return p, nil
149+
}
150+
115151
func main() {
116152
// Required for building shared library
117153
}

0 commit comments

Comments
 (0)