Skip to content

Commit

Permalink
First pass code cleanup with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Siecje committed Jan 18, 2024
1 parent 77787bd commit fa6a3a8
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 62 deletions.
43 changes: 21 additions & 22 deletions htmd/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def cli():
'--all-templates',
is_flag=True,
default=False,
help='Include all templates.'
help='Include all templates.',
)
def start(all_templates):
create_directory('templates/')
Expand Down Expand Up @@ -87,27 +87,27 @@ def verify():
# SITE_NAME is not required
message = '[site] name is not set in config.toml.'
click.echo(click.style(message, fg='yellow'))

if not correct:
sys.exit(1)


def set_post_time(app, post, property, date_time):
def set_post_time(app, post, field, date_time):
file_path = os.path.join(
app.config['FLATPAGES_ROOT'],
post.path + app.config['FLATPAGES_EXTENSION']
post.path + app.config['FLATPAGES_EXTENSION'],
)
with open(file_path, 'r') as file:
lines = file.readlines()

found = False
with open(file_path, 'w') as file:
for line in lines:
if not found and property in line:
line = f'{property}: {date_time.isoformat()}\n'
if not found and field in line:
line = f'{field}: {date_time.isoformat()}\n'
found = True
elif not found and '...' in line:
file.write(f'{property}: {date_time.isoformat()}\n')
file.write(f'{field}: {date_time.isoformat()}\n')
found = True
file.write(line)

Expand All @@ -119,37 +119,36 @@ def set_posts_datetime(app, posts):
if 'updated' not in post.meta:
published = post.meta.get('published')
if isinstance(published, datetime.datetime):
property = 'updated'
field = 'updated'
else:
property = 'published'
field = 'published'
else:
property = 'updated'
field = 'updated'

post_datetime = post.meta.get(property)
post_datetime = post.meta.get(field)
now = datetime.datetime.now()
current_time = now.time()
if isinstance(post_datetime, datetime.date):
post_datetime = datetime.datetime.combine(
post_datetime, current_time
post_datetime, current_time,
)
else:
post_datetime = now
post.meta[property] = post_datetime
set_post_time(app, post, property, post_datetime)

post.meta[field] = post_datetime
set_post_time(app, post, field, post_datetime)


@cli.command('build', short_help='Create static version of the site.')
@click.pass_context
@click.option(
'--css-minify/--no-css-minify',
default=True,
help='If CSS should be minified'
help='If CSS should be minified',
)
@click.option(
'--js-minify/--no-js-minify',
default=True,
help='If JavaScript should be minified'
help='If JavaScript should be minified',
)
def build(ctx, css_minify, js_minify):
ctx.invoke(verify)
Expand Down Expand Up @@ -188,22 +187,22 @@ def build(ctx, css_minify, js_minify):
@click.option(
'--host', '-h',
default='127.0.0.1',
help='Location to access the files.'
help='Location to access the files.',
)
@click.option(
'--port', '-p',
default=9090,
help='Port on which to serve the files.'
help='Port on which to serve the files.',
)
@click.option(
'--css-minify/--no-css-minify',
default=True,
help='If CSS should be minified'
help='If CSS should be minified',
)
@click.option(
'--js-minify/--no-js-minify',
default=True,
help='If JavaScript should be minified'
help='If JavaScript should be minified',
)
def preview(ctx, host, port, css_minify, js_minify):
from . import site
Expand Down
61 changes: 37 additions & 24 deletions htmd/site.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import datetime
import os
import sys
import tomllib

from bs4 import BeautifulSoup
from feedwerk.atom import AtomFeed
from flask import (
abort, Blueprint, Flask, render_template, url_for
)
from flask import abort, Blueprint, Flask, render_template, url_for
from flask_flatpages import FlatPages, pygments_style_defs
from flask_frozen import Freezer
from htmlmin import minify
Expand All @@ -16,6 +13,7 @@

this_dir = os.path.dirname(os.path.abspath(__file__))


def get_project_dir():
current_directory = os.getcwd()

Expand All @@ -36,6 +34,7 @@ def get_project_dir():

return os.getcwd()


project_dir = get_project_dir()

