Skip to content

Commit

Permalink
refactor: ♻️ use jinja template for README (#1011)
Browse files Browse the repository at this point in the history
## Description

This PR makes the README use a jinja template.

I added some content, but it should obviously be refined further.

With values:
![Screenshot from 2025-01-28
11-27-40](https://github.com/user-attachments/assets/192f06d2-daea-4ed3-a4ac-7a8897524c35)

Without values:
![Screenshot from 2025-01-28
11-40-26](https://github.com/user-attachments/assets/7c7e391f-cd9a-4f41-a893-8b58f9d6e569)

Closes #748 

<!-- Select quick/in-depth as necessary -->
This PR needs a medium-depth review.

## Checklist

- [x] Added or updated tests
- [x] Updated documentation
- [x] Ran `just run-all`

---------

Co-authored-by: Luke W. Johnston <[email protected]>
  • Loading branch information
martonvago and lwjohnst86 authored Jan 28, 2025
1 parent d22a7a1 commit 7d14d55
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 12 deletions.
4 changes: 2 additions & 2 deletions seedcase_sprout/core/create_package_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ def create_package_structure(path: Path) -> list[Path]:
package_path = create_id_path(path, id)
create_dir(package_path)

properties = PackageProperties.default().compact_dict
properties = PackageProperties.default()
properties_path = create_properties_path(package_path)
readme = create_readme_text(properties)
readme_path = create_readme_path(package_path)

return [
write_json(properties, properties_path),
write_json(properties.compact_dict, properties_path),
write_file(readme, readme_path),
create_dir(package_path / "resources"),
]
84 changes: 74 additions & 10 deletions seedcase_sprout/core/create_readme_text.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
def create_readme_text(properties: dict) -> str:
from datetime import datetime
from importlib.resources import files
from pathlib import Path

from jinja2 import Environment, FileSystemLoader

from seedcase_sprout.core.properties import (
LicenseProperties,
PackageProperties,
)

TEMPLATES_PATH: Path = files("seedcase_sprout.core").joinpath("templates")


def create_readme_text(properties: PackageProperties) -> str:
"""Creates a string containing the README text.
Args:
Expand All @@ -7,13 +21,63 @@ def create_readme_text(properties: dict) -> str:
Returns:
A string with the README text based on the properties.
"""
# TODO: Finish this once Properties have been finished.
# resources = # Python code to convert the resource details in the dict as
# a Markdown list.

readme_text = (
f"# {properties['name']}: {properties['title']}\n\n"
f"{properties['description']}\n\n"
f"There are {len(properties['resources'])} resources in this package."
env = Environment(loader=FileSystemLoader(TEMPLATES_PATH))
env.filters["join_names"] = join_names
env.filters["format_date"] = format_date
env.filters["inline_code"] = inline_code
env.filters["format_link"] = format_link
template = env.get_template("README.jinja2")
return template.render(properties=properties)


def join_names(licenses: list[LicenseProperties] | None) -> str:
"""Joins license names into a comma-separated list.
Args:
licenses: The licenses.
Returns:
A comma-separated list of names.
"""
return ", ".join(license.name for license in licenses) if licenses else "N/A"


def format_date(created: str | None) -> str:
"""Transforms ISO date stamp to human-readable format.
Args:
created: The ISO date stamp.
Returns:
The date in a human-readable format.
"""
return (
datetime.fromisoformat(created).strftime("%d %B %Y, %H:%M")
if created
else "N/A"
)
return readme_text


def inline_code(value: str | None) -> str:
"""Adds inline code formatting to the input.
Args:
value: The value to format as inline code.
Returns:
The value formatted as inline code.
"""
return f"`{value}`" if value else "N/A"


def format_link(url: str | None, title: str = "See more") -> str:
"""Formats a URL as a markdown link.
Args:
url: The URL to format.
title: The title to show for the link. Defaults to "See more".
Returns:
A markdown link using the URL and the title.
"""
return f"[{title}]({url})" if url else "N/A"
21 changes: 21 additions & 0 deletions seedcase_sprout/core/templates/README.jinja2
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# {{ properties.title or "N/A" }}

{{ properties.description or "N/A" }}

| Field | Value |
|----------|-----------------------------------------|
| Name | {{ properties.name | inline_code }} |
| ID | {{ properties.id | inline_code }} |
| Version | {{ properties.version | inline_code }} |
| Homepage | {{ properties.homepage | format_link }} |
| Created | {{ properties.created | format_date }} |
| Licenses | {{ properties.licenses | join_names }} |

{% if properties.resources -%}
## Data Resources
{% for resource in properties.resources %}
{{ loop.index }}. **{{ resource.title }}**: {{ resource.description }}
{%- endfor %}
{% else -%}
No resources available.
{% endif %}
54 changes: 54 additions & 0 deletions tests/core/test_create_readme_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from seedcase_sprout.core.create_readme_text import create_readme_text
from seedcase_sprout.core.properties import (
ContributorProperties,
LicenseProperties,
PackageProperties,
ResourceProperties,
)


def test_creates_readme():
"""Should be able to create a README for a set of properties."""
properties = PackageProperties(
name="diabetes-hypertension-study",
title="Diabetes and Hypertension Study",
homepage="www.my-page.com/diabetes-2021",
id="123-abc-123",
description="This is my package.",
version="2.0.0",
created="2024-05-14T05:00:01+00:00",
contributors=[
ContributorProperties(
title="Jamie Jones",
email="[email protected]",
path="example.com/jamie_jones",
roles=["creator"],
)
],
resources=[
ResourceProperties(
title="First Resource", description="This is my first resource."
),
ResourceProperties(
title="Second Resource", description="This is my second resource."
),
],
licenses=[
LicenseProperties(
name="ODC-BY-1.0",
path="https://opendatacommons.org/licenses/by",
title="Open Data Commons Attribution License 1.0",
),
LicenseProperties(
name="APL-1.0",
path="https://opensource.org/license/apl1-0-php",
title="Adaptive Public License 1.0",
),
],
)
assert create_readme_text(properties)


def test_creates_readme_with_empty_values():
"""Should be able to create a README for an empty set of properties."""
assert create_readme_text(PackageProperties())

0 comments on commit 7d14d55

Please sign in to comment.