Created
March 12, 2024 16:07
-
-
Save PetrGlad/9efd9882211f57f16ef42646915fb658 to your computer and use it in GitHub Desktop.
Code pile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
import jinja2 | |
import pygments | |
import pygments.lexers as lexers | |
from pygments.formatters import HtmlFormatter | |
CSS_CLASS = ".code" | |
N_COLUMNS = 15 | |
HTML_TEMPLATE = """ | |
<html> | |
<head> | |
<title>Pile of code</title> | |
<style> | |
{{style}} | |
.container { | |
column-count: {{n_columns}}; | |
width: 250% | |
} | |
.code { | |
width: 180% | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
{% for snippet in snippets %} | |
{{ snippet }} | |
{% endfor %} | |
</div> | |
</body> | |
</html> | |
""" | |
FORMATTER = HtmlFormatter(style="friendly", linenos=True, cssclass=CSS_CLASS) | |
def render_html(snippets): | |
jin_env = jinja2.Environment() | |
template = jin_env.from_string(HTML_TEMPLATE) | |
return template.render( | |
{ | |
"style": FORMATTER.get_style_defs(CSS_CLASS), | |
"n_columns": N_COLUMNS, | |
"snippets": snippets, | |
} | |
) | |
def colorize(file_name): | |
print(f"Colorizing {file_name}") | |
with open(file_name) as f: | |
code = f.read() | |
try: | |
lexer = lexers.get_lexer_for_filename(file_name, stripall=True) | |
except pygments.util.ClassNotFound: | |
lexer = pygments.lexers.special.TextLexer() | |
return pygments.highlight(code, lexer, FORMATTER) | |
name_exclusions = re.compile(".+\.(png|xlsx)$") | |
snippets = [] | |
for root, dirs, files in os.walk("stripped-2024-03"): | |
for filename in files: | |
if name_exclusions.match(filename): | |
continue | |
snippets.append(colorize(os.path.join(root, filename))) | |
with open("aaa.html", "w") as f: | |
f.write(render_html(snippets)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment