lib/awesome-privacy-readme-gen.py
188 lines · 7503 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"[[1]}"
38 "&color=%235f53f4&cacheSeconds=3600)]"
39 f"(https://github.com/{repoUrl})"
40 )
41
42def tosElement(tosdrId):
43 if not tosdrId:
44 return ""
45 return f"[](https://tosdr.org/en/service/{tosdrId})"
46
47def statsElement(isOpenSource, isSecurityAudited, isAcceptsCrypto):
48 statsStr = ""
49 if isOpenSource == True:
50 statsStr += "📦 Open Source "
51 if isSecurityAudited == True:
52 statsStr += "🛡️ Security Audited "
53 if isAcceptsCrypto == True:
54 statsStr += "💰 Accepts Anonymous Payment "
55 return statsStr
56
57def awesomePrivacyReport(categoryName, sectionName, serviceName):
58 if not serviceName:
59 return ""
60 def slugify(name):
61 return (name or '').lower().replace(' ', '-')
62 return (
63 f"[![{serviceName} on Awesome Privacy]"
64 f"(https://img.shields.io/badge/View%20Report-FC60A8?style=flat&logo=awesomelists&label={serviceName.replace(' ', '_')})]"
65 f"(https://awesome-privacy.xyz/{slugify(categoryName)}/{slugify(sectionName)}/{slugify(serviceName)})"
66 )
67
68def makeStatsCard():
69 return (
70 f"\t- <details><summary>Stats</summary>\n\n"
71 f""
72 f"\n\n</details>"
73 )
74
75def makeHref(text):
76 if not text: return "#"
77 return re.sub(r'[^\w\s-]', '', text.lower()).replace(" ", "-")
78
79def makeContents():
80 contents = "<blockquote><details>\n"
81 contents += "<summary>📋 <b>Contents</b></summary>\n"
82
83 for category in data.get('categories'):
84 contents += f"\n- **{category.get('name')}**"
85 for section in category.get('sections'):
86 contents += (
87 f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
88 f"({len(section.get('services') or [])})"
89 )
90 contents += "\n</details></blockquote>\n\n"
91 return contents
92
93def makeAwesomePrivacy():
94 markdown = ""
95 for category in data.get('categories'):
96 markdown += f"## {category.get('name')}\n\n"
97 for section in category.get('sections'):
98 markdown += f"### {section.get('name')}\n\n"
99 # Add intro
100 if section.get('intro'):
101 markdown += f"{section.get('intro')}\n"
102 # No services yet
103 if not section.get('services') or len(section.get('services')) == 0:
104 markdown += (
105 "<p align=\"center\">"
106 "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
107 "<i>Check back soon, or help us complete it by submitting a pull request</i>"
108 "</p>"
109 )
110 # For each service, list it's name, icon, url, and description
111 for app in section.get('services') or []:
112 markdown += (
113 f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
114 f"({app.get('url')})** - {app.get('description')} "
115 + ((
116 f"\t- <details>\n\t\t<summary>Stats</summary>\n\n\t\t"
117 f"{repoElement(app.get('github'))} "
118 f"{tosElement(app.get('tosdrId'))} "
119 f"{awesomePrivacyReport(category.get('name'), section.get('name'), app.get('name'))} \n"
120 f"{statsElement(app.get('openSource'), app.get('securityAudited'), app.get('acceptsCrypto'))} \n"
121 f"\n\t\t</details>\n"
122 )
123 if app.get('github') or app.get('tosdrId') else '')
124 )
125 markdown += "\n"
126 # If word of warning exists, append it
127 if section.get('wordOfWarning'):
128 markdown += "<details>\n<summary>⚠️ <b>Word of Warning</b></summary>\n\n"
129 markdown += f"> {section.get('wordOfWarning')}\n\n"
130 markdown += "</details>\n\n"
131 # If notable mentions exists, append it (either as a list or a single string)
132 if section.get('notableMentions'):
133 markdown += "<details>\n<summary>✳️ <b>Notable Mentions</b></summary>\n\n"
134 if isinstance(section.get('notableMentions'), list):
135 for mention in section.get('notableMentions'):
136 markdown += f"> - [{mention.get('name')}]({mention.get('url')})" + (
137 f" - {mention.get('description')}" if mention.get('description') else "\n"
138 )
139 else:
140 notable_mentions = section.get('notableMentions').replace('\n', '\n> ')
141 markdown += f"> {notable_mentions}"
142
143 markdown += "</details>\n\n"
144 # If further info exists, append it
145 if section.get('furtherInfo'):
146 markdown += "<details>\n<summary>ℹ️ <b>Further Info</b></summary>\n\n"
147 markdown += f"> {section.get('furtherInfo')}"
148 markdown += "</details>\n\n"
149 markdown += "<p align=\"right\"><sup><a href=\"#top\">⬆️ [Back to Top]</a></sub></p>\n"
150 markdown += "\n---\n\n"
151 return markdown
152
153awesome_privacy_results = makeContents() + makeAwesomePrivacy()
154
155# Update the README.md between markers
156logger.info("Reading README.md file...")
157with open(readme_path, 'r') as file:
158 readme_content = file.read()
159
160def update_content_between_markers(content, start_marker, end_marker, new_content):
161 logger.info(f"Updating content between {start_marker} and {end_marker} markers...")
162 start_index = content.find(start_marker)
163 end_index = content.find(end_marker)
164
165 if start_index != -1 and end_index != -1:
166 before_section = content[:start_index + len(start_marker)]
167 after_section = content[end_index:]
168 updated_content = before_section + '\n' + new_content + after_section
169 return updated_content
170 else:
171 logger.error(f"Markers {start_marker} and {end_marker} not found.")
172 return content
173
174# Update guides and resources in README.md
175readme_content = update_content_between_markers(
176 readme_content,
177 "<!-- awesome-privacy-start -->",
178 "<!-- awesome-privacy-end -->",
179 awesome_privacy_results
180)
181
182# Write back the updated content to README.md
183logger.info("Writing back to README.md...")
184with open(readme_path, 'w') as file:
185 file.write(readme_content)
186
187# All done. Time to go home for tea and medals.
188logger.info("Script completed successfully!")