table_templater.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Parser for test templates
  2. #
  3. # Copyright (c) 2021 Virtuozzo International GmbH.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. import itertools
  19. from lark import Lark
  20. grammar = """
  21. start: ( text | column_switch | row_switch )+
  22. column_switch: "{" text ["|" text]+ "}"
  23. row_switch: "[" text ["|" text]+ "]"
  24. text: /[^|{}\[\]]+/
  25. """
  26. parser = Lark(grammar)
  27. class Templater:
  28. def __init__(self, template):
  29. self.tree = parser.parse(template)
  30. c_switches = []
  31. r_switches = []
  32. for x in self.tree.children:
  33. if x.data == 'column_switch':
  34. c_switches.append([el.children[0].value for el in x.children])
  35. elif x.data == 'row_switch':
  36. r_switches.append([el.children[0].value for el in x.children])
  37. self.columns = list(itertools.product(*c_switches))
  38. self.rows = list(itertools.product(*r_switches))
  39. def gen(self, column, row):
  40. i = 0
  41. j = 0
  42. result = []
  43. for x in self.tree.children:
  44. if x.data == 'text':
  45. result.append(x.children[0].value)
  46. elif x.data == 'column_switch':
  47. result.append(column[i])
  48. i += 1
  49. elif x.data == 'row_switch':
  50. result.append(row[j])
  51. j += 1
  52. return ''.join(result)