lib/awesome-privacy-readme-gen.py
185 lines · 7056 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=14
22
23def iconElement(serviceUrl, serviceIcon):
24 path = serviceIcon or f"https://icon.horse/icon/{urlparse(serviceUrl).netloc}"
25 return f"<img src='{path}' width='{icon_size}' alt='' />"
26
27def slugify(title):
28 if not title:
29 return ''
30 title = title.lower()
31 title = re.sub(r'\s+', '-', title)
32 title = re.sub(r'\+|&', 'and', title)
33 title = title.replace('?', '')
34 return title
35
36_MD_PATTERNS = [
37 re.compile(r'\[([^\]]*)\]\([^)]*\)'), # [text](url) — group 1 = visible text
38 re.compile(r'\*\*(.+?)\*\*'), # **bold**
39 re.compile(r'`([^`]+)`'), # `code`
40 re.compile(r'(?<!\*)\*([^*]+)\*(?!\*)'), # *italic*
41]
42
43def truncateMarkdown(text, maxLen=200):
44 """Returns (truncated_text, was_truncated) preserving markdown constructs."""
45 if len(text) <= maxLen:
46 return text, False
47
48 result = []
49 visible = 0
50 i = 0
51
52 while i < len(text) and visible < maxLen:
53 for pattern in _MD_PATTERNS:
54 m = pattern.match(text, i)
55 if m:
56 result.append(m.group(0))
57 visible += len(m.group(1))
58 i = m.end()
59 break
60 else:
61 result.append(text[i])
62 visible += 1
63 i += 1
64
65 return ''.join(result).rstrip(), True
66
67def makeHref(text):
68 if not text: return "#"
69 return re.sub(r'[^\w\s-]', '', text.lower()).replace(" ", "-")
70
71def makeContents(data):
72 contents = "<blockquote><details open>\n"
73 contents += "<summary>📋 <b>Contents</b></summary>\n"
74
75 for category in data.get('categories'):
76 contents += f"\n- **{category.get('name')}**"
77 for section in category.get('sections'):
78 if (len(section.get('services') or []) > 0):
79 contents += (
80 f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
81 f"({len(section.get('services') or [])})"
82 )
83 contents += "\n</details></blockquote>\n\n"
84 return contents
85
86def makeAwesomePrivacy(data):
87 markdown = ""
88 for category in data.get('categories'):
89 markdown += f"## {category.get('name')}\n\n"
90 for section in category.get('sections'):
91 markdown += f"### {section.get('name')}\n\n"
92 # Add intro
93 if section.get('intro'):
94 markdown += f"{section.get('intro')}\n"
95 # No services yet
96 if not section.get('services') or len(section.get('services')) == 0:
97 markdown += (
98 "<p align=\"center\">"
99 "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
100 "<i>Check back soon, or help us complete it by submitting a pull request</i>"
101 "</p>"
102 )
103 # For each service, list it's name, icon, url, and description
104 for app in section.get('services') or []:
105 description, was_truncated = truncateMarkdown(' '.join(app.get('description', '').split()))
106 ap_link = (
107 f"https://awesome-privacy.xyz/"
108 f"{slugify(category.get('name'))}/{slugify(section.get('name'))}/{slugify(app.get('name'))}"
109 )
110 ellipsis = f"[…]({ap_link} \"View full {app.get('name')} report\")" if was_truncated else ""
111 markdown += (
112 f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
113 f"({app.get('url')})** - {description}{ellipsis} \n"
114 )
115 markdown += "\n"
116 # If word of warning exists, append it
117 if section.get('wordOfWarning'):
118 markdown += "<details>\n<summary>⚠️ <b>Word of Warning</b></summary>\n\n"
119 markdown += f"> {section.get('wordOfWarning')}\n\n"
120 markdown += "</details>\n\n"
121 # If notable mentions exists, append it (either as a list or a single string)
122 if section.get('notableMentions'):
123 markdown += "<details>\n<summary>✳️ <b>Notable Mentions</b></summary>\n\n"
124 if isinstance(section.get('notableMentions'), list):
125 for mention in section.get('notableMentions'):
126 markdown += f"> - [{mention.get('name')}]({mention.get('url')})" + (
127 f" - {mention.get('description')}" if mention.get('description') else "\n"
128 )
129 else:
130 notable_mentions = section.get('notableMentions').replace('\n', '\n> ')
131 markdown += f"> {notable_mentions}"
132
133 markdown += "</details>\n\n"
134 # If further info exists, append it
135 if section.get('furtherInfo'):
136 markdown += "<details>\n<summary>ℹ️ <b>Further Info</b></summary>\n\n"
137 markdown += f"> {section.get('furtherInfo')}"
138 markdown += "</details>\n\n"
139 markdown += "<p align=\"right\"><sup><a href=\"#top\">⬆️ [Back to Top]</a></sub></p>\n"
140 markdown += "\n---\n\n"
141 return markdown
142
143def update_content_between_markers(content, start_marker, end_marker, new_content):
144 logger.info(f"Updating content between {start_marker} and {end_marker} markers...")
145 start_index = content.find(start_marker)
146 end_index = content.find(end_marker)
147
148 if start_index != -1 and end_index != -1:
149 before_section = content[:start_index + len(start_marker)]
150 after_section = content[end_index:]
151 updated_content = before_section + '\n' + new_content + after_section
152 return updated_content
153 else:
154 logger.error(f"Markers {start_marker} and {end_marker} not found.")
155 return content
156
157
158def main():
159 logger.info("Reading the awesome-privacy file...")
160 with open(app_list_file_path, 'r') as file:
161 data = yaml.safe_load(file)
162
163 awesome_privacy_results = makeContents(data) + makeAwesomePrivacy(data)
164
165 logger.info("Reading README.md file...")
166 with open(readme_path, 'r') as file:
167 readme_content = file.read()
168
169 readme_content = update_content_between_markers(
170 readme_content,
171 "<!-- awesome-privacy-start -->",
172 "<!-- awesome-privacy-end -->",
173 awesome_privacy_results,
174 )
175
176 logger.info("Writing back to README.md...")
177 with open(readme_path, 'w') as file:
178 file.write(readme_content)
179
180 # All done. Time to go home for tea and medals.
181 logger.info("Script completed successfully!")
182
183
184if __name__ == "__main__":
185 main()