lib/awesome-privacy-readme-gen.py

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