Skip to content

Commit

Permalink
Add precommits with black and import sort
Browse files Browse the repository at this point in the history
  • Loading branch information
goanpeca committed May 7, 2020
1 parent 9307708 commit 8f158d3
Show file tree
Hide file tree
Showing 9 changed files with 239 additions and 187 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,6 @@ jobs:
- name: Check manifest
run: |
check-manifest -v
# - name: Run pre commit checks
# run: |
# pre-commit run -a
- name: Run pre commit checks
run: |
pre-commit run -a
11 changes: 11 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# See: https://pre-commit.com/

repos:
- repo: https://github.com/ambv/black
rev: 19.3b0
hooks:
- id: black
- repo: https://github.com/asottile/reorder_python_imports
rev: v1.7.0
hooks:
- id: reorder-python-imports
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@
- Ensure universal builds
- Bugfix in build program
- Better README

## Version 0.2 (February 2, 2016)

- Python 3 compatibility (thanks to Dan Bauman).
- colored error output during build, fix for Markdown-formatted item subtitles.

## Version 0.1 (September 1, 2016)

- Initial release.
35 changes: 35 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Contributing

## Development environment

Create a development environment with `Python>=3.6`.

You can then install the development and test dependencies with:

```bash
python -m pip install lektor
python -m pip install --editable .[test]
```

## Tests

To run the test suite, we use `pytest`:

```bash
pytest . --tb=long -svv
```

## Pre-commit

We use precommit hooks to ensure code style and format.

Install `precommit` from pip

```bash
pip install pre-commit
pre-commit install
```

Now after each commit, the style hooks will run and auto format the code.

You can also manually run the pre-commit hooks without a commit with `pre-commit run -a`.
7 changes: 0 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,3 @@ Link to the feed in a template like this:
```
{{ '/blog@atom/main'|url }}
```

# Changes

2016-06-02: Version 0.2. Python 3 compatibility (thanks to Dan Bauman),
colored error output during build, fix for Markdown-formatted item subtitles.

2016-01-09: Version 0.1, initial release.
105 changes: 55 additions & 50 deletions lektor_atom.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
# -*- coding: utf-8 -*-
import sys
import hashlib
import sys
import uuid
from datetime import datetime, date
from datetime import date
from datetime import datetime

import click
import pkg_resources
from lektor.build_programs import BuildProgram
from lektor.context import get_ctx
from lektor.context import url_to
from lektor.db import F
from lektor.environment import Expression
from lektor.pluginsystem import Plugin
from lektor.context import get_ctx, url_to
from lektor.sourceobj import VirtualSourceObject
from lektor.utils import build_url

from werkzeug.contrib.atom import AtomFeed
from markupsafe import escape
from werkzeug.contrib.atom import AtomFeed

PY2 = sys.version_info[0] == 2

Expand All @@ -33,11 +34,11 @@ def __init__(self, parent, feed_id, plugin):

@property
def path(self):
return self.parent.path + '@atom/' + self.feed_id
return self.parent.path + "@atom/" + self.feed_id

@property
def url_path(self):
p = self.plugin.get_atom_config(self.feed_id, 'url_path')
p = self.plugin.get_atom_config(self.feed_id, "url_path")
if p:
return p

Expand All @@ -51,7 +52,7 @@ def __getattr__(self, item):

@property
def feed_name(self):
return self.plugin.get_atom_config(self.feed_id, 'name') or self.feed_id
return self.plugin.get_atom_config(self.feed_id, "name") or self.feed_id


def get(item, field, default=None):
Expand All @@ -61,7 +62,7 @@ def get(item, field, default=None):


def get_id(s):
b = hashlib.md5(s.encode('utf-8')).digest()
b = hashlib.md5(s.encode("utf-8")).digest()
return uuid.UUID(bytes=b, version=3).urn


Expand All @@ -73,7 +74,7 @@ def get_item_title(item, field):

def get_item_body(item, field):
if field not in item:
raise RuntimeError('Body field %r not found in %r' % (field, item))
raise RuntimeError("Body field %r not found in %r" % (field, item))
with get_ctx().changed_base_url(item.url_path):
return text_type(escape(item[field]))

Expand All @@ -91,24 +92,26 @@ def get_item_updated(item, field):
class AtomFeedBuilderProgram(BuildProgram):
def produce_artifacts(self):
self.declare_artifact(
self.source.url_path,
sources=list(self.source.iter_source_filenames()))
self.source.url_path, sources=list(self.source.iter_source_filenames())
)

def build_artifact(self, artifact):
ctx = get_ctx()
feed_source = self.source
blog = feed_source.parent

summary = get(blog, feed_source.blog_summary_field) or ''
if hasattr(summary, '__html__'):
subtitle_type = 'html'
summary = get(blog, feed_source.blog_summary_field) or ""
if hasattr(summary, "__html__"):
subtitle_type = "html"
summary = text_type(summary.__html__())
else:
subtitle_type = 'text'
blog_author = text_type(get(blog, feed_source.blog_author_field) or '')
generator = ('Lektor Atom Plugin',
'https://github.com/ajdavis/lektor-atom',
pkg_resources.get_distribution('lektor-atom').version)
subtitle_type = "text"
blog_author = text_type(get(blog, feed_source.blog_author_field) or "")
generator = (
"Lektor Atom Plugin",
"https://github.com/ajdavis/lektor-atom",
pkg_resources.get_distribution("lektor-atom").version,
)

feed = AtomFeed(
title=feed_source.feed_name,
Expand All @@ -118,7 +121,8 @@ def build_artifact(self, artifact):
feed_url=url_to(feed_source, external=True),
url=url_to(blog, external=True),
id=get_id(ctx.env.project.id),
generator=generator)
generator=generator,
)

