lib/awesome-privacy-readme-gen.py
145 lines · 5800 bytes
1"""
2Reads app list from awesome-privacy.yml,
3formats into markdown, and inserts into README.md
4"""
5
6import os
7import re
8import yaml
9import logging
10from urllib.parse import urlparse
11
12# Configure Logging
13LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
14logging.basicConfig(level=LOG_LEVEL)
15logger = logging.getLogger(__name__)
16
17# Determine the project root based on the script's location
18project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19app_list_file_path = os.path.join(project_root, 'awesome-privacy.yml')
20readme_path = os.path.join(project_root, '.github/README.md')
21icon_size=16
22
23# Read the main YAML file, where all data lives
24logger.info("Reading the awesome-privacy file...")
25with open(app_list_file_path, 'r') as file:
26 data = yaml.safe_load(file)
27
28def iconElement(serviceUrl, serviceIcon):
29 path = serviceIcon or f"https://icon.horse/icon/{urlparse(serviceUrl).netloc}"
30 return f"<img src='{path}' width='{icon_size}' height='{icon_size}' alt='icon' />"
31
32def repoElement(repoUrl):
33 if not repoUrl:
34 return ""
35 return (
36 f"\t- [[1]}"
38 "&labelColor=%230d1117&color=%23302982&cacheSeconds=3600)]"
39 f"(https://github.com/{repoUrl})\n"
40 )
41
42def makeHref(text):
43 if not text: return "#"
44 return re.sub(r'[^\w\s-]', '', text.lower()).replace(" ", "-")
45
46def makeContents():
47 contents = "## Contents\n\n"
48 for category in data.get('categories'):
49 contents += f"- **{category.get('name')}**"
50 for section in category.get('sections'):
51 contents += (
52 f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
53 f"({len(section.get('services') or [])})"
54 )
55 contents += "\n"
56 return contents
57
58def makeAwesomePrivacy():
59 markdown = ""
60 for category in data.get('categories'):
61 markdown += f"## {category.get('name')}\n\n"
62 for section in category.get('sections'):
63 markdown += f"### {section.get('name')}\n\n"
64 # Add intro
65 if section.get('intro'):
66 markdown += f"{section.get('intro')}\n"
67 # No services yet
68 if not section.get('services') or len(section.get('services')) == 0:
69 markdown += (
70 "<p align=\"center\">"
71 "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
72 "<i>Check back soon, or help us complete it by submitting a pull request</i>"
73 "</p>"
74 )
75 # For each service, list it's name, icon, url, and description
76 for app in section.get('services') or []:
77 markdown += (
78 f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
79 f"({app.get('url')})** - {app.get('description')} "
80 f"{repoElement(app.get('github'))}"
81 )
82 markdown += "\n"
83 # If word of warning exists, append it
84 if section.get('wordOfWarning'):
85 markdown += "<details>\n<summary>⚠️ <b>Word of Warning</b></summary>\n\n"
86 markdown += f"> {section.get('wordOfWarning')}\n\n"
87 markdown += "</details>\n\n"
88 # If notable mentions exists, append it (either as a list or a single string)
89 if section.get('notableMentions'):
90 markdown += "<details>\n<summary>✳️ <b>Notable Mentions</b></summary>\n\n"
91 if isinstance(section.get('notableMentions'), list):
92 for mention in section.get('notableMentions'):
93 markdown += f"> - [{mention.get('name')}]({mention.get('url')})" + (
94 f" - {mention.get('description')}" if mention.get('description') else "\n"
95 )
96 else:
97 notable_mentions = section.get('notableMentions').replace('\n', '\n> ')
98 markdown += f"> {notable_mentions}"
99
100 markdown += "</details>\n\n"
101 # If further info exists, append it
102 if section.get('furtherInfo'):
103 markdown += "<details>\n<summary>ℹ️ <b>Further Info</b></summary>\n\n"
104 markdown += f"> {section.get('furtherInfo')}"
105 markdown += "</details>\n\n"
106 markdown += "<p align=\"right\"><sup><a href=\"#top\">⬆️ [Back to Top]</a></sub></p>\n"
107 markdown += "\n---\n\n"
108 return markdown
109
110awesome_privacy_results = makeContents() + makeAwesomePrivacy()
111
112# Update the README.md between markers
113logger.info("Reading README.md file...")
114with open(readme_path, 'r') as file:
115 readme_content = file.read()
116
117def update_content_between_markers(content, start_marker, end_marker, new_content):
118 logger.info(f"Updating content between {start_marker} and {end_marker} markers...")
119 start_index = content.find(start_marker)
120 end_index = content.find(end_marker)
121
122 if start_index != -1 and end_index != -1:
123 before_section = content[:start_index + len(start_marker)]
124 after_section = content[end_index:]
125 updated_content = before_section + '\n' + new_content + after_section
126 return updated_content
127 else:
128 logger.error(f"Markers {start_marker} and {end_marker} not found.")
129 return content
130
131# Update guides and resources in README.md
132readme_content = update_content_between_markers(
133 readme_content,
134 "<!-- awesome-privacy-start -->",
135 "<!-- awesome-privacy-end -->",
136 awesome_privacy_results
137)
138
139# Write back the updated content to README.md
140logger.info("Writing back to README.md...")
141with open(readme_path, 'w') as file:
142 file.write(readme_content)
143
144# All done. Time to go home for tea and medals.
145logger.info("Script completed successfully!")