Parser.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import os
  2. import re
  3. from .CronFile import CronFile
  4. class Parser:
  5. def parse(self):
  6. cronFile = CronFile()
  7. crontab = ""
  8. with os.popen("crontab -l") as stream:
  9. crontab = stream.read()
  10. result = crontab
  11. begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE)
  12. while begin:
  13. section = begin.group(1)
  14. cronFile.add_fragment(None, crontab[:begin.span()[0]])
  15. crontab = crontab[begin.span()[1]:]
  16. end = re.search("^\s*#\s*END\({0}\).*$".format(section), crontab, flags=re.MULTILINE)
  17. if end:
  18. cronFile.add_fragment(section, crontab[:end.span()[0]])
  19. crontab = crontab[end.span()[1]:]
  20. begin = re.search("^\s*#\s*BEGIN\((\w+)\).*$", crontab, flags=re.MULTILINE)
  21. cronFile.add_fragment(None, crontab)
  22. return cronFile
  23. def render(self, cronFile):
  24. result = ""
  25. for fragment in cronFile.fragments:
  26. if fragment[0] is None:
  27. result += fragment[1]
  28. else:
  29. result += "\n# BEGIN({0})".format(fragment[0])
  30. result += fragment[1]
  31. result += "\n# END({0})\n".format(fragment[0])
  32. return result