ini.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "ini.h"
  2. #include <util/string/strip.h>
  3. #include <util/stream/input.h>
  4. using namespace NConfig;
  5. namespace {
  6. inline TStringBuf StripComment(TStringBuf line) {
  7. return line.Before('#').Before(';');
  8. }
  9. }
  10. TConfig NConfig::ParseIni(IInputStream& in) {
  11. TConfig ret = ConstructValue(TDict());
  12. {
  13. TConfig* cur = &ret;
  14. TString line;
  15. while (in.ReadLine(line)) {
  16. TStringBuf tmp = StripComment(line);
  17. TStringBuf stmp = StripString(tmp);
  18. if (stmp.empty()) {
  19. continue;
  20. }
  21. if (stmp[0] == '[') {
  22. //start section
  23. if (*(stmp.end() - 1) != ']') {
  24. ythrow TConfigParseError() << "malformed section " << stmp;
  25. }
  26. stmp = TStringBuf(stmp.data() + 1, stmp.end() - 1);
  27. cur = &ret;
  28. while (!!stmp) {
  29. TStringBuf section;
  30. stmp.Split('.', section, stmp);
  31. cur = &cur->GetNonConstant<TDict>()[section];
  32. if (!cur->IsA<TDict>()) {
  33. *cur = ConstructValue(TDict());
  34. }
  35. }
  36. } else {
  37. //value
  38. TStringBuf key, value;
  39. tmp.Split('=', key, value);
  40. auto& dict = cur->GetNonConstant<TDict>();
  41. auto strippedValue = TString(StripString(value));
  42. dict[StripString(key)] = ConstructValue(strippedValue);
  43. }
  44. }
  45. }
  46. return ret;
  47. }