|
| 1 | +from datetime import datetime |
| 2 | +from typing import Dict, Any |
| 3 | + |
| 4 | +from jinja2.ext import Extension |
| 5 | + |
| 6 | + |
| 7 | +class CurrentYearExtension(Extension): |
| 8 | + """ |
| 9 | + Jinja extension that adds a {{ current_year }} variable containing the current year. |
| 10 | + """ |
| 11 | + |
| 12 | + def __init__(self, environment): |
| 13 | + super().__init__(environment) |
| 14 | + environment.globals["current_year"] = str(datetime.now().year) |
| 15 | + |
| 16 | + |
| 17 | +class GitExtension(Extension): |
| 18 | + """ |
| 19 | + Jinja extension that adds support for filters: |
| 20 | + - git_user_name: returns the default user name from git config |
| 21 | + - git_user_email: returns the default user email from git config |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, environment): |
| 25 | + super().__init__(environment) |
| 26 | + |
| 27 | + try: |
| 28 | + import subprocess |
| 29 | + |
| 30 | + stdout = subprocess.check_output( |
| 31 | + ["git", "config", "--get", "user.name"], |
| 32 | + text=True, |
| 33 | + stderr=subprocess.DEVNULL, |
| 34 | + ).strip() |
| 35 | + environment.filters["git_user_name"] = lambda default="": stdout or default |
| 36 | + except (subprocess.SubprocessError, FileNotFoundError): |
| 37 | + environment.filters["git_user_name"] = lambda default="": default |
| 38 | + |
| 39 | + try: |
| 40 | + import subprocess |
| 41 | + |
| 42 | + stdout = subprocess.check_output( |
| 43 | + ["git", "config", "--get", "user.email"], |
| 44 | + text=True, |
| 45 | + stderr=subprocess.DEVNULL, |
| 46 | + ).strip() |
| 47 | + environment.filters["git_user_email"] = lambda default="": stdout or default |
| 48 | + except (subprocess.SubprocessError, FileNotFoundError): |
| 49 | + environment.filters["git_user_email"] = lambda default="": default |
| 50 | + |
| 51 | + |
| 52 | +class SlugifyExtension(Extension): |
| 53 | + """ |
| 54 | + Jinja extension that adds a filter: |
| 55 | + - slugify: to convert "The text" into "the-text" or "the_text" if underscore=True |
| 56 | + """ |
| 57 | + |
| 58 | + def __init__(self, environment): |
| 59 | + super().__init__(environment) |
| 60 | + |
| 61 | + def slugify(text, underscore=False): |
| 62 | + import re |
| 63 | + import unicodedata |
| 64 | + |
| 65 | + text = unicodedata.normalize("NFKD", text) |
| 66 | + text = text.encode("ascii", "ignore").decode("ascii") |
| 67 | + text = text.lower() |
| 68 | + text = re.sub(r"[^a-z0-9]+", "_" if underscore else "-", text) |
| 69 | + text = re.sub(r"[-_]+", "_" if underscore else "-", text) |
| 70 | + text = text.strip("_" if underscore else "-") |
| 71 | + return text |
| 72 | + |
| 73 | + environment.filters["slugify"] = slugify |
0 commit comments