lib/awesome-privacy-readme-gen.py

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