Skip to content

Commit

Permalink
Merge pull request #21 from CristianLara/version-aware-tutorial-links
Browse files Browse the repository at this point in the history
[Tutorials] Github and Colab links point to the correct version matching the currently viewed tutorial
  • Loading branch information
CristianLara authored Nov 22, 2024
2 parents 5776cd9 + cfa6fb5 commit 9b986f4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 15 deletions.
57 changes: 43 additions & 14 deletions scripts/convert_ipynb_to_mdx.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import json
import re
import shutil
import subprocess
import uuid
import io
import argparse
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from typing import Any, Dict, List, Tuple, Union, Optional

import mdformat # @manual=fbsource//third-party/pypi/mdformat:mdformat
import nbformat
Expand Down Expand Up @@ -156,24 +158,35 @@ def create_imports() -> str:
return f"{imports}\n"


def get_current_git_tag() -> Optional[str]:
"""
Retrieve the current Git tag if the current commit is tagged.
Returns:
Optional[str]: The current Git tag as a string if available, otherwise None.
"""
try:
tag = subprocess.check_output(['git', 'describe', '--tags', '--exact-match'], stderr=subprocess.STDOUT).strip().decode('utf-8')
return tag
except subprocess.CalledProcessError:
return None


def create_buttons(
nb_metadata: Dict[str, Dict[str, str]],
tutorial_folder_name: str,
) -> str:
"""
Create buttons that link to Colab and GitHub for the tutorial.
Args:
nb_metadata (Dict[str, Dict[str, str]]): Metadata for the tutorial.
tutorial_folder_name (str): The name of the tutorial folder where the MDX
converted files exist. This is typically just the name of the Jupyter
notebook file.
Returns:
str: MDX formatted buttons.
"""
github_url = f"https://github.com/cristianlara/Ax/blob/main/tutorials/{nb_metadata['id']}.ipynb"
colab_url = f"https://colab.research.google.com/github/cristianlara/Ax/blob/main/tutorials/{nb_metadata['id']}/{nb_metadata['id']}.ipynb"
version = get_current_git_tag() or "main"
github_url = f"https://github.com/cristianlara/Ax/blob/{version}/tutorials/{nb_metadata['id']}/{nb_metadata['id']}.ipynb"
colab_url = f"https://colab.research.google.com/github/cristianlara/Ax/blob/{version}/tutorials/{nb_metadata['id']}/{nb_metadata['id']}.ipynb"
return f'<LinkButtons\n githubUrl="{github_url}"\n colabUrl="{colab_url}"\n/>\n\n'


Expand Down Expand Up @@ -966,7 +979,7 @@ def transform_notebook(path: Path, nb_metadata: object) -> str:
mdx = ""
mdx += create_frontmatter(path, nb_metadata)
mdx += create_imports()
mdx += create_buttons(nb_metadata, path.stem)
mdx += create_buttons(nb_metadata)
for cell in nb["cells"]:
cell_type = cell["cell_type"]

Expand All @@ -987,17 +1000,33 @@ def transform_notebook(path: Path, nb_metadata: object) -> str:
return mdx


def clean_up_directories() -> None:
"""
Delete output from previously converted notebooks. Particularly useful for
removing plot data since those filenames are randomly generated and won't
be replaced with future runs.
Returns:
None: Does not return anything.
"""
if TUTORIALS_DIR.exists():
# We intentionally leave the static `index.mdx` file in place since that is not autogenerated.
for item in os.scandir(TUTORIALS_DIR):
if item.is_dir():
shutil.rmtree(item.path)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert tutorial notebooks into mdx files.")
parser.add_argument("--clean", action='store_true', help="Delete output from previously converted notebooks.")
args = parser.parse_args()

tutorials_metadata = load_nb_metadata()
print("--------------------------------------------")
print("Converting tutorial notebooks into mdx files")
print("--------------------------------------------")
if TUTORIALS_DIR.exists():
# Remove previous tutorial docs if any. We intentionally leave the
# static `index.mdx` file in place since that is not autogenerated.
for item in os.scandir(TUTORIALS_DIR):
if item.is_dir():
shutil.rmtree(item.path)
if args.clean:
clean_up_directories()
for metadata in tutorials_metadata:
path = (LIB_DIR / "tutorials" / metadata["id"] / (metadata["id"] + ".ipynb")).resolve()
print(f"{path.stem}")
Expand Down
2 changes: 1 addition & 1 deletion scripts/make_docs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ if [[ $ONLY_DOCUSAURUS == false ]]; then
echo "-----------------------------------"
echo "Generating tutorials"
echo "-----------------------------------"
python3 scripts/convert_ipynb_to_mdx.py
python3 scripts/convert_ipynb_to_mdx.py --clean

fi # end of not only Docusaurus block

Expand Down

0 comments on commit 9b986f4

Please sign in to comment.