Skip to content

Commit

Permalink
Fix missing dataclasses dependency for py3.6 (#33)
Browse files Browse the repository at this point in the history
-   Fix linting errors.
-   Add dataclasses dependency for Python < 3.7.
  • Loading branch information
domvwt authored May 6, 2021
1 parent 4e04d2b commit f654e7c
Show file tree
Hide file tree
Showing 17 changed files with 159 additions and 167 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,8 @@ repos:
language: system
entry: poetry run mypy
types: [python]
- id: version
name: Version
language: system
entry: python -m tests.check_package_version
types: [python]
22 changes: 6 additions & 16 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,19 @@ language: python
os: linux
dist: xenial
python:
- 3.9
- 3.8
- 3.7
- 3.6
- 3.7
- 3.8
- 3.9

env:
- INSTALL_DEPS=""
- INSTALL_DEPS="--no-dev"

before_install:
- curl -fsS -o get-poetry.py https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py
- python get-poetry.py -y
- export PATH="$PATH:$HOME/.poetry/bin"
- poetry config virtualenvs.in-project true
- EXTRA_INSTALLS=""
- EXTRA_INSTALLS="ipython pandas matplotlib bokeh plotly kaleido weasyprint beautifulsoup4 html5lib"

install:
- poetry install $INSTALL_DEPS -E test
- pip install . pytest coverage $EXTRA_INSTALLS

script:
- python -m tests.check_package_version
- black --check .
- flake8
- mypy esparto tests
- coverage run --append --source esparto -m pytest

after_success:
Expand Down
16 changes: 12 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,32 @@ coverage: ## check code coverage quickly with the default Python
docstrings: ## generate google format docstrings
pyment esparto -o google -w

docs: ## generate Sphinx HTML documentation, including API docs
mkdocs clean
mkdocs build
docs: class-diagram ## generate documentation, including API docs
mkdocs build --clean

servedocs: ## compile the docs watching for changes
mkdocs serve -a "`hostname -I | xargs`:8000"

deploydocs: ## deploy docs to github pages
mkdocs gh-deploy

class-diagram: ## make UML class diagram
pyreverse esparto -o png -f ALL --ignore _contentdeps.py,_options.py,_publish.py
mv classes.png devdocs/classes.png
rm packages.png

release: dist class-diagram ## package and upload a release
reqs: ## output requirements.txt
poetry export -f requirements.txt -o requirements.txt --without-hashes

release: dist ## package and upload a release
poetry publish

dist: clean ## builds source and wheel package
poetry build
ls -l dist

hooks: ## run pre-commit hooks on all files
pre-commit run -a

install: clean ## install the package to the active Python's site-packages
poetry install
Binary file modified devdocs/classes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions docs/04-about/release-notes.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
Release Notes
=============

0.2.5 (2021-05-06)
------------------

- Fix linting errors.
- Add dataclasses dependency for Python < 3.7.


0.2.4 (2021-05-04)
------------------

Expand Down
13 changes: 5 additions & 8 deletions esparto/_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ def __eq__(self, other):
if isinstance(other, self.__class__):
if hasattr(self.content, "__iter__") and hasattr(other.content, "__iter__"):
return all(x == y for x, y in zip(self.content, other.content))
else:
return self.content == other.content

return self.content == other.content
return False

def __ne__(self, other):
Expand Down Expand Up @@ -479,13 +477,12 @@ def to_html(self, **kwargs) -> str:
html = f"<img src='{temp_file.name}'>\n"
return html

else:
html, js = components(self.content)
html, js = components(self.content)

# Remove outer <div> tag so we can give our own attributes
html = _remove_outer_div(html)
# Remove outer <div> tag so we can give our own attributes
html = _remove_outer_div(html)

return f"<div class='mb-3' style='width: {self.width}; height: {self.height};'>{html}\n{js}\n</div>"
return f"<div class='mb-3' style='width: {self.width}; height: {self.height};'>{html}\n{js}\n</div>"


class FigurePlotly(Content):
Expand Down
21 changes: 9 additions & 12 deletions esparto/_contentdeps.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from collections import UserDict
from dataclasses import dataclass
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from typing import Set
from typing import List, Set

from esparto import _INSTALLED_MODULES, _MODULE_PATH
from esparto._options import _get_source_from_options
from esparto._options import get_source_from_options


@dataclass
Expand All @@ -16,16 +16,13 @@ class ContentDependency:
target: str


@dataclass
class ResolvedDeps:
def __init__(self):
self.head = list()
self.tail = list()
head: List[str] = field(default_factory=list)
tail: List[str] = field(default_factory=list)


class ContentDependencyDict(UserDict):
def __init__(self):
super().__init__()

def __add__(self, other: ContentDependency):
self.data[other.name] = other
return self
Expand All @@ -35,7 +32,7 @@ def __add__(self, other: ContentDependency):


@lru_cache(maxsize=None)
def content_dependency_dict() -> ContentDependencyDict:
def lazy_content_dependency_dict() -> ContentDependencyDict:
bootstrap_cdn = (
'<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" '
+ 'integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">'
Expand Down Expand Up @@ -78,10 +75,10 @@ def resolve_deps(
) -> ResolvedDeps:
resolved_deps = ResolvedDeps()

source = _get_source_from_options(source)
source = get_source_from_options(source)

for dep in required_deps:
dep_details: ContentDependency = content_dependency_dict()[dep]
dep_details: ContentDependency = lazy_content_dependency_dict()[dep]
getattr(resolved_deps, dep_details.target).append(getattr(dep_details, source))

return resolved_deps
12 changes: 4 additions & 8 deletions esparto/_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,7 @@ def __eq__(self, other):
return self._title == other._title and all(
(x == y for x, y in zip(self.children, other.children))
)
else:
return False
return False

def __ne__(self, other):
return not self.__eq__(other)
Expand Down Expand Up @@ -349,8 +348,7 @@ def save_html(

if return_html:
return html
else:
return None
return None

def save(
self,
Expand Down Expand Up @@ -380,8 +378,7 @@ def save(

if return_html:
return html
else:
return None
return None

def save_pdf(
self, filepath: str = "./esparto-doc.pdf", return_html: bool = False
Expand All @@ -403,8 +400,7 @@ def save_pdf(

if return_html:
return html
else:
return None
return None

def __init__(
self,
Expand Down
5 changes: 2 additions & 3 deletions esparto/_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@ class ConfigOptions:
options = ConfigOptions()


def _get_source_from_options(source):
def get_source_from_options(source):
if source == "esparto.options":
if options.offline_mode:
return options._offline_source
else:
return options._online_source
elif source in ["cdn", "inline"]:
return source
else:
raise ValueError(f"Unrecognised source: {source}")
raise ValueError(f"Unrecognised source: {source}")
59 changes: 26 additions & 33 deletions esparto/_publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,18 @@
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union

from jinja2 import Environment, PackageLoader, select_autoescape # type: ignore
from jinja2 import Environment, PackageLoader # type: ignore

if TYPE_CHECKING:
from esparto._layout import Page, Layout
from esparto._content import Content

from esparto import _INSTALLED_MODULES
from esparto._contentdeps import resolve_deps
from esparto._options import _get_source_from_options, options
from esparto._options import get_source_from_options, options

_ENV = Environment(
loader=PackageLoader("esparto", "resources/jinja"),
autoescape=select_autoescape(["xml"]),
)

_BASE_TEMPLATE = _ENV.get_template("base.html")
Expand Down Expand Up @@ -42,7 +41,7 @@ def publish_html(
"""

required_deps = document._required_dependencies()
dependency_source = _get_source_from_options(dependency_source)
dependency_source = get_source_from_options(dependency_source)
resolved_deps = resolve_deps(required_deps, source=dependency_source)

html_rendered: str = _BASE_TEMPLATE.render(
Expand All @@ -60,8 +59,7 @@ def publish_html(

if return_html:
return html_prettified
else:
return None
return None


def publish_pdf(
Expand All @@ -80,35 +78,31 @@ def publish_pdf(
"""
if "weasyprint" not in _INSTALLED_MODULES:
raise ModuleNotFoundError("Install weasyprint for PDF support")
else:
import weasyprint as weasy # type: ignore
import weasyprint as weasy # type: ignore

temp_dir = Path(options.pdf_temp_dir)
temp_dir.mkdir(parents=True, exist_ok=True)
temp_dir = Path(options.pdf_temp_dir)
temp_dir.mkdir(parents=True, exist_ok=True)

html_rendered = publish_html(
document=document,
filepath=None,
return_html=True,
dependency_source="inline",
pdf_mode=True,
)
pdf_doc = weasy.HTML(
string=html_rendered, base_url=options.pdf_temp_dir
).render()
pdf_doc.metadata.title = document.title
pdf_doc.write_pdf(filepath)
html_rendered = publish_html(
document=document,
filepath=None,
return_html=True,
dependency_source="inline",
pdf_mode=True,
)
pdf_doc = weasy.HTML(string=html_rendered, base_url=options.pdf_temp_dir).render()
pdf_doc.metadata.title = document.title
pdf_doc.write_pdf(filepath)

for f in temp_dir.iterdir():
f.unlink()
temp_dir.rmdir()
for f in temp_dir.iterdir():
f.unlink()
temp_dir.rmdir()

html_prettified = _prettify_html(html_rendered)
html_prettified = _prettify_html(html_rendered)

if return_html:
return html_prettified
else:
return None
if return_html:
return html_prettified
return None


def nb_display(
Expand Down Expand Up @@ -138,7 +132,7 @@ def nb_display(
elif hasattr(item, "_dependencies"):
required_deps = item._dependencies

dependency_source = _get_source_from_options(dependency_source)
dependency_source = get_source_from_options(dependency_source)

resolved_deps = resolve_deps(required_deps, source=dependency_source)
head_deps = "\n".join(resolved_deps.head)
Expand All @@ -165,8 +159,7 @@ def nb_display(

if return_html:
return render_html
else:
return None
return None


def _prettify_html(html: Optional[str]) -> str:
Expand Down
Loading

0 comments on commit f654e7c

Please sign in to comment.