Skip to content

Commit 5c40bc3

Browse files
committed
Enhance JSON review processing script with improved logging and error handling
Added detailed print statements to track the progress of label checks, JSON file processing, and error handling. Enhanced feedback for existing labels and improved error messages for various exceptions. Updated the main function to provide a summary of processed files and their statuses, ensuring better visibility into the processing workflow.
1 parent ecb9721 commit 5c40bc3

File tree

1 file changed

+64
-10
lines changed

1 file changed

+64
-10
lines changed

Scripts/process_json_reviews.py

Lines changed: 64 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -117,16 +117,25 @@ def ensure_labels_exist(repo: Any) -> None:
117117
"incorrect": "d73a4a", # Red
118118
}
119119

120-
existing_labels = {label.name: label for label in repo.get_labels()}
120+
print(f" Checking for required labels...")
121+
try:
122+
existing_labels = {label.name: label for label in repo.get_labels()}
123+
print(f" ✓ Retrieved {len(existing_labels)} existing labels from repository")
124+
except Exception as e:
125+
print(f" ✗ Failed to retrieve labels: {e}", file=sys.stderr)
126+
raise
121127

122128
for label_name, label_color in required_labels.items():
123129
if label_name not in existing_labels:
124130
try:
125131
repo.create_label(label_name, label_color)
126-
print(f" ✓ Created label: {label_name}")
132+
print(f" ✓ Created label: {label_name} (color: {label_color})")
127133
except Exception as e:
128134
# Label might already exist or we don't have permission
129135
print(f" ⚠ Could not create label '{label_name}': {e}", file=sys.stderr)
136+
# Continue anyway - the label might have been created by another process
137+
else:
138+
print(f" ✓ Label already exists: {label_name}")
130139

131140

132141
def create_github_issue(repo: Any, review_data: Dict[str, Any]) -> Optional[int]:
@@ -161,97 +170,142 @@ def create_github_issue(repo: Any, review_data: Dict[str, Any]) -> Optional[int]
161170
def process_json_file(file_path: Path, repo: Any) -> Tuple[bool, Optional[str]]:
162171
"""Process a single JSON review file."""
163172
try:
173+
print(f" Reading file: {file_path}")
164174
# Read and parse JSON
165-
with open(file_path, 'r') as f:
175+
with open(file_path, 'r', encoding='utf-8') as f:
166176
review_data = json.load(f)
177+
print(f" ✓ Successfully parsed JSON")
167178

168179
# Validate review
180+
print(f" Validating review data...")
169181
is_valid, error_msg = validate_review(review_data)
170182
if not is_valid:
183+
print(f" ✗ Validation failed: {error_msg}")
171184
return False, error_msg
185+
print(f" ✓ Validation passed")
172186

173187
# Create GitHub Issue
188+
print(f" Creating GitHub Issue...")
174189
issue_number = create_github_issue(repo, review_data)
175190
if issue_number is None:
191+
print(f" ✗ Failed to create GitHub Issue")
176192
return False, "Failed to create GitHub Issue"
193+
print(f" ✓ Created GitHub Issue #{issue_number}")
177194

178195
# Move file to processed directory
196+
print(f" Moving file to processed directory...")
179197
processed_path = PROCESSED_DIR / file_path.name
180198
os.makedirs(PROCESSED_DIR, exist_ok=True)
181199
shutil.move(str(file_path), str(processed_path))
200+
print(f" ✓ Moved to: {processed_path}")
182201

183202
return True, None
184203

185204
except json.JSONDecodeError as e:
205+
print(f" ✗ JSON decode error: {e}")
186206
return False, f"Invalid JSON: {e}"
207+
except FileNotFoundError as e:
208+
print(f" ✗ File not found: {e}")
209+
return False, f"File not found: {e}"
210+
except PermissionError as e:
211+
print(f" ✗ Permission error: {e}")
212+
return False, f"Permission error: {e}"
187213
except Exception as e:
214+
print(f" ✗ Unexpected error: {e}")
215+
import traceback
216+
traceback.print_exc()
188217
return False, f"Error processing file: {e}"
189218

190219

