src/commands/prettify.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 2

Size

Lines of Code 47
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 40
mnd 2
bc 2
fnc 2
dl 0
loc 47
bpm 1
cpm 2
noi 0
c 0
b 0
f 0
rs 10

2 Functions

Rating   Name   Duplication   Size   Complexity  
A prettify.ts ➔ parseJSONLine 0 12 2
A prettify.ts ➔ prettify 0 18 2
1
import * as vscode from 'vscode';
2
import { LINE_SEPERATOR, TAB_SIZE } from '../constants';
3
import { commandDecorator } from './utils';
4
5
export const MESSAGES = {
6
    SUCCESS_MESSAGE : 'Logs prettified',
7
    ERROR_MESSAGE   : 'Error occured',
8
9
    EDITOR_NOT_FOUND : 'No editor found'
10
};
11
12
function parseJSONLine(line: string, index: number) {
13
    try {
14
        const json = JSON.parse(line);
15
16
        return JSON.stringify(json, null, TAB_SIZE);
17
    } catch (error) {
18
        console.error(`CANT_PARSE_LINE ${index}`);
19
        console.error(line);
20
        console.error(error);
21
22
        return line;
23
    }
24
}
25
26
export function prettify() {
27
    const editor = vscode.window.activeTextEditor;
28
29
    if (!editor) {
30
        return console.error(MESSAGES.EDITOR_NOT_FOUND);
31
    }
32
33
    const raw = editor.document.getText();
34
    const lines = raw.split(LINE_SEPERATOR);
35
    const modified = lines.map((line, index) => parseJSONLine(line, index));
36
37
    editor.edit(builder => {
38
        const firstLine = editor.document.lineAt(0);
39
        const lastLine = editor.document.lineAt(editor.document.lineCount - 1);
40
        const range = new vscode.Range(firstLine.range.start, lastLine.range.end);
41
42
        builder.replace(range, modified.join('\n'));
43
    });
44
}
45
46
export default commandDecorator(prettify, MESSAGES);
47