Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
extension.ts
Go to the documentation of this file.
1
44import * as path from "path";
45import * as vscode from 'vscode';
46import { moduleName } from './constants';
47import { logger } from './modules/logger';
48import { Darling } from "./modules/darling";
49import { MorseTranslator } from './modules/morseCode';
50import { getMessage } from './modules/messageProvider';
51import { LazyFileLoader } from './modules/lazyFileLoad';
52import { CommentGenerator } from './modules/commentGenerator';
53import { CodeConfig, CodeConfigType } from "./modules/processConfiguration";
54import { Watermark } from "./modules/watermark";
55import { RandomLogo } from "./modules/randomLogo";
56import { query } from "./modules/querier";
57
58// Extension boot message
59const earlyLog = vscode.window.createOutputChannel('AsperHeader-Preboot');
60earlyLog.appendLine('>>> AsperHeader: imports success');
61logger.info(getMessage("bootingUp"));
62
63// ---- Shared variables ----
64
65const updatingDocuments = new WeakSet<vscode.TextDocument>();
66earlyLog.appendLine('>>> AsperHeader: WeakSet initialised');
67
69earlyLog.appendLine('>>> AsperHeader: CodeConfigType initialised');
70
71
72// --- Helper functions ---
73
83function getFileInfo(editor: vscode.TextEditor) {
84 logger.debug(getMessage("inFunction", "getFileInfo"));
85 const document = editor.document;
86 const filePath = document.uri.fsPath;
87 const fileName = document.uri.path.split('/').pop() || "unknown";
88 const fileExtension = fileName.includes('.') ? fileName.split('.').pop() : "none";
89 const languageId = document.languageId;
90
91 return { filePath, fileName, fileExtension, languageId };
92}
93earlyLog.appendLine('>>> AsperHeader: getFileInfo initialised');
94
95// --- Command implementations ---
96
105 logger.debug(getMessage("inFunction", "helloWorldCommand"));
106 vscode.window.showInformationMessage(getMessage("helloWorldGreetingsCommand", moduleName));
107}
108earlyLog.appendLine('>>> AsperHeader: helloWorldCommand initialised');
109
118async function sayHelloWorldCommand() {
119 logger.debug(getMessage("inFunction", "sayHelloWorldCommand"));
120 const editor = vscode.window.activeTextEditor;
121 if (!editor) {
122 logger.Gui.error(getMessage("noActiveEditor"));
123 return;
124 }
125 const { filePath, fileName, fileExtension, languageId } = getFileInfo(editor);
126 const message = getMessage("sayHelloWorldResponse", fileExtension, fileName, filePath, languageId);
127 await editor.edit(editBuilder => editBuilder.insert(new vscode.Position(0, 0), message));
128 logger.Gui.info(getMessage("messageWritten"));
129}
130earlyLog.appendLine('>>> AsperHeader: sayHelloWorldCommand initialised');
131
141async function updateSaveSafe(document: vscode.TextDocument, comment_generator: CommentGenerator) {
142 logger.debug(getMessage("inFunction", "updateSaveSafe"));
143 if (updatingDocuments.has(document)) {
144 return;
145 }
146 updatingDocuments.add(document);
147 try {
148 await comment_generator.refreshHeader(document);
149 if (document.isDirty) {
150 const status = await document.save();
151 if (!status) {
152 logger.Gui.error(getMessage("fileSaveFailed"));
153 }
154 }
155 } finally {
156 updatingDocuments.delete(document);
157 }
158}
159earlyLog.appendLine('>>> AsperHeader: updateSaveSafe initialised');
160
170 logger.debug(getMessage("inFunction", "refreshWorkspaceName"));
171 let workspaceName: string | undefined;
172
173 if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
174 workspaceName = vscode.workspace.workspaceFolders[0].name;
175 }
176 else if ((vscode.workspace as any).rootPath) {
177 const rootPath = (vscode.workspace as any).rootPath as string;
178 workspaceName = rootPath.split(/[\\/]/).pop();
179 }
180
181 CodeConfig.setWorkspaceName(workspaceName);
182}
183earlyLog.appendLine('>>> AsperHeader: refreshWorkspaceName initialised');
184
193async function toMorseGui() {
194 logger.debug(getMessage("inFunction", "toMorseGui"));
195 const usr_input: string | undefined = await query.input(getMessage("toMorseGetInput"));
196 if (usr_input === undefined) {
197 logger.Gui.info(getMessage("operationCanceled"));
198 return;
199 }
200 const converted_response: string = MorseTranslator.toMorse(usr_input);
201 logger.info(getMessage("convertedContentCli", converted_response));
202 logger.Gui.info(`${converted_response}`);
203 logger.Gui.info(getMessage("convertedContentGui"));
204}
205earlyLog.appendLine('>>> AsperHeader: toMorseGui initialised');
206
215async function fromMorseGui() {
216 logger.debug(getMessage("inFunction", "fromMorseGui"));
217 const usr_input: string | undefined = await query.input(getMessage("fromMorseGetInput"));
218 if (usr_input === undefined) {
219 logger.Gui.info(getMessage("operationCanceled"));
220 return;
221 }
222 const converted_response: string = MorseTranslator.fromMorse(usr_input);
223 logger.info(getMessage("convertedContentCli", converted_response));
224 logger.Gui.info(`${converted_response}`);
225 logger.Gui.info(getMessage("convertedContentGui"));
226}
227earlyLog.appendLine('>>> AsperHeader: fromMorseGui initialised');
228
243export async function activate(context: vscode.ExtensionContext) {
244 logger.updateInitialisationStatus(true);
245 logger.info(getMessage("inActivate"));
246 // Initialising the variables of the CodeConfiguration class
247 await CodeConfiguration.refreshVariables();
248 logger.info(getMessage("variablesRefreshed"));
249 // Updating the logger settings
250 logger.updateInstallationState(context);
251 logger.info(getMessage("inActivateAfterLogger"));
252 logger.Gui.debug(`context.extensionPath: ${context.extensionPath}`);
253 logger.info(getMessage("inActivateAfterGuiDebug"));
254
255 // Class initialisers
256 const COMMENTS_FORMAT = new LazyFileLoader<any>();
257 logger.debug(getMessage("classInitialised", "LazyFileLoader", moduleName));
258 earlyLog.appendLine('>>> AsperHeader: LazyFileLoader initialised');
259 const COMMENT_GENERATOR: CommentGenerator = new CommentGenerator(COMMENTS_FORMAT);
260 logger.debug(getMessage("classInitialised", "CommentGenerator", moduleName));
261 earlyLog.appendLine('>>> AsperHeader: CommentGenerator initialised');
262 const DARLING: Darling = new Darling();
263 earlyLog.appendLine('>>> AsperHeader: Darling initialised');
264 logger.debug(getMessage("classInitialised", "Darling", moduleName));
265 const WATERMARK: Watermark = new Watermark();
266 earlyLog.appendLine('>>> AsperHeader: Watermark initialised');
267 logger.debug(getMessage("classInitialised", "Watermark", moduleName));
268 const RANDOM_LOGO: RandomLogo = new RandomLogo();
269 earlyLog.appendLine('>>> AsperHeader: RandomLogo initialised');
270 logger.debug(getMessage("classInitialised", "RandomLogo", moduleName));
271 logger.debug(getMessage("classesInitialised"));
272
273 const jsonLanguagePath: string = path.join(
274 context.extensionPath,
275 "assets",
276 "formatingRules",
277 "languages.min.json"
278 );
279 const alternateJsonLanguagePath: string = path.join(
280 context.extensionPath,
281 "dist",
282 "assets",
283 "formatingRules",
284 "languages.min.json"
285 );
286 const darlingPath: string = path.join(
287 context.extensionPath,
288 "assets",
289 "bonus",
290 "ditf.min.json"
291 );
292 const alternateDarlingPath: string = path.join(
293 context.extensionPath,
294 "dist",
295 "assets",
296 "bonus",
297 "ditf.min.json"
298 );
299 const watermarkPath: string = path.join(
300 context.extensionPath,
301 "assets",
302 "bonus",
303 "watermark.min.json"
304 );
305 const alternateWatermarkPath: string = path.join(
306 context.extensionPath,
307 "dist",
308 "assets",
309 "bonus",
310 "watermark.min.json"
311 );
312 const logoPath: string = path.join(
313 context.extensionPath,
314 "assets",
315 "asciiArt"
316 );
317 const alternateLogoPath: string = path.join(
318 context.extensionPath,
319 "dist",
320 "assets",
321 "asciiArt"
322 );
323 logger.debug(getMessage("pathsSet"));
324 // Updating the current working directories of the classes
325 await DARLING.updateCurrentWorkingDirectory(context.extensionPath);
326 await WATERMARK.updateCurrentWorkingDirectory(context.extensionPath);
327 RANDOM_LOGO.updateCurrentWorkingDirectory(context.extensionPath);
328 await COMMENTS_FORMAT.updateCurrentWorkingDirectory(context.extensionPath);
329 logger.debug(getMessage("currentWorkingDirectorySet"));
330 // Updating the default file paths of the classes
331 await DARLING.updateFilePath(darlingPath);
332 await WATERMARK.updateFilePath(watermarkPath);
333 await RANDOM_LOGO.updateRootDir(logoPath, alternateLogoPath);
334 await COMMENTS_FORMAT.updateFilePath(jsonLanguagePath);
335 logger.debug(getMessage("filePathsAndRootDirsUpdated"));
336 // Updating the backup paths of the classes
337 await DARLING.updateAlternateFilePath(alternateDarlingPath);
338 await WATERMARK.updateAlternateFilePath(alternateWatermarkPath);
339 await COMMENTS_FORMAT.updateAlternateFilePath(alternateJsonLanguagePath);
340 logger.debug(getMessage("filePathAlternateSet"));
341 // Initialising the random logo of the Comment generator class
342 COMMENT_GENERATOR.updateLogoInstanceRandomiser(RANDOM_LOGO);
343 logger.info(getMessage("extensionActivated", moduleName), 3);
344
345
346 context.subscriptions.push(
347 vscode.commands.registerCommand(`${moduleName}.helloWorld`, helloWorldCommand),
348 vscode.commands.registerCommand(`${moduleName}.sayHelloWorld`, sayHelloWorldCommand),
349 vscode.commands.registerCommand(`${moduleName}.injectHeader`, () => { refreshWorkspaceName(); COMMENT_GENERATOR.injectHeader(); }),
350 vscode.commands.registerCommand(`${moduleName}.refreshHeader`, () => { refreshWorkspaceName(); COMMENT_GENERATOR.refreshHeader(vscode.window.activeTextEditor?.document); }),
351 vscode.commands.registerCommand(`${moduleName}.darling`, DARLING.displayRandomPersonInWindow.bind(DARLING)),
352 vscode.commands.registerCommand(`${moduleName}.author`, WATERMARK.displayRandomAuthorWatermarkInWindow.bind(WATERMARK)),
353 vscode.commands.registerCommand(`${moduleName}.displayRandomLogo`, RANDOM_LOGO.displayRandomLogoInWindow.bind(RANDOM_LOGO)),
354 vscode.commands.registerCommand(`${moduleName}.toMorse`, toMorseGui),
355 vscode.commands.registerCommand(`${moduleName}.fromMorse`, fromMorseGui),
356 vscode.workspace.onDidSaveTextDocument(async (document: vscode.TextDocument) => { await updateSaveSafe(document, COMMENT_GENERATOR); }),
357 vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(moduleName)) { await CodeConfiguration.refreshVariables(); logger.debug(getMessage("variablesRefreshed")); } })
358 );
359 logger.debug(getMessage("subscriptionsAdded"));
360}
361earlyLog.appendLine('>>> AsperHeader: activate called');
362
371export function deactivate() { }
Intelligent file header generation and management system.
Generic lazy file loader with caching and type safety @template T The expected type of the loaded fil...
Static utility class for Morse code translation operations.
Definition morseCode.ts:102
export const moduleName
Module identifier used in package.json and extension marketplace.
Definition constants.ts:59
function async sayHelloWorldCommand()
Inserts greeting message with current file information.
Definition extension.ts:118
import *as vscode from vscode
Definition extension.ts:45
const earlyLog
Definition extension.ts:59
import *as path from path
Definition extension.ts:44
function async fromMorseGui()
Converts Morse code input to plain text through interactive GUI dialog.
Definition extension.ts:215
function export deactivate()
Extension cleanup and deactivation handler.
Definition extension.ts:371
function async toMorseGui()
Converts user input to Morse code through interactive GUI dialog.
Definition extension.ts:193
const updatingDocuments
Definition extension.ts:65
const CodeConfiguration
Definition extension.ts:68
function async updateSaveSafe(document:vscode.TextDocument, comment_generator:CommentGenerator)
Thread-safe document update handler for save events.
Definition extension.ts:141
function refreshWorkspaceName()
Updates cached workspace name from VS Code workspace state.
Definition extension.ts:169
function helloWorldCommand()
Displays a simple greeting message from the extension.
Definition extension.ts:104
function getFileInfo(editor:vscode.TextEditor)
Extracts comprehensive file information from VS Code text editor.
Definition extension.ts:83
function async activate(context:vscode.ExtensionContext)
Main extension activation entry point.
Definition extension.ts:243
export const logger
Singleton logger instance providing unified logging interface for the entire extension.
Definition logger.ts:910
export const getMessage
Exported function for direct message retrieval.
export type CodeConfigType
Type alias for the Configuration class.
export const CodeConfig
Exported configuration singleton for extension-wide access @export Primary configuration interface us...
export const query
Convenience singleton export for direct access to Query functionality @export Primary interface for u...
Definition querier.ts:345