A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 

175 líneas
5.7 KiB

  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import logging
  4. import os
  5. import shutil
  6. import subprocess
  7. page_src = """#! /usr/bin/env python
  8. # -*- coding: utf-8 -*-
  9. import os
  10. import sys
  11. os.chdir("..")
  12. sys.path.insert(0, ".")
  13. from mako.template import Template
  14. from mako.lookup import TemplateLookup
  15. from copyvios.cookies import parse_cookies
  16. def main(environ, start_response):
  17. lookup = TemplateLookup(directories=["{{pages_dir}}"],
  18. input_encoding="utf8")
  19. template = Template(filename="{{src}}", module_directory="{{temp_dir}}",
  20. lookup=lookup, format_exceptions=True)
  21. headers = [("Content-Type", "text/html")]
  22. cookies = parse_cookies(environ)
  23. page = template.render(environ=environ, headers=headers,
  24. cookies=cookies).encode("utf8")
  25. start_response("200 OK", headers)
  26. return [page]
  27. if __name__ == "__main__":
  28. from flup.server.fcgi import WSGIServer
  29. WSGIServer(main).run()
  30. """
  31. rewrite_script_src = """match URL into $ with ^/~earwig/{0}(\?.*?)?$
  32. if matched then
  33. set URL = /~earwig/www/{1}.fcgi$1
  34. goto END
  35. endif
  36. """
  37. class Builder(object):
  38. def __init__(self):
  39. self.build_dir = "www"
  40. self.static_dir = "static"
  41. self.pages_dir = "pages"
  42. self.support_dir = "pages/support"
  43. self.temp_dir = "temp"
  44. self.rs_file = "rewrite.script"
  45. self.root = logging.getLogger("builder")
  46. self.root.addHandler(logging.NullHandler())
  47. self._pages = []
  48. def _enable_logging(self):
  49. handler = logging.StreamHandler()
  50. handler.setFormatter(_LogFormatter())
  51. self.root.addHandler(handler)
  52. self.root.setLevel(logging.DEBUG)
  53. def _replace_file(self, name, program, logger):
  54. logger.debug("{0} {1}".format(program, name))
  55. replacement = subprocess.check_output([program, name])
  56. os.remove(name)
  57. with open(name, "w") as fp:
  58. fp.write(replacement)
  59. def _gen_page(self, page, base):
  60. if not page.endswith(".mako"):
  61. base.warn("Skipping {0} (not endswith('.mako'))".format(page))
  62. return
  63. logger = base.getChild(page.rsplit(".", 1)[0])
  64. self._pages.append(page.rsplit(".", 1)[0])
  65. src = os.path.join(self.pages_dir, page)
  66. dest = os.path.join(self.build_dir, page.replace(".mako", ".fcgi"))
  67. logger.debug("build {0} -> {1}".format(src, dest))
  68. content = page_src.replace("{{src}}", src)
  69. content = content.replace("{{pages_dir}}", self.pages_dir)
  70. content = content.replace("{{temp_dir}}", self.temp_dir)
  71. with open(dest, "w") as fp:
  72. fp.write(content)
  73. logger.debug("chmod 0755 {0}".format(dest))
  74. os.chmod(dest, 0755)
  75. def clean(self):
  76. logger = self.root.getChild("clean")
  77. targets = (self.build_dir, self.temp_dir)
  78. for target in targets:
  79. if os.path.exists(target):
  80. logger.debug("rm -r {0}".format(target))
  81. shutil.rmtree(target)
  82. logger.debug("mkdir {0}".format(target))
  83. os.mkdir(target)
  84. def gen_static(self):
  85. logger = self.root.getChild("static")
  86. dest = os.path.join(self.build_dir, "static")
  87. logger.debug("copytree {0} -> {1}".format(self.static_dir, dest))
  88. shutil.copytree(self.static_dir, dest)
  89. for dirpath, dirnames, filenames in os.walk(dest):
  90. for filename in filenames:
  91. name = os.path.join(dirpath, filename)
  92. if name.endswith(".js"):
  93. self._replace_file(name, "uglifyjs", logger)
  94. elif name.endswith(".css"):
  95. self._replace_file(name, "uglifycss", logger)
  96. def gen_pages(self):
  97. logger = self.root.getChild("pages")
  98. pages = os.listdir(self.pages_dir)
  99. for page in pages:
  100. if not os.path.isfile(os.path.join(self.pages_dir, page)):
  101. continue
  102. self._gen_page(page, logger)
  103. def gen_zws(self):
  104. logger = self.root.getChild("zws")
  105. target = self.rs_file
  106. if os.path.exists(target):
  107. logger.debug("rm {0}".format(target))
  108. os.remove(target)
  109. logger.debug("build rewrite.script")
  110. with open(target, "w") as fp:
  111. fp.write(rewrite_script_src.format("", "index"))
  112. for page in self._pages:
  113. fp.write(rewrite_script_src.format(page, page))
  114. def build(self):
  115. self._enable_logging()
  116. self.root.info("Building project...")
  117. self.clean()
  118. self.gen_static()
  119. self.gen_pages()
  120. self.gen_zws()
  121. self.root.info("Done!")
  122. class _LogFormatter(logging.Formatter):
  123. def __init__(self):
  124. fmt = "[%(asctime)s %(lvl)s] %(name)s: %(message)s"
  125. datefmt = "%Y-%m-%d %H:%M:%S"
  126. _format = super(_LogFormatter, self).format
  127. self.format = lambda record: _format(self.colorize(record))
  128. super(_LogFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
  129. def colorize(self, record):
  130. l = record.levelname.ljust(8)
  131. if record.levelno == logging.DEBUG:
  132. record.lvl = l.join(("\x1b[34m", "\x1b[0m")) # Blue
  133. if record.levelno == logging.INFO:
  134. record.lvl = l.join(("\x1b[32m", "\x1b[0m")) # Green
  135. if record.levelno == logging.WARNING:
  136. record.lvl = l.join(("\x1b[33m", "\x1b[0m")) # Yellow
  137. if record.levelno == logging.ERROR:
  138. record.lvl = l.join(("\x1b[31m", "\x1b[0m")) # Red
  139. if record.levelno == logging.CRITICAL:
  140. record.lvl = l.join(("\x1b[1m\x1b[31m", "\x1b[0m")) # Bold red
  141. return record
  142. if __name__ == "__main__":
  143. Builder().build()