mirror of
https://forge.chapril.org/tykayn/orgmode-to-gemini-blog
synced 2025-06-20 09:04:42 +02:00
refacto
This commit is contained in:
parent
9267636687
commit
086287fad3
48 changed files with 536 additions and 1681 deletions
200
build_indexes.py
200
build_indexes.py
|
@ -1,59 +1,58 @@
|
|||
import os
|
||||
import argparse
|
||||
import re
|
||||
import datetime
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
|
||||
import re
|
||||
from website_config import configs_sites
|
||||
from enrich_html import enrich_one_file
|
||||
from website_config import configs_sites, global_config
|
||||
|
||||
# from enrich_html import static_page_path
|
||||
# génère l'index gemini et html des articles rangés par langue
|
||||
|
||||
parser = argparse.ArgumentParser(description="Générer un site Web à partir de fichiers HTML.")
|
||||
parser.add_argument("source", help="Le chemin vers le dossier contenant les fichiers HTML.")
|
||||
parser.add_argument("title", default="Mon site Web", help="Le titre du site Web.")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Variables personnalisables
|
||||
DOSSIER_SOURCE = 'sources/'+args.source # Nom du dossier contenant les fichiers Markdown
|
||||
FICHIER_INDEX = 'index_'+args.source # Nom du fichier d'index à générer
|
||||
# TITRE_INDEX = f" # {args.title} - Articles"
|
||||
DOSSIER_SOURCE = 'sources/' + args.source # Nom du dossier contenant les fichiers Markdown
|
||||
FICHIER_INDEX = 'index_' + args.source # Nom du fichier d'index à générer
|
||||
TITRE_INDEX = f""
|
||||
source_files_extension="org"
|
||||
source_files_extension = "org"
|
||||
|
||||
config_title = configs_sites[args.source]['BLOG_TITLE']
|
||||
|
||||
# Expression régulière pour extraire la date et le slug du nom de fichier org
|
||||
regex = r"^(\d{14})(-[a-zA-Z0-9_-]+)\.gmi$"
|
||||
regex_orgroam = r"^(\d{14})_([a-zA-Z0-9_-]+)\.gmi$"
|
||||
regex = r"^(\d{14})(-[a-zA-Z0-9_-]+)\.gmi$"
|
||||
regex_orgroam = r"^(\d{14})_([a-zA-Z0-9_-]+)\.gmi$"
|
||||
|
||||
use_article_file_for_name=False
|
||||
use_article_file_for_name = (not global_config["slug_with_year"])
|
||||
website_name = args.source
|
||||
|
||||
|
||||
def trouver_nom_article(fichier_org, format="html"):
|
||||
print('fichier_org, ',fichier_org)
|
||||
# print('fichier_org, ', fichier_org)
|
||||
with open(fichier_org, 'r') as file:
|
||||
lignes = file.readlines()
|
||||
|
||||
|
||||
nom_article = ''
|
||||
|
||||
# print('trouver_nom_article format',format)
|
||||
# Expressions régulières pour trouver les titres de niveau 1 et 2
|
||||
if format == 'html':
|
||||
titre_niveau_1 = r'^\<h1 id.*?\>(.+)\<\/h1\>$'
|
||||
titre_niveau_1 = r'<h1\s+(?:id|data-created)="[^"]*">(.*?)</h1>'
|
||||
titre_niveau_2 = r'^\<h2.*?\>(.+)\<\/h2\>$'
|
||||
else:
|
||||
titre_niveau_1 = r'^\*+ (.+)$'
|
||||
titre_niveau_2 = r'^\*\*+ (.+)$'
|
||||
|
||||
|
||||
|
||||
# Itérer sur les lignes du fichier
|
||||
for ligne in lignes:
|
||||
# Rechercher un titre de niveau 1
|
||||
titre_niveau_1_match = re.match(titre_niveau_1, ligne)
|
||||
if titre_niveau_1_match:
|
||||
titre_niveau_1_texte = titre_niveau_1_match.group(1)
|
||||
if titre_niveau_1_texte.lower() != "article" and titre_niveau_1_texte.lower() != "liens" :
|
||||
if titre_niveau_1_texte.lower() != "article" and titre_niveau_1_texte.lower() != "liens":
|
||||
nom_article = titre_niveau_1_texte
|
||||
break
|
||||
else:
|
||||
|
@ -62,18 +61,18 @@ def trouver_nom_article(fichier_org, format="html"):
|
|||
if titre_niveau_2_match:
|
||||
nom_article = titre_niveau_2_match.group(1)
|
||||
break
|
||||
print(f"Nom de l'article : {nom_article}")
|
||||
|
||||
return nom_article.replace(args.source+'_', '').replace('_', ' ')
|
||||
# print(f"Nom de l'article : {nom_article}")
|
||||
|
||||
return nom_article.replace(args.source + '_', '').replace('_', ' ')
|
||||
|
||||
|
||||
def find_year_and_slug(fichier):
|
||||
fichier = fichier.replace('..','.')
|
||||
fichier = fichier.replace('..', '.')
|
||||
# print(f" ------------ build_indexes: find in {fichier} -------------")
|
||||
slug = fichier.replace('.gmi','')
|
||||
slug = fichier.replace('.gmi', '')
|
||||
annee = '2024'
|
||||
date_str= '2024-00-00'
|
||||
date= '2024-00-00'
|
||||
date_str = '2024-00-00'
|
||||
date = '2024-00-00'
|
||||
match = re.match(regex_orgroam, fichier)
|
||||
|
||||
if match:
|
||||
|
@ -89,12 +88,12 @@ def find_year_and_slug(fichier):
|
|||
date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
|
||||
else:
|
||||
date = datetime.datetime.strptime(date_str, "%Y%m%d%H%M%S")
|
||||
date_string_replaced = str(date).replace(' 00:00:00','')
|
||||
slug = fichier.replace('.gmi','')
|
||||
slug = slug.replace(date_string_replaced,'')
|
||||
date_string_replaced = str(date).replace(' 00:00:00', '')
|
||||
slug = fichier.replace('.gmi', '')
|
||||
slug = slug.replace(date_string_replaced, '')
|
||||
slug = enlever_premier_tiret_ou_underscore(slug)
|
||||
|
||||
annee = str(date.year).replace(' 00:00:00','')
|
||||
|
||||
annee = str(date.year).replace(' 00:00:00', '')
|
||||
# else:
|
||||
# print('ERREUR aucun slug trouvé')
|
||||
|
||||
|
@ -113,7 +112,6 @@ def enlever_premier_tiret_ou_underscore(chaîne):
|
|||
return chaîne
|
||||
|
||||
|
||||
|
||||
# création des dossiers intermédiaires s'il y en a
|
||||
# déplace le fichier dans le dossier spécifié
|
||||
def create_path_folders_and_move_file(path, file):
|
||||
|
@ -121,15 +119,17 @@ def create_path_folders_and_move_file(path, file):
|
|||
|
||||
shutil.move(file, path)
|
||||
|
||||
|
||||
def get_files_list_of_folder(folder_path):
|
||||
# Vérifie si le dossier existe
|
||||
# Vérifie si le dossier existe
|
||||
if not os.path.exists(folder_path):
|
||||
print(f" ------------ build_indexes: Erreur : Le dossier '{dossier_md}' n'existe pas.")
|
||||
print(f" ------------ build_indexes: Erreur : Le dossier '{folder_path}' n'existe pas.")
|
||||
return
|
||||
print('----------- get_files_list_of_folder: folder_path : ',folder_path)
|
||||
# print('----------- get_files_list_of_folder: folder_path : ', folder_path)
|
||||
# Liste les fichiers articles, trie par nom décroissant
|
||||
try:
|
||||
fichiers_md = sorted([f.replace('.'+source_files_extension, '.gmi') for f in os.listdir(folder_path) if f.endswith(source_files_extension)], reverse=True)
|
||||
fichiers_md = sorted([f.replace('.' + source_files_extension, '.gmi') for f in os.listdir(folder_path) if
|
||||
f.endswith(source_files_extension)], reverse=True)
|
||||
print('fichiers trouvés:', len(fichiers_md))
|
||||
return fichiers_md
|
||||
except OSError as e:
|
||||
|
@ -140,99 +140,87 @@ def get_files_list_of_folder(folder_path):
|
|||
# transformer le nom du fichier orgmode en une création de dossier de l'année, et un sous dossier du nom du slug dans le nom de fichier, contenant un seul fichier d'index afin de faire de l'url rewrite en dur.
|
||||
# le nom de fichier org commence par une date YYYY-MM-DD ou bien YYYYMMDDHHmmss, est suivie d'un slug, et finit par l'extension .org
|
||||
|
||||
# Titre pour le fichier d'index
|
||||
|
||||
|
||||
def empty_folder_content(path):
|
||||
print("empty ", path)
|
||||
# parcours tous les fichiers et sous-dossiers du dossier
|
||||
# for filename in os.listdir(path):
|
||||
# file_path = os.path.join(path, filename)
|
||||
|
||||
# # supprime le fichier ou le sous-dossier
|
||||
# if os.path.isfile(file_path):
|
||||
# os.remove(file_path)
|
||||
# else:
|
||||
# shutil.rmtree(file_path)
|
||||
|
||||
|
||||
def generer_index(dossier_source, fichier_index, titre_index):
|
||||
def generer_index(dossier_source, fichier_index):
|
||||
# Chemin absolu du dossier parent (pour sauver le fichier d'index)
|
||||
dossier_parent = os.path.dirname(os.path.abspath(__file__))
|
||||
empty_folder_content(dossier_parent+'/html-websites/'+args.source+'/')
|
||||
|
||||
|
||||
# Chemin complet du dossier contenant les Markdown
|
||||
chemin_dossier_source = os.path.join(dossier_parent, dossier_source)
|
||||
|
||||
files_static = get_files_list_of_folder(chemin_dossier_source+'/')
|
||||
files_fr = get_files_list_of_folder(chemin_dossier_source+'/lang_fr')
|
||||
files_en = get_files_list_of_folder(chemin_dossier_source+'/lang_en')
|
||||
|
||||
|
||||
files_static = get_files_list_of_folder(chemin_dossier_source + '/')
|
||||
files_fr = get_files_list_of_folder(chemin_dossier_source + '/lang_fr')
|
||||
files_en = get_files_list_of_folder(chemin_dossier_source + '/lang_en')
|
||||
|
||||
# Chemin complet pour le fichier d'index
|
||||
chemin_fichier_index_gemini = os.path.join(dossier_parent, fichier_index+'.gmi')
|
||||
chemin_fichier_index_html = os.path.join(dossier_parent, '/'+fichier_index+'.html')
|
||||
|
||||
chemin_fichier_index_gemini = os.path.join(dossier_parent, 'gemini-capsules', args.source, 'index.gmi')
|
||||
chemin_fichier_index_html = os.path.join(dossier_parent, 'html-websites', args.source, 'index.html')
|
||||
|
||||
print('\n index html: ', chemin_fichier_index_html)
|
||||
# Génère le contenu du fichier d'index
|
||||
contenu_index_gmi = f"{titre_index}\n{'- ' * len(titre_index)}\n\n"
|
||||
contenu_index_html = f"{titre_index}\n{'- ' * len(titre_index)}\n\n"
|
||||
contenu_index_gmi = f"{config_title}\n{'- ' * len(config_title)}\n\n"
|
||||
contenu_index_html = f"{config_title}\n{'- ' * len(config_title)}\n\n"
|
||||
|
||||
contenu_index_gmi += "\n# Navigation\n-------------------------\n"
|
||||
contenu_index_html += "<h1>Navigation</h1>"
|
||||
for fichier in files_static:
|
||||
print(" -------- fichier ",fichier)
|
||||
link_html = fichier.replace('.gmi','.html')
|
||||
link_org = fichier.replace('.gmi','.org')
|
||||
contenu_index_gmi += f"=> {fichier}\n"
|
||||
|
||||
# print(" -------- fichier ", fichier)
|
||||
link_html = fichier.replace('.gmi', '.html')
|
||||
link_org = fichier.replace('.gmi', '.org')
|
||||
file_path_org = os.path.join(dossier_parent, "sources", website_name, link_org)
|
||||
article_name = trouver_nom_article(file_path_org, 'org')
|
||||
|
||||
if article_name:
|
||||
contenu_index_gmi += f"=> {fichier} {article_name}\n"
|
||||
else:
|
||||
contenu_index_gmi += f"=> {fichier}\n"
|
||||
|
||||
if fichier != "index.gmi":
|
||||
print(' -------- rechercher le nom de l article dans le fichier ')
|
||||
# print(' -------- rechercher le nom de l article dans le fichier ')
|
||||
if use_article_file_for_name:
|
||||
article_name = link_html
|
||||
else:
|
||||
file_path_org = os.path.join(dossier_parent,"sources",website_name, link_org)
|
||||
print('-------------- trouver_nom_article ',file_path_org)
|
||||
article_name=trouver_nom_article(file_path_org, 'org')
|
||||
|
||||
article_name = trouver_nom_article(file_path_org, 'org')
|
||||
|
||||
if not article_name:
|
||||
article_name = link_html
|
||||
else:
|
||||
article_name = 'Index'
|
||||
article_name = article_name.replace('_',' ')
|
||||
article_name = article_name.replace('_', ' ')
|
||||
contenu_index_html += f"<br><a href=/{link_html}>{article_name}</a>"
|
||||
|
||||
# ne préciser la langue français que si on a des articles en Anglais
|
||||
if len(files_en):
|
||||
contenu_index_gmi += "\n# Articles en Français\n-------------------------\n"
|
||||
# contenu_index_html += "<h1>Articles en Français</h1>"
|
||||
lang_folder="lang_fr/"
|
||||
|
||||
lang_folder = "lang_fr/"
|
||||
|
||||
# ----------- indexer les articles en Français ------------------
|
||||
for fichier in files_fr:
|
||||
date_string, année, slug = find_year_and_slug(fichier)
|
||||
|
||||
|
||||
new_folder=f"{année}/{slug}"
|
||||
new_folder_path_this_article = os.path.join(dossier_parent, 'html-websites/'+args.source+'/'+new_folder+'/')
|
||||
|
||||
contenu_index_gmi += f"=> {fichier}\n"
|
||||
link_html = fichier.replace('..gmi','.html')
|
||||
link_html = fichier.replace('.gmi','.html')
|
||||
link_html = fichier.replace('.gmi', '.html')
|
||||
chemin_fichier_this_article_html = chemin_dossier_source + '/lang_fr/converted/' + link_html
|
||||
chemin_fichier_this_article_html = chemin_dossier_source + '/lang_fr/converted/' + link_html
|
||||
|
||||
chemin_fichier_this_article = chemin_dossier_source+'/lang_fr/converted/'+link_html
|
||||
|
||||
article_name=trouver_nom_article(chemin_fichier_this_article)
|
||||
link_org = fichier.replace('.gmi', '.org')
|
||||
file_path_org = os.path.join(dossier_parent, "sources", website_name, lang_folder, link_org)
|
||||
article_name = trouver_nom_article(file_path_org, 'org')
|
||||
|
||||
if not article_name:
|
||||
article_name=slug.replace('-', ' ')
|
||||
article_name = slug.replace('-', ' ')
|
||||
|
||||
# contenu_index_html += f"<br><a href=/{lang_folder}/{link_html}>{link_html}</a>"
|
||||
contenu_index_html += f"<br><a href=/{année}/{slug}>{année} {article_name}</a>"
|
||||
if global_config["slug_with_year"]:
|
||||
new_folder = f"{année}/{slug}"
|
||||
new_folder_path_this_article = os.path.join(dossier_parent,
|
||||
'html-websites/' + args.source + '/' + new_folder + '/')
|
||||
|
||||
os.makedirs(os.path.dirname(new_folder_path_this_article), exist_ok=True)
|
||||
# déplacer le fichier html dans le dossier slug, et le renommer en index.html ensuite pour ne pas modifier l'index du blog
|
||||
shutil.copy(chemin_fichier_this_article, new_folder_path_this_article+'index.html')
|
||||
# déplacer le fichier html dans le dossier slug,
|
||||
# et le renommer en index.html ensuite pour ne pas modifier l'index du blog
|
||||
contenu_index_html += f"<br><a href=/{année}/{slug}>{année} {article_name}</a>"
|
||||
os.makedirs(os.path.dirname(new_folder_path_this_article), exist_ok=True)
|
||||
shutil.copy(chemin_fichier_this_article_html, new_folder_path_this_article + 'index.html')
|
||||
else:
|
||||
contenu_index_html += f"<br><a href=/{lang_folder}/{link_html}>{link_html}</a>"
|
||||
|
||||
# ---------------- pareil en anglais TODO
|
||||
# contenu_index_gmi += "\n# Articles in English\n-------------------------\n"
|
||||
|
@ -240,29 +228,25 @@ def generer_index(dossier_source, fichier_index, titre_index):
|
|||
# lang_folder="lang_en/"
|
||||
# for fichier in files_en:
|
||||
# ----------------------------------------
|
||||
|
||||
print(contenu_index_gmi)
|
||||
|
||||
print('chemin_fichier_index_html' , dossier_parent+chemin_fichier_index_html)
|
||||
print('chemin_fichier_index_html', chemin_fichier_index_html)
|
||||
print(' ')
|
||||
with open(dossier_parent+chemin_fichier_index_html, 'w', encoding='utf-8') as file:
|
||||
file.write('<html><head><title>'+args.title+'</title><link rel=\"stylesheet\" href=\"/style.css\"></link></head><body>'+contenu_index_html+'</article></body></html>')
|
||||
with open(chemin_fichier_index_html, 'w', encoding='utf-8') as file:
|
||||
print('contenu_index_html', contenu_index_html)
|
||||
contenu_index_html = enrich_one_file(contenu_index_html)
|
||||
file.write(contenu_index_html)
|
||||
print(f" ------------ build_indexes: Fichier d'index '{chemin_fichier_index_html}' généré avec succès.")
|
||||
|
||||
|
||||
destination_html = dossier_parent+'/html-websites/'+args.source+'/'
|
||||
shutil.copy(dossier_parent+chemin_fichier_index_html, destination_html)
|
||||
shutil.copy(destination_html+chemin_fichier_index_html, destination_html+'index.html')
|
||||
|
||||
|
||||
|
||||
# Écrit le contenu dans le fichier d'index
|
||||
try:
|
||||
with open(chemin_fichier_index_gemini, 'w', encoding='utf-8') as file:
|
||||
file.write(contenu_index_gmi)
|
||||
print(f" ------------ build_indexes: Fichier d'index gemini '{chemin_fichier_index_gemini}' généré avec succès.")
|
||||
|
||||
print(
|
||||
f" ------------ build_indexes: Fichier d'index gemini '{chemin_fichier_index_gemini}' généré avec succès.")
|
||||
|
||||
except OSError as e:
|
||||
print(f" ------------ build_indexes: Erreur lors de l'écriture du fichier d'index : {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
generer_index(DOSSIER_SOURCE, FICHIER_INDEX, TITRE_INDEX)
|
||||
generer_index(DOSSIER_SOURCE, FICHIER_INDEX)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue