-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_queries_developer.js
More file actions
632 lines (559 loc) Β· 21 KB
/
Copy pathlinear_queries_developer.js
File metadata and controls
632 lines (559 loc) Β· 21 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import 'dotenv/config';
import { LinearClient } from '@linear/sdk';
import { hasMergedPR } from './team_issues_report.js';
// Load API key from environment variable
const apiKey = process.env.LINEAR_API_KEY;
const accessToken = process.env.LINEAR_ACCESS_TOKEN;
if (!apiKey && !accessToken) {
throw new Error('Please set either LINEAR_API_KEY or LINEAR_ACCESS_TOKEN in your .env file');
}
// With Personal API Key or OAuth 2.0 Access Token
const linearClient = apiKey
? new LinearClient({ apiKey })
: new LinearClient({ accessToken });
/**
* Normalize line terminators to standard \n
* Replaces Unicode line separators (U+2028) and paragraph separators (U+2029)
* with standard newline characters
*/
function normalizeLineTerminators(text) {
if (!text) return text;
return text
.replace(/\u2028/g, '\n') // Line Separator
.replace(/\u2029/g, '\n') // Paragraph Separator
.replace(/\r\n/g, '\n') // Windows line endings
.replace(/\r/g, '\n'); // Old Mac line endings
}
/**
* Get user activity including comments, reactions, and issue interactions
* @param {string} userEmail - Email of the user to track
* @param {Object} options - Optional filters
* @param {Date} options.since - Only get activity since this date
* @param {number} options.limit - Maximum number of results per query
* @param {boolean} options.includeArchived - Linear `includeArchived` on issues and comments queries (default false)
*/
async function getUserActivity(userEmail, options = {}) {
const { since, limit = 100, includeArchived = false } = options;
try {
// First, find the user by email (with pagination to get all users)
const userSpinner = createSpinner('Searching for user');
userSpinner.start();
let user = null;
let hasNextPage = true;
let after = null;
const allUsers = [];
// Fetch all users with pagination
while (hasNextPage) {
const usersResponse = await linearClient.users({
first: 50,
...(after && { after }),
});
allUsers.push(...usersResponse.nodes);
hasNextPage = usersResponse.pageInfo.hasNextPage;
after = usersResponse.pageInfo.endCursor;
}
userSpinner.stop();
console.log(` Found ${allUsers.length} users in workspace`);
// Try to find user by email (case-insensitive)
user = allUsers.find(u =>
u.email && u.email.toLowerCase() === userEmail.toLowerCase()
);
// If not found by exact email, try partial match
if (!user) {
user = allUsers.find(u =>
u.email && u.email.toLowerCase().includes(userEmail.toLowerCase())
);
}
// Debug: show first few users if not found
if (!user) {
console.log('\n Available users (first 10):');
allUsers.slice(0, 10).forEach(u => {
console.log(` - ${u.name} (${u.email || 'no email'})`);
});
throw new Error(`User with email ${userEmail} not found. Found ${allUsers.length} users total.`);
}
console.log(`\nπ Fetching activity for: ${user.name} (${user.email})\n`);
const activity = {
user: {
id: user.id,
name: user.name,
email: user.email,
},
comments: [],
reactions: [],
issueUpdates: [],
issueCreations: [],
issueAssignments: [],
withMergedPRs: 0,
};
// Get all comments by this user
const commentsSpinner = createSpinner('Fetching comments');
commentsSpinner.start();
const commentsFilter = {
user: { id: { eq: user.id } },
};
if (since) {
commentsFilter.createdAt = { gte: since };
}
const comments = await linearClient.comments({
filter: commentsFilter,
first: limit,
...(includeArchived && { includeArchived: true }),
});
for (const comment of comments.nodes) {
const issue = await comment.issue;
activity.comments.push({
id: comment.id,
body: normalizeLineTerminators(comment.body || ''),
createdAt: comment.createdAt,
issue: {
id: issue?.id,
title: issue?.title,
identifier: issue?.identifier,
url: issue?.url,
},
});
}
commentsSpinner.stop();
console.log(` Found ${comments.nodes.length} comment(s)`);
// Get reactions by this user
const reactionsSpinner = createSpinner('Fetching reactions');
reactionsSpinner.start();
let reactions = { nodes: [] };
let reactionsByIssue = new Map();
try {
reactions = await linearClient.reactions({
filter: {
user: { id: { eq: user.id } },
...(since && { createdAt: { gte: since } }),
},
first: limit,
});
// Group reactions by issue
for (const reaction of reactions.nodes) {
const issue = await reaction.issue;
if (issue) {
if (!reactionsByIssue.has(issue.id)) {
reactionsByIssue.set(issue.id, []);
}
reactionsByIssue.get(issue.id).push({
emoji: reaction.emoji,
createdAt: reaction.createdAt,
});
// Also add to reactions array
activity.reactions.push({
id: reaction.id,
emoji: reaction.emoji,
createdAt: reaction.createdAt,
issue: {
id: issue.id,
title: issue.title,
identifier: issue.identifier,
url: issue.url,
},
});
}
}
reactionsSpinner.stop();
} catch (err) {
reactionsSpinner.stop();
console.warn(' Warning: Could not fetch reactions:', err.message);
console.warn(' Reactions feature may not be available in your Linear workspace');
}
// Get issues where user has interacted (commented or reacted)
const interactionsSpinner = createSpinner('Fetching issue interactions');
interactionsSpinner.start();
const issueIdsWithActivity = new Set();
// Add issue IDs from comments
activity.comments.forEach(comment => {
if (comment.issue?.id) {
issueIdsWithActivity.add(comment.issue.id);
}
});
// Add issue IDs from reactions
reactionsByIssue.forEach((_, issueId) => {
issueIdsWithActivity.add(issueId);
});
// Fetch issue details for issues with activity
for (const issueId of issueIdsWithActivity) {
try {
const issue = await linearClient.issue(issueId);
if (issue) {
const issueComments = activity.comments.filter(c => c.issue?.id === issueId);
const issueReactions = reactionsByIssue.get(issueId) || [];
activity.issueUpdates.push({
issue: {
id: issue.id,
title: issue.title,
identifier: issue.identifier,
url: issue.url,
state: (await issue.state)?.name,
},
comments: issueComments.map(c => ({
id: c.id,
body: c.body,
createdAt: c.createdAt,
})),
reactions: issueReactions,
lastUpdated: issue.updatedAt,
});
}
} catch (err) {
console.warn(` Warning: Could not fetch issue ${issueId}:`, err.message);
}
}
interactionsSpinner.stop();
console.log(` Found ${activity.issueUpdates.length} issue interaction(s)`);
// Get issues assigned to user
const assignedSpinner = createSpinner('Fetching issues assigned to user');
assignedSpinner.start();
const assignedFilter = {
assignee: { id: { eq: user.id } },
};
if (since) {
assignedFilter.updatedAt = { gte: since };
}
const assignedIssues = await linearClient.issues({
filter: assignedFilter,
first: limit,
...(includeArchived && { includeArchived: true }),
});
console.log(` Found ${assignedIssues.nodes.length} assigned issue(s)`);
for (const issue of assignedIssues.nodes) {
const state = await issue.state;
activity.issueAssignments.push({
id: issue.id,
title: issue.title,
identifier: issue.identifier,
url: issue.url,
state: state?.name,
updatedAt: issue.updatedAt,
description: normalizeLineTerminators(issue.description || ''),
});
}
assignedSpinner.stop();
console.log(` Found ${assignedIssues.nodes.length} assigned issue(s)`);
// Get issues created by user
const createdSpinner = createSpinner('Fetching issues created by user');
createdSpinner.start();
const createdFilter = {
creator: { id: { eq: user.id } },
};
if (since) {
createdFilter.updatedAt = { gte: since };
}
const createdIssues = await linearClient.issues({
filter: createdFilter,
first: limit,
...(includeArchived && { includeArchived: true }),
});
console.log(` Found ${createdIssues.nodes.length} created issue(s)`);
for (const issue of createdIssues.nodes) {
activity.issueCreations.push({
id: issue.id,
title: issue.title,
identifier: issue.identifier,
url: issue.url,
createdAt: issue.createdAt,
updatedAt: issue.updatedAt,
description: normalizeLineTerminators(issue.description || ''),
});
}
createdSpinner.stop();
console.log(` Found ${createdIssues.nodes.length} created issue(s)`);
const mergedSpinner = createSpinner('Checking issues for merged PRs');
mergedSpinner.start();
let mergedPRCount = 0;
for (const issue of assignedIssues.nodes) {
if (await hasMergedPR(issue)) {
mergedPRCount++;
}
}
const assignedIssueIds = new Set(assignedIssues.nodes.map((i) => i.id));
for (const issue of createdIssues.nodes) {
if (!assignedIssueIds.has(issue.id) && (await hasMergedPR(issue))) {
mergedPRCount++;
}
}
mergedSpinner.stop();
console.log(` Found ${mergedPRCount} issue(s) with merged PR(s) (assigned + created, deduplicated)`);
activity.withMergedPRs = mergedPRCount;
return activity;
} catch (error) {
console.error('Error fetching user activity:', error);
throw error;
}
}
/**
* Display summary of user activity (minimal console output)
*/
function displaySummary(activity) {
console.log('\n' + '='.repeat(80));
console.log(`π ACTIVITY SUMMARY FOR ${activity.user.name.toUpperCase()}`);
console.log('='.repeat(80));
console.log(`\n Total Comments: ${activity.comments.length}`);
console.log(` Issue Interactions: ${activity.issueUpdates.length}`);
console.log(` Issues Created: ${activity.issueCreations.length}`);
console.log(` Issues Assigned: ${activity.issueAssignments.length}`);
console.log(` Issues with merged PRs: ${activity.withMergedPRs}`);
console.log('='.repeat(80) + '\n');
}
/**
* Show loading spinner with timer
*/
function createSpinner(message) {
const frames = ['β ', 'β ', 'β Ή', 'β Έ', 'β Ό', 'β ΄', 'β ¦', 'β §', 'β ', 'β '];
let frameIndex = 0;
let startTime = Date.now();
let intervalId = null;
const update = () => {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
const frame = frames[frameIndex % frames.length];
process.stdout.write(`\r${frame} ${message} (${elapsed}s)`);
frameIndex++;
};
return {
start: () => {
startTime = Date.now();
intervalId = setInterval(update, 100);
},
stop: () => {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
process.stdout.write(`\rβ
${message} completed in ${elapsed}s\n`);
}
};
}
/**
* Format and display user activity in a readable way (for file export)
* This function is kept for backward compatibility but doesn't output to console
*/
function displayActivity(activity) {
// This function is now only used internally for generating text reports
// Console output is handled by displaySummary()
return generateTextReport(activity);
}
/**
* Generate formatted text report
*/
function generateTextReport(activity) {
let report = '\n' + '='.repeat(80) + '\n';
report += `π ACTIVITY REPORT FOR ${activity.user.name.toUpperCase()}\n`;
report += '='.repeat(80) + '\n';
report += `\nπ COMMENTS (${activity.comments.length}):\n`;
if (activity.comments.length === 0) {
report += ' No comments found\n';
} else {
activity.comments.forEach((comment, idx) => {
report += `\n ${idx + 1}. Issue: ${comment.issue.identifier} - ${comment.issue.title}\n`;
report += ` Date: ${new Date(comment.createdAt).toLocaleString()}\n`;
report += ` URL: ${comment.issue.url}\n`;
report += ` Comment:\n`;
// Indent the comment body for better readability
const normalizedBody = normalizeLineTerminators(comment.body);
const commentLines = normalizedBody.split('\n');
commentLines.forEach(line => {
report += ` ${line}\n`;
});
});
}
report += `\n㪠ISSUE INTERACTIONS (${activity.issueUpdates.length}):\n`;
if (activity.issueUpdates.length === 0) {
report += ' No issue interactions found\n';
} else {
activity.issueUpdates.forEach((interaction, idx) => {
report += `\n ${idx + 1}. Issue: ${interaction.issue.identifier} - ${interaction.issue.title}\n`;
report += ` State: ${interaction.issue.state}\n`;
report += ` Comments: ${interaction.comments.length}\n`;
report += ` Reactions: ${interaction.reactions.length}\n`;
if (interaction.reactions.length > 0) {
report += ` Reaction emojis: ${interaction.reactions.map(r => r.emoji).join(', ')}\n`;
}
report += ` Last Updated: ${new Date(interaction.lastUpdated).toLocaleString()}\n`;
report += ` URL: ${interaction.issue.url}\n`;
});
}
report += `\n⨠ISSUES CREATED (${activity.issueCreations.length}):\n`;
if (activity.issueCreations.length === 0) {
report += ' No issues created\n';
} else {
activity.issueCreations.forEach((issue, idx) => {
report += `\n ${idx + 1}. ${issue.identifier} - ${issue.title}\n`;
report += ` Created: ${new Date(issue.createdAt).toLocaleString()}\n`;
if (issue.description) {
report += ` Description:\n`;
const normalizedDesc = normalizeLineTerminators(issue.description);
const descLines = normalizedDesc.split('\n');
descLines.forEach(line => {
report += ` ${line}\n`;
});
}
});
}
report += `\nπ ISSUES ASSIGNED (${activity.issueAssignments.length}):\n`;
if (activity.issueAssignments.length === 0) {
report += ' No issues assigned\n';
} else {
activity.issueAssignments.forEach((issue, idx) => {
report += `\n ${idx + 1}. ${issue.identifier} - ${issue.title} [${issue.state}]\n`;
if (issue.updatedAt) {
report += ` Updated: ${new Date(issue.updatedAt).toLocaleString()}\n`;
}
if (issue.description) {
report += ` Description:\n`;
const normalizedDesc = normalizeLineTerminators(issue.description);
const descLines = normalizedDesc.split('\n');
descLines.forEach(line => {
report += ` ${line}\n`;
});
}
});
}
report += '\n' + '='.repeat(80) + '\n';
report += '\nπ SUMMARY:\n';
report += ` Total Comments: ${activity.comments.length}\n`;
report += ` Issue Interactions: ${activity.issueUpdates.length}\n`;
report += ` Issues Created: ${activity.issueCreations.length}\n`;
report += ` Issues Assigned: ${activity.issueAssignments.length}\n`;
report += ` Issues with merged PRs: ${activity.withMergedPRs}\n`;
report += '='.repeat(80) + '\n';
return report;
}
/**
* Export activity to text file
*/
async function exportActivityToText(activity, filename = null) {
const fs = await import('fs/promises');
const path = await import('path');
// Create reports directory if it doesn't exist
const reportsDir = 'reports';
try {
await fs.mkdir(reportsDir, { recursive: true });
} catch (err) {
// Directory might already exist, that's fine
}
if (!filename) {
// Generate filename based on user and date
const userSlug = activity.user.email.split('@')[0].replace(/[^a-z0-9]/gi, '_');
const dateStr = new Date().toISOString().split('T')[0];
filename = `activity_report_${userSlug}_${dateStr}.txt`;
}
// Ensure filename is in the reports directory
const filepath = path.join(reportsDir, filename);
const report = generateTextReport(activity);
await fs.writeFile(filepath, report, 'utf8');
return filepath;
}
/**
* Export activity to JSON file
*/
async function exportActivityToJSON(activity, filename = null) {
const fs = await import('fs/promises');
const path = await import('path');
// Create reports directory if it doesn't exist
const reportsDir = 'reports';
try {
await fs.mkdir(reportsDir, { recursive: true });
} catch (err) {
// Directory might already exist, that's fine
}
if (!filename) {
// Generate filename based on user and date
const userSlug = activity.user.email.split('@')[0].replace(/[^a-z0-9]/gi, '_');
const dateStr = new Date().toISOString().split('T')[0];
filename = `activity_report_${userSlug}_${dateStr}.json`;
}
// Ensure filename is in the reports directory
const filepath = path.join(reportsDir, filename);
await fs.writeFile(filepath, JSON.stringify(activity, null, 2), 'utf8');
return filepath;
}
// Main execution
async function main() {
// Get user email from command line or environment variable
const userEmail = process.argv[2] || process.env.USER_EMAIL;
if (!userEmail) {
console.error('β Please provide a user email as an argument:');
console.error(' node linear_queries.js user@example.com');
console.error('\n Or set USER_EMAIL in your .env file');
process.exit(1);
}
// Optional: Get activity since a specific date (e.g., last 30 days)
// Pass 0 or "all" to get all activity
const daysBackArg = process.argv[3];
let daysBack = 30;
let since = null;
if (daysBackArg) {
if (daysBackArg.toLowerCase() === 'all' || daysBackArg === '0') {
daysBack = null;
console.log('π
Fetching ALL activity (no date filter)\n');
} else {
daysBack = parseInt(daysBackArg);
if (isNaN(daysBack)) {
console.error(`β Invalid days argument: ${daysBackArg}. Use a number or "all"`);
process.exit(1);
}
since = new Date();
since.setDate(since.getDate() - daysBack);
console.log(`π
Fetching activity from the last ${daysBack} days (since ${since.toLocaleDateString()})\n`);
}
} else {
since = new Date();
since.setDate(since.getDate() - daysBack);
console.log(`π
Fetching activity from the last ${daysBack} days (since ${since.toLocaleDateString()})\n`);
}
const includeArchived =
process.env.INCLUDE_ARCHIVED_ISSUES === '1' ||
process.env.INCLUDE_ARCHIVED_ISSUES === 'true' ||
process.argv.includes('--include-archived');
if (includeArchived) {
console.log('π¦ Including archived issues in issues & comments queries (Linear includeArchived)\n');
}
try {
const activity = await getUserActivity(userEmail, { since, limit: 100, includeArchived });
// Check if we got zero results but there might be activity outside the date range
const totalActivity = activity.comments.length + activity.issueUpdates.length +
activity.issueCreations.length + activity.issueAssignments.length;
if (totalActivity === 0 && since) {
console.log('\nβ οΈ No activity found in the specified date range.');
console.log(' Try running without a date filter to see all activity:');
console.log(` node linear_queries.js ${userEmail} all\n`);
}
// Show summary in console
displaySummary(activity);
// Show loading spinner while generating and saving report
const spinner = createSpinner('Generating report');
spinner.start();
try {
// Automatically save text report to file
const reportFile = await exportActivityToText(activity);
// Optionally export to JSON
let jsonFile = null;
if (process.argv.includes('--export') || process.argv.includes('--json')) {
jsonFile = await exportActivityToJSON(activity);
}
spinner.stop();
console.log(`\nβ
Report saved to: ${reportFile}`);
if (jsonFile) {
console.log(`β
JSON exported to: ${jsonFile}`);
}
console.log('');
} catch (err) {
spinner.stop();
throw err;
}
} catch (error) {
console.error('β Error:', error.message);
process.exit(1);
}
}
// Run if this file is executed directly (not imported)
const isMainModule = import.meta.url === `file://${process.argv[1]}` ||
process.argv[1]?.endsWith('linear_queries.js');
if (isMainModule) {
main();
}
export { getUserActivity, displayActivity, displaySummary, exportActivityToJSON, exportActivityToText, generateTextReport };