Skip to content

Instantly share code, notes, and snippets.

@vst
Last active November 2, 2022 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vst/b6a00c523ca20ef1a1a375a252c3fb0d to your computer and use it in GitHub Desktop.
Save vst/b6a00c523ca20ef1a1a375a252c3fb0d to your computer and use it in GitHub Desktop.
[mdbook Plugin] Add gitinfo to sidebar
## 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