lib/awesome-privacy-readme-gen.py

178 lines · 7045 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        "&labelColor=%230d1117&color=%23302982&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 awesomePrivacyReport(categoryName, sectionName, serviceName):
 48  if not serviceName:
 49      return ""
 50  def slugify(name):
 51      return (name or '').lower().replace(' ', '-')
 52  return (
 53      f"[![{serviceName} on Awesome Privacy]"
 54      f"(https://img.shields.io/badge/{serviceName.replace(' ', '_')}-FC60A8?style=flat&logo=awesomelists&label=Awesome%20Privacy)]"
 55      f"(https://awesome-privacy.xyz/{slugify(categoryName)}/{slugify(sectionName)}/{slugify(serviceName)})"
 56  )
 57
 58def makeStatsCard():
 59  return (
 60      f"\t- <details><summary>Stats</summary>\n\n"
 61      f""
 62      f"\n\n</details>"
 63  )
 64
 65def makeHref(text):
 66    if not text: return "#"
 67    return re.sub(r'[^\w\s-]', '', text.lower()).replace(" ", "-")
 68
 69def makeContents():
 70    contents = "<details>\n"
 71    contents += "<summary><h2>Contents</h2></summary>\n"
 72
 73    for category in data.get('categories'):
 74        contents += f"\n- **{category.get('name')}**"
 75        for section in category.get('sections'):
 76            contents += (
 77                f"\n\t- [{section.get('name')}](#{makeHref(section.get('name'))}) "
 78                f"({len(section.get('services') or [])})"
 79            )
 80    contents += "\n</details>\n\n"
 81    return contents
 82
 83def makeAwesomePrivacy():
 84  markdown = ""
 85  for category in data.get('categories'):
 86      markdown += f"## {category.get('name')}\n\n"
 87      for section in category.get('sections'):
 88          markdown += f"### {section.get('name')}\n\n"
 89          # Add intro
 90          if section.get('intro'):
 91            markdown += f"{section.get('intro')}\n"
 92          # No services yet
 93          if not section.get('services') or len(section.get('services')) == 0:
 94            markdown += (
 95              "<p  align=\"center\">"
 96              "<b>⚠️ This section is still a work in progress ⚠️</b><br />"
 97              "<i>Check back soon, or help us complete it by submitting a pull request</i>"
 98              "</p>"
 99            )
100          # For each service, list it's name, icon, url, and description
101          for app in section.get('services') or []:
102              markdown += (
103                  f"- **[{iconElement(app.get('url'), app.get('icon'))} {app.get('name')}]"
104                  f"({app.get('url')})** - {app.get('description')} "
105
106                  + ((
107                    f"\t- <details>\n\t\t<summary>Stats</summary>\n\n\t\t"
108                    f"{repoElement(app.get('github'))} "
109                    f"{tosElement(app.get('tosdrId'))} "
110                    f"{awesomePrivacyReport(category.get('name'), section.get('name'), app.get('name'))} \n"
111                    f"\n\t\t</details>\n"
112                  )
113                  if app.get('github') or app.get('tosdrId') else '')
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
143awesome_privacy_results = makeContents() + makeAwesomePrivacy()
144
145# Update the README.md between markers
146logger.info("Reading README.md file...")
147with open(readme_path, 'r') as file:
148    readme_content = file.read()
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# Update guides and resources in README.md
165readme_content = update_content_between_markers(
166  readme_content,
167  "<!-- awesome-privacy-start -->",
168  "<!-- awesome-privacy-end -->",
169  awesome_privacy_results
170)
171
172# Write back the updated content to README.md
173logger.info("Writing back to README.md...")
174with open(readme_path, 'w') as file:
175    file.write(readme_content)
176
177# All done. Time to go home for tea and medals.
178logger.info("Script completed successfully!")