forked from callmekatootie/carbonate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
298 lines (234 loc) · 7.3 KB
/
index.js
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
const core = require('@actions/core')
const github = require('@actions/github')
const gcb = require('gfm-code-blocks')
const { default: Axios } = require('axios')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid')
const FormData = require('form-data')
const path = require('path')
const util = require('util')
const prettier = require('prettier')
const {
IMAGE_FILE_EXT,
IMGUR_API_URL,
CARBON_API_URL,
CARBON_DEFAULT_SETTINGS
} = require('./constants')
const unlink = util.promisify(fs.unlink)
/**
* Formats the code using prettier
* @param {String} code The code block to format
* @param {Object} options The Prettier options
* @param {String} parser The Prettier parser
*/
function formatCode (code, options, parser) {
try {
return prettier.format(code, { ...options, parser })
} catch (error) {
core.debug('An error occurred when using prettier')
core.debug(error)
// Return unformatted code
return code
}
}
/**
* Generates the image using Carbon's API
* @param {String} code The code to generate image for
* @param {Object} options The {Unofficial} Carbon API options
*/
async function generateImage (code, options) {
const uuid = uuidv4()
core.info('Generating image from the code...')
try {
const res = await Axios.post(CARBON_API_URL, {
code,
...CARBON_DEFAULT_SETTINGS,
...options
}, {
responseType: 'stream'
})
const writeStream = fs.createWriteStream(path.join(__dirname, `${uuid}${IMAGE_FILE_EXT}`))
return new Promise((resolve, reject) => {
let error
res.data.pipe(writeStream)
writeStream.on('error', (err) => {
error = err
core.error('An error occurred downloading the generated image from Carbon')
core.debug(error)
writeStream.close()
reject(error)
})
writeStream.on('close', () => {
if (!error) {
// Return the file id
resolve(uuid)
}
})
})
} catch (error) {
core.error('An error occurred when trying to generate image for the code')
core.debug(error)
// Throw the error to abort the operation
throw error
}
}
/**
* Uploads the image to Imgur
* @param {String} imageId The uuid of the image
*/
async function uploadImage (imageId) {
const clientId = core.getInput('imgur-client-id')
const form = new FormData()
form.append('image', fs.createReadStream(path.join(__dirname, `${imageId}${IMAGE_FILE_EXT}`)))
core.info('Uploading image to imgur...')
try {
const res = await Axios.post(IMGUR_API_URL, form, {
headers: {
Authorization: `Client-ID ${clientId}`,
...form.getHeaders()
}
})
return res.data.data.link
} catch (error) {
core.error('An error occurred when trying to upload image to imgur')
core.debug(error)
throw error
}
}
/**
* Replaces the code block in a comment with the
* corresponding image's url
* @param {String} commentBody The entire comment body
* @param {String} imageUrl The image to replace the code block with
*/
function replaceCodeBlockWithImage (commentBody, imageUrl) {
// TODO - Support more than one code block
const codeblock = gcb(commentBody)[0]
// ! DO NOT change the formatting for this constant's value
// ! Intentionally set this way for the markdown to be correct during render
const replaceWith = `\n<p align="center"><img src="${imageUrl}"/></p>\n\n---\n\n<details><summary>View raw code</summary>
<p>
${codeblock.block}
</p></details>\n\n---\n\n`
return commentBody.replace(codeblock.block, replaceWith)
}
/**
* Updates the comment
* @param {Object} comment Details about the comment
*/
async function updateComment (comment) {
const githubToken = core.getInput('github-token')
const octokit = github.getOctokit(githubToken)
core.info('Updating comment...')
try {
await octokit.issues.updateComment(comment)
} catch (error) {
core.error('Error occurred updating the comment')
core.debug(error)
throw error
}
}
/**
* Updates the issue
* @param {Object} issue Details about the issue
*/
async function updateIssue (issue) {
const githubToken = core.getInput('github-token')
const octokit = github.getOctokit(githubToken)
core.info('Updating issue...')
try {
await octokit.issues.update(issue)
} catch (error) {
core.error('Error occurred updating the issue')
core.debug(error)
throw error
}
}
/**
* Main function
*/
async function execute () {
let imageId
let code
let body
const usePrettier = core.getInput('use-prettier') === 'true'
const prettierParser = core.getInput('prettier-parser')
let prettierOptions = {}
let carbonOptions = {}
try {
prettierOptions = JSON.parse(core.getInput('prettier-options'))
} catch (error) {
core.info('Prettier options is not passed or not a valid JSON string. Falling back to default')
}
try {
carbonOptions = JSON.parse(core.getInput('carbon-options'))
} catch (error) {
core.info('Carbon options is not passed or not a valid JSON string. Falling back to default')
}
try {
const { eventName, payload } = github.context
core.debug(`Event name: ${eventName}`)
core.debug(`Payload action: ${payload.action}`)
if (eventName !== 'issues' && eventName !== 'issue_comment') {
core.info(`Unsupported event ${eventName}`)
return
}
core.debug('Is a supported event')
if ((eventName === 'issues' && payload.action !== 'opened') ||
(eventName === 'issue_comment' && payload.action !== 'created')) {
core.info(`Unsupported type ${payload.action} for event ${eventName}`)
return
}
core.debug('Is a supported type')
if (eventName === 'issues') {
body = payload.issue.body
} else {
body = payload.comment.body
}
core.debug(`Body is ${body}`)
core.debug('Before extracting code blocks')
const codeblocks = gcb(body)
core.debug('After extracting code blocks')
// TODO - Support more than one code block
if (codeblocks.length !== 1) {
core.info('No code block found or more than one code block found. Unsupported scenario for now. Quitting.')
return
}
core.debug(`Is prettier active: ${usePrettier}`)
if (usePrettier) {
code = formatCode(codeblocks[0].code, prettierOptions, prettierParser)
} else {
code = codeblocks[0].code
}
core.debug(`Extracted code block is ${code}`)
imageId = await generateImage(code, carbonOptions)
const imageUrl = await uploadImage(imageId)
core.debug(`The imgur url is ${imageUrl}`)
const updatedComment = replaceCodeBlockWithImage(body, imageUrl)
core.debug(`The updated comment is ${updateComment}`)
const updates = {
owner: payload.repository.owner.login,
repo: payload.repository.name,
body: updatedComment
}
if (eventName === 'issues') {
updates.issue_number = payload.issue.number
await updateIssue(updates)
} else {
updates.comment_id = payload.comment.id
await updateComment(updates)
}
core.info('Task completed')
} catch (error) {
core.setFailed(error.message)
} finally {
core.startGroup('View event payload')
core.debug(JSON.stringify(github, null, 4))
core.endGroup()
// Cleanup
if (imageId) {
await unlink(path.resolve(__dirname, `${imageId}${IMAGE_FILE_EXT}`))
}
}
}
execute()