|
| 1 | +package libraryproperties |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/url" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + |
| 8 | + "github.com/arduino/go-paths-helper" |
| 9 | + "github.com/arduino/go-properties-orderedmap" |
| 10 | + "github.com/xeipuuv/gojsonschema" |
| 11 | +) |
| 12 | + |
| 13 | +func Properties(libraryPath *paths.Path) (*properties.Map, error) { |
| 14 | + libraryProperties, err := properties.Load(libraryPath.Join("library.properties").String()) |
| 15 | + if err != nil { |
| 16 | + return nil, err |
| 17 | + } |
| 18 | + return libraryProperties, nil |
| 19 | +} |
| 20 | + |
| 21 | +func Validate(libraryProperties *properties.Map) *gojsonschema.Result { |
| 22 | + workingPath, _ := os.Getwd() |
| 23 | + schemaPath := paths.New(workingPath).Join("arduino-library-properties-schema.json") |
| 24 | + uriFriendlySchemaPath := filepath.ToSlash(schemaPath.String()) |
| 25 | + schemaPathURI := url.URL{ |
| 26 | + Scheme: "file", |
| 27 | + Path: uriFriendlySchemaPath, |
| 28 | + } |
| 29 | + schemaLoader := gojsonschema.NewReferenceLoader(schemaPathURI.String()) |
| 30 | + |
| 31 | + documentLoader := gojsonschema.NewGoLoader(libraryProperties) |
| 32 | + |
| 33 | + result, err := gojsonschema.Validate(schemaLoader, documentLoader) |
| 34 | + if err != nil { |
| 35 | + panic(err.Error()) |
| 36 | + } |
| 37 | + |
| 38 | + return result |
| 39 | +} |
| 40 | + |
| 41 | +func FieldMissing(fieldName string, validationResult *gojsonschema.Result) bool { |
| 42 | + return ValidationErrorMatch("required", "(root)", fieldName+" is required", validationResult) |
| 43 | +} |
| 44 | + |
| 45 | +func FieldPatternMismatch(fieldName string, validationResult *gojsonschema.Result) bool { |
| 46 | + return ValidationErrorMatch("pattern", fieldName, "", validationResult) |
| 47 | +} |
| 48 | + |
| 49 | +func ValidationErrorMatch(typeQuery string, fieldQuery string, descriptionQuery string, validationResult *gojsonschema.Result) bool { |
| 50 | + if validationResult.Valid() { |
| 51 | + // No error, so nothing to match |
| 52 | + return false |
| 53 | + } |
| 54 | + for _, validationError := range validationResult.Errors() { |
| 55 | + if typeQuery == "" || typeQuery == validationError.Type() { |
| 56 | + if fieldQuery == "" || fieldQuery == validationError.Field() { |
| 57 | + if descriptionQuery == "" || descriptionQuery == validationError.Description() { |
| 58 | + return true |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return false |
| 65 | +} |
0 commit comments