Repository navigation
Expand file tree
/
Copy pathgithub-activity.js
More file actions
105 lines (86 loc) · 2.18 KB
/
Copy pathgithub-activity.js
File metadata and controls
105 lines (86 loc) · 2.18 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
#!/usr/bin/env node
"use strict";
const https = require("https");
function usage(){
console.error("Usage: github-activity <username>");
}
function capitalise(text) {
if (!text || typeof text !== "string") return stringify(text ?? "");
return text[0].toUpperCase() + text.slice(1);
}
/**
* Makes an HTTPS GET request and returns parsed JSON
*/
function requestJson(url) {
return new Promise((resolve, reject) => {
const req = https.request(
url,
{
method: "GET",
headers: {
"User-Agent": "github-activity-cli",
"Accept": "application/vnd.github+json",
},
},
(res) => {
let data = "";
res.on("data", chunk => (data += chunk));
res.on("end", () => {
const status = res.statusCode;
if (status === 404) {
reject(new Error("User not found"));
return;
}
if (status !== 200) {
reject(new Error(`GitHub API error (${status})`));
return;
}
try {
resolve(JSON.parse(data));
} catch {
reject(new Error("Invalid JSON response"));
}
});
}
);
req.on("error", err => reject(err));
req.end();
});
}
/**
* Converts GitHub events into readable lines
*/
function formatEvent(event) {
const type = event.type;
const repo = event.repo?.name ?? "unknown repo";
const payload = event.payload ?? {};
if (type === "PushEvent") {
return `- Pushed ${payload.size ?? "some"} commits to ${repo}`;
}
if (type === "IssuesEvent") {
return `- ${capitalize(payload.action)} an issue in ${repo}`;
}
if (type === "WatchEvent") {
return `- Starred ${repo}`;
}
return `- ${type} on ${repo}`;
}
/**
* Program entry point
*/
async function main() {
const username = process.argv[2];
if (!username) {
usage();
process.exit(1);
}
const url = `https://api.github.com/users/${username}/events/public`;
const events = await requestJson(url);
events.slice(0, 15).forEach(event => {
console.log(formatEvent(event));
});
}
main().catch(err => {
console.error("Error:", err.message);
process.exit(1);
});