Skip to content

Commit

Permalink
Use pathlib
Browse files Browse the repository at this point in the history
  • Loading branch information
Siecje committed Jan 19, 2024
1 parent c330b06 commit 9dc5066
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 120 deletions.
40 changes: 20 additions & 20 deletions htmd/cli.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import importlib
import os
from pathlib import Path
import sys

import click
Expand Down Expand Up @@ -28,23 +28,23 @@ def cli():
help='Include all templates.',
)
def start(all_templates):
create_directory('templates/')
dir_templates = create_directory('templates/')
if all_templates:
copy_missing_templates()
else:
copy_site_file('templates', '_layout.html')
copy_site_file(dir_templates, '_layout.html')

create_directory('static/')
copy_site_file('static', '_reset.css')
copy_site_file('static', 'style.css')
dir_static = create_directory('static/')
copy_site_file(dir_static, '_reset.css')
copy_site_file(dir_static, 'style.css')

create_directory('pages/')
copy_site_file('pages', 'about.html')
dir_pages = create_directory('pages/')
copy_site_file(dir_pages, 'about.html')

create_directory('posts/')
copy_site_file('posts', 'example.md')
dir_posts = create_directory('posts/')
copy_site_file(dir_posts, 'example.md')

copy_site_file('', 'config.toml')
copy_site_file(Path(), 'config.toml')
click.echo('Add the site name and edit settings in config.toml')


Expand Down Expand Up @@ -92,15 +92,15 @@ def verify():


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

found = False
with open(file_path, 'w') as file:
with file_path.open('w') as file:
for line in lines:
if not found and field in line:
# Update datetime value
Expand Down Expand Up @@ -159,10 +159,10 @@ def build(ctx, css_minify, js_minify):
app = site.app

if css_minify:
combine_and_minify_css(app.static_folder)
combine_and_minify_css(Path(app.static_folder))

if js_minify:
combine_and_minify_js(app.static_folder)
combine_and_minify_js(Path(app.static_folder))

if css_minify or js_minify:
# reload to set app.config['INCLUDE_CSS'] and app.config['INCLUDE_JS']
Expand Down Expand Up @@ -213,10 +213,10 @@ def preview(_ctx, host, port, css_minify, js_minify):
app = site.app

if css_minify:
combine_and_minify_css(app.static_folder)
combine_and_minify_css(Path(app.static_folder))

if js_minify:
combine_and_minify_js(app.static_folder)
combine_and_minify_js(Path(app.static_folder))

app.run(debug=True, host=host, port=port)

Expand Down
31 changes: 16 additions & 15 deletions htmd/site.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from pathlib import Path
import sys
import tomllib

Expand All @@ -11,41 +12,41 @@
from jinja2 import ChoiceLoader, FileSystemLoader, TemplateNotFound


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


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

while True:
file_path = os.path.join(current_directory, 'config.toml')
file_path = current_directory / 'config.toml'

if os.path.isfile(file_path):
if file_path.is_file():
return current_directory

# Move to the parent directory
parent_directory = os.path.dirname(current_directory)
parent_directory = current_directory.parent

# If the current and parent directories are the same, break the loop
if current_directory == parent_directory:
break

current_directory = parent_directory

return os.getcwd()
return Path.cwd()


project_dir = get_project_dir()

app = Flask(
__name__,
static_folder=os.path.join(project_dir, 'static'),
template_folder=os.path.join(this_dir, 'example_site', 'templates'),
static_folder=project_dir / 'static',
template_folder=this_dir / 'example_site' / 'templates',
)


try:
with open(os.path.join(project_dir, 'config.toml'), 'rb') as config_file:
with (project_dir / 'config.toml').open('rb') as config_file:
htmd_config = tomllib.load(config_file)
except FileNotFoundError:
msg = 'Can not find config.toml'
Expand Down Expand Up @@ -81,11 +82,11 @@ 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'),
app.config['FLATPAGES_ROOT'] = (
project_dir / app.config.get('POSTS_FOLDER')
)
app.config['FREEZER_DESTINATION'] = os.path.join(
project_dir, app.config.get('BUILD_FOLDER'),
app.config['FREEZER_DESTINATION'] = (
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 @@ -111,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/')),
FileSystemLoader(project_dir / 'templates/'),
app.jinja_loader,
])

