DevStack supporting tools in python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dsconf.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright 2017 IBM
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. # Implementation of ini add / remove for devstack. We don't use the
  15. # python ConfigFile parser because that ends up rewriting the entire
  16. # file and doesn't ensure comments remain.
  17. import re
  18. import shutil
  19. import tempfile
  20. class IniFile(object):
  21. """Class for manipulating ini files in place."""
  22. def __init__(self, fname):
  23. self.fname = fname
  24. def add(self, section, name, value):
  25. """add a key / value to an ini file in a section.
  26. The new key value will be added at the beginning of the
  27. section, if no section is found a new section and key value
  28. will be added to the end of the file.
  29. """
  30. temp = tempfile.NamedTemporaryFile(mode='r')
  31. shutil.copyfile(self.fname, temp.name)
  32. found = False
  33. with open(temp.name) as reader:
  34. with open(self.fname, "w") as writer:
  35. for line in reader.readlines():
  36. writer.write(line)
  37. m = re.match("\[([^\[\]]+)\]", line)
  38. if m and m.group(1) == section:
  39. found = True
  40. writer.write("%s = %s\n" % (name, value))
  41. if not found:
  42. writer.write("[%s]\n" % section)
  43. writer.write("%s = %s\n" % (name, value))
  44. def remove(self, section, name):
  45. """remove a key / value from an ini file in a section."""
  46. temp = tempfile.NamedTemporaryFile(mode='r')
  47. shutil.copyfile(self.fname, temp.name)
  48. current_section = ""
  49. with open(temp.name) as reader:
  50. with open(self.fname, "w") as writer:
  51. for line in reader.readlines():
  52. m = re.match("\[([^\[\]]+)\]", line)
  53. if m:
  54. current_section = m.group(1)
  55. if current_section == section:
  56. if re.match("%s\s*\=" % name, line):
  57. continue
  58. else:
  59. writer.write(line)
  60. else:
  61. writer.write(line)