Skip to content

Commit 5cf8f38

Browse files
CopilotSamiranRai
andauthored
refactor: fix bugs, remove dead code, add JSDoc, improve maintainability
Agent-Logs-Url: https://github.com/SamiranRai/Glyph-Tool/sessions/e276b0f1-40c0-4980-901f-ef5a61bedb3b Co-authored-by: SamiranRai <62708507+SamiranRai@users.noreply.github.com>
1 parent 1fcbdd5 commit 5cf8f38

File tree

8 files changed

+423
-493
lines changed

8 files changed

+423
-493
lines changed

extension.js

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,73 @@
11
const vscode = require("vscode");
22

3-
// Importing "highlightWords functions"
43
const { highlightWords } = require("./src/features/highlightWord");
5-
6-
// Importing "scanAllFilesContainKeywords" && "watchFiles"
7-
const {
8-
scanAllFilesContainKeywords,
9-
watchFiles,
10-
} = require("./src/features/fileScanner");
11-
12-
// Importing initDB
4+
const { scanAllFilesContainKeywords, watchFiles } = require("./src/features/fileScanner");
135
const {
146
initDB,
157
loadAllTimestampsToMemory,
168
highlightTimeStamps,
179
saveTimestamp,
1810
} = require("./src/db/levelDb");
19-
20-
const {generateKeywordKey}= require('./src/utility/db_required/keyGenerator')
21-
22-
23-
// Importing "CustomSidebarProvider"
11+
const { generateKeywordKey } = require("./src/utility/db_required/keyGenerator");
2412
const CustomSidebarProvider = require("./src/sidebar/customSidebar");
2513