Expand All @@ -133,7 +134,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=project_dir / app.config.get('PAGES_FOLDER'),
)


Expand Down
42 changes: 22 additions & 20 deletions htmd/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from importlib.resources import as_file, files
import os
from pathlib import Path
import shutil

import click
Expand All @@ -8,64 +8,66 @@


def create_directory(name):
directory = Path(name)
try:
os.mkdir(name)
directory.mkdir()
except FileExistsError:
msg = f'{name} already exists and was not created.'
click.echo(click.style(msg, fg='yellow'))
else:
click.echo(click.style(f'{name} was created.', fg='green'))
return directory


def combine_and_minify_css(static_folder):
# Combine and minify all .css files in the static folder
css_files = sorted([
f for f in os.listdir(static_folder)
if f.endswith('.css') and f != 'combined.min.css'
f for f in static_folder.iterdir()
if f.name.endswith('.css') and f.name != 'combined.min.css'
])
if not css_files:
# There are no .css files in the static folder
return

with open(os.path.join(static_folder, 'combined.min.css'), 'w') as master:
with (static_folder / 'combined.min.css').open('w') as master:
for f in css_files:
with open(os.path.join(static_folder, f), 'r') as css_file:
with (static_folder / f).open('r') as css_file:
# combine all .css files into one
master.write(css_file.read())

with open(os.path.join(static_folder, 'combined.min.css'), 'r') as master:
with (static_folder / 'combined.min.css').open('r') as master:
combined = master.read()
with open(os.path.join(static_folder, 'combined.min.css'), 'w') as master:
with (static_folder / 'combined.min.css').open('w') as master:
master.write(compress(combined))


def combine_and_minify_js(static_folder):
# Combine and minify all .js files in the static folder
js_files = sorted([
f for f in os.listdir(static_folder)
if f.endswith('.js')
and f != 'combined.min.js'
f for f in static_folder.iterdir()
if f.name.endswith('.js')
and f.name != 'combined.min.js'
])
if not js_files:
# There are no .js files in the static folder
return

with open(os.path.join(static_folder, 'combined.min.js'), 'w') as master:
with (static_folder / 'combined.min.js').open('w') as master:
for f in js_files:
with open(os.path.join(static_folder, f), 'r') as js_file:
with (static_folder / f).open('r') as js_file:
# combine all .js files into one
master.write(js_file.read())

# minify should be done after combined to avoid duplicate identifiers
# minifying each file will use 'a' for the first identifier
with open(os.path.join(static_folder, 'combined.min.js'), 'r') as master:
with (static_folder / 'combined.min.js').open('r') as master:
combined = master.read()
with open(os.path.join(static_folder, 'combined.min.js'), 'w') as master:
with (static_folder / 'combined.min.js').open('w') as master:
master.write(jsmin(combined))


def copy_file(source, destination):
if os.path.exists(destination) is False:
if destination.exists() is False:
shutil.copyfile(source, destination)
click.echo(click.style(f'{destination} was created.', fg='green'))
else:
Expand All @@ -76,17 +78,17 @@ def copy_file(source, destination):
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))
file_name = template_file.name
copy_file(template_file, Path('templates') / file_name)


def copy_site_file(directory, filename):
if directory == '':
if directory.name == '':
anchor = 'htmd.example_site'
else:
anchor = f'htmd.example_site.{directory}'
source_path = files(anchor) / filename
destination_path = os.path.join(directory, filename)
destination_path = directory / filename

with as_file(source_path) as file:
copy_file(file, destination_path)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ ignore = [
"RET504",
"S101",
"UP015",
"ANN", "PTH",
"ANN",
]
select = ["ALL"]

Expand Down
Loading

0 comments on commit 9dc5066

Please sign in to comment.