lib/awesome-privacy-readme-gen.py
147 lines · 5866 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 = "<details>\n"
48 contents += "<summary><h2>Contents</h2></summary>\n"
49
50 for category in data.get('categories'):
51 contents += f"\n- **{category.get('name')}**"
52 for section in category.get('sections'):
53 contents += (
54 f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
55 f"({len(section.get('services') or [])})"
56 )
57 contents += "\n</details>\n\n"
58 return contents
59
60def makeAwesomePrivacy():
61 markdown = ""
62 for category in data.get('categories'):
63 markdown += f"## {category.get('name')}\n\n"
64 for section in category.get('sections'):
65 markdown += f"### {section.get('name')}\n\n"
66 # Add intro
67 if section.get('intro'):
68 markdown += f"{section.get('intro')}\n"
69 # No services yet
70 if not section.get('services') or len(section.get('services')) == 0:
71 markdown += (
72 "<p align=\"center\">"
73 "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
74 "<i>Check back soon, or help us complete it by submitting a pull request</i>"
75 "</p>"
76 )
77 # For each service, list it's name, icon, url, and description
78 for app in section.get('services') or []:
79 markdown += (
80 f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
81 f"({app.get('url')})** - {app.get('description')} "
82 f"{repoElement(app.get('github'))}"
83 )
84 markdown += "\n"
85 # If word of warning exists, append it
86 if section.get('wordOfWarning'):
87 markdown += "<details>\n<summary>⚠️ <b>Word of Warning</b></summary>\n\n"
88 markdown += f"> {section.get('wordOfWarning')}\n\n"
89 markdown += "</details>\n\n"
90 # If notable mentions exists, append it (either as a list or a single string)
91 if section.get('notableMentions'):
92 markdown += "<details>\n<summary>✳️ <b>Notable Mentions</b></summary>\n\n"
93 if isinstance(section.get('notableMentions'), list):
94 for mention in section.get('notableMentions'):
95 markdown += f"> - [{mention.get('name')}]({mention.get('url')})" + (
96 f" - {mention.get('description')}" if mention.get('description') else "\n"
97 )
98 else:
99 notable_mentions = section.get('notableMentions').replace('\n', '\n> ')
100 markdown += f"> {notable_mentions}"
101
102 markdown += "</details>\n\n"
103 # If further info exists, append it
104 if section.get('furtherInfo'):
105 markdown += "<details>\n<summary>ℹ️ <b>Further Info</b></summary>\n\n"
106 markdown += f"> {section.get('furtherInfo')}"
107 markdown += "</details>\n\n"
108 markdown += "<p align=\"right\"><sup><a href=\"#top\">⬆️ [Back to Top]</a></sub></p>\n"
109 markdown += "\n---\n\n"
110 return markdown
111
112awesome_privacy_results = makeContents() + makeAwesomePrivacy()
113
114# Update the README.md between markers
115logger.info("Reading README.md file...")
116with open(readme_path, 'r') as file:
117 readme_content = file.read()
118
119def update_content_between_markers(content, start_marker, end_marker, new_content):
120 logger.info(f"Updating content between {start_marker} and {end_marker} markers...")
121 start_index = content.find(start_marker)
122 end_index = content.find(end_marker)
123
124 if start_index != -1 and end_index != -1:
125 before_section = content[:start_index + len(start_marker)]
126 after_section = content[end_index:]
127 updated_content = before_section + '\n' + new_content + after_section
128 return updated_content
129 else:
130 logger.error(f"Markers {start_marker} and {end_marker} not found.")
131 return content
132
133# Update guides and resources in README.md
134readme_content = update_content_between_markers(
135 readme_content,
136 "<!-- awesome-privacy-start -->",
137 "<!-- awesome-privacy-end -->",
138 awesome_privacy_results
139)
140
141# Write back the updated content to README.md
142logger.info("Writing back to README.md...")
143with open(readme_path, 'w') as file:
144 file.write(readme_content)
145
146# All done. Time to go home for tea and medals.
147logger.info("Script completed successfully!")