-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear-start-clockify-timer.ts
More file actions
306 lines (252 loc) · 8.83 KB
/
linear-start-clockify-timer.ts
File metadata and controls
306 lines (252 loc) · 8.83 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
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
299
300
301
302
303
304
305
306
import type { Issue } from '@linear/sdk'
import confirm from '@inquirer/confirm'
import input from '@inquirer/input'
import select from '@inquirer/select'
import { LinearClient } from '@linear/sdk'
import axios from 'axios'
import parse from 'parse-duration'
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
import { dotenv, fs, minimist, sleep, spinner } from 'zx'
dotenv.config('.env')
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const cacheFile = path.join(__dirname, '.cache')
type State = {
linearApiKey?: string
linearUrl?: string
linearIssue?: Issue
clockifyApiKey?: string
clockifyWorkspaceId?: string
clockifyProjectId?: string
clockifyProjects: ClockifyProject[]
clockifyTimerStartDate?: Date
clockifyTimerId?: string
clockifyTimerParams?: Record<string, any>
}
type Flags = { linearUrl?: string }
type ClockifyProject = { id: string; name: string; clientName?: string }
type Cache = { linearClockifyTimer: { linearUrl?: string; clockifyWorkspaceId?: string; clockifyProjectId?: string } }
class LinearStartClockifyTimer {
private cache: Cache = { linearClockifyTimer: {} }
private state: State = {
linearApiKey: process.env.LINEAR_API_KEY,
clockifyApiKey: process.env.CLOCKIFY_API_KEY,
clockifyProjects: [],
}
private flags: Flags = {}
private linear = new LinearClient({ apiKey: this.state.linearApiKey })
private clockify = axios.create({
baseURL: 'https://api.clockify.me/api/v1',
headers: { 'X-Api-Key': this.state.clockifyApiKey },
})
constructor() {
const validations = this.validate()
if (validations.includes(false)) {
console.error('❌ Validation failed. Please check your environment variables.')
process.exit(1)
}
}
private validate() {
const validations = []
if (!this.state.linearApiKey) {
console.error('❌ LINEAR_API_KEY is required. Please add it to your .env file.')
validations.push(false)
}
if (!this.state.clockifyApiKey) {
console.error('❌ CLOCKIFY_API_KEY is required. Please add it to your .env file.')
validations.push(false)
}
return validations
}
private async writeCache(cache: Cache['linearClockifyTimer']) {
await fs.writeJson(cacheFile, {
...this.cache,
linearClockifyTimer: {
...this.cache.linearClockifyTimer,
...cache,
},
})
await this.getCache()
}
async getCache() {
try {
this.cache = await fs.readJson(cacheFile)
this.cache.linearClockifyTimer = this.cache.linearClockifyTimer ?? {}
} catch (_e) {
this.cache = { linearClockifyTimer: {} }
}
}
parseFlags() {
const {
_: [url],
} = minimist(process.argv.slice(2))
this.flags.linearUrl = url
}
async verifyClockifyWorkspace() {
if (this.cache.linearClockifyTimer.clockifyWorkspaceId) {
this.state.clockifyWorkspaceId = this.cache.linearClockifyTimer.clockifyWorkspaceId
return
}
// Fetch available workspaces from Clockify
const workspacesResponse = await this.clockify.get('/workspaces')
const workspaces = workspacesResponse.data
if (!workspaces || workspaces.length === 0) {
console.error('❌ No workspaces found. Please check your Clockify API key.')
process.exit(1)
}
// Present workspaces to user for selection
this.state.clockifyWorkspaceId = await select({
message: 'Select a Clockify workspace:',
choices: workspaces.map((workspace: any) => ({
name: `${workspace.name} (${workspace.id})`,
value: workspace.id,
})),
})
// Update cache with selected workspace
await this.writeCache({ clockifyWorkspaceId: this.state.clockifyWorkspaceId })
}
async getClockifyProjects() {
// Fetch available projects from the selected workspace
const projectsResponse = await this.clockify.get<ClockifyProject[]>(
`/workspaces/${this.state.clockifyWorkspaceId}/projects`,
)
const projects = projectsResponse.data
if (!projects || projects.length === 0) {
console.error('❌ No projects found in the selected workspace.')
process.exit(1)
}
this.state.clockifyProjects = projects
}
async askForClockifyProject() {
// Present projects to user for selection (always prompt, but use cache as default)
this.state.clockifyProjectId = await select({
message: 'Select a project:',
choices: this.state.clockifyProjects.map((project: any) => ({
name: `${project.name} (${project.clientName || 'No client'})`,
value: project.id,
})),
default: this.cache.linearClockifyTimer.clockifyProjectId || undefined,
})
await this.writeCache({ clockifyProjectId: this.state.clockifyProjectId })
}
async askForLinearIssueUrl() {
// Get Linear issue URL (first step)
this.state.linearUrl = await input({
message: 'Enter the Linear issue URL:',
default: this.flags.linearUrl ?? this.cache.linearClockifyTimer.linearUrl ?? '',
required: true,
})
// Validate Linear URL format
const linearIssueId = this.state.linearUrl.match(/linear\.app\/[^/]+\/issue\/([^/]+)/)?.[1]
if (!linearIssueId) {
console.error('❌ Invalid Linear issue URL. Please provide a valid URL.')
process.exit(1)
}
// Fetch Linear issue details
this.state.linearIssue = await this.linear.issue(linearIssueId)
if (!this.state.linearIssue) {
console.error(`❌ Issue with ID ${linearIssueId} not found.`)
process.exit(1)
}
await this.writeCache({ linearUrl: this.state.linearUrl })
}
async askForConfirmation() {
const confirmation = await confirm({
message: `Start timer?`,
default: true,
})
if (confirmation) {
await this.startClockifyTimer()
let stopSpinner = true
process.on('SIGINT', async () => {
stopSpinner = false
process.stdout.write('\r')
await sleep(1000)
process.stdout.write('\r')
await this.stopClockifyTimer()
})
while (stopSpinner) {
await this.logElapsedTime()
}
} else {
const time = await input({
message: 'Enter time to add (e.g., 1h30m, 45m):',
required: true,
})
const timeInMs = parse(time)
this.startClockifyTimer(timeInMs)
}
}
async startClockifyTimer(duration?: number | null) {
// Extract Linear issue details
const { url: issueUrl, title: linearTitle, identifier: linearId } = this.state.linearIssue ?? {}
let start: Date | undefined
let end: Date | undefined
if (duration) {
start = new Date(Date.now() - duration)
end = new Date()
} else {
start = new Date()
end = undefined
}
// Start Clockify timer
this.state.clockifyTimerStartDate = start
this.state.clockifyTimerParams = {
billable: true,
description: `[${linearId}] ${linearTitle} - ${issueUrl}`,
projectId: this.state.clockifyProjectId,
start: this.state.clockifyTimerStartDate.toISOString(),
end: end ? end.toISOString() : undefined,
type: 'REGULAR',
}
const startTimerResponse = await this.clockify.post(
`/workspaces/${this.state.clockifyWorkspaceId}/time-entries`,
this.state.clockifyTimerParams,
)
if (startTimerResponse.statusText !== 'Created') {
console.error('❌ Failed to start timer:', startTimerResponse)
process.exit(1)
}
this.state.clockifyTimerId = startTimerResponse.data.id
}
async stopClockifyTimer() {
const stopTracking = await confirm({ message: 'Stop time tracking?', default: true })
if (stopTracking) {
await this.clockify.put(
`/workspaces/${this.state.clockifyWorkspaceId}/time-entries/${this.state.clockifyTimerId}`,
{
...this.state.clockifyTimerParams,
end: new Date().toISOString(),
},
)
}
console.info(`Total Time Logged: ${this.calculateElapsedTime()}`)
process.exit(0)
}
calculateElapsedTime() {
const elapsed = Date.now() - (this.state.clockifyTimerStartDate?.getTime() || 0)
const seconds = Math.floor(elapsed / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const remainingSeconds = seconds % 60
const remainingMinutes = minutes % 60
const parts: string[] = []
if (hours > 0) parts.push(`${hours}h`)
if (remainingMinutes > 0 || hours > 0) parts.push(`${remainingMinutes}m`)
parts.push(`${remainingSeconds}s`)
return parts.join(' ')
}
logElapsedTime() {
return spinner(this.calculateElapsedTime(), () => sleep(1000))
}
}
const timer = new LinearStartClockifyTimer()
timer.parseFlags()
await timer.getCache()
await timer.verifyClockifyWorkspace()
const projectsPromise = timer.getClockifyProjects()
await timer.askForLinearIssueUrl()
await projectsPromise
await timer.askForClockifyProject()
await timer.askForConfirmation()