forked from lifeparticle/Ruby-Cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_readme.py
52 lines (44 loc) · 1.5 KB
/
build_readme.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
import requests
import pathlib
import json
import sys
import re
import os
# https://www.ruby-lang.org/en/feeds/news.rss
root = pathlib.Path(__file__).parent.resolve()
def replace_chunk(content, marker, chunk, inline=False):
# build the regular expression pattern, DOTALL will match any character, including a newline
r = re.compile(
r"<!-- {} starts -->.*<!-- {} ends -->".format(marker, marker),
re.DOTALL,
)
# add newline before and after
if not inline:
chunk = "\n{}\n".format(chunk)
# build the final chunk by adding comments before and after the chunk
chunk = "<!-- {} starts -->{}<!-- {} ends -->".format(marker, chunk, marker)
# replace matched string using pattern provided with the chunk
return r.sub(chunk, content)
def fetch_blog_posts(link):
result = []
response = requests.get(link)
if response.status_code == 200:
posts = json.loads(response.text)["items"]
for post in posts:
result.append(post)
elif response.status_code == 404:
print('Not Found: ') + link
return result
if __name__ == "__main__":
readme = root / "README.md"
readme_contents = readme.open().read()
rewritten = readme_contents
posts = fetch_blog_posts("https://api.rss2json.com/v1/api.json?rss_url=https://www.ruby-lang.org/en/feeds/news.rss")
if len(posts) != 0:
# markdown formatting
posts_md = "\n".join(
["* [{title}]({link}) <br/> <sub>{pubDate}</sub>".format(**post) for post in posts]
)
print(posts_md)
rewritten = replace_chunk(rewritten, "news", posts_md)
readme.open("w").write(rewritten)