Skip to content

Commit

Permalink
Merge pull request #42 from seapagan/improve-cli-metadata
Browse files Browse the repository at this point in the history
Add improvements to the CLI metadata generation.
  • Loading branch information
seapagan authored Jan 25, 2023
2 parents d235f9c + 3cfb621 commit b2c401a
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 29 deletions.
49 changes: 32 additions & 17 deletions commands/custom.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
"""CLI functionality to customize the template."""
import os
import sys
from pathlib import Path

from datetime import date

import asyncclick as click
import tomli
import tomli_w
from jinja2 import Template
from rich import print

from config.helpers import LICENCES, template


def get_config_path():
"""Return the full path of the custom config file."""
script_dir = Path(os.path.dirname(os.path.realpath(sys.argv[0])))
return script_dir / "config" / "metadata.py"


def get_toml_path():
"""Return the full path of the pyproject.toml."""
script_dir = Path(os.path.dirname(os.path.realpath(sys.argv[0])))
return script_dir / "pyproject.toml"
from config.helpers import (
LICENCES,
get_api_version,
get_config_path,
get_toml_path,
template,
)


def init():
Expand All @@ -36,6 +29,8 @@ def init():
},
"author": "Grant Ramsay (seapagan)",
"website": "https://www.gnramsay.com",
"email": "[email protected]",
"this_year": date.today().year,
}

out = Template(template).render(data)
Expand Down Expand Up @@ -80,7 +75,7 @@ def choose_license():

