forked from kriskbx/gitlab-time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtimekeeper.js
More file actions
executable file
路325 lines (260 loc) 路 9.3 KB
/
Copy pathtimekeeper.js
File metadata and controls
executable file
路325 lines (260 loc) 路 9.3 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import Fs from '../core/filesystem.js';
import Frame from './storage/frame.js';
import Issue from '../core/api/issue.js';
import MergeRequest from '../core/api/mergeRequest.js';
import FrameCollection from './storage/frameCollection.js';
const classes = {
issue: Issue,
merge_request: MergeRequest
};
const CURRENT_FILE = '~current.tmp';
class Timekeeper {
constructor(config) {
this.config = config;
}
/**
* Path to the pointer file that names the currently
* active frame (has no contents if stopped). config.frameDir
* can change after construction (eg. once `project` is set),
* so this stays a getter rather than a value cached once.
*/
get currentFile() {
return Fs.join(this.config.frameDir, CURRENT_FILE);
}
/**
* The currently active frame, or null if none is running.
* Only one frame can be active at a time, so this is a direct
* lookup instead of scanning every frame file.
* @returns {Frame|null}
*/
getCurrentFrame() {
if (!Fs.exists(this.currentFile)) {
let running = new FrameCollection(this.config).frames.find(frame => frame.stop === null);
Fs.writeText(this.currentFile, running ? running.id : '');
return running;
}
let id = Fs.readText(this.currentFile).trim();
if (!id) return null;
let f = Frame.fromFile(this.config, Fs.join(this.config.frameDir, id + '.json'));
if(f.stop != null) {
// lost sync. reset
Fs.remove(this.currentFile);
let running = new FrameCollection(this.config).frames.find(frame => frame.stop === null);
Fs.writeText(this.currentFile, running ? running.id : '');
f = running;
}
return f;
}
/**
* Records the given frame as the currently active one, or clears
* it when called with null/undefined.
* @param {Frame|null} [frame]
*/
setCurrentFrame(frame) {
Fs.writeText(this.currentFile, frame ? frame.id : '');
}
/**
* Frames that still need a GitLab time record: their tracked duration
* doesn't match what's already been recorded as notes.
* @returns {Promise<FrameCollection>}
*/
async pendingFrames() {
let frames = new FrameCollection(this.config);
frames.filter(frame => !(Math.ceil(frame.duration) === frame.notes.reduce((n, m) => (n + m.time), 0)));
return frames;
}
/**
* Group all finished, synced frames by year and month (based on
* start time), for archiving. Refuses to run while frames are
* still waiting to be synced to GitLab.
* @returns {Promise<Object>} {year: {month: [frame, ...]}}
*/
async archiveInit() {
let pending = await this.pendingFrames();
if (pending.length > 0) {
throw new Error('Not all frames are synced yet. Run `gtt sync` first.');
}
let grouped = {};
await new FrameCollection(this.config).forEach(frame => {
if (frame.stop === null) return;
let year = frame.date.format('YYYY'),
month = frame.date.format('MM');
if (!grouped[year]) grouped[year] = {};
if (!grouped[year][month]) grouped[year][month] = [];
grouped[year][month].push(frame);
});
return grouped;
}
/**
* Sync the given frames to GitLab: resolve or create their issue/merge
* request, refresh the frame title, then push a time record note for
* whatever duration hasn't been recorded yet. One call, three internal
* phases (resolve/details/update) - callers no longer choreograph them.
* @param {FrameCollection} frames typically the result of pendingFrames()
* @param {Object} [hooks]
* @param {(phase: 'resolve'|'details'|'update', total: number) => void} [hooks.onPhase] called once per phase, before it starts
* @param {() => void} [hooks.onProgress] called after each frame is resolved/updated
* @returns {Promise<FrameCollection>} the frames that were synced
*/
async sync(frames, {onPhase = () => {}, onProgress = () => {}} = {}) {
if (frames.length === 0) return frames;
let resources = {};
onPhase('resolve', frames.length);
await frames.forEach(async frame => {
let project = frame.project,
type = frame.resource.type,
id = frame.resource.id;
if (!(project in resources)) {
resources[project] = {issue: {}, merge_request: {}};
}
if (id in resources[project][type]) {
return;
}
resources[project][type][id] = new classes[type](this.config, {});
try {
await resources[project][type][id].make(project, id, frame.resource.new);
} catch (error) {
throw new Error(`Could not resolve ${type} ${id} on "${project}": ${error.message ?? error}`);
}
onProgress();
});
onPhase('details', frames.length);
await frames.forEach(frame => {
let project = frame.project,
type = frame.resource.type,
id = frame.resource.id;
if (id in resources[project][type]) {
frame.title = resources[project][type][id].data.title;
}
});
onPhase('update', frames.length);
await frames.forEach(async frame => {
let time = frame.duration,
project = frame.project,
type = frame.resource.type,
id = frame.resource.id;
if (frame.notes.length > 0)
time = Math.ceil(frame.duration) - parseInt(frame.notes.reduce((n, m) => (n + m.time), 0));
try {
await this._addTime(resources, frame, time);
} catch (error) {
throw new Error(`Could not update ${type} ${id} on ${project}: ${error.message ?? error}`);
}
onProgress();
});
return frames;
}
async _addTime(resources, frame, time) {
let resource = resources[frame.project][frame.resource.type][frame.resource.id];
let createdNote = await resource.createTime(Math.ceil(time), frame._stop, frame.note);
let noteid = createdNote ?.id?.split('/')?.pop();
// fallback, if gitlab does not return the created note
if(!isNaN(noteid)) {
noteid = parseInt(noteid)
} else {
await resource.getNotes()
noteid = resource.notes[0].id;
}
if (frame.resource.new) {
delete frame.resource.new;
frame.resource.title = frame.resource.id;
frame.resource.id = resource.data.iid;
}
frame.notes.push({
id: noteid,
time: Math.ceil(time)
});
frame.write(true);
}
/**
*
* @returns {Promise}
*/
async status() {
let frame = this.getCurrentFrame();
if (!frame) return [];
return [frame];
}
/**
*
* @returns {Promise}
*/
async log() {
let frames = {},
times = {};
await new FrameCollection(this.config)
.forEach(frame => {
if (frame.stop === null) return;
let date = frame.date.format('YYYY-MM-DD');
if (!frames[date]) frames[date] = [];
if (!times[date]) times[date] = 0;
frames[date].push(frame);
times[date] += Math.ceil(frame.duration);
});
return {frames, times};
}
/**
*
* @returns {Promise}
*/
async all() {
let frames = [];
await new FrameCollection(this.config)
.forEach(frame => {
frames.push(frame);
});
return {frames};
}
/**
*
* @returns {Promise}
*/
async resume(frame) {
if (!frame) {
throw new Error("No task found to resume.");
}
return this.start(frame.project, frame.resource.type, frame.resource.id, frame.note);
}
list(project, type, state, my) {
this.config.set('project', project);
return classes[type].list(this.config, this.config.get('project'), state, my);
}
/**
*
* @param project
* @param type
* @param id
* @returns {Promise}
*/
async start(project, type, id, note) {
this.config.set('project', project);
if (this.getCurrentFrame())
throw new Error("Already running. Please stop it first with 'gtt stop'.");
let frame = new Frame(this.config, id, type, note).startMe();
this.setCurrentFrame(frame);
return frame;
}
/**
*
* @returns {Promise}
*/
async stop() {
let frame = this.getCurrentFrame();
if (!frame) throw new Error('No projects started.');
frame.stopMe();
this.setCurrentFrame(null);
return [frame];
}
/**
*
* @returns {Promise}
*/
async cancel() {
let frame = this.getCurrentFrame();
if (!frame) throw new Error('No projects started.');
Fs.remove(Fs.join(this.config.frameDir, frame.id + '.json'));
this.setCurrentFrame(null);
return [frame];
}
}
export default Timekeeper;