model_parser.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. local string = string
  2. local table = table
  3. local io = io
  4. local lyaml = require("lyaml")
  5. local M = {}
  6. -- Parameters that do not get inherited.
  7. local NO_INHERIT = {abstract = true}
  8. local MODEL_PATH = "./config/model/"
  9. local function camel2snake(src)
  10. return string.lower(
  11. string.gsub(
  12. string.gsub (src, "^pas:", ""), -- Strip namespace.
  13. "([^^])(%u)", "%1_%2" -- Uppercase (except initial) to underscore.
  14. )
  15. )
  16. end
  17. M.parse_model = function(mod_id)
  18. local hierarchy = {}
  19. local function traverse(mod_id)
  20. print("traversing:", mod_id)
  21. local fname = camel2snake (mod_id)
  22. local fh = assert(io.open(MODEL_PATH .. fname .. ".yml"), "r")
  23. local yml_data = fh:read("a")
  24. fh:close()
  25. local model = lyaml.load(yml_data)
  26. model.id = mod_id
  27. --print("Model: ")
  28. --for k, v in pairs(model) do print (k, v) end
  29. -- Prepend to hierarchy.
  30. table.insert(hierarchy, 1, model)
  31. if model.broader then traverse(model.broader) end
  32. end
  33. traverse(mod_id)
  34. local lineage = {} -- Config ID lineage, from ancestor to leaf.
  35. for _, mod in ipairs(hierarchy) do table.insert(lineage, mod.id) end
  36. --[[
  37. for k, v in ipairs(hierarchy) do
  38. for kk, vv in pairs(v) do print(k, kk, vv) end
  39. end
  40. --]]
  41. local function merge(src, dest)
  42. for k, v in pairs(src) do
  43. if NO_INHERIT[k] then goto continue end
  44. if type(v) == "table" then
  45. dest[k] = dest[k] or {}
  46. assert(type(dest[k]) == "table")
  47. merge(v, dest[k])
  48. else
  49. dest[k] = v
  50. end
  51. ::continue::
  52. end
  53. end
  54. local config = {}
  55. for _, src_config in ipairs(hierarchy) do
  56. merge(src_config, config)
  57. end
  58. return config
  59. end
  60. return M