Skip to content

Commit 3221253

Browse files
committed
refactor: rewrote the logger
Simplifies the calls and renames methods to more intuitive names
1 parent 755ce0c commit 3221253

File tree

10 files changed

+96
-121
lines changed

10 files changed

+96
-121
lines changed

src/extension.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ import { FortlsClient } from './lsp/client';
1212
import { FortranHoverProvider } from './features/hover-provider';
1313
import { FortranLintingProvider } from './features/linter-provider';
1414
import { EXTENSION_ID, FortranDocumentSelector } from './lib/tools';
15-
import { LoggingService } from './services/logging-service';
15+
import { Logger } from './services/logging-service';
1616
import { WhatsNew } from './features/commands';
1717

1818
// Make it global to catch errors when activation fails
19-
const loggingService = new LoggingService();
19+
const logger = new Logger(vscode.window.createOutputChannel('Modern Fortran'));
2020

2121
export async function activate(context: vscode.ExtensionContext) {
2222
const config = vscode.workspace.getConfiguration(EXTENSION_ID);
@@ -27,34 +27,34 @@ export async function activate(context: vscode.ExtensionContext) {
2727
const symbolsType = config.get<string>('provide.symbols');
2828
detectDeprecatedOptions();
2929

30-
loggingService.logInfo(`Extension Name: ${pkg.displayName}`);
31-
loggingService.logInfo(`Extension Version: ${pkg.version}`);
32-
loggingService.logInfo(`Linter set to: ${linterType}`);
33-
loggingService.logInfo(`Formatter set to: ${formatterType}`);
34-
loggingService.logInfo(`Autocomplete set to: ${autocompleteType}`);
35-
loggingService.logInfo(`Hover set to: ${hoverType}`);
36-
loggingService.logInfo(`Symbols set to: ${symbolsType}`);
30+
logger.info(`Extension Name: ${pkg.displayName}`);
31+
logger.info(`Extension Version: ${pkg.version}`);
32+
logger.info(`Linter set to: ${linterType}`);
33+
logger.info(`Formatter set to: ${formatterType}`);
34+
logger.info(`Autocomplete set to: ${autocompleteType}`);
35+
logger.info(`Hover set to: ${hoverType}`);
36+
logger.info(`Symbols set to: ${symbolsType}`);
3737

3838
// Linter is always activated but will only lint if compiler !== Disabled
39-
const linter = new FortranLintingProvider(loggingService);
39+
const linter = new FortranLintingProvider(logger);
4040
linter.activate(context.subscriptions);
4141
vscode.languages.registerCodeActionsProvider(FortranDocumentSelector(), linter);
4242

4343
if (formatterType !== 'Disabled') {
4444
const disposable: vscode.Disposable = vscode.languages.registerDocumentFormattingEditProvider(
4545
FortranDocumentSelector(),
46-
new FortranFormattingProvider(loggingService)
46+
new FortranFormattingProvider(logger)
4747
);
4848
context.subscriptions.push(disposable);
4949
}
5050

5151
if (autocompleteType === 'Built-in') {
52-
const completionProvider = new FortranCompletionProvider(loggingService);
52+
const completionProvider = new FortranCompletionProvider(logger);
5353
vscode.languages.registerCompletionItemProvider(FortranDocumentSelector(), completionProvider);
5454
}
5555

5656
if (hoverType === 'Built-in' || hoverType === 'Both') {
57-
const hoverProvider = new FortranHoverProvider(loggingService);
57+
const hoverProvider = new FortranHoverProvider(logger);
5858
vscode.languages.registerHoverProvider(FortranDocumentSelector(), hoverProvider);
5959
}
6060

@@ -64,7 +64,7 @@ export async function activate(context: vscode.ExtensionContext) {
6464
}
6565

6666
if (!config.get<boolean>('fortls.disabled')) {
67-
new FortlsClient(loggingService, context).activate();
67+
new FortlsClient(logger, context).activate();
6868
}
6969
// override VS Code's default implementation of the debug hover
7070
// here we match Fortran derived types and scope them appropriately
@@ -129,7 +129,7 @@ function detectDeprecatedOptions() {
129129
if (selected === 'Open Settings') {
130130
vscode.commands.executeCommand('workbench.action.openGlobalSettings');
131131
}
132-
loggingService.logError(`The following deprecated options have been detected:\n${oldArgs}`);
132+
logger.error(`The following deprecated options have been detected:\n${oldArgs}`);
133133
});
134134
}
135135

