-
Notifications
You must be signed in to change notification settings - Fork 1
/
wdidy.js
executable file
·211 lines (196 loc) · 6.33 KB
/
wdidy.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
const path = require('path')
const fs = require('fs')
const dotenv = require('dotenv')
const axios = require('axios')
const moment = require('moment')
require('dotenv').config({ path: path.join(__dirname, '.env') })
function createGitHubApi() {
return axios.create({
baseURL: 'https://api.github.com/',
headers: {
Authorization: `token ${process.env.GITHUBTOKEN}`,
},
})
}
function getLastWorkingDay() {
const today = moment()
let lastWorkingDay
switch (today.day()) {
case 1: // Monday
lastWorkingDay = today.clone().subtract(3, 'days')
break
case 0: // Sunday
lastWorkingDay = today.clone().subtract(2, 'days')
break
case 6: // Saturday
lastWorkingDay = today.clone().subtract(1, 'day')
break
default: // Weekdays (Tuesday - Friday)
lastWorkingDay = today.clone().subtract(1, 'day')
if (lastWorkingDay.day() === 0) {
lastWorkingDay.subtract(2, 'days')
} else if (lastWorkingDay.day() === 6) {
lastWorkingDay.subtract(1, 'day')
}
break
}
// Return an object containing the start and end dates
return {
start: lastWorkingDay.clone().startOf('day'),
end: lastWorkingDay.clone().endOf('day'),
}
}
async function fetchRepositories() {
const activeRepositories = 30
const perPage = 100 // Number of repositories to return per page (max 100)
const githubApi = createGitHubApi()
const { data: repos } = await githubApi.get(`user/repos?per_page=${perPage}`)
// Sort the repositories by updated_at in descending order
const sortedRepos = repos.sort(
(a, b) => new Date(b.updated_at) - new Date(a.updated_at),
)
// Return only the first activeRepositories repositories
const activeRepos = sortedRepos.slice(0, activeRepositories)
// Check if there are more active repositories on the next page
if (activeRepos.length < activeRepositories && repos.length === perPage) {
// If there are more repositories on the next page, recursively fetch the next page
const nextActiveRepos = await fetchRepositories(page + 1)
// Concatenate the active repositories from the next page with the current active repositories
return activeRepos.concat(
nextActiveRepos.slice(0, activeRepositories - activeRepos.length),
)
}
return activeRepos.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
}
async function getUser() {
try {
const githubApi = createGitHubApi()
const { data: user } = await githubApi.get(`user`)
return user
} catch (error) {
console.error(`No user found for this token`)
}
}
async function fetchCommits(repo, startDate, endDate, user) {
try {
const githubApi = createGitHubApi()
const { data: commits } = await githubApi.get(
`repos/${repo.owner.login}/${repo.name}/commits`,
{
params: {
since: startDate.toISOString(),
until: endDate.toISOString(),
},
},
)
const userCommits = commits.filter((commit) => commit?.author?.login === user?.login)
return userCommits
} catch (error) {
if (error.response.status === 409) {
console.error(`No commits found for repository: ${repo.name}`)
return []
}
throw error
}
}
async function generateBulletPoints(summary) {
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo',
messages: [
{
role: 'user',
content: `Create a numbered list of 3 to 6 key accomplishments from my recent GitHub commits for a concise stand-up summary. Use the provided commit summary as reference:\n\n${summary}`,
},
],
temperature: 0.7,
},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAIKEY}`,
},
},
)
const output = response.data.choices[0].message.content.trim()
const bulletPoints = output.split('\n')
return bulletPoints
} catch (error) {
console.error('Error generating bullet points:', error.message)
return []
}
}
function getLineFromUser() {
return new Promise((resolve, reject) => {
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
})
rl.on('line', (input) => {
rl.close()
resolve(input)
})
})
}
function saveEnvFile() {
const envPath = path.join(__dirname, '.env')
const envConfig = dotenv.parse(fs.readFileSync(envPath))
Object.assign(envConfig, {
GITHUBTOKEN: process.env.GITHUBTOKEN,
OPENAIKEY: process.env.OPENAIKEY,
})
fs.writeFileSync(envPath, stringifyEnv(envConfig))
}
function stringifyEnv(envConfig) {
let str = ''
for (const key in envConfig) {
str += `${key}=${envConfig[key]}\n`
}
return str
}
async function WDIDY() {
console.log('\n_____ What Did I Do Yesterday: _____\n')
if (!process.env.GITHUBTOKEN) {
console.log('Please provide your GitHub token:')
console.log('=> Generate a GitHub token here: https://github.com/settings/tokens/new')
process.env.GITHUBTOKEN = await getLineFromUser()
saveEnvFile()
}
if (!process.env.OPENAIKEY) {
console.log('Please provide your OpenAI API key:')
console.log('=> Generate an OpenAI key here: https://platform.openai.com/')
process.env.OPENAIKEY = await getLineFromUser()
saveEnvFile()
}
const { start, end } = getLastWorkingDay()
console.log(`\nThe last working day was on ${start.format('dddd, MMMM Do YYYY')}:\n`)
const user = await getUser()
const repos = await fetchRepositories()
for (const repo of repos) {
let summaryData = []
const commits = await fetchCommits(repo, start, end, user)
if (commits.length > 0) {
const commitMessages = commits.map((commit) => commit.commit.message)
summaryData.push({
repository: repo.name,
commitCount: commits.length,
commitMessages: commitMessages,
})
const summary = JSON.stringify(summaryData, null, 2)
if (summary !== '[]') {
console.log(`\nOn ${repo.name} repository:`)
const bulletPoints = await generateBulletPoints(summary)
for (const point of bulletPoints) {
console.log(`${point}`)
}
}
}
}
console.log('\n_____ End of the report _____\n')
return
}
WDIDY().catch((error) => {
console.error('An error occurred:', error.message)
})