Guest User

Untitled

a guest
Mar 4th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. require "yaml"
  2.  
  3. pit = {}
  4.  
  5. local home = os.getenv("HOME")
  6. local editor = os.getenv("EDITOR")
  7.  
  8. function pit.switch(profile)
  9. pit.path.profile = pit.path.pitdir .. profile .. ".yaml"
  10. local file = io.open(pit.path.config, "w")
  11. if not file then
  12. io.stderr:write("cannot open "..pit.path.config)
  13. return nil
  14. end
  15. file:write(yaml.dump({profile="default"}))
  16. file:flush()
  17. file:close()
  18. return profile
  19. end
  20. function pit.profile()
  21. local data = yaml.load_file(pit.path.config)
  22. if data then
  23. profile = data.profile
  24. elseif not profile then
  25. pit.switch("default")
  26. profile = "default"
  27. end
  28. return profile
  29. end
  30. function pit.edit(name, req)
  31. local path = os.tmpname()
  32. local tmp = io.open(path, "w")
  33. local opt = {}
  34. opt[name] = req
  35. tmp:write(yaml.dump(opt))
  36. tmp:flush()
  37. os.execute(editor.." "..path)
  38. opt = yaml.load_file(path)
  39. tmp:close()
  40. os.remove(path)
  41. return opt[name]
  42. end
  43. function pit.validopt(opt, req)
  44. for i,v in pairs(req) do
  45. if not opt[i] then
  46. return false
  47. end
  48. end
  49. return true
  50. end
  51. function pit.get(name, req)
  52. local opts = yaml.load_file(pit.path.profile)
  53. if not opts then
  54. opts = {}
  55. opts[name] = {}
  56. elseif not opts[name] then
  57. opts[name] = {}
  58. elseif pit.validopt(opts[name], req) then
  59. return opts[name]
  60. end
  61. local opt = pit.edit(name, req)
  62. for i,v in pairs(opt) do
  63. opts[name][i] = v
  64. end
  65. local file = io.open(pit.path.profile, "w")
  66. file:write(yaml.dump(opts))
  67. file:close()
  68. return opts[name]
  69. end
  70.  
  71. pit.path = {}
  72. pit.path.pitdir = home .. "/.pit/"
  73. pit.path.config = pit.path.pitdir.."pit.yaml"
  74. pit.path.profile = pit.path.pitdir..pit.profile()..".yaml"
  75.  
  76. -- print(yaml.dump(pit.get("test", {username="id",password="password"})))
Add Comment
Please, Sign In to add comment