14+
/**
15+
* Called by VS Code when the extension is activated.
16+
* Initialises the database, runs the first workspace scan, registers all
17+
* commands and views, and starts the real-time file watcher.
18+
* @param {import('vscode').ExtensionContext} context
19+
*/
2620
async function activate(context) {
27-
await initDB(context); // ✅ Load existing timestamps from globalState
21+
// Load persisted timestamps before any scan so existing entries are not duplicated.
22+
await initDB(context);
2823
await loadAllTimestampsToMemory(context);
24+
2925
const results = await scanAllFilesContainKeywords(context);
3026
for (const item of results) {
3127
const upperCaseKeyword = (item.keyword + ":").toUpperCase();
32-
const fileName = item.file || 'unknown';
28+
const fileName = item.file || "unknown";
3329
const line = item.line ?? 0;
3430
const uniqueKey = generateKeywordKey(upperCaseKeyword, fileName, line);
3531

3632
if (!highlightTimeStamps.has(uniqueKey)) {
3733
await saveTimestamp(upperCaseKeyword, fileName, line, context);
3834
}
3935
}
40-
await highlightWords(context); // ✅ Now use safely without resetting others
4136

42-
// Registering Highlight Word Command
43-
let highlightWordCommand = vscode.commands.registerCommand(
37+
await highlightWords(context);
38+
39+
// Commands
40+
const highlightWordCommand = vscode.commands.registerCommand(
4441
"highlightWord.afterColon",
4542
async () => await highlightWords(context)
4643
);
4744

48-
// Register File Scanner Command
49-
let scanHighlightedKeywordFiles = vscode.commands.registerCommand(
45+
const scanHighlightedKeywordFiles = vscode.commands.registerCommand(
5046
"scanAllfiles.containDefaultKeyword",
5147
async () => await scanAllFilesContainKeywords(context)
5248
);
5349

54-
// Registering Custom SideBar
55-
let customSidebar = vscode.window.registerWebviewViewProvider(
50+
// Sidebar
51+
const customSidebar = vscode.window.registerWebviewViewProvider(
5652
"customSidebar",
5753
new CustomSidebarProvider(context)
5854
);
59-
// Push commands to subscriptions
60-
context.subscriptions.push(highlightWordCommand);
61-
context.subscriptions.push(scanHighlightedKeywordFiles);
62-
context.subscriptions.push(customSidebar);
6355

64-
// Start watching for file changes
65-
await watchFiles(context); // 🚀 This ensures real-time updates
56+
context.subscriptions.push(
57+
highlightWordCommand,
58+
scanHighlightedKeywordFiles,
59+
customSidebar
60+
);
61+
62+
// Start watching for file changes (also hooks into onDidChangeTextDocument).
63+
await watchFiles(context);
6664

6765
vscode.window.onDidChangeActiveTextEditor(() => highlightWords(context));
6866
vscode.workspace.onDidChangeTextDocument(() => highlightWords(context));
6967
await highlightWords(context);
7068
}
7169

70+
/** Called by VS Code when the extension is deactivated. */
7271
function deactivate() {}
7372

7473
module.exports = { activate, deactivate };

src/db/levelDb.js

Lines changed: 67 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -1,189 +1,131 @@
1-
const {generateKeywordKey} = require('./../utility/db_required/keyGenerator');
1+
const { generateKeywordKey } = require('./../utility/db_required/keyGenerator');
22

3+
// In-memory store of keyword timestamps, keyed by a canonical compound key
4+
// (<KEYWORD>|<fileName>|<line>). Loaded from VS Code globalState on startup.
35
let highlightTimeStamps = new Map();
46

7+
// ---------------------------------------------------------------------------
8+
// Lifecycle
9+
// ---------------------------------------------------------------------------
510

11+
/**
12+
* Initialises the in-memory timestamp store from VS Code's persisted
13+
* globalState. Must be called once during extension activation before any
14+
* other DB functions are used.
15+
* @param {import('vscode').ExtensionContext} context
16+
*/
617
async function initDB(context) {
718
try {
819
const data = await context.globalState.get("highlightTimeStamps", {});
920
highlightTimeStamps.clear();
10-
1121
for (const [key, value] of Object.entries(data)) {
12-
highlightTimeStamps.set(key, value); // ✅ Already a fully qualified key
22+
highlightTimeStamps.set(key, value);
1323
}
14-
15-
console.log("Timestamps successfully loaded from global-state.");
1624
} catch (err) {
17-
console.error({
18-
errorMessage: "Failed to initialize the DB.",
19-
err,
20-
});
25+
console.error({ errorMessage: "Failed to initialize the DB.", err });
2126
}
2227
}
2328

29+
/**
30+
* Reloads all timestamps from globalState into the in-memory store.
31+
* Useful when the store may be out of sync with the persisted data.
32+
* @param {import('vscode').ExtensionContext} context
33+
*/
2434
async function loadAllTimestampsToMemory(context) {
2535
const stored = (await context.globalState.get("highlightTimeStamps")) || {};
26-
highlightTimeStamps.clear(); // Ensure clean slate
36+
highlightTimeStamps.clear();
2737
for (const [key, value] of Object.entries(stored)) {
2838
highlightTimeStamps.set(key, value);
2939
}
3040
}
3141

42+
// ---------------------------------------------------------------------------
43+
// Persistence helper
44+
// ---------------------------------------------------------------------------
45+
46+
/**
47+
* Writes the current in-memory timestamp map to VS Code's globalState.
48+
* @param {import('vscode').ExtensionContext} context
49+
*/
3250
async function persist(context) {
3351
try {
3452
const data = Object.fromEntries(highlightTimeStamps);
35-
console.log("Persisting Timestamps: ", data);
3653
await context.globalState.update("highlightTimeStamps", data);
3754
} catch (err) {
38-
console.error({
39-
errorMessage: "Failed to persist() timeStamp.",
40-
err,
41-
});
55+
console.error({ errorMessage: "Failed to persist() timeStamp.", err });
4256
}
4357
}
4458

45-
46-
async function saveTimestamp(keyword, fileName=null, line=null, context) {
59+
// ---------------------------------------------------------------------------
60+
// CRUD operations
61+
// ---------------------------------------------------------------------------
62+
63+
/**
64+
* Saves a timestamp for the given keyword location if one does not already
65+
* exist. Existing timestamps are intentionally preserved so that the original
66+
* discovery time is never overwritten.
67+
* @param {string} keyword Uppercase keyword with trailing colon (e.g. "TODO:").
68+
* @param {string|null} fileName Source file name or path.
69+
* @param {number|null} line 1-based line number.
70+
* @param {import('vscode').ExtensionContext} context
71+
*/
72+
async function saveTimestamp(keyword, fileName = null, line = null, context) {
4773
try {
4874
const key = generateKeywordKey(keyword, fileName, line);
4975
if (!highlightTimeStamps.has(key)) {
50-
const currentTime = Date.now();
51-
highlightTimeStamps.set(key, currentTime);
52-
console.log("Saved timestamp for:", key);
76+
highlightTimeStamps.set(key, Date.now());
5377
await persist(context);
54-
} else {
55-
console.log("⏱️ Existing timestamp preserved for:", key);
5678
}
5779
} catch (err) {
58-
console.error({
59-
errorMessage: "Failed to save() timestamp.",
60-
err,
61-
});
80+
console.error({ errorMessage: "Failed to save() timestamp.", err });
6281
}
6382
}
6483

84+
/**
85+
* Deletes the timestamp for the given keyword location.
86+
* @param {string} keyword
87+
* @param {string} filePath
88+
* @param {number} line
89+
* @param {import('vscode').ExtensionContext} context
90+
*/
6591
async function deleteTimestamp(keyword, filePath, line, context) {
6692
try {
67-
const key = key(keyword, filePath, line);
93+
const key = generateKeywordKey(keyword, filePath, line);
6894
if (highlightTimeStamps.has(key)) {
6995
highlightTimeStamps.delete(key);
70-
console.log("Deleted timestamp for:", key);
7196
await persist(context);
7297
}
7398
} catch (err) {
74-
console.error({
75-
errorMessage: "Failed to Delete() timestamp.",
76-
err,
77-
});
99+
console.error({ errorMessage: "Failed to Delete() timestamp.", err });
78100
}
79101
}
80102

103+
/**
104+
* Returns the stored timestamp (ms since epoch) for the given keyword location,
105+
* or `undefined` if not found.
106+
* @param {string} keyword
107+
* @param {string} fileName
108+
* @param {number} line
109+
* @returns {number|undefined}
110+
*/
81111
function getTimestamp(keyword, fileName, line) {
82112
return highlightTimeStamps.get(generateKeywordKey(keyword, fileName, line));
83113
}
84114

115+
/**
116+
* Returns the full in-memory timestamp map (read-only by convention).
117+
* @returns {Map<string, number>}
118+
*/
85119
function getAllTimestamps() {
86120
return highlightTimeStamps;
87121
}
88122

89-
90-
91123
module.exports = {
92124
initDB,
93125
saveTimestamp,
94126
deleteTimestamp,
95127
getTimestamp,
96128
getAllTimestamps,
97129
highlightTimeStamps,
98-
loadAllTimestampsToMemory
130+
loadAllTimestampsToMemory,
99131
};
100-
101-
// async function initDB(context, highlightTimeStamps) {
102-
// try {
103-
// const data = context.globalState.get("highlightTimeStamps", {});
104-
// highlightTimeStamps.clear();
105-
// Object.entries(data).forEach(([key, value]) =>
106-
// highlightTimeStamps.set(key, value)
107-
// );
108-
// console.log({
109-
// context,
110-
// highlightTimeStamps
111-
// })
112-
// console.log("Timestamps successfully loaded from global-state.");
113-
// } catch (err) {
114-
// console.error({
115-
// ERRORMESSAGE: "Failed to load timestamps from global-state!",
116-
// err,
117-
// });
118-
// }
119-
// }
120-
121-
// async function saveTimestamp(keyword, highlightTimeStamps, context) {
122-
// const currentTime = Date.now();
123-
// try {
124-
// const existingTime = highlightTimeStamps.get(keyword);
125-
// if (existingTime && existingTime === currentTime) return;
126-
127-
// console.log("Saved timestamp for:", keyword);
128-
// highlightTimeStamps.set(keyword, currentTime);
129-
// await persist(context, highlightTimeStamps);
130-
// } catch (err) {
131-
// console.error({
132-
// ERRORMESSAGE: "Failed to save timestamp to global-state!",
133-
// err,
134-
// });
135-
// }
136-
// }
137-
138-
// async function deleteTimestamp(keyword, highlightTimeStamps, context) {
139-
// try {
140-
// console.log(`Successfully deleted timestamp for ${keyword}.`);
141-
// highlightTimeStamps.delete(keyword);
142-
// await persist(context, highlightTimeStamps);
143-
// } catch (err) {
144-
// console.error({
145-
// ERRORMESSAGE: "Failed to delete timestamp from global-state!",
146-
// err,
147-
// });
148-
// }
149-
// }
150-
151-
// async function loadTimestampsFromDB(context) {
152-
// const globalState = context.globalState;
153-
// const saved = globalState.get("highlightTimeStamps");
154-
155-
// if (saved) {
156-
// for (const [key, value] of Object.entries(saved)) {
157-
// highlightTimeStamps.set(key, value);
158-
// }
159-
// } else {
160-
// console.log("No saved timestamps found in globalState.");
161-
// }
162-
// }
163-
164-
// async function persist(context, highlighttimestamps) {
165-
// try {
166-
// // if (!context || !context.globalState || !context.globalState.update) {
167-
// // throw new Error("❌ Missing or invalid extension context or globalState!");
168-
// // }
169-
// console.log("🧪 Context during persist():", {
170-
// CONTEXTEXISTS: !!context,
171-
// GLOBALSTATEEXISTS: !!context?.globalState,
172-
// UPDATEEXISTS: typeof context?.globalState?.update === "function",
173-
// });
174-
// const data = Object.fromEntries(highlighttimestamps);
175-
// await context.globalState.update("highlightTimeStamps", data);
176-
// } catch (err) {
177-
// console.error({
178-
// ERRORMESSAGE: "Failed to save to global-state!",
179-
// err,
180-
// });
181-
// }
182-
// }
183-
184-
// module.exports = {
185-
// initDB,
186-
// saveTimestamp,
187-
// deleteTimestamp,
188-
// loadTimestampsFromDB,
189-
// };

0 commit comments

Comments
 (0)