Skip to content

Commit

Permalink
Fix errors in documentation of examples
Browse files Browse the repository at this point in the history
- also factor-out docs-supportive utils to another module so they can be used in API
  • Loading branch information
e-lo committed Oct 7, 2024
1 parent dfb08bb commit cc9dd07
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 75 deletions.
2 changes: 1 addition & 1 deletion docs/datamodels.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

!!! warning

These models are **not** the canonical schema and may or may not be completely accurate and up to date – although we try our best. The canonical schema is maintained in json-schema format and is documented on the [schemas](../json-schemas) page – but this is much nicer to read so we recommend you stay here.
These models are **not** the canonical schema and may or may not be completely accurate and up to date – although we try our best. The canonical schema is maintained in json-schema format and is documented on the [schemas](json-schemas.md) page – but this is much nicer to read so we recommend you stay here.

::: projectcard.models.project.ProjectModel
options:
Expand Down
4 changes: 2 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ Project Cards represent information about a tranportation infrastructure project

The ProjectCard schema is represented as a [json-schema](https://json-schema.org) in the `/schema` directory. More details: [json-schemas page](json-schemas.md).

The rendering of json-schema leaves a wee bit to be desired, so you might prefer revieweing the schema in [datamodels].
The rendering of json-schema leaves a wee bit to be desired, so you might prefer revieweing the schema in [datamodels](datamodels.md).

## Data Model

If you are working in a python environment, you might find it easier to use the [pydantic](https://docs.pydantic.dev/) data models which are synced to the json-schema. More details: [datamodels page](datamodels.md).

### Example Data

Example project cards can be found in the `/examples` directory and on the [examples page](examples.md) as well as within the [datamodels] documentation.
Example project cards can be found in the `/examples` directory and on the [examples page](examples.md) as well as within the [datamodels](datamodels.md) documentation.

## Basic Usage

Expand Down
58 changes: 2 additions & 56 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
"""Functions for mkdocs documentation."""

import logging
import os
import re
from pathlib import Path

from projectcard import ProjectCard
from projectcard.utils import slug_to_str
from projectcard.docs import card_list_to_table

SCHEMA_DIR = Path("projectcard") / "schema"

Expand Down Expand Up @@ -56,24 +52,6 @@ def document_schema(schema_filename: str) -> str:
content = _rm_html_between_tags(content, tag="footer")
return content

def _categories_as_str(card: ProjectCard) -> str:
if len(card.change_types) == 1:
return slug_to_str(card.change_type)

_cat_str = "Multiple: "
_cat_str += ", ".join([f"{slug_to_str(c)}" for c in list(set(card.change_types))])
return _cat_str

def _card_to_md(card: ProjectCard) -> str:
with Path(card.file).open("r") as file:
file_txt = file.read_text()
_card_md = f"\n###{card.project.title()}\n\n"
_card_md += f"**Category**: {_categories_as_str(card)}\n"
_card_md += f'``` yaml title="examples/{Path(card.file).name}"\n\n'
_card_md += file_txt
_card_md += "\n```\n"
return _card_md

@env.macro
def list_examples(data_dir: Path) -> str:
"""Outputs a simple list of the directories in a folder in markdown.
Expand All @@ -82,39 +60,7 @@ def list_examples(data_dir: Path) -> str:
data_dir: directory to search in
Returns: markdown-formatted list
"""
from projectcard.io import _make_slug, read_cards

table_fields = ["Category", "Notes"]

data_dir = Path(env.project_dir) / data_dir

_md_examples = "\n## Cards\n"
_md_table = (
"| **Name** | **"
+ "** | **".join(table_fields)
+ "** |\n| "
+ " ----- | " * (len(table_fields) + 1)
+ "\n"
)

def _card_to_mdrow(card):
_md_row = (
f"| [{card.project.title()}](#{_make_slug(card.project).replace('_','-')}) | "
)
_md_row += f" {_categories_as_str(card)} |"
_md_row += f" {card.notes} |\n"
return _md_row

_example_cards = None
_example_cards = read_cards(data_dir)

for _card in _example_cards.values():
_md_table += _card_to_mdrow(_card)
_md_examples += _card_to_md(_card)

example_md = _md_table + _md_examples

return example_md
return card_list_to_table(Path(env.project_dir) / data_dir)


def _get_html_between_tags(content: str, tag: str = "body") -> str:
Expand Down
62 changes: 62 additions & 0 deletions projectcard/docs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Utilities to assist in documentation which may be useful for other purposes."""
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

from .utils import slug_to_str, make_slug
from .io import read_cards


if TYPE_CHECKING:

Check failure on line 11 in projectcard/docs.py

View workflow job for this annotation

GitHub Actions / run-tests

Ruff (I001)

projectcard/docs.py:2:1: I001 Import block is un-sorted or un-formatted
from .projectcard import ProjectCard


def card_to_md(card: ProjectCard) -> str:
"""Convert a project card contents to markdown text inserted as yaml."""
_card_md = f"\n###{card.project.title()}\n\n"
_card_md += f"**Category**: {_categories_as_str(card.change_types)}\n"
_card_md += f'``` yaml title="examples/{Path(card.file).name}"\n\n'
_card_md += card.file.read_text()
_card_md += "\n```\n"
return _card_md


def _categories_as_str(change_types: list[str] ) -> str:
if len(change_types) == 1:
return slug_to_str(change_types[0])

_cat_str = "Multiple: "
_cat_str += ", ".join([f"{slug_to_str(c)}" for c in list(set(change_types))])
return _cat_str


def _card_to_mdrow(card):
_md_row = (
f"| [{card.project.title()}](#{make_slug(card.project).replace('_','-')}) | "
)
_md_row += f" {_categories_as_str(card.change_types)} |"
_md_row += f" {card.notes} |\n"
return _md_row



def card_list_to_table(card_dir: Path) -> str:
"""Generates a table of all project cards in a directory followed by the cards."""
CARD_LIST_TABLE_FIELDS = ["Category", "Notes"]
md_examples = "\n## Cards\n"
md_table = (
"| **Name** | **"
+ "** | **".join(CARD_LIST_TABLE_FIELDS)
+ "** |\n| "
+ " ----- | " * (len(CARD_LIST_TABLE_FIELDS) + 1)
+ "\n"
)

example_cards = read_cards(card_dir)

for card in example_cards.values():
md_table += _card_to_mdrow(card)
md_examples += card_to_md(card)

return md_table + md_examples
11 changes: 2 additions & 9 deletions projectcard/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ def _read_wrangler(filepath: Path) -> dict:

def write_card(project_card, filename: Optional[Path] = None):
"""Writes project card dictionary to YAML file."""
default_filename = _make_slug(project_card.project) + ".yml"
from .utils import make_slug
default_filename = make_slug(project_card.project) + ".yml"
filename = filename or Path(default_filename)

if not project_card.valid:
Expand Down Expand Up @@ -138,14 +139,6 @@ def dict_to_yaml_with_comments(d):
return "\n".join(final_yaml_lines)


def _make_slug(text, delimiter: str = "_"):
"""Makes a slug from text."""
import re

text = re.sub("[,.;@#?!&$']+", "", text.lower())
return re.sub("[\ ]+", delimiter, text)


def _replace_selected(txt: str, change_dict: dict = REPLACE_KEYS):
"""Will returned uppercased text if matches a select set of values.
Expand Down
1 change: 1 addition & 0 deletions projectcard/models/selections.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ class SelectFacility(BaseModel):
model_node_id: 4
to:
model_node_id: 5
```
!!! Example "Example: Select all links on SR320 which have 1 or 2 managed lanes."
```yaml
Expand Down
14 changes: 7 additions & 7 deletions projectcard/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ def _update_dict_key(dictdata: dict, findkey, replacekey):
return dictdata


def slug_to_str(slug: str) -> str:
"""Convert a slug to a string.
def make_slug(text, delimiter: str = "_"):
"""Makes a slug from text."""
import re

Args:
slug: string to convert
text = re.sub("[,.;@#?!&$']+", "", text.lower())
return re.sub("[\ ]+", delimiter, text)

Returns:
str: converted string

"""
def slug_to_str(slug: str) -> str:
"""Convert a slug to a more readible sstring."""
return slug.replace("-", " ").replace("_", " ").title()

0 comments on commit cc9dd07

Please sign in to comment.