added recursive page generation

This commit is contained in:
specCon18 2025-02-02 20:37:46 -05:00
parent 4a07aec860
commit d865326ee4
6 changed files with 146 additions and 2 deletions

32
content/index.md Normal file
View file

@ -0,0 +1,32 @@
# Tolkien Fan Club
**I like Tolkien**. Read my [first post here](/majesty) (sorry the link doesn't work yet)
> All that is gold does not glitter
## Reasons I like Tolkien
* You can spend years studying the legendarium and still not understand its depths
* It can be enjoyed by children and adults alike
* Disney *didn't ruin it*
* It created an entirely new genre of fantasy
## My favorite characters (in order)
1. Gandalf
2. Bilbo
3. Sam
4. Glorfindel
5. Galadriel
6. Elrond
7. Thorin
8. Sauron
9. Aragorn
Here's what `elflang` looks like (the perfect coding language):
```
func main(){
fmt.Println("Hello, World!")
}
```

18
content/nested/test.md Normal file
View file

@ -0,0 +1,18 @@
# My First Blog Post
Welcome to my **fantastic** blog! I hope you enjoy your stay.
## Things I Like
* Coding
* Writing
* Making static sites
> Every journey begins with a single static page
Here's a sample of my favorite code:
```python
def hello():
return "Welcome to my blog!"
```

View file

@ -1 +1,2 @@
python3 src/main.py
cd public && python3 -m http.server 8888

View file

@ -2,6 +2,14 @@ from textnode import TextNode,TextType
from conversions import markdown_to_html_node
import shutil
import os
import re
def extract_title(markdown):
split = markdown.split("\n")
for item in split:
if item.startswith("# "):
return(item.strip("# "))
raise Exception("no title found")
def empty_public():
dir_path = os.path.abspath("./public/")
@ -21,9 +29,50 @@ def copy_directory_recursive(src, dest):
# Recursively copy source directory to destination
shutil.copytree(src, dest)
def get_files_from_path_recursively(path):
files = []
for entry in os.scandir(path):
if entry.is_file():
files.append(entry.path) # Use full path
elif entry.is_dir():
# Recursively get files from subdirectory
files.extend(get_files_from_path_recursively(entry.path))
return files
def generate_page(from_path, template_path, dest_path):
for file_path in get_files_from_path_recursively(from_path):
match = re.search(r"content/(.*)", file_path)
if match:
relative_path = match.group(1)
print(f"Generating page from {file_path} to {dest_path}{re.sub(r'\.md$', '.html', relative_path)} using {template_path}")
# Read the markdown file
with open(file_path, 'r') as file:
md = file.read()
# Read the template
with open(template_path, 'r') as file:
template = file.read()
title = extract_title(md)
html = markdown_to_html_node(md).to_html()
final_html = template.replace("{{ Title }}", title)
final_html = final_html.replace("{{ Content }}", html)
# Create output directory if it doesn't exist
output_dir = os.path.dirname(f"{dest_path}/{relative_path}")
os.makedirs(output_dir, exist_ok=True)
# Write the final HTML
with open(f"{dest_path}/{re.sub(r'\.md$', '.html', relative_path)}", "w") as f:
f.write(final_html)
def main():
empty_public()
copy_directory_recursive("./static/","./public/")
empty_public()
copy_directory_recursive("./static/","./public/")
generate_page("./content/","./template.html","./public/")
if __name__=="__main__":
main()

27
src/test_main.py Normal file
View file

@ -0,0 +1,27 @@
def test_extract_title():
# Basic case
assert extract_title("# Simple Title") == "Simple Title"
# Extra spaces case
assert extract_title("# Extra Spaces ") == " Extra Spaces "
# Multiple lines case
text = """# Main Title
## Subtitle
Some content
More content"""
assert extract_title(text) == "Main Title"
# Empty input
try:
extract_title("")
assert False, "Empty input should raise exception"
except Exception:
assert True
# Invalid headers
try:
extract_title("##Not a title\nJust some text")
assert False, "Invalid header should raise exception"
except Exception:
assert True

17
template.html Normal file
View file

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> {{ Title }} </title>
<link href="/index.css" rel="stylesheet">
</head>
<body>
<article>
{{ Content }}
</article>
</body>
</html>