Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
87 lines (76 loc) · 2.49 KB
/
Copy pathmain.js
File metadata and controls
87 lines (76 loc) · 2.49 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
const core = require('@actions/core')
const http = require('@actions/http-client')
const path = require('path')
const fs = require('fs').promises
/**
* The main function for the action.
* @returns {Promise<void>} Resolves when the action is complete.
*/
async function run() {
try {
const inputs = {
webhookURL: core.getInput('MATTERMOST_WEBHOOK_URL', { required: true }),
channel: core.getInput('MATTERMOST_CHANNEL'),
username: core.getInput('MATTERMOST_USERNAME'),
icon: core.getInput('MATTERMOST_ICON_URL'),
text: core.getInput('TEXT'),
payload: core.getInput('PAYLOAD'),
filename: core.getInput('PAYLOAD_FILENAME')
}
const finalPayload = await generatePayload(inputs)
core.debug(`${JSON.stringify(finalPayload, undefined, 4)}`)
await sendNotification(inputs.webhookURL, finalPayload)
} catch (error) {
core.setFailed(error.message)
}
}
async function sendNotification(webhookURL, payload) {
const client = new http.HttpClient()
const response = await client.post(webhookURL, JSON.stringify(payload))
await response.readBody()
if (response.message.statusCode === 200) {
core.info('Successfully sent notification!')
} else {
core.error(`Unexpected status code: ${response.message.statusCode}`)
throw new Error(`${response.message.statusMessage}`)
}
}
async function generatePayload(inputs) {
const legacyPayloadFilePath = path.join(__dirname, '..', inputs.filename)
const legacyPayloadFileData = await checkLegacy(legacyPayloadFilePath)
if (legacyPayloadFileData) {
return legacyPayloadFileData
}
if (inputs.payload !== '') {
core.debug(`Will use the PAYLOAD input as is`)
return JSON.parse(inputs.payload)
} else if (inputs.text !== '') {
core.debug('Will use the TEXT input to generate the payload.')
const payload = {
channel: inputs.channel,
username: inputs.username,
icon_url: inputs.icon,
text: inputs.text
}
return payload
} else {
throw new Error('You need to provide TEXT or PAYLOAD input')
}
}
async function checkLegacy(filePath) {
try {
await fs.access(filePath, fs.constants.F_OK)
const legacyData = await fs.readFile(filePath)
return legacyData
} catch (error) {
if (error.code === 'ENOENT' || error.code === 'EISDIR') {
core.debug(`File ${filePath} does not exist. Moving along ...`)
return
} else {
throw new Error(`You need to provide a valid readable file: ${error}`)
}
}
}
module.exports = {
run
}