-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
90 lines (76 loc) · 2.38 KB
/
index.ts
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
import * as github from '@actions/github'
import { IssueCommentEvent } from '@octokit/webhooks-definitions/schema'
import { info, getInput, setOutput } from '@actions/core'
import * as fs from 'fs'
import { execSync } from 'child_process'
import { exit } from 'process'
const ctx = github.context.payload as IssueCommentEvent
const body = ctx.comment.body.trim()
if (!body.toLowerCase().startsWith('# weight')) {
info('No `# Weight` title found, ignoring…')
exit(0)
}
const match = body.match(/(\d+(\.\d+)?) lbs/)
const weight = parseFloat((match ?? [])[1])
if (!weight || Number.isNaN(weight)) throw new Error("Couldn’t extract weight data point")
const height = (() => {
const value = getInput('height')
const match = value.match(/(\d+)'(\d+)"/)
if (match) {
const cm = (parseInt(match[1]) * 12 + parseInt(match[2])) * 2.54
return cm
}
})()
const kg = weight * 0.453592
const bmi = (() => {
if (!height || Number.isNaN(height)) return
const bmi = kg / Math.pow(height / 100, 2)
return bmi
})()
setOutput('bmi', bmi)
interface Datum {
weight: { lb: number, kg: number }
date: string
}
const data = (() => {
try {
const data = fs.readFileSync('./weight.json', 'utf-8')
const json = JSON.parse(data)
return json as Datum[]
} catch {
return []
}
})()
data.push({
weight: {
lb: weight, kg
},
date: new Date().toISOString().substring(0,10)
})
const sum = (a: number, b: Datum) => b.weight.lb + a
const mean = data.reduce(sum, 0) / data.length
const mean7 = data.slice(-7).reduce(sum, 0) / data.length
fs.writeFileSync('./weight.json', JSON.stringify(data, null, 2))
execSync('git add weight.json')
execSync("git commit -m 'Add Weight'")
execSync("git push origin HEAD")
const slug = process.env.GITHUB_REPOSITORY!
const [owner, repo] = slug.split('/')
const token = getInput('token')!
const octokit = github.getOctokit(token)
await octokit.rest.reactions.createForIssueComment({
repo, owner, comment_id: ctx.comment.id, content: "+1"
})
const bmiRender = bmi ? bmi.toFixed(1) : '-'
await octokit.rest.issues.updateComment({
repo, owner, comment_id: ctx.comment.id, body: `
# Weight
| Key | Value |
| :--- | ---: |
| Weight | *${weight.toFixed(1)}* lb |
| Weight | ${kg.toFixed(1)} kg |
| BMI | ${bmiRender} |
| Mean | ${mean.toFixed(1)} lbs |
| Mean7 | ${mean7.toFixed(1)} lbs |
`
})