Last active
November 2, 2022 00:25
-
-
Save vst/b6a00c523ca20ef1a1a375a252c3fb0d to your computer and use it in GitHub Desktop.
[mdbook Plugin] Add gitinfo to sidebar
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
## Usage: | |
## | |
## 1. Add this script next to `book.toml` under file name `mdbook_plugin_gitinfo.py` | |
## 2. Update `book.toml`: | |
## | |
## ```toml | |
## [preprocessor.gitinfo] | |
## command = "python3 mdbook_plugin_gitinfo.py" | |
## renderers = ["html"] | |
## ``` | |
import json | |
import subprocess | |
import sys | |
from typing import Any, Dict, List, Optional, TypedDict, Union | |
class Book(TypedDict): | |
context: "BookContext" | |
content: "BookContent" | |
class BookContext(TypedDict): | |
root: str | |
config: Dict[str, Any] | |
renderer: str | |
mdbook_version: str | |
class BookContent(TypedDict): | |
sections: List[Union[Dict[str, Any], str]] | |
def read_book() -> Book: | |
context, content = json.load(sys.stdin) | |
return {"context": context, "content": content} | |
def write_book(book: Book) -> None: | |
json.dump(book["content"], sys.stdout) | |
def plugin_add_version(book: Book) -> Book: | |
gitinfo = get_gitinfo() | |
version = "ERR: No Git Information" if gitinfo is None else gitinfo | |
book["content"]["sections"].append("Separator") | |
book["content"]["sections"].append( | |
{ | |
"Chapter": { | |
"name": f"Version: {version}", | |
"content": "", | |
"sub_items": [], | |
"parent_names": [], | |
} | |
} | |
) | |
return book | |
def get_gitinfo() -> Optional[str]: | |
result = subprocess.run(["git", "describe", "--always"], capture_output=True) | |
return result.stdout.decode("utf-8") if result.returncode == 0 else None | |
def main(): | |
book = read_book() | |
book = plugin_add_version(book) | |
write_book(book) | |
if __name__ == "__main__": | |
## Did we receive an argument? | |
if len(sys.argv) > 1: | |
## Is the call a "support" predicate? | |
if sys.argv[1] == "supports": | |
## We support all kind of renderers: | |
sys.exit(0) | |
## Run the plugin: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment