| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | import json |
| 3 | import os |
| 4 | import subprocess |
| 5 | import sys |
| 6 | import urllib.request |
| 7 | from datetime import datetime, timezone |
| 8 | |
| 9 | def validate_environment(): |
| 10 | """Validate required environment variables.""" |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 11 | if not os.environ.get('GITHUB_SHA'): |
| 12 | print("Error: GITHUB_SHA environment variable is required") |
| 13 | sys.exit(1) |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 14 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 15 | if not os.environ.get('GITHUB_REPOSITORY'): |
| 16 | print("Error: GITHUB_REPOSITORY environment variable is required") |
| 17 | sys.exit(1) |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 18 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 19 | if not os.environ.get('DISCORD_WEBHOOK_FOR_COMMITS'): |
| 20 | print("Error: DISCORD_WEBHOOK_FOR_COMMITS environment variable is required") |
| 21 | sys.exit(1) |
| 22 | |
| 23 | def get_commit_info(): |
| 24 | """Extract commit information using git commands.""" |
| 25 | try: |
| 26 | # Get commit message (subject line) |
| 27 | commit_message = subprocess.check_output( |
| 28 | ['git', 'log', '-1', '--pretty=format:%s'], |
| 29 | text=True, stderr=subprocess.DEVNULL |
| 30 | ).strip() |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 31 | |
| 32 | # Get commit body (description) |
| 33 | commit_body = subprocess.check_output( |
| 34 | ['git', 'log', '-1', '--pretty=format:%b'], |
| 35 | text=True, stderr=subprocess.DEVNULL |
| 36 | ).strip() |
| 37 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 38 | # Get commit author |
| 39 | commit_author = subprocess.check_output( |
| 40 | ['git', 'log', '-1', '--pretty=format:%an'], |
| 41 | text=True, stderr=subprocess.DEVNULL |
| 42 | ).strip() |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 43 | |
| 44 | return commit_message, commit_body, commit_author |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 45 | except subprocess.CalledProcessError as e: |
| 46 | print(f"Failed to get commit information: {e}") |
| 47 | sys.exit(1) |
| 48 | |
| Philip Zeyliger | c3ecabb | 2025-06-06 22:29:03 +0000 | [diff] [blame^] | 49 | def truncate_text(text, max_length): |
| 50 | """Truncate text to fit within Discord's limits.""" |
| 51 | if len(text) <= max_length: |
| 52 | return text |
| 53 | # Find a good place to cut off, preferably at a sentence or paragraph boundary |
| 54 | truncated = text[:max_length - 3] # Leave room for "..." |
| 55 | |
| 56 | # Try to cut at paragraph boundary |
| 57 | last_double_newline = truncated.rfind('\n\n') |
| 58 | if last_double_newline > max_length // 2: # Only if we're not cutting too much |
| 59 | return truncated[:last_double_newline] + "\n\n..." |
| 60 | |
| 61 | # Try to cut at sentence boundary |
| 62 | last_period = truncated.rfind('. ') |
| 63 | if last_period > max_length // 2: # Only if we're not cutting too much |
| 64 | return truncated[:last_period + 1] + " ..." |
| 65 | |
| 66 | # Otherwise just truncate with ellipsis |
| 67 | return truncated + "..." |
| 68 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 69 | def main(): |
| 70 | # Validate we're running in the correct environment |
| 71 | validate_environment() |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 72 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 73 | # Check for test mode |
| 74 | if os.environ.get('DISCORD_TEST_MODE') == '1': |
| 75 | print("Running in test mode - will not send actual webhook") |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 76 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 77 | # Get commit information from git |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 78 | commit_message, commit_body, commit_author = get_commit_info() |
| 79 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 80 | # Get remaining info from environment |
| 81 | github_sha = os.environ.get('GITHUB_SHA') |
| 82 | commit_sha = github_sha[:8] |
| 83 | commit_url = f"https://github.com/{os.environ.get('GITHUB_REPOSITORY')}/commit/{github_sha}" |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 84 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 85 | # Create timestamp |
| 86 | timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')[:-3] + 'Z' |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 87 | |
| Philip Zeyliger | c3ecabb | 2025-06-06 22:29:03 +0000 | [diff] [blame^] | 88 | # Truncate fields to fit Discord's limits |
| 89 | # Discord embed limits: title (256), description (4096), field value (1024) |
| 90 | title = truncate_text(commit_message, 256) |
| 91 | description = truncate_text(commit_body, 2000) # Use 2000 to be safe |
| 92 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 93 | # Create Discord webhook payload |
| 94 | payload = { |
| 95 | "embeds": [ |
| 96 | { |
| Philip Zeyliger | c3ecabb | 2025-06-06 22:29:03 +0000 | [diff] [blame^] | 97 | "title": title, |
| 98 | "description": description, |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 99 | "color": 5814783, |
| 100 | "fields": [ |
| 101 | { |
| 102 | "name": "Author", |
| 103 | "value": commit_author, |
| 104 | "inline": True |
| 105 | }, |
| 106 | { |
| 107 | "name": "Commit", |
| 108 | "value": f"[{commit_sha}]({commit_url})", |
| 109 | "inline": True |
| 110 | }, |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 111 | ], |
| 112 | "timestamp": timestamp |
| 113 | } |
| 114 | ] |
| 115 | } |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 116 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 117 | # Convert to JSON |
| 118 | json_payload = json.dumps(payload) |
| Philip Zeyliger | c3ecabb | 2025-06-06 22:29:03 +0000 | [diff] [blame^] | 119 | |
| 120 | # Debug: print payload size info |
| 121 | if os.environ.get('DISCORD_TEST_MODE') == '1': |
| 122 | print(f"Payload size: {len(json_payload)} bytes") |
| 123 | print(f"Title length: {len(payload['embeds'][0]['title'])} chars") |
| 124 | print(f"Description length: {len(payload['embeds'][0]['description'])} chars") |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 125 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 126 | # Test mode - just print the payload |
| 127 | if os.environ.get('DISCORD_TEST_MODE') == '1': |
| 128 | print("Generated Discord payload:") |
| 129 | print(json.dumps(payload, indent=2)) |
| 130 | print("✓ Test mode: payload generated successfully") |
| 131 | return |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 132 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 133 | # Send to Discord webhook |
| 134 | webhook_url = os.environ.get('DISCORD_WEBHOOK_FOR_COMMITS') |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 135 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 136 | req = urllib.request.Request( |
| 137 | webhook_url, |
| 138 | data=json_payload.encode('utf-8'), |
| Philip Zeyliger | f178755 | 2025-05-28 02:44:39 +0000 | [diff] [blame] | 139 | headers={ |
| 140 | 'Content-Type': 'application/json', |
| 141 | 'User-Agent': 'sketch.dev developers' |
| 142 | } |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 143 | ) |
| Josh Bleecher Snyder | fa30677 | 2025-05-28 09:37:04 -0700 | [diff] [blame] | 144 | |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 145 | try: |
| 146 | with urllib.request.urlopen(req) as response: |
| 147 | if response.status == 204: |
| 148 | print("Discord notification sent successfully") |
| 149 | else: |
| 150 | print(f"Discord webhook returned status: {response.status}") |
| Philip Zeyliger | f178755 | 2025-05-28 02:44:39 +0000 | [diff] [blame] | 151 | response_body = response.read().decode('utf-8') |
| 152 | print(f"Response body: {response_body}") |
| Philip Zeyliger | 9e3c867 | 2025-05-27 17:09:14 +0000 | [diff] [blame] | 153 | sys.exit(1) |
| 154 | except urllib.error.HTTPError as e: |
| 155 | print(f"Discord webhook HTTP error: {e.code} - {e.reason}") |
| 156 | try: |
| 157 | error_body = e.read().decode('utf-8') |
| 158 | print(f"Error details: {error_body}") |
| 159 | if e.code == 403 and 'error code: 1010' in error_body: |
| 160 | print("Error 1010: Webhook not found - the Discord webhook URL may be invalid or expired") |
| 161 | except: |
| 162 | pass |
| 163 | sys.exit(1) |
| 164 | except Exception as e: |
| 165 | print(f"Failed to send Discord notification: {e}") |
| 166 | sys.exit(1) |
| 167 | |
| 168 | if __name__ == "__main__": |
| 169 | main() |