Skip to content

Commit

Permalink
Improve url support and error handling
Browse files Browse the repository at this point in the history
- Fixed an issue where a file at the root was getting "index.html"
  spuriously appended.
- Refactored json/yaml file handling and improved messaging around
  errors.
  • Loading branch information
tsaylor committed Jun 10, 2020
1 parent 2b3b32f commit 007351c
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 23 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
venv
build
dist
*egg-info
8 changes: 4 additions & 4 deletions easybake/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import argparse
from .easybake import SiteBuilder, serve, clean

parser = argparse.ArgumentParser(prog="easybake", description="Generate a static website")
parser = argparse.ArgumentParser(
prog="easybake", description="Generate a static website"
)
parser.add_argument(
"command", type=str, help="The action to take (e.g. build, serve)",
)
Expand All @@ -18,9 +20,7 @@
args = parser.parse_args()

if args.command.lower() == "build":
sb = SiteBuilder(
args.site, template_dir=args.templates, content_dir=args.content
)
sb = SiteBuilder(args.site, template_dir=args.templates, content_dir=args.content)
sb.build()
elif args.command.lower() == "serve":
serve()
Expand Down
48 changes: 30 additions & 18 deletions easybake/easybake.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __init__(
template_dir="templates",
content_dir="content",
asset_dir="assets",
base_dir=os.getcwd()
base_dir=os.getcwd(),
):
self.BASE_DIR = base_dir
self.sitefile_path = sitefile_path
Expand All @@ -27,11 +27,16 @@ def __init__(
self.env = Environment(loader=FileSystemLoader(self.BASE_DIR))

def load_datafile(self, datafile):
with open(os.path.join(self.content_dir, datafile)) as f:
if datafile.endswith("json"):
return self.load_json_or_yaml(os.path.join(self.content_dir, datafile))

def load_json_or_yaml(self, path):
with open(path) as f:
if path.endswith("json"):
data = json.load(f)
elif datafile.endswith("yaml"):
data = yaml.safe_load(f)
elif path.endswith("yaml"):
# I can't catch exceptions well in yaml so this at least lets yaml report it better
txt = f.read()
data = yaml.safe_load(txt)
else:
data = {}
data = self.process_data(data)
Expand All @@ -50,20 +55,21 @@ def process_data(self, data):

def load_sitefile(self, sitefile):
try:
with open(self.sitefile_path) as f:
if self.sitefile_path.endswith("json"):
data = json.load(f)
elif self.sitefile_path.endswith("yaml"):
data = yaml.load(f)
else:
data = None
data = self.load_json_or_yaml(self.sitefile_path)
except (TypeError, FileNotFoundError):
print("Can't load sitefile '{}'".format(self.sitefile_path))
print(
"Can't load sitefile '{}'".format(self.sitefile_path), file=sys.stdout
)
sys.exit(1)
except json.decoder.JSONDecodeError:
print("Provided sitefile '{}' is not valid JSON".format(self.sitefile_path))
print(
"Provided sitefile '{}' is not valid JSON".format(self.sitefile_path),
file=sys.stdout,
)
sys.exit(1)
if data == {}:
print("Site file is empty!", file=sys.stdout)
sys.exit(1)
data = self.process_data(data)
return data

def load_template(self, template):
Expand All @@ -78,16 +84,22 @@ def render(self, obj):
data.update(obj["data"])
content = template.render(**data)
for a in obj.get("assets", []):
shutil.copy(os.path.join(self.asset_dir, a), os.path.join("build", "assets", a))
shutil.copy(
os.path.join(self.asset_dir, a), os.path.join("build", "assets", a)
)
return content

def write_page(self, content):
url = content["url"]
if url.endswith("/"):
url += "index.html"
if url.startswith("/"):
url = url[1:]
dirpath = os.path.join("build", url)
urlparts = url.split("/")
dirpath = os.path.join("build", *urlparts[:-1])
filename = urlparts[-1]
os.makedirs(dirpath, exist_ok=True)
with open(dirpath + "index.html", "w") as f:
with open(os.path.join(dirpath, filename), "w") as f:
f.write(content["rendered"])

def build(self):
Expand Down
2 changes: 2 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
flake8
black
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="easybake",
version="0.0.1",
version="0.0.2",
author="Tim Saylor",
author_email="[email protected]",
description="A static site builder",
Expand Down

0 comments on commit 007351c

Please sign in to comment.