-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathvalidate_json.py
More file actions
231 lines (189 loc) · 6.85 KB
/
validate_json.py
File metadata and controls
231 lines (189 loc) · 6.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import argparse
import base64
import json
import os
import re
import sys
import requests
from generate_plugininfo import validateRequiredFields
GITHUB_REPO_PATTERN = re.compile(
r"https://github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)"
)
def make_headers(token):
headers = {"Accept": "application/vnd.github+json"}
if token:
headers["Authorization"] = f"token {token}"
return headers
def github_get_json(url, token):
response = requests.get(url, headers=make_headers(token), timeout=20)
try:
payload = response.json()
except ValueError:
payload = None
return response, payload
def extract_repo(value):
candidate = value.strip().rstrip("/")
if candidate.startswith("https://github.com/"):
match = GITHUB_REPO_PATTERN.search(candidate)
if match:
return match.group(1).lower()
return None
if candidate.count("/") == 1 and " " not in candidate:
return candidate.lower()
return None
def repo_from_issue_content(issue_content):
lines = issue_content.splitlines()
for line in lines:
if line.startswith("Repo URL:"):
repo = extract_repo(line.split("Repo URL:", 1)[1])
if repo:
return repo
for line in lines:
repo = extract_repo(line)
if repo:
return repo
return None
def validate_local_plugin_json(path):
try:
with open(path, "r", encoding="utf-8") as f:
plugin_data = json.load(f)
except FileNotFoundError:
print(f"ERROR: Local file not found: {path}")
return False
except json.JSONDecodeError as e:
print(f"ERROR: Invalid JSON in {path}: {e}")
return False
except OSError as e:
print(f"ERROR: Could not read {path}: {e}")
return False
if not validateRequiredFields(plugin_data):
print(f"ERROR: plugin.json metadata validation failed for {path}.")
return False
print(f"OK: Local JSON is valid: {path}")
return True
def validate_remote_repo(repo, token):
project_url = f"https://api.github.com/repos/{repo}"
latest_release_url = f"{project_url}/releases/latest"
release_response, release_data = github_get_json(latest_release_url, token)
if release_response.status_code == 401:
print("ERROR: Bad credentials, check access token.")
return False
if release_response.status_code == 404:
print(
"ERROR: Could not get release information. "
"Likely the repo has tags but no associated release, or the repo is private."
)
return False
if not release_response.ok:
print(
f"ERROR: Failed to fetch release data ({release_response.status_code}) from {latest_release_url}"
)
return False
if not isinstance(release_data, dict):
print(f"ERROR: Failed to parse release data JSON from {latest_release_url}")
return False
tag = release_data.get("tag_name")
if not tag:
print("ERROR: Latest release did not contain a tag_name.")
return False
plugin_json_url = f"{project_url}/contents/plugin.json?ref={tag}"
plugin_response, plugin_data = github_get_json(plugin_json_url, token)
if plugin_response.status_code == 404:
print(f"ERROR: plugin.json not found for release tag '{tag}'.")
return False
if not plugin_response.ok:
print(
f"ERROR: Failed to fetch plugin.json ({plugin_response.status_code}) from {plugin_json_url}"
)
return False
if not isinstance(plugin_data, dict):
print(f"ERROR: Failed to parse plugin.json metadata from {plugin_json_url}")
return False
encoded_content = plugin_data.get("content")
if not encoded_content:
print(
f"ERROR: plugin.json metadata did not include file content at {plugin_json_url}"
)
return False
try:
decoded = base64.b64decode(encoded_content.replace("\n", ""), validate=True)
plugin_json = json.loads(decoded)
except (ValueError, json.JSONDecodeError) as e:
print(f"ERROR: plugin.json in {repo} at tag '{tag}' is not valid JSON: {e}")
return False
if not validateRequiredFields(plugin_json):
print(f"ERROR: plugin.json metadata validation failed for {repo} at tag '{tag}'.")
return False
print(f"OK: Remote plugin.json is valid for {repo} at tag '{tag}'.")
return True
def parse_args():
parser = argparse.ArgumentParser(
description="Validate plugin.json from GitHub issue content, repo URL, or a local file."
)
parser.add_argument(
"legacy_token",
nargs="?",
help="GitHub token (legacy positional argument, kept for CI compatibility).",
)
parser.add_argument("--token", help="GitHub token. Optional for public repos.")
parser.add_argument(
"--issue-content", help="Issue body text containing a repo URL."
)
parser.add_argument(
"--issue-content-file",
help="Path to a file containing issue body text.",
)
parser.add_argument(
"--repo-url",
help="Repository URL or owner/repo string to validate directly.",
)
parser.add_argument(
"--plugin-json",
help="Path to a local plugin.json file to validate directly.",
)
return parser.parse_args()
def main():
args = parse_args()
token = args.token or args.legacy_token or os.environ.get("GITHUB_TOKEN")
issue_content = args.issue_content
if not issue_content and args.issue_content_file:
try:
with open(args.issue_content_file, "r", encoding="utf-8") as f:
issue_content = f.read()
except OSError as e:
print(f"ERROR: Failed to read --issue-content-file: {e}")
return 1
if not issue_content:
issue_content = os.environ.get("ISSUE_CONTENT")
checks_run = 0
failures = 0
if args.plugin_json:
checks_run += 1
if not validate_local_plugin_json(args.plugin_json):
failures += 1
repo = None
if args.repo_url:
repo = extract_repo(args.repo_url)
if not repo:
print(
"ERROR: Could not parse --repo-url. Use https://github.com/owner/repo or owner/repo."
)
return 1
elif issue_content:
repo = repo_from_issue_content(issue_content)
if not repo:
print("ERROR: Could not find a GitHub repo URL in issue content.")
return 1
if repo:
checks_run += 1
if not validate_remote_repo(repo, token):
failures += 1
if checks_run == 0:
print(
"ERROR: Nothing to validate. Provide --plugin-json, --repo-url, --issue-content, "
"--issue-content-file, or set ISSUE_CONTENT."
)
return 1
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())