-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathextension.js
455 lines (400 loc) · 14.4 KB
/
extension.js
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
const fs = require("fs");
const { exec } = require("child_process");
const path = require("path");
const vscode = require("vscode");
const http = require("http");
const querystring = require("querystring");
const axios = require("axios");
require("dotenv").config({ path: path.resolve(__dirname, ".env") });
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const AUTH_URL = process.env.AUTH_URL;
const TOKEN_URL = process.env.TOKEN_URL;
const REDIRECT_URI = process.env.REDIRECT_URI;
const GITHUB_API_URL = process.env.GITHUB_API_URL;
const REPO_NAME = process.env.REPO_NAME;
/**
* @param {vscode.ExtensionContext} context
*/
async function handleRepoAndChangelog(accessToken, changedFiles) {
try {
const userResponse = await axios.get(`${GITHUB_API_URL}/user`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
const username = userResponse.data.login;
const today = new Date().toISOString().split("T")[0]; // Format: YYYY-MM-DD
const changelogFileName = `CHANGELOG_${today}.md`;
let contentsResponse;
try {
contentsResponse = await axios.get(
`${GITHUB_API_URL}/repos/${username}/${REPO_NAME}/contents`,
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
} catch (error) {
if (error.response && error.response.status === 404) {
const newContent = generateChangelogContent(changedFiles);
const base64NewContent = Buffer.from(newContent).toString("base64");
await createFile(accessToken, username, changelogFileName, base64NewContent);
return;
} else {
throw error;
}
}
const changelogFile = contentsResponse.data.find(
(file) => file.name === changelogFileName
);
const changesList = changedFiles
.map(
(file) =>
`| ${new Date().toLocaleString()} | ${file.fileName} | ${
file.additions
} Additions & ${file.deletions} Deletions|`
)
.join("\n");
if (changelogFile) {
const changelogContentResponse = await axios.get(changelogFile.download_url);
const changelogContent = changelogContentResponse.data;
const updatedContent = appendToTable(changelogContent, changesList);
const base64UpdatedContent =
Buffer.from(updatedContent).toString("base64");
await updateFile(accessToken, username, changelogFile, base64UpdatedContent);
} else {
const newContent = generateChangelogContent(changedFiles);
const base64NewContent = Buffer.from(newContent).toString("base64");
await createFile(accessToken, username, changelogFileName, base64NewContent);
}
vscode.window.showInformationMessage(`Changes pushed to Repository`);
} catch (error) {
vscode.window.showErrorMessage(
"Error handling repository and CHANGELOG: " + error.message
);
}
}
function appendToTable(existingContent, newChanges) {
const tableRegex = /\| Time \(UTC\)[\s\S]*?\n(\|[-]+.*?\n)?([\s\S]*?)\n$/;
const match = tableRegex.exec(existingContent);
if (match) {
const existingTable = match[2] || "";
const updatedTable = `${existingTable.trim()}\n${newChanges.trim()}`;
return existingContent.replace(match[2], updatedTable);
} else {
return (
existingContent +
`\n| Time (UTC) | Files Modified | Changes (Addition/Deletion) |\n|------------------------|-----------------------------------|-----------------------------|\n${newChanges}`
);
}
}
function generateChangelogContent(changedFiles) {
const changesList = changedFiles
.map(
(file) =>
`| ${new Date().toLocaleString()} | ${file.fileName} | ${
file.additions
} Additions & ${file.deletions} Deletions |`
)
.join("\n");
return `# Daily Changelog
This file logs the changes made on ${new Date().toLocaleDateString()}.
| Time (UTC) | Files Modified | Changes (Addition/Deletion) |
|------------------------|-----------------------------------|-----------------------------|
${changesList}
`;
}
async function updateFile(accessToken, username, file, content) {
try {
await axios.put(
`${GITHUB_API_URL}/repos/${username}/${REPO_NAME}/contents/${file.path}`,
{
message: `Update ${file.name} with change log`,
content: content,
sha: file.sha,
},
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
} catch (error) {
vscode.window.showErrorMessage(
`Error updating ${file.name}: ` + error.message
);
}
}
async function createFile(accessToken, username, fileName, content) {
try {
await axios.put(
`${GITHUB_API_URL}/repos/${username}/${REPO_NAME}/contents/${fileName}`,
{
message: `Create ${fileName} with initial content`,
content: content,
},
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
} catch (error) {
vscode.window.showErrorMessage(
`Error creating ${fileName}: ` + error.message
);
}
}
async function activate(context) {
const disposable = vscode.commands.registerCommand(
"gitclock.startOAuth",
async function () {
try {
const { default: open } = await import("open");
vscode.window.showInformationMessage("Opening GitHub login page...");
open(AUTH_URL);
const server = http.createServer(async (req, res) => {
if (req.url.startsWith("/oauthCallback")) {
const queryParams = querystring.parse(req.url.split("?")[1]);
const code = queryParams.code;
if (!code) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Error: No code received.");
return;
}
try {
const tokenResponse = await axios.post(
TOKEN_URL,
{
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code: code,
redirect_uri: REDIRECT_URI,
},
{ headers: { Accept: "application/json" } }
);
const accessToken = tokenResponse.data.access_token;
if (accessToken) {
vscode.window.showInformationMessage(
"GitHub login successful!"
);
context.globalState.update("githubAccessToken", accessToken);
checkAndCreateRepo(accessToken);
} else {
vscode.window.showErrorMessage(
"Failed to obtain access token."
);
}
} catch (error) {
vscode.window.showErrorMessage(
"Error exchanging code for token: " + error.message
);
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("You can close this window and return to VS Code.");
server.close();
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}
});
server.listen(5000, () => {
});
} catch (error) {
vscode.window.showErrorMessage(
"Error starting OAuth flow: " + error.message
);
}
}
);
context.subscriptions.push(disposable);
const accessToken = context.globalState.get("githubAccessToken");
if (!accessToken) {
vscode.window.showErrorMessage(
"You are not authenticated. Please log in using GitHub."
);
} else {
checkAndCreateRepo(accessToken);
monitorFileChanges(accessToken);
}
}
async function monitorFileChanges(accessToken) {
const currentWorkingDir = vscode.workspace.workspaceFolders?.[0]?.uri?.fsPath;
if (!currentWorkingDir) {
return;
}
setInterval(async () => {
exec(
"git status --short",
{ cwd: currentWorkingDir },
async (error, stdout) => {
if (error) {
return;
}
if (stdout.trim() === "") {
return;
}
const changedFiles = await Promise.all(
stdout
.split("\n")
.filter((line) => line.trim() !== "")
.map(async (line) => {
const [status, ...fileParts] = line.trim().split(/\s+/);
const fileName = fileParts.join(" ");
if (status === "??") {
return {
status: "New file (untracked)",
fileName,
additions: 0,
deletions: 0,
};
} else if (status === "M") {
const diffResult = await getDiffStats(
currentWorkingDir,
fileName
);
return { status: "Modified", fileName, ...diffResult };
} else {
return { status, fileName, additions: 0, deletions: 0 };
}
})
);
try {
await handleRepoAndChangelog(accessToken, changedFiles);
vscode.window.showInformationMessage("Changes logged successfully!");
} catch (err) {
}
}
);
}, 30 * 60 * 1000);
}
function getDiffStats(cwd, fileName) {
return new Promise((resolve) => {
exec(`git diff --numstat -- "${fileName}"`, { cwd }, (error, stdout) => {
if (error || !stdout.trim()) {
resolve({ additions: undefined, deletions: undefined });
return;
}
const [additions, deletions] = stdout.trim().split("\t");
resolve({
additions: parseInt(additions, 10),
deletions: parseInt(deletions, 10),
});
});
});
}
async function checkAndCreateRepo(accessToken) {
try {
const userResponse = await axios.get(`${GITHUB_API_URL}/user`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
const username = userResponse.data.login;
try {
const reposResponse = await axios.get(`${GITHUB_API_URL}/user/repos`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
const repoExists = reposResponse.data.some(
(repo) => repo.name === REPO_NAME
);
if (repoExists) {
vscode.window.showInformationMessage(
`Repository "${REPO_NAME}" exists.`
);
} else {
await createRepo(accessToken);
await createReadmeFile(accessToken, username);
}
} catch (error) {
vscode.window.showErrorMessage(
"Error checking repository: " +
(error.response ? error.response.data.message : error.message)
);
}
} catch (error) {
if (error.response && error.response.status === 404) {
vscode.window.showErrorMessage(
"Authentication failed or repository creation failed."
);
}
}
}
async function createRepo(accessToken) {
try {
const createRepoResponse = await axios.post(
`${GITHUB_API_URL}/user/repos`,
{
name: REPO_NAME,
private: false,
},
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
if (createRepoResponse.status === 201) {
vscode.window.showInformationMessage(
`Repository "${REPO_NAME}" created successfully.`
);
} else {
vscode.window.showErrorMessage("Failed to create repository.");
}
} catch (error) {
vscode.window.showErrorMessage(
"Error creating repository: " + error.message
);
}
}
async function createReadmeFile(accessToken, username) {
try {
const readmeContent = `# Git Clock
GitClock is an automation extension for Visual Studio Code that ensures your GitHub contributions remain active
![Extension Logo](https://raw.githubusercontent.com/author-sanjay/gitclock/master/logo.jpeg)
## Features
- **Automatic Commit Every 30 Minutes**: The extension automatically commits changes every 30 minutes to ensure that your work is regularly logged on main branch so that your git contribution is counted.
- **Sync Logs in Main Branch**: All your sync logs are stored in the \`main\` branch, ensuring that your contributions are tracked, even if you're working on a different branch.
- **Keeps Track of Your Hard Work**: By syncing your changes to the main branch, your contributions are always counted in the repository history, providing visibility of your continuous progress.
- **Works on Any Branch**: No need to worry about not being on the main branch. \`gitClock\` ensures your work is recorded regardless of the branch you're working on.
- **Customizable Commit Messages**: The commit messages are automatically generated to reflect the time and sync details, making your commit history clean and organized.
- **Lightweight and Simple**: The extension works quietly in the background without interrupting your workflow, only committing changes when necessary.
## Installation
1. **Manually:**
- Download the \`.vsix\` file from https://open-vsx.org/extension/authorSanju/gitclock.
- In Visual Studio Code, go to the Extensions view.
- Click the three dots on the top right and select **Install from VSIX**.
- Browse and select the \`.vsix\` file.
2. **VS Code:**
- We are trying to get our extension on VS code Marketplace
## Usage
1. After installation, activate the extension via the **Command Palette** (\`Ctrl+Shift+P\` / \`Cmd+Shift+P\`).
2. Search for \`GitClock: Authenticate\` and select it to authenticate the extension with the profile where you want your contributions to be counted.
## Contributing
- Fork the repository.
- Clone your fork: git clone https://github.com/your-username/your-extension-name.git
- Install dependencies: npm install
- Make your changes.
- Test extension
- Commit and push your changes.
- Create a pull request with a description of what you've changed.
## License
This extension is licensed under the MIT License. See LICENSE for more details.
`;
const base64Content = Buffer.from(readmeContent).toString("base64");
await axios.put(
`${GITHUB_API_URL}/repos/${username}/${REPO_NAME}/contents/README.md`,
{
message: "Add initial README.md",
content: base64Content,
},
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
vscode.window.showInformationMessage(
`README.md added to repository "${REPO_NAME}" successfully.`
);
} catch (error) {
vscode.window.showErrorMessage(
"Error creating README.md: " + error.message
);
}
}
function deactivate() {
console.log("GitClock extension deactivated.");
}
module.exports = {
activate,
deactivate,
};