build.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python
  2. import os
  3. import json
  4. import toml
  5. from typing import Dict
  6. from chevron import render
  7. from shutil import copytree, rmtree
  8. from config import PATH_PARTIAL, PATH_SRC, PATH_THEME, PATH_THEME_DEST, \
  9. PATH_DEST, FILE_SITE, DEF_THEME
  10. def read_config(file: str) -> Dict:
  11. """
  12. @api {} / read config
  13. @apiName read_config
  14. @apiGroup function
  15. @apiParam {string} file filename of config
  16. @apiSuccess {dict} config dict reflect to the config file
  17. @apiError FileNotFound FileUnaccessable FileParseError
  18. """
  19. _, ext = os.path.splitext(file)
  20. loader = toml.loads if ext.lower() == '.toml' else json.loads
  21. with open(file, 'rt') as fh:
  22. val = loader(fh.read())
  23. val['lambdas'] = {
  24. 'equal_output' : equal_output,
  25. }
  26. return val
  27. return {}
  28. def build_file(hash, file:str) -> str:
  29. """
  30. build a single mustache file
  31. @hash: parameters
  32. @file: str filename of mustache
  33. @return: str html populated.
  34. """
  35. with open(file, "rt") as fh:
  36. return render(template=fh, data=hash, partials_path=PATH_PARTIAL)
  37. def build_all():
  38. # load config
  39. hash = read_config(FILE_SITE)
  40. site = hash.get('site')
  41. if not site:
  42. print('{} error'.format(FILE_SITE))
  43. exit(-1)
  44. # theme
  45. if not site.get('theme'):
  46. site['theme'] = DEF_THEME
  47. theme_src_dir = os.path.join(PATH_THEME, site.get('theme'))
  48. theme_dest_dir = PATH_THEME_DEST
  49. # remote old theme
  50. try:
  51. rmtree(theme_dest_dir)
  52. except Exception:
  53. pass
  54. # copy theme
  55. try:
  56. copytree(theme_src_dir, theme_dest_dir)
  57. except Exception as e:
  58. print('ERROR: theme error:', e)
  59. exit(-2)
  60. for r, _, fl in os.walk(PATH_SRC):
  61. for f in fl:
  62. name, ext = os.path.splitext(f)
  63. if ext.lower() != '.mustache':
  64. continue
  65. fullname = os.path.join(r, f)
  66. hash['file'] = '{}.html'.format(name)
  67. html_str = build_file(hash, fullname)
  68. if not html_str:
  69. print('WARNING: empty output:', fullname)
  70. fullhtml = os.path.join(PATH_DEST, '{}.html'.format(name))
  71. with open(fullhtml, 'wt') as fh:
  72. fh.write(html_str)
  73. def equal_output(text, render):
  74. """
  75. mustache lambda: 实现三元语义
  76. a==b?c:d
  77. 渲染后,如果 a == b 则 最终渲染 c 否则 最终渲染 d
  78. """
  79. result = render(text)
  80. parts = result.split("?")
  81. compares = parts[0].split("==")
  82. values = parts[1].split(":")
  83. return values[0].strip() if compares[0].strip() == compares[1].strip() else values[1].strip()
  84. if __name__ == '__main__':
  85. build_all()