validation.odin 1008 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package flags
  2. import "core:fmt"
  3. import "core:reflect"
  4. import "core:strconv"
  5. _ :: fmt
  6. _ :: reflect
  7. _ :: strconv
  8. // Validate that all the required arguments are set.
  9. validate :: proc(data: ^$T, max_pos: int, set_args: []string) -> Error {
  10. fields := reflect.struct_fields_zipped(T)
  11. check_fields: for field in fields {
  12. tag := reflect.struct_tag_lookup(field.tag, TAG_ARGS) or_continue
  13. if _, ok := get_struct_subtag(tag, SUBTAG_REQUIRED); ok {
  14. was_set := false
  15. // Check if it was set by name.
  16. check_set_args: for set_arg in set_args {
  17. if get_field_name(field) == set_arg {
  18. was_set = true
  19. break check_set_args
  20. }
  21. }
  22. // Check if it was set by position.
  23. if pos, has_pos := get_struct_subtag(tag, SUBTAG_POS); has_pos {
  24. value, value_ok := strconv.parse_int(pos)
  25. if value < max_pos {
  26. was_set = true
  27. }
  28. }
  29. if !was_set {
  30. return Validation_Error {
  31. fmt.tprintf("required argument `%s` was not set", field.name),
  32. }
  33. }
  34. }
  35. }
  36. return nil
  37. }