Skip to content

Commit

Permalink
Merge branch 'webpage' into 'master'
Browse files Browse the repository at this point in the history
Only open and write to webpage once its contents have been filled

See merge request cwinpy/cwinpy!191
  • Loading branch information
mattpitkin committed Apr 26, 2024
2 parents 2b67abc + 4ea7a5e commit 3f7657a
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions cwinpy/pe/webpage.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from pathlib import Path
from typing import Union

Expand Down Expand Up @@ -175,6 +176,33 @@ class CWPage(page):
generating CWInPy-specific summary pages.
"""

def __init__(self, html_file, web_dir, base_url, label):
if hasattr(html_file, "close") and hasattr(html_file, "name"):
# passing an file pointer, so close and get name
self.html_file = html_file.name
html_file.close()
elif isinstance(html_file, (str, os.PathLike)):
self.html_file = html_file
else:
raise TypeError("html_file must be a file path or file pointer.")

self.web_dir = web_dir
self.base_url = base_url
self.label = label
self.content = []

def add_content(self, content, indent=0):
"""
Add content into list for writing at close time rather than writing
to an open file.
"""

if isinstance(content, list):
for c in content:
self.content.append(" " * indent + self._check_content(c))
else:
self.content.append(" " * indent + self._check_content(content))

def _setup_navbar(self, background_colour: str = None):
if background_colour == "navbar-dark" or background_colour is None:
self.add_content(
Expand Down Expand Up @@ -561,7 +589,11 @@ def close(self):
)

self.add_content("</body>\n</html>\n") # close off page
self.html_file.close()

# write content to file
with open(self.html_file, "a") as fp:
for line in self.content:
fp.write(line)


def make_html(
Expand Down Expand Up @@ -627,6 +659,6 @@ def open_html(web_dir, base_url, html_page, label):
pass

htmlfile = Path(web_dir) / f"{html_page}.html"
f = open(htmlfile, "a")
htmlfile.touch() # create file (if non-existant)

return CWPage(f, web_dir, base_url, label)
return CWPage(htmlfile, web_dir, base_url, label)

0 comments on commit 3f7657a

Please sign in to comment.