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