191220
def main() -> None:
192221
"""Main function to process JSON review files."""
222+
print("="*50)
223+
print("Processing JSON Review Files")
224+
print("="*50)
225+
193226
# Get GitHub token from environment
194227
github_token = os.environ.get("GITHUB_TOKEN")
195228
if not github_token:
196229
print("Error: GITHUB_TOKEN environment variable not set", file=sys.stderr)
197230
print("Note: For GitHub Actions, this is automatically set as GITHUB_TOKEN", file=sys.stderr)
198231
sys.exit(1)
232+
else:
233+
print(f"✓ GITHUB_TOKEN is set (length: {len(github_token)})")
199234

200235
# Initialize GitHub client
201236
try:
237+
print(f"\nConnecting to GitHub repository: {REPO_OWNER}/{REPO_NAME}")
202238
g = Github(github_token)
203239
repo = g.get_repo(f"{REPO_OWNER}/{REPO_NAME}")
240+
print(f"✓ Successfully connected to repository")
204241
except Exception as e:
205-
print(f"Error: Failed to connect to GitHub repository: {e}", file=sys.stderr)
242+
print(f"Error: Failed to connect to GitHub repository: {e}", file=sys.stderr)
206243
import traceback
207244
traceback.print_exc()
208245
sys.exit(2)
209246

210247
# Ensure directories exist
248+
print(f"\nChecking directories...")
211249
os.makedirs(REVIEWS_DIR, exist_ok=True)
212250
os.makedirs(PROCESSED_DIR, exist_ok=True)
251+
print(f"✓ Reviews directory: {REVIEWS_DIR}")
252+
print(f"✓ Processed directory: {PROCESSED_DIR}")
213253

214254
# Find all JSON files in reviews directory (exclude processed directory)
255+
print(f"\nScanning for JSON files in {REVIEWS_DIR}...")
256+
all_json_files = list(REVIEWS_DIR.glob("*.json"))
215257
json_files = [
216-
f for f in REVIEWS_DIR.glob("*.json")
258+
f for f in all_json_files
217259
if f.parent.name != "processed" # Exclude files in processed subdirectory
218260
]
219261

262+
print(f"Found {len(all_json_files)} total JSON file(s)")
263+
print(f"Found {len(json_files)} JSON file(s) to process (excluding processed/)")
264+
220265
if not json_files:
221-
print("No JSON review files found in reviews/ directory")
266+
print("\nNo JSON review files found in reviews/ directory")
267+
print("Exiting successfully (no files to process)")
222268
return
223269

224-
print(f"Found {len(json_files)} JSON review file(s) to process")
225-
226270
# Process each file
227271
processed_count = 0
228272
failed_count = 0
229273
failed_files = []
230274

231275
for json_file in json_files:
232-
print(f"\nProcessing: {json_file.name}")
276+
print(f"\n{'='*50}")
277+
print(f"Processing: {json_file.name}")
278+
print(f"{'='*50}")
233279
success, error_msg = process_json_file(json_file, repo)
234280

235281
if success:
236282
processed_count += 1
283+
print(f"✓ Successfully processed: {json_file.name}")
237284
else:
238285
failed_count += 1
239286
failed_files.append((json_file.name, error_msg))
240-
print(f" ✗ Failed: {error_msg}")
287+
print(f"✗ Failed to process: {json_file.name}")
288+
print(f" Error: {error_msg}")
241289

242290
# Summary
243291
print(f"\n{'='*50}")
244292
print(f"Processing Summary:")
293+
print(f"{'='*50}")
245294
print(f" ✓ Successfully processed: {processed_count}")
246295
print(f" ✗ Failed: {failed_count}")
296+
print(f" Total files: {len(json_files)}")
247297

248298
if failed_files:
249299
print(f"\nFailed files:")
250300
for filename, error in failed_files:
251301
print(f" - {filename}: {error}")
252302

253303
if failed_count > 0:
304+
print(f"\n✗ Exiting with error code 1 due to {failed_count} failed file(s)")
254305
sys.exit(1)
306+
else:
307+
print(f"\n✓ All files processed successfully")
308+
sys.exit(0)
255309

256310

257311
if __name__ == "__main__":

0 commit comments

Comments
 (0)