craft-letter/scripts/create_newsletter.py
2026-01-22 11:45:03 +01:00

72 lines
2.2 KiB
Python

import argparse
import locale
from pathlib import Path
from datetime import datetime, timedelta
MONDAY = 0 # 0 = Monday, 1=Tuesday, 2=Wednesday...
def get_next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0: # Target day already happened this week
days_ahead += 7
return d + timedelta(days_ahead)
def set_publication_date_for_humans(text: str, publication_date: datetime) -> str:
locale.setlocale(locale.LC_TIME, "fr_FR")
date = publication_date.strftime("%d %B %Y")
return text.replace("{DATE}", date)
def set_publication_date_for_pelican(text: str, publication_date: datetime) -> str:
date_digits = publication_date.isoformat()[0:10]
return text.replace("{DATE_DIGITS}", date_digits)
def set_publication_date_for_seo(text: str, publication_date: datetime) -> str:
locale.setlocale(locale.LC_TIME, "en_US")
date_utc = publication_date.strftime("%a %b %d %Y")
return text.replace("{DATE_UTC}", date_utc)
# Parse the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", required=True, type=int, help="Newsletter number")
args = parser.parse_args()
# Load the newsletter template
template = Path("./template/newsletter.md")
content = template.read_text()
new_content = content.replace("{LETTER_NUMBER}", str(args.number))
today = datetime.today()
next_monday = get_next_weekday(today, MONDAY)
new_content = set_publication_date_for_humans(new_content, next_monday)
new_content = set_publication_date_for_pelican(new_content, next_monday)
new_content = set_publication_date_for_seo(new_content, next_monday)
# Create the new file
destination = Path(f"./content/newsletter/craft-letter-{args.number}.md")
destination.write_text(new_content)
# Load the homepage template
template = Path("./template/index.md")
content = template.read_text()
new_content = set_publication_date_for_pelican(content, next_monday)
new_content = set_publication_date_for_seo(new_content, next_monday)
for i in reversed(range(args.number)):
link = f"* [Lettre n°{i + 1}]({{filename}}/newsletter/craft-letter-{i + 1}.md)\n"
new_content += link
# Update the index page
destination = Path("./content/pages/index.md")
destination.write_text(new_content)