app = Flask(
Expand All @@ -54,7 +53,7 @@ def get_project_dir():

# Flask configs are flat, config.toml is not
# Define the configuration keys and their default values
# [section, key, default]
# 'Flask config': [section, key, default]
config_keys = {
'SITE_NAME': ['site', 'name', ''],
'SITE_URL': ['site', 'url', ''],
Expand Down Expand Up @@ -83,10 +82,10 @@ def get_project_dir():

# To avoid full paths in config.toml
app.config['FLATPAGES_ROOT'] = os.path.join(
project_dir, app.config.get('POSTS_FOLDER')
project_dir, app.config.get('POSTS_FOLDER'),
)
app.config['FREEZER_DESTINATION'] = os.path.join(
project_dir, app.config.get('BUILD_FOLDER')
project_dir, app.config.get('BUILD_FOLDER'),
)
app.config['FREEZER_REMOVE_EXTRA_FILES'] = False
app.config['FLATPAGES_EXTENSION'] = app.config.get('POSTS_EXTENSION')
Expand All @@ -113,7 +112,7 @@ def truncate_post_html(post_html):
# Include current htmd site templates
app.jinja_loader = ChoiceLoader([
FileSystemLoader(os.path.join(project_dir, 'templates/')),
app.jinja_loader
app.jinja_loader,
])

MONTHS = {
Expand All @@ -134,7 +133,7 @@ def truncate_post_html(post_html):
pages = Blueprint(
'pages',
__name__,
template_folder=os.path.join(project_dir, app.config.get('PAGES_FOLDER'))
template_folder=os.path.join(project_dir, app.config.get('PAGES_FOLDER')),
)


Expand All @@ -144,7 +143,7 @@ def format_html(response):
if app.config.get('PRETTY_HTML', False):
response.data = BeautifulSoup(
response.data,
'html.parser'
'html.parser',
).prettify()
elif app.config.get('MINIFY_HTML', False):
response.data = minify(response.data.decode('utf-8'))
Expand Down Expand Up @@ -183,20 +182,22 @@ def feed():
feed_url=url_for('all_posts'),
subtitle=subtitle,
title=name,
url=url
url=url,
)
for post in posts:
url = url_for(
'post',
year=post.meta.get('published').strftime('%Y'),
month=post.meta.get('published').strftime('%m'),
day=post.meta.get('published').strftime('%d'),
path=post.path
path=post.path,
)

post_datetime = post.meta.get('updated') or post.meta.get('published')
atom.add(
post.meta.get('title'), post.html, content_type='html',
post.meta.get('title'),
post.html,
content_type='html',
author=post.meta.get('author', app.config.get('DEFAULT_AUTHOR')),
url=url,
updated=post_datetime,
Expand Down Expand Up @@ -252,21 +253,27 @@ def all_tags():
@app.route('/tags/<string:tag>/')
def tag(tag):
tagged = [p for p in posts if tag in p.meta.get('tags', [])]
sorted_posts = sorted(tagged, reverse=True,
key=lambda p: p.meta.get('published'))
sorted_posts = sorted(
tagged,
reverse=True,
key=lambda p: p.meta.get('published'),
)
return render_template('tag.html', posts=sorted_posts, tag=tag)


@app.route('/author/<author>/')
def author(author):
author_posts = [p for p in posts if author == p.meta.get('author', '')]
sorted_posts = sorted(author_posts, reverse=True,
key=lambda p: p.meta.get('published'))
sorted_posts = sorted(
author_posts,
reverse=True,
key=lambda p: p.meta.get('published'),
)
return render_template(
'author.html',
active='author',
author=author,
posts=sorted_posts
posts=sorted_posts,
)


Expand All @@ -285,8 +292,11 @@ def year_view(year):
]
if not year_posts:
abort(404)
sorted_posts = sorted(year_posts, reverse=False,
key=lambda p: p.meta.get('published'))
sorted_posts = sorted(
year_posts,
reverse=False,
key=lambda p: p.meta.get('published'),
)
return render_template('year.html', year=year, posts=sorted_posts)


Expand All @@ -298,14 +308,17 @@ def month_view(year, month):
]
if not month_posts:
abort(404)
sorted_posts = sorted(month_posts, reverse=False,
key=lambda p: p.meta.get('published'))
sorted_posts = sorted(
month_posts,
reverse=False,
key=lambda p: p.meta.get('published'),
)
month_string = MONTHS[month]
return render_template(
'month.html',
year=year,
month_string=month_string,
posts=sorted_posts
posts=sorted_posts,
)


Expand Down Expand Up @@ -338,7 +351,7 @@ def page_not_found(e):
def year_view():
for post in posts:
yield {
'year': post.meta.get('published').year
'year': post.meta.get('published').year,
}


Expand Down
6 changes: 2 additions & 4 deletions htmd/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ def combine_and_minify_js(static_folder):
with open(os.path.join(static_folder, 'combined.min.js'), 'w') as master:
master.write(jsmin(combined))


def copy_file(source, destination):
if os.path.exists(destination) is False:
shutil.copyfile(source, destination)
Expand All @@ -80,10 +81,7 @@ def copy_missing_templates():
template_dir = files('htmd.example_site') / 'templates'
for template_file in sorted(template_dir.iterdir()):
file_name = os.path.basename(template_file)
copy_file(
template_file,
os.path.join('templates/', file_name)
)
copy_file(template_file, os.path.join('templates/', file_name))


def copy_site_file(directory, filename):
Expand Down
17 changes: 17 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ Homepage = "https://github.com/siecje/htmd"
Issues = "https://github.com/siecje/htmd/issues"
Repository = "https://github.com/siecje/htmd.git"

[tool.ruff.lint]
select = ["ALL"]
ignore = [
"D100", "D103", "D104", "D203", "D211", "D212", "D213",
"INP001",
"RET504",
"S101",
"UP015",
]

[tool.ruff.lint.flake8-quotes]
inline-quotes = "single"
multiline-quotes = "single"

[tool.ruff.format]
quote-style = "single"

[tool.setuptools]
include-package-data = true

Expand Down
Loading

0 comments on commit fa6a3a8

Please sign in to comment.