src/features/completion-provider.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as vscode from 'vscode';
44
import { isPositionInString, FORTRAN_KEYWORDS } from '../lib/helper';
55
import { getDeclaredFunctions } from '../lib/functions';
66
import { EXTENSION_ID } from '../lib/tools';
7-
import { LoggingService } from '../services/logging-service';
7+
import { Logger } from '../services/logging-service';
88
import intrinsics from './intrinsics.json';
99

1010
class CaseCoverter {
@@ -35,7 +35,7 @@ class CaseCoverter {
3535
}
3636

3737
export class FortranCompletionProvider implements vscode.CompletionItemProvider {
38-
constructor(private loggingService: LoggingService) {}
38+
constructor(private logger: Logger) {}
3939
public provideCompletionItems(
4040
document: vscode.TextDocument,
4141
position: vscode.Position,

src/features/formatting-provider.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as which from 'which';
66
import * as vscode from 'vscode';
77
import * as cp from 'child_process';
88

9-
import { LoggingService } from '../services/logging-service';
9+
import { Logger } from '../services/logging-service';
1010
import {
1111
FORMATTERS,
1212
EXTENSION_ID,
@@ -18,7 +18,7 @@ import {
1818
export class FortranFormattingProvider implements vscode.DocumentFormattingEditProvider {
1919
private readonly workspace = vscode.workspace.getConfiguration(EXTENSION_ID);
2020
private formatter: string | undefined;
21-
constructor(private logger: LoggingService) {}
21+
constructor(private logger: Logger) {}
2222

2323
public async provideDocumentFormattingEdits(
2424
document: vscode.TextDocument,
@@ -32,7 +32,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
3232
} else if (formatterName === 'findent') {
3333
return this.doFormatFindent(document);
3434
} else {
35-
this.logger.logError('Cannot format document with formatter set to Disabled');
35+
this.logger.error('Cannot format document with formatter set to Disabled');
3636
}
3737

3838
return undefined;
@@ -46,7 +46,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
4646
private async doFormatFprettify(document: vscode.TextDocument): Promise<vscode.TextEdit[]> {
4747
// fprettify can only do FortranFreeFrom
4848
if (document.languageId !== 'FortranFreeForm') {
49-
this.logger.logError(`fprettify can only format FortranFreeForm, change
49+
this.logger.error(`fprettify can only format FortranFreeForm, change
5050
to findent for FortranFixedForm formatting`);
5151
return undefined;
5252
}
@@ -56,7 +56,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
5656
const formatter: string = path.join(formatterPath, formatterName);
5757
// If no formatter is detected try and install it
5858
if (!which.sync(formatter, { nothrow: true })) {
59-
this.logger.logWarning(`Formatter: ${formatterName} not detected in your system.
59+
this.logger.warn(`Formatter: ${formatterName} not detected in your system.
6060
Attempting to install now.`);
6161
const msg = `Installing ${formatterName} through pip with --user option`;
6262
promptForMissingTool(formatterName, msg, 'Python', ['Install'], this.logger);
@@ -66,7 +66,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
6666
const edits: vscode.TextEdit[] = [];
6767
const [stdout, stderr] = await spawnAsPromise(formatter, args, undefined, document.getText());
6868
edits.push(new vscode.TextEdit(getWholeFileRange(document), stdout));
69-
if (stderr) this.logger.logInfo(`fprettify error output: ${stderr}`);
69+
if (stderr) this.logger.info(`fprettify error output: ${stderr}`);
7070
return edits;
7171
}
7272

@@ -81,7 +81,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
8181
const formatter: string = path.join(formatterPath, formatterName);
8282
// If no formatter is detected try and install it
8383
if (!which.sync(formatter, { nothrow: true })) {
84-
this.logger.logWarning(`Formatter: ${formatterName} not detected in your system.
84+
this.logger.warn(`Formatter: ${formatterName} not detected in your system.
8585
Attempting to install now.`);
8686
const msg = `Installing ${formatterName} through pip with --user option`;
8787
promptForMissingTool(formatterName, msg, 'Python', ['Install'], this.logger);
@@ -91,7 +91,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
9191
const edits: vscode.TextEdit[] = [];
9292
const [stdout, stderr] = await spawnAsPromise(formatter, args, undefined, document.getText());
9393
edits.push(new vscode.TextEdit(getWholeFileRange(document), stdout));
94-
if (stderr) this.logger.logInfo(`findent error output: ${stderr}`);
94+
if (stderr) this.logger.info(`findent error output: ${stderr}`);
9595
return edits;
9696
}
9797

@@ -107,7 +107,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
107107
this.formatter = this.workspace.get('formatting.formatter', 'Disabled');
108108

109109
if (!FORMATTERS.includes(this.formatter)) {
110-
this.logger.logError(`Unsupported formatter: ${this.formatter}`);
110+
this.logger.error(`Unsupported formatter: ${this.formatter}`);
111111
}
112112
return this.formatter;
113113
}
@@ -130,7 +130,7 @@ export class FortranFormattingProvider implements vscode.DocumentFormattingEditP
130130
private getFormatterPath(): string {
131131
const formatterPath: string = this.workspace.get('formatting.path', '');
132132
if (formatterPath !== '') {
133-
this.logger.logInfo(`Formatter located in: ${formatterPath}`);
133+
this.logger.info(`Formatter located in: ${formatterPath}`);
134134
}
135135

136136
return formatterPath;

src/features/hover-provider.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { CancellationToken, TextDocument, Position, Hover } from 'vscode';
2-
import { LoggingService } from '../services/logging-service';
2+
import { Logger } from '../services/logging-service';
33
import intrinsics from './intrinsics.json';
44

55
export class FortranHoverProvider {
6-
constructor(private loggingService: LoggingService) {}
6+
constructor(private logger: Logger) {}
77
public provideHover(
88
document: TextDocument,
99
position: Position,

src/features/linter-provider.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@ import * as cp from 'child_process';
55
import which from 'which';
66

77
import * as vscode from 'vscode';
8-
import { LoggingService } from '../services/logging-service';
8+
import { Logger } from '../services/logging-service';
99
import { FortranDocumentSelector, resolveVariables } from '../lib/tools';
1010
import * as fg from 'fast-glob';
1111
import { glob } from 'glob';
1212
import { arraysEqual } from '../lib/helper';
1313
import { RescanLint } from './commands';
1414

1515
export class FortranLintingProvider {
16-
constructor(private logger: LoggingService = new LoggingService()) {}
16+
constructor(private logger: Logger = new Logger()) {}
1717

1818
private diagnosticCollection: vscode.DiagnosticCollection;
1919
private compiler: string;
@@ -167,7 +167,7 @@ export class FortranLintingProvider {
167167
}
168168

169169
modout = resolveVariables(modout);
170-
this.logger.logInfo(`Linter.moduleOutput: ${modFlag} ${modout}`);
170+
this.logger.info(`Linter.moduleOutput: ${modFlag} ${modout}`);
171171
return [modFlag, modout];
172172
}
173173

@@ -195,7 +195,7 @@ export class FortranLintingProvider {
195195
// Update our cache input
196196
this.cache['includePaths'] = includePaths;
197197
// Output the original include paths
198-
this.logger.logInfo(`Linter.include:\n${includePaths.join('\r\n')}`);
198+
this.logger.info(`Linter.include:\n${includePaths.join('\r\n')}`);
199199
// Resolve internal variables and expand glob patterns
200200
const resIncludePaths = includePaths.map(e => resolveVariables(e));
201201
// fast-glob cannot work with Windows paths
@@ -212,12 +212,12 @@ export class FortranLintingProvider {
212212
// Try to recover from fast-glob failing due to EACCES using slower more
213213
// robust glob.
214214
} catch (eacces) {
215-
this.logger.logWarning(`You lack read permissions for an include directory
215+
this.logger.warn(`You lack read permissions for an include directory
216216
or more likely a glob match from the input 'includePaths' list. This can happen when
217217
using overly broad root level glob patters e.g. /usr/lib/** .
218218
No reason to worry. I will attempt to recover.
219219
You should consider adjusting your 'includePaths' if linting performance is slow.`);
220-
this.logger.logWarning(`${eacces.message}`);
220+
this.logger.warn(`${eacces.message}`);
221221
try {
222222
const globIncPaths: string[] = [];
223223
for (const i of resIncludePaths) {
@@ -228,7 +228,7 @@ export class FortranLintingProvider {
228228
return globIncPaths;
229229
// if we failed again then our includes are somehow wrong. Abort
230230
} catch (error) {
231-
this.logger.logError(`Failed to recover: ${error}`);
231+
this.logger.error(`Failed to recover: ${error}`);
232232
}
233233
}
234234
}
@@ -243,7 +243,7 @@ export class FortranLintingProvider {
243243
this.compiler = config.get<string>('compiler', 'gfortran');
244244
this.compilerPath = config.get<string>('compilerPath', '');
245245
if (this.compilerPath === '') this.compilerPath = which.sync(this.compiler);
246-
this.logger.logInfo(`using linter: ${this.compiler} located in: ${this.compilerPath}`);
246+
this.logger.info(`using linter: ${this.compiler} located in: ${this.compilerPath}`);
247247
return this.compilerPath;
248248
}
249249

@@ -287,7 +287,7 @@ export class FortranLintingProvider {
287287
const lnStr: string = ln === -1 ? 'none' : ln.toString();
288288
args.push(`-ffree-line-length-${lnStr}`, `-ffixed-line-length-${lnStr}`);
289289
}
290-
this.logger.logInfo(`Linter.arguments:\n${args.join('\r\n')}`);
290+
this.logger.info(`Linter.arguments:\n${args.join('\r\n')}`);
291291

292292
// Resolve internal variables but do not apply glob pattern matching
293293
return args.map(e => resolveVariables(e));

src/lib/tools.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as os from 'os';
22
import * as vscode from 'vscode';
33
import * as assert from 'assert';
44
import * as cp from 'child_process';
5-
import { LoggingService } from '../services/logging-service';
5+
import { Logger } from '../services/logging-service';
66
import { isString, isArrayOfString } from './helper';
77

88
export const LS_NAME = 'fortls';
@@ -106,7 +106,7 @@ export async function promptForMissingTool(
106106
msg: string,
107107
toolType: string,
108108
opts: string[],
109-
logger?: LoggingService,
109+
logger?: Logger,
110110
action?: () => void
111111
) {
112112
const items = ['Install'];
@@ -118,14 +118,14 @@ export async function promptForMissingTool(
118118
break;
119119

120120
case 'VSExt':
121-
logger.logInfo(`Installing VS Marketplace Extension with id: ${tool}`);
121+
logger.info(`Installing VS Marketplace Extension with id: ${tool}`);
122122
vscode.commands.executeCommand('extension.open', tool);
123123
vscode.commands.executeCommand('workbench.extensions.installExtension', tool);
124-
logger.logInfo(`Extension ${tool} successfully installed`);
124+
logger.info(`Extension ${tool} successfully installed`);
125125
break;
126126

127127
default:
128-
logger.logError(`Failed to install tool: ${tool}`);
128+
logger.error(`Failed to install tool: ${tool}`);
129129
vscode.window.showErrorMessage(`Failed to install tool: ${tool}`);
130130
break;
131131
}
@@ -142,22 +142,22 @@ export async function promptForMissingTool(
142142
* @param pyPackage name of python package in PyPi
143143
* @param logger `optional` logging channel for output
144144
*/
145-
export function installPythonTool(pyPackage: string, logger?: LoggingService) {
145+
export function installPythonTool(pyPackage: string, logger?: Logger) {
146146
const installProcess = cp.spawnSync(
147147
'pip',
148148
'install --user --upgrade '.concat(pyPackage).split(' ')
149149
);
150150
if (installProcess.error) {
151-
logger.logError(
151+
logger.error(
152152
`Python package ${pyPackage} failed to install with code: ${installProcess.error}`
153153
);
154154
}
155155
if (installProcess.stdout) {
156156
const sep = '-'.repeat(80);
157-
logger.logInfo(
157+
logger.info(
158158
`pip install --user --upgrade ${pyPackage}:\n${sep}\n${installProcess.stdout}${sep}`
159159
);
160-
logger.logInfo(`pip install was successful`);
160+
logger.info(`pip install was successful`);
161161
}
162162
}
163163

src/lsp/client.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
isFortran,
1313
getOuterMostWorkspaceFolder,
1414
} from '../lib/tools';
15-
import { LoggingService } from '../services/logging-service';
15+
import { Logger } from '../services/logging-service';
1616
import { RestartLS } from '../features/commands';
1717

1818
// The clients are non member variables of the class because they need to be
@@ -21,8 +21,8 @@ import { RestartLS } from '../features/commands';
2121
export const clients: Map<string, LanguageClient> = new Map();
2222

2323
export class FortlsClient {
24-
constructor(private logger: LoggingService, private context?: vscode.ExtensionContext) {
25-
this.logger.logInfo('Fortran Language Server');
24+
constructor(private logger: Logger, private context?: vscode.ExtensionContext) {
25+
this.logger.info('Fortran Language Server');
2626

2727
// if context is present
2828
if (context !== undefined) {
@@ -109,7 +109,7 @@ export class FortlsClient {
109109
if (!folder) {
110110
const fileRoot: string = path.dirname(document.uri.fsPath);
111111
if (clients.has(fileRoot)) return; // already registered
112-
this.logger.logInfo(
112+
this.logger.info(
113113
'Initialising Language Server for file: ' +
114114
`${document.uri.fsPath} with command-line options: ${args.join(', ')}`
115115
);
@@ -133,7 +133,7 @@ export class FortlsClient {
133133
if (!clients.has(folder.uri.toString())) {
134134
folder = getOuterMostWorkspaceFolder(folder);
135135
if (clients.has(folder.uri.toString())) return; // already registered
136-
this.logger.logInfo(
136+
this.logger.info(
137137
'Initialising Language Server for workspace: ' +
138138
`${document.uri.fsPath} with command-line options: ${args.join(', ')}`
139139
);
@@ -317,7 +317,7 @@ export class FortlsClient {
317317
fortlsDisabled = true;
318318
}
319319
if (install.stdout) {
320-
this.logger.logInfo(install.stdout.toString());
320+
this.logger.info(install.stdout.toString());
321321
fortlsDisabled = false;
322322
}
323323
} else if (opt == 'Disable') {
@@ -336,7 +336,7 @@ export class FortlsClient {
336336
* Restart the language server
337337
*/
338338
private async restartLS(): Promise<void> {
339-
this.logger.logInfo('Restarting language server...');
339+
this.logger.info('Restarting language server...');
340340
vscode.window.showInformationMessage('Restarting language server...');
341341
await this.deactivate();
342342
await this.activate();

0 commit comments

Comments
 (0)