-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
236 lines (210 loc) · 6.27 KB
/
server.js
File metadata and controls
236 lines (210 loc) · 6.27 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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const fs = require("fs");
const path = require("path");
/**
* Environment variables
*/
const USERNAME = process.env.GITHUB_USERNAME;
const TOKEN = process.env.GITHUB_TOKEN;
const PORT = process.env.PORT || 3000;
/**
* File paths
*/
const CACHE_FILE = path.join(__dirname, "cache.json");
const BLACKLIST_FILE = path.join(__dirname, "blacklist.json");
/**
* In-memory data structures
*/
let cache = {};
let blacklist = {
repos: [],
paths: [],
languages: [],
};
/**
* Load the cache or blacklist data from file
* @param {string} filePath - The path to the file
* @param {Object} defaultValue - The default value if file does not exist or is invalid
* @returns {Object} - The loaded data or default value
*/
function loadDataFromFile(filePath, defaultValue) {
if (fs.existsSync(filePath)) {
try {
const data = JSON.parse(fs.readFileSync(filePath));
if (data && typeof data === "object") {
return data;
}
} catch (err) {
console.error(`Error reading ${filePath}:`, err);
}
} else {
fs.writeFileSync(filePath, JSON.stringify(defaultValue));
}
return defaultValue;
}
cache = loadDataFromFile(CACHE_FILE, cache);
blacklist = loadDataFromFile(BLACKLIST_FILE, blacklist);
const app = express();
app.use(bodyParser.json());
/**
* Save the cache to a file
*/
async function saveCacheToFile() {
try {
await fs.promises.writeFile(CACHE_FILE, JSON.stringify(cache, null, 2));
} catch (err) {
console.error("Error saving cache file:", err);
}
}
/**
* Get the GitHub rate limit status
* @returns {Promise<Object>} - The rate limit status
*/
async function getRateLimit() {
try {
const url = "https://api.github.com/rate_limit";
const response = await axios.get(url, {
auth: {
username: USERNAME,
password: TOKEN,
},
});
return response.data;
} catch (error) {
console.error("Error fetching rate limit:", error.message);
throw error;
}
}
/**
* Get the repositories for a given GitHub username
* @param {string} username - The GitHub username
* @returns {Promise<Array>} - List of repositories
*/
async function getRepositories(username) {
try {
const url = `https://api.github.com/users/${username}/repos?per_page=100`;
const response = await axios.get(url, {
auth: {
username: USERNAME,
password: TOKEN,
},
});
return response.data;
} catch (error) {
console.error("Error fetching repositories:", error.message);
throw error;
}
}
/**
* Fetch and aggregate lines of code for a given repository
* @param {Object} repo - The repository object
* @returns {Promise<Object>} - An object that maps languages to their lines of code
*/
async function fetchLanguageCountsForRepo(repo) {
const repoName = repo.full_name;
const latestCommit = repo.pushed_at;
// Use cache if the data is up-to-date
if (cache[repoName] && cache[repoName].latestCommit === latestCommit) {
return cache[repoName].languages;
}
const ignoredPaths = blacklist.paths.join(",");
const url = `https://api.codetabs.com/v1/loc?github=${repoName}&ignored=${ignoredPaths}`;
const response = await axios.get(url);
const languages = {};
response.data.forEach((languageData) => {
const language = languageData.language;
const lines = languageData.linesOfCode;
// Ignore blacklisted languages
if (!blacklist.languages.includes(language)) {
languages[language] = (languages[language] || 0) + lines;
}
});
// Update cache
cache[repoName] = { latestCommit, languages };
await saveCacheToFile();
return languages;
}
/**
* Aggregate lines of code across multiple repositories
* @param {Array} repos - List of repository objects
* @returns {Promise<Object>} - An object that maps languages to their total lines of code
*/
async function aggregateLanguageCounts(repos) {
const languageCounts = {};
for (const repo of repos) {
if (!blacklist.repos.includes(repo.name)) {
const repoLanguages = await fetchLanguageCountsForRepo(repo);
for (const [language, lines] of Object.entries(repoLanguages)) {
if (!languageCounts[language]) {
languageCounts[language] = 0;
}
languageCounts[language] += lines;
}
}
}
return languageCounts;
}
/**
* Count the lines of code across all repositories or a specific repository of a given GitHub user
* @param {string} username - The GitHub username
* @param {string} [repoName] - The optional GitHub repository name
* @returns {Promise<Object>} - An object that maps languages to their total lines of code
*/
async function countLinesOfCode(username, repoName) {
const repos = await getRepositories(username);
if (repoName) {
const repo = repos.find((r) => r.name === repoName);
if (repo) {
return fetchLanguageCountsForRepo(repo);
} else {
throw new Error(`Repository ${repoName} not found`);
}
} else {
return aggregateLanguageCounts(repos);
}
}
/**
* Route to get the total lines of code in all repositories of a given user
*/
app.get("/languages/:username", async (req, res) => {
try {
const rateLimit = await getRateLimit();
if (rateLimit.rate.remaining === 0) {
return res
.status(429)
.json({ error: "Rate limit exceeded. Try again later." });
}
const username = req.params.username;
const totalLines = await countLinesOfCode(username);
res.json(totalLines);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* Route to get the total lines of code for a specific repository of a given user
*/
app.get("/languages/:username/:repoName", async (req, res) => {
try {
const rateLimit = await getRateLimit();
if (rateLimit.rate.remaining === 0) {
return res
.status(429)
.json({ error: "Rate limit exceeded. Try again later." });
}
const { username, repoName } = req.params;
const totalLines = await countLinesOfCode(username, repoName);
res.json(totalLines);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* Start the server on the specified port
*/
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});