-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwp_to_jekyll.py
136 lines (111 loc) · 4.73 KB
/
wp_to_jekyll.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import html
import argparse
from datetime import datetime
from xml.etree import ElementTree as ET
import unicodedata
# Névterek definiálása, amelyeket a WordPress export XML használ
NAMESPACES = {
'wp': 'http://wordpress.org/export/1.2/',
'content': 'http://purl.org/rss/1.0/modules/content/',
'excerpt': 'http://purl.org/rss/1.0/modules/excerpt/',
'dc': 'http://purl.org/dc/elements/1.1/',
}
def slugify(text):
"""
Szöveg átalakítása URL-barát slug formátumra
"""
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('ascii')
text = re.sub(r'[^\w\s-]', '', text.lower())
return re.sub(r'[-\s]+', '-', text).strip('-_')
def process_wordpress_export(xml_file, output_dir, by_category=True):
"""
WordPress export XML fájl feldolgozása és Jekyll-kompatibilis fájlok készítése
"""
# Kimenet mappa létrehozása, ha még nem létezik
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# XML fájl beolvasása
tree = ET.parse(xml_file)
root = tree.getroot()
# Csatorna (channel) elem megkeresése
channel = root.find('channel')
if channel is None:
print("Hiba: Az XML fájl nem tartalmaz 'channel' elemet!")
return
# Bejegyzések feldolgozása
for item in channel.findall('item'):
# Csak a 'post' típusú elemek kellenek
post_type = item.find('.//wp:post_type', NAMESPACES)
if post_type is None or post_type.text != 'post':
continue
# Bejegyzés státuszának ellenőrzése
post_status = item.find('.//wp:status', NAMESPACES)
if post_status is None or post_status.text != 'publish':
continue
# Alapadatok kinyerése
title = item.find('title').text if item.find('title') is not None else 'Untitled'
# Tartalom kinyerése
content_node = item.find('.//content:encoded', NAMESPACES)
content = content_node.text if content_node is not None else ''
# Link kinyerése
link_node = item.find('link')
link = link_node.text if link_node is not None else ''
# Publikálás dátuma
pub_date_node = item.find('pubDate')
if pub_date_node is not None and pub_date_node.text:
try:
pub_date = datetime.strptime(pub_date_node.text, '%a, %d %b %Y %H:%M:%S %z')
date_prefix = pub_date.strftime('%Y-%m-%d')
except ValueError:
date_prefix = datetime.now().strftime('%Y-%m-%d')
else:
date_prefix = datetime.now().strftime('%Y-%m-%d')
# Kategóriák kinyerése
categories = []
for cat in item.findall('category'):
if cat.get('domain') == 'category' and cat.text != 'Uncategorized':
# Kihagyjuk az 'Uncategorized' kategóriát
categories.append(cat.text)
# Ha nincs kategória, akkor "uncategorized" mappába tesszük
if not categories:
categories = ['uncategorized']
# Fájl létrehozása kategóriánként
for category in categories:
# Kategória mappájának létrehozása
category_slug = slugify(category)
category_dir = os.path.join(output_dir, category_slug)
if not os.path.exists(category_dir):
os.makedirs(category_dir)
# Fájlnév generálása
slug = slugify(title)
filename = f"{date_prefix}-{slug}.md"
file_path = os.path.join(category_dir, filename)
# YAML frontmatter és tartalom elkészítése
frontmatter = f"""---
layout: post
title: "{title}"
date: {date_prefix}
categories:
- {category_slug}
---
link: {link}
{content}
"""
# Fájl kiírása
with open(file_path, 'w', encoding='utf-8') as file:
file.write(frontmatter)
print(f"Bejegyzés létrehozva: {file_path}")
def main():
parser = argparse.ArgumentParser(description='WordPress export fájlból Jekyll markdown fájlok generálása')
parser.add_argument('xml_file', help='WordPress export XML fájl elérési útja')
parser.add_argument('--output', '-o', default='_posts', help='Kimeneti mappa elérési útja (alapértelmezés: _posts)')
parser.add_argument('--by-category', '-c', action='store_true', help='Bejegyzések rendezése kategóriánként')
args = parser.parse_args()
process_wordpress_export(args.xml_file, args.output, args.by_category)
print("WordPress export feldolgozása kész!")
if __name__ == "__main__":
main()