Skip to content

Commit

Permalink
refactor: Project data is controlled as struct
Browse files Browse the repository at this point in the history
  • Loading branch information
attakei committed Feb 18, 2024
1 parent 07d4e5c commit f335fbb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
27 changes: 25 additions & 2 deletions rst_pypi_ref/core.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
"""Core module."""
import re
from dataclasses import dataclass
from typing import List, Optional

from docutils import nodes
from docutils.parsers.rst import roles
from docutils.parsers.rst.states import Inliner


@dataclass
class Project:
"""Project data struct on PyPI."""

name: str
version: Optional[str] = None

@classmethod
def parse(cls, fullname: str) -> "Project":
spec = fullname.split("==")
if len(spec) == 1:
return cls(name=spec[0])
return cls(name=spec[0], version=spec[1])

@property
def url(self) -> str:
url = f"https://pypi.org/project/{self.name}/"
if self.version:
url += f"{self.version}/"
return url


def build_package_url(fullname: str) -> str:
"""Build ref URL for package fullname after parsed."""
spec = fullname.split("==")
Expand Down Expand Up @@ -34,8 +57,8 @@ def pypi_reference_role(
if matched:
title = matched.group("title")
target = matched.group("target")
url = build_package_url(target)
return [nodes.reference(rawtext, title, refuri=url, **options)], messages
project = Project.parse(target)
return [nodes.reference(rawtext, title, refuri=project.url, **options)], messages


def bootstrap():
Expand Down
10 changes: 5 additions & 5 deletions tests/test_it.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ def test_title_and_target(self):
assert node["refuri"] == "https://pypi.org/project/docutils/"


class TestForBuildPackageUrl:
class TestForProject:
def test_name_only(self):
url = core.build_package_url("docutils")
assert url == "https://pypi.org/project/docutils/"
project = core.Project(name="docutils")
assert project.url == "https://pypi.org/project/docutils/"

def test_with_version(self):
url = core.build_package_url("docutils==0.1.0")
assert url == "https://pypi.org/project/docutils/0.1.0/"
project = core.Project(name="docutils", version="0.1.0")
assert project.url == "https://pypi.org/project/docutils/0.1.0/"


class TestForParse:
Expand Down

0 comments on commit f335fbb

Please sign in to comment.