if feed_source.items:
# "feed_source.items" is a string like "site.query('/blog')".
Expand All @@ -130,7 +134,7 @@ def build_artifact(self, artifact):
if feed_source.item_model:
items = items.filter(F._model == feed_source.item_model)

order_by = '-' + feed_source.item_date_field
order_by = "-" + feed_source.item_date_field
items = items.order_by(order_by).limit(int(feed_source.limit))

for item in items:
Expand All @@ -143,48 +147,49 @@ def build_artifact(self, artifact):
get_item_body(item, feed_source.item_body_field),
xml_base=url_to(item, external=True),
url=url_to(item, external=True),
content_type='html',
id=get_id(u'%s/%s' % (
ctx.env.project.id,
item['_path'].encode('utf-8'))),
content_type="html",
id=get_id(
u"%s/%s" % (ctx.env.project.id, item["_path"].encode("utf-8"))
),
author=item_author,
updated=get_item_updated(item, feed_source.item_date_field))
updated=get_item_updated(item, feed_source.item_date_field),
)
except Exception as exc:
msg = '%s: %s' % (item['_id'], exc)
click.echo(click.style('E', fg='red') + ' ' + msg)
msg = "%s: %s" % (item["_id"], exc)
click.echo(click.style("E", fg="red") + " " + msg)

with artifact.open('wb') as f:
f.write(feed.to_string().encode('utf-8'))
with artifact.open("wb") as f:
f.write(feed.to_string().encode("utf-8"))


class AtomPlugin(Plugin):
name = u'Lektor Atom plugin'
description = u'Lektor plugin that generates Atom feeds.'
name = u"Lektor Atom plugin"
description = u"Lektor plugin that generates Atom feeds."

defaults = {
'source_path': '/',
'name': None,
'url_path': None,
'filename': 'feed.xml',
'blog_author_field': 'author',
'blog_summary_field': 'summary',
'items': None,
'limit': 50,
'item_title_field': 'title',
'item_body_field': 'body',
'item_author_field': 'author',
'item_date_field': 'pub_date',
'item_model': None,
"source_path": "/",
"name": None,
"url_path": None,
"filename": "feed.xml",
"blog_author_field": "author",
"blog_summary_field": "summary",
"items": None,
"limit": 50,
"item_title_field": "title",
"item_body_field": "body",
"item_author_field": "author",
"item_date_field": "pub_date",
"item_model": None,
}

def get_atom_config(self, feed_id, key):
default_value = self.defaults[key]
return self.get_config().get('%s.%s' % (feed_id, key), default_value)
return self.get_config().get("%s.%s" % (feed_id, key), default_value)

def on_setup_env(self, **extra):
self.env.add_build_program(AtomFeedSource, AtomFeedBuilderProgram)

@self.env.virtualpathresolver('atom')
@self.env.virtualpathresolver("atom")
def feed_path_resolver(node, pieces):
if len(pieces) != 1:
return
Expand All @@ -195,12 +200,12 @@ def feed_path_resolver(node, pieces):
if _id not in config.sections():
return

source_path = self.get_atom_config(_id, 'source_path')
source_path = self.get_atom_config(_id, "source_path")
if node.path == source_path:
return AtomFeedSource(node, _id, plugin=self)

@self.env.generator
def generate_feeds(source):
for _id in self.get_config().sections():
if source.path == self.get_atom_config(_id, 'source_path'):
if source.path == self.get_atom_config(_id, "source_path"):
yield AtomFeedSource(source, _id, self)
58 changes: 25 additions & 33 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,43 @@

from setuptools import setup

with io.open('README.md', 'rt', encoding="utf8") as f:
with io.open("README.md", "rt", encoding="utf8") as f:
readme = f.read()

_description_re = re.compile(r'description\s+=\s+(?P<description>.*)')
_description_re = re.compile(r"description\s+=\s+(?P<description>.*)")

with open('lektor_atom.py', 'rb') as f:
description = str(ast.literal_eval(_description_re.search(
f.read().decode('utf-8')).group(1)))
with open("lektor_atom.py", "rb") as f:
description = str(
ast.literal_eval(_description_re.search(f.read().decode("utf-8")).group(1))
)

tests_require = [
'lxml',
'pytest'
],
tests_require = (["lxml", "pytest"],)


setup(
author=u'A. Jesse Jiryu Davis',
author_email='[email protected]',
author=u"A. Jesse Jiryu Davis",
author_email="[email protected]",
description=description,
install_requires=[
'MarkupSafe',
'Werkzeug<1.0', # Werkzeug 1.0 removed the feed generator
"MarkupSafe",
"Werkzeug<1.0", # Werkzeug 1.0 removed the feed generator
],
keywords='Lektor plugin static-site blog atom rss',
license='MIT',
keywords="Lektor plugin static-site blog atom rss",
license="MIT",
long_description=readme,
long_description_content_type='text/markdown',
name='lektor-atom',
py_modules=['lektor_atom'],
url='https://github.com/nixjdm/lektor-atom',
version='0.3.1',
long_description_content_type="text/markdown",
name="lektor-atom",
py_modules=["lektor_atom"],
url="https://github.com/nixjdm/lektor-atom",
version="0.3.1",
classifiers=[
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Lektor',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
"Environment :: Plugins",
"Environment :: Web Environment",
"Framework :: Lektor",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
],
entry_points={
'lektor.plugins': [
'atom = lektor_atom:AtomPlugin',
]
},
extras_require={
'test': tests_require,
},
entry_points={"lektor.plugins": ["atom = lektor_atom:AtomPlugin"]},
extras_require={"test": tests_require},
tests_require=tests_require,
)
Loading

0 comments on commit 8f158d3

Please sign in to comment.