tparsecfg.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. discard """
  2. targets: "c js"
  3. """
  4. import parsecfg, streams
  5. when not defined(js):
  6. # bug #6046
  7. var config = newConfig()
  8. config.setSectionKey("foo", "bar", "-1")
  9. config.setSectionKey("foo", "foo", "abc")
  10. from stdtest/specialpaths import buildDir
  11. import os
  12. const file = buildDir / "tparsecfg.ini"
  13. config.writeConfig(file)
  14. # file now contains
  15. # [foo]
  16. # bar=-1
  17. # foo=abc
  18. var config2 = loadConfig(file)
  19. let bar = config2.getSectionValue("foo", "bar")
  20. let foo = config2.getSectionValue("foo", "foo")
  21. assert(bar == "-1")
  22. assert(foo == "abc")
  23. ## Creating a configuration file.
  24. var dict1 = newConfig()
  25. dict1.setSectionKey("", "charset", "utf-8")
  26. dict1.setSectionKey("Package", "name", "hello")
  27. dict1.setSectionKey("Package", "--threads", "on")
  28. dict1.setSectionKey("Author", "name", "lihf8515")
  29. dict1.setSectionKey("Author", "qq", "10214028")
  30. dict1.setSectionKey("Author", "email", "lihaifeng@wxm.com")
  31. var ss = newStringStream()
  32. dict1.writeConfig(ss)
  33. ## Reading a configuration file.
  34. var dict2 = loadConfig(newStringStream(ss.data))
  35. var charset = dict2.getSectionValue("", "charset")
  36. var threads = dict2.getSectionValue("Package", "--threads")
  37. var pname = dict2.getSectionValue("Package", "name")
  38. var name = dict2.getSectionValue("Author", "name")
  39. var qq = dict2.getSectionValue("Author", "qq")
  40. var email = dict2.getSectionValue("Author", "email")
  41. doAssert charset == "utf-8"
  42. doAssert threads == "on"
  43. doAssert pname == "hello"
  44. doAssert name == "lihf8515"
  45. doAssert qq == "10214028"
  46. doAssert email == "lihaifeng@wxm.com"
  47. ## Modifying a configuration file.
  48. var dict3 = loadConfig(newStringStream(ss.data))
  49. dict3.setSectionKey("Author", "name", "lhf")
  50. doAssert $dict3 == """charset=utf-8
  51. [Package]
  52. name=hello
  53. --threads:on
  54. [Author]
  55. name=lhf
  56. qq=10214028
  57. email="lihaifeng@wxm.com"
  58. """
  59. ## Deleting a section key in a configuration file.
  60. var dict4 = loadConfig(newStringStream(ss.data))
  61. dict4.delSectionKey("Author", "email")
  62. doAssert $dict4 == """charset=utf-8
  63. [Package]
  64. name=hello
  65. --threads:on
  66. [Author]
  67. name=lihf8515
  68. qq=10214028
  69. """