while choice.strip().lower() not in [lic.lower() for lic in license_list]:
choice = click.prompt(
f"\nChoose a license from the following options.\n"
f"\nChoose a license from the following options:\n"
f"{license_strings}\nYour Choice of License?",
type=str,
default=custom_metadata.license_info["name"],
Expand All @@ -89,6 +84,18 @@ def choose_license():
return get_case_insensitive_dict(choice)


def choose_version(current_version):
"""Change the version or reset it."""
choice = click.prompt(
"Version Number (use * to reset to '0.0.1')",
type=str,
default=current_version,
)
if choice == "*":
return "0.0.1"
return choice


@click.group(name="custom")
def customize_group():
"""Customize the Template Strings and Metadata.
Expand All @@ -105,6 +112,7 @@ def metadata():
Documentation, Author details, Repository URL and more.
"""
print("\n[green]API-Template : Customize application Metadata\n")

data = {
"title": click.prompt(
"Enter your API title", type=str, default=custom_metadata.title
Expand All @@ -114,6 +122,7 @@ def metadata():
type=str,
default=custom_metadata.description,
),
"version": choose_version(get_api_version()),
"repo": click.prompt(
"URL to your Repository",
type=str,
Expand All @@ -136,14 +145,19 @@ def metadata():
default=custom_metadata.contact["url"],
),
}

data["this_year"] = date.today().year

print("\nYou have entered the following data:")
print(f"[green]Title : [/green]{data['title']}")
print(f"[green]Description : [/green]{data['desc']}")
print(f"[green]Version : [/green]{data['version']}")
print(f"[green]Repository : [/green]{data['repo']}")
print(f"[green]License : [/green]{data['license']['name']}")
print(f"[green]Author : [/green]{data['author']}")
print(f"[green]Email : [/green]{data['email']}")
print(f"[green]Website : [/green]{data['website']}")
print(f"[green](C) Year : [/green]{data['this_year']}")

if click.confirm("\nIs this Correct?", abort=True, default=True):
# write the metadata
Expand All @@ -161,6 +175,7 @@ def metadata():
with open(get_toml_path(), "rb") as f:
config = tomli.load(f)
config["tool"]["poetry"]["name"] = data["title"]
config["tool"]["poetry"]["version"] = data["version"]
config["tool"]["poetry"]["description"] = data["desc"]
config["tool"]["poetry"]["authors"] = [
f"{data['author']} <{data['email']}>"
Expand Down
41 changes: 39 additions & 2 deletions config/helpers.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,53 @@
"""Define the structure of the MetadataBase class."""
"""Helper classes and functions for config use."""
import os
import sys
from dataclasses import dataclass
from pathlib import Path

import tomli


def get_toml_path():
"""Return the full path of the pyproject.toml."""
script_dir = Path(os.path.dirname(os.path.realpath(__name__)))

return script_dir / "pyproject.toml"


def get_config_path():
"""Return the full path of the custom config file."""
script_dir = Path(os.path.dirname(os.path.realpath(sys.argv[0])))
return script_dir / "config" / "metadata.py"


def get_api_version() -> str:
"""Return the API version from the pyproject.toml file."""
try:
with open(get_toml_path(), "rb") as f:
config = tomli.load(f)
version = config["tool"]["poetry"]["version"]

return version

except Exception as e:
print(f"Cannot read the pyproject.toml file : {e}")
quit(3)


"""Define the structure of the MetadataBase class."""


@dataclass
class MetadataBase:
"""This is the base Metadata class used for customizsation."""
"""This is the base Metadata class used for customization."""

title: str
description: str
repository: str
contact: dict[str, str]
license_info: dict[str, str]
email: str
year: str


# List of acceptable Opensource Licenses with a link to their text.
Expand Down Expand Up @@ -47,6 +83,7 @@ class MetadataBase:
"url": "{{ website }}",
},
email="{{ email }}",
year="{{ this_year }}"
)
"""
3 changes: 2 additions & 1 deletion config/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
"url": "https://opensource.org/licenses/MIT",
},
contact={
"name": "Grant Ramsay",
"name": "Grant Ramsay (seapagan)",
"url": "https://www.gnramsay.com",
},
email="[email protected]",
year="2023"
)
1 change: 1 addition & 0 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class Settings(BaseSettings):
repository = custom_metadata.repository
contact = custom_metadata.contact
license_info = custom_metadata.license_info
year = custom_metadata.year

# email settings
mail_username = "test_username"
Expand Down
3 changes: 2 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from fastapi.staticfiles import StaticFiles
from rich import print

from config.helpers import get_api_version
from config.settings import get_settings
from database.db import database
from resources import config_error
Expand All @@ -17,7 +18,7 @@
docs_url=None, # we customize this ourselves
license_info=get_settings().license_info,
contact=get_settings().contact,
version="1.3.0",
version=get_api_version(),
)

app.include_router(api_router)
Expand Down
25 changes: 19 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
[tool.poetry]
name = "API Template"
version = "1.3.0"
version = "1.3.1"
description = "Run 'api-admin custom metadata' to change this information."
authors = ["Grant Ramsay <[email protected]>"]
authors = [
"Grant Ramsay (seapagan) <[email protected]>",
]
license = "MIT"
readme = "README.md"

Expand All @@ -23,20 +25,31 @@ anyio = "^3.6.2"
email-validator = "^1.3.1"
tomli = "^2.0.1"
tomli-w = "^1.0.0"
fastapi-mail = { extras = ["httpx"], version = "^1.2.0" }

[tool.poetry.dependencies.fastapi-mail]
extras = [
"httpx",
]
version = "^1.2.0"

[tool.poetry.dependencies.uvicorn]
extras = ["standard"]
extras = [
"standard",
]
version = "^0.20.0"

[tool.poetry.dependencies.passlib]
extras = ["bcrypt"]
extras = [
"bcrypt",
]
version = "^1.7.4"

[tool.poetry.group.dev.dependencies]
openapi-readme = "^0.2.1"
aiosmtpd = "^1.4.4"

[build-system]
requires = ["poetry-core"]
requires = [
"poetry-core",
]
build-backend = "poetry.core.masonry.api"
3 changes: 3 additions & 0 deletions resources/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from fastapi import APIRouter, Header, Request
from fastapi.templating import Jinja2Templates

from config.helpers import get_api_version
from config.settings import get_settings

router = APIRouter()
Expand All @@ -23,6 +24,8 @@ def root_path(
"repository": get_settings().repository,
"author": get_settings().contact["name"],
"website": get_settings().contact["url"],
"year": get_settings().year,
"version": get_api_version(),
}
return templates.TemplateResponse("index.html", context)

Expand Down
4 changes: 2 additions & 2 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<body>
<header>
<h1>{{ title }}</h1>
<h1>{{ title }} v{{ version }}</h1>
<h2>{{ description }}</h2>
</header>
<main>
Expand All @@ -42,7 +42,7 @@ <h2>{{ description }}</h2>
<a href="{{ website }}" rel="noopener noreferrer"
>{{ author }}</a
>
2022
{{ year }}
</footer>
</body>
</html>

0 comments on commit b2c401a

Please sign in to comment.