-
Notifications
You must be signed in to change notification settings - Fork 0
147 lines (127 loc) · 6.55 KB
/
json-format.yml
File metadata and controls
147 lines (127 loc) · 6.55 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
name: Validate database1.json and Create Issue on Error
on:
push:
branches:
- main
paths:
- 'database1.json' # Only run when database1.json changes
jobs:
validate_json:
runs-on: ubuntu-latest
# We need full content access and permission to push back a fix (if valid)
# or create an issue (if invalid).
permissions:
contents: write # Needed for committing the formatted file
issues: write # Needed for creating and assigning the issue
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Validate JSON, Fix Formatting, and Create Issue on Syntax Error
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const path = 'database1.json';
const ASSIGNEE = 'alboxer2000'; // User to assign the issue to
let content;
let parsedContent;
let errorDetails = '';
// 1. Read the file content
try {
content = fs.readFileSync(path, 'utf8');
} catch (readError) {
console.log(`Could not read file ${path}. Skipping validation.`);
return;
}
// 2. Attempt to parse the JSON content
try {
parsedContent = JSON.parse(content);
console.log(`Successfully parsed JSON in ${path}`);
// --- Case A: JSON is valid. Reformat, commit, create/close issue if needed. ---
// Use 2 spaces for consistent formatting and ensure a trailing newline
const nicelyFormattedContent = JSON.stringify(parsedContent, null, 2) + '\n';
// Only proceed if the formatting actually changed.
if (content !== nicelyFormattedContent) {
console.log('JSON requires reformatting. Committing fix and creating resolution issue.');
// Get the current file's SHA to update it
const fileData = await github.rest.repos.getContent({
owner: context.repo.owner,
repo: context.repo.repo,
path: path,
ref: context.sha // Use the current commit SHA
});
const sha = fileData.data.sha;
// 1. Update the file content (Commit the fix)
await github.rest.repos.createOrUpdateFileContents({
owner: context.repo.owner,
repo: context.repo.repo,
path: path,
message: `style(json): Automatically format ${path} (Action Fix)`,
content: Buffer.from(nicelyFormattedContent).toString('base64'),
sha: sha, // Required for updating an existing file
committer: {
name: 'GitHub Action JSON Formatter',
email: 'github-actions[bot]@users.noreply.github.com',
},
author: {
name: 'GitHub Action JSON Formatter',
email: 'github-actions[bot]@users.noreply.github.com',
},
});
console.log(`Successfully committed reformatted ${path}`);
// 2. Create the resolution issue
const resolvedTitle = `✅ JSON Formatting Auto-Fixed in ${path}`;
const resolvedBody = `The file \`${path}\` was pushed with inconsistent formatting (e.g., incorrect indentation or extra whitespace). \n\nThe GitHub Action automatically corrected the formatting using 2-space indentation and committed the fix back to the branch. This issue is being closed automatically.`;
const newIssue = await github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: resolvedTitle,
body: resolvedBody,
labels: ['auto-fix', 'resolved'],
assignees: [ASSIGNEE]
});
// 3. Close the issue immediately
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: newIssue.data.number,
state: 'closed',
state_reason: 'completed'
});
console.log(`Successfully created and closed issue #${newIssue.data.number} documenting the format fix.`);
} else {
console.log('JSON is already nicely formatted. No commit or issue needed.');
}
} catch (parseError) {
// --- Case B: JSON is invalid (syntax error). Create open issue and let job succeed. ---
errorDetails = parseError.message;
console.error(`JSON validation failed: ${errorDetails}`);
const issueTitle = `JSON Syntax Error in ${path}`;
// 4. Construct the issue body
const issueBody = 'A critical JSON formatting error was detected in `' + path + '` during the latest push.\n\n'
+ '**Problem:** **' + errorDetails + '**\n\n'
+ 'The Action cannot automatically repair critical syntax errors (like missing commas or brackets). Please fix the file.\n\n'
+ '---\n'
+ '### File Content:\n'
+ 'The malformed JSON content that triggered the failure is below:\n'
+ '```json\n'
+ content + '\n'
+ '```\n\n'
+ '---\n'
+ '### Mistake Details:\n'
+ errorDetails;
// 5. Create the GitHub Issue and assign (Issue remains open)
await github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: issueTitle,
body: issueBody,
labels: ['bug', 'json-error', 'action-required'],
assignees: [ASSIGNEE] // Assigned to alboxer2000
});
console.log('Successfully created and assigned a new GitHub Issue.');
// NOTE: The 'throw new Error' has been removed here.
// The action will now exit gracefully with a success status
// after creating the issue.
}