Skip to content

Commit

Permalink
Merge pull request #24 from rtuszik/develop
Browse files Browse the repository at this point in the history
v0.5.0
  • Loading branch information
rtuszik authored Nov 8, 2024
2 parents 170de28 + b2ea8fb commit 073a4a9
Show file tree
Hide file tree
Showing 13 changed files with 1,319 additions and 1,425 deletions.
210 changes: 9 additions & 201 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
.aider*
output/*


*.log

env
venv
.venv
.env

cheatsheets/*
!cheatsheets/example-cheatsheet.yaml

Expand All @@ -10,12 +18,6 @@ cheatsheets/*
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
Expand All @@ -25,25 +27,6 @@ Icon
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### macOS Patch ###
# iCloud generated files
*.icloud

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
Expand All @@ -65,180 +48,5 @@ share/python-wheels/
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml

# ruff
.ruff_cache/

# LSP config files
pyrightconfig.json

### venv ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
pip-selfcheck.json

### Vim ###
# Swap
[._]*.s[a-v][a-z]
!*.svg # comment out if you don't need vector files
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]

# Session
Session.vim
Sessionx.vim

# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~

# End of https://www.toptal.com/developers/gitignore/api/Vim,macOS,Python,venv
*pycache*
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pyyaml==6.0.2
jinja2==3.1.4
python-dotenv==1.0.1
ruamel.yaml==0.18.6
Empty file added src/__init__.py
Empty file.
33 changes: 17 additions & 16 deletions src/generate_cheatsheet.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import yaml
from ruamel.yaml import YAML
from jinja2 import Environment, FileSystemLoader
import sys
import os
Expand All @@ -8,6 +8,13 @@
from logger import get_logger
from pathlib import Path

# Create YAML instances once
yaml_safe = YAML(typ='safe')
yaml_rw = YAML()
yaml_rw.indent(mapping=2, sequence=4, offset=2)
yaml_rw.preserve_quotes = True
yaml_rw.width = 100

load_dotenv()

# Define base paths
Expand All @@ -29,16 +36,13 @@

def load_yaml(file_path: Path) -> dict | None:
try:
with open(file_path, "r") as file:
return yaml.safe_load(file)
with open(file_path, "r", encoding='utf-8') as file:
return yaml_safe.load(file)
except FileNotFoundError:
logging.error(f"Error: YAML file '{file_path}' not found.")
return None
except yaml.YAMLError as e:
logging.error(f"Error parsing YAML file '{file_path}': {e}")
return None
except Exception as e:
logging.error(f"Unexpected error reading file '{file_path}': {e}")
logging.error(f"Error reading YAML file '{file_path}': {e}")
return None


Expand Down Expand Up @@ -119,9 +123,8 @@ def get_layout_info(data):
"system": layout.get("system", "Darwin"),
}


def generate_html(data, keyboard_layouts, system_mappings):
template_path = TEMPLATES_DIR / "cheatsheet_template.html"
template_path = "cheatsheets/cheatsheet-template.html"
layout_info = get_layout_info(data)
data["shortcuts"] = normalize_shortcuts(
data, system_mappings.get(layout_info["system"], {})
Expand All @@ -135,13 +138,11 @@ def generate_html(data, keyboard_layouts, system_mappings):


def validate_and_lint(yaml_file):
errors = validate_yaml(yaml_file)
validation_result = validate_yaml(yaml_file)
warnings = lint_yaml(yaml_file)

if errors:
logging.error(f"Validation errors in {yaml_file}:")
for error in errors:
logging.error(f" - {error}")
if not validation_result:
logging.error(f"Validation failed for {yaml_file}")
return False

if warnings:
Expand All @@ -153,7 +154,7 @@ def validate_and_lint(yaml_file):

def write_html_content(html_output, html_content):
try:
with open(html_output, "w") as file:
with open(html_output, "w", encoding='utf-8') as file:
file.write(html_content)
except IOError as e:
logging.error(f"Error writing to output file: {e}")
Expand Down Expand Up @@ -197,7 +198,7 @@ def generate_index(cheatsheets):

index_output = os.path.join(OUTPUT_DIR, "index.html")

with open(index_output, "w") as file:
with open(index_output, "w", encoding='utf-8') as file:
file.write(html_content)

logging.info(f"Index page generated: {index_output}")
Expand Down
23 changes: 15 additions & 8 deletions src/template_renderer.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
from jinja2 import Template
from jinja2 import Environment, FileSystemLoader
from logger import get_logger
from pathlib import Path

logging = get_logger()

def render_template(template_path, data):
"""
Render a template from the given path with provided data.
"""
try:
with open(template_path, "r") as file:
template = Template(file.read())
# Use the templates directory directly
templates_dir = Path(__file__).parent / "templates"

env = Environment(
loader=FileSystemLoader(str(templates_dir))
)

template = env.get_template(str(template_path))
return template.render(**data)

except FileNotFoundError:
logging.error(f"Error: Template file '{template_path}' not found.")
return None
except Exception as e:
logging.error(f"Error reading template file: {e}")
return None

try:
return template.render(**data)
except Exception as e:
logging.error(f"Error rendering template: {e}")
return None
16 changes: 16 additions & 0 deletions src/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en" charset="UTF-8">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{% block header %}{% endblock %}
<title>
{% block title %}{% endblock %}
</title>
{% block page_styles %}{% endblock %}
</head>
<body class="dark-mode">
{% block content %}{% endblock %}
{% block javascript %}{% endblock %}
</body>
</html>
Loading

0 comments on commit 073a4a9

Please sign in to comment.