aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/commands/cargo_watch.ts
blob: 9864ce01ac818c38dacc991eb10398c07c51be21 (plain)
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
import * as child_process from 'child_process';
import * as path from 'path';
import * as vscode from 'vscode';
import { Server } from '../server';
import { terminate } from '../utils/processes';
import { StatusDisplay } from './watch_status';


export class CargoWatchProvider {
    private diagnosticCollection?: vscode.DiagnosticCollection;
    private cargoProcess?: child_process.ChildProcess;
    private outBuffer: string = '';
    private statusDisplay?: StatusDisplay;
    private outputChannel?: vscode.OutputChannel;

    public activate(subscriptions: vscode.Disposable[]) {
        subscriptions.push(this);
        this.diagnosticCollection = vscode.languages.createDiagnosticCollection(
            'rustc'
        );

        this.statusDisplay = new StatusDisplay(subscriptions);
        this.outputChannel = vscode.window.createOutputChannel(
            'Cargo Watch Trace'
        );
            
        // Start the cargo watch with json message
        this.cargoProcess = child_process.spawn(
            'cargo',
            ['watch', '-x', '\"check --message-format json\"'],
            {
                stdio: ['ignore', 'pipe', 'pipe'],
                cwd: vscode.workspace.rootPath,
                windowsVerbatimArguments: true,
            }
        );

        this.cargoProcess.stdout.on('data', (s: string) => {
            this.processOutput(s, (line) => {
                this.logInfo(line);
                this.parseLine(line);
            });
        });

        this.cargoProcess.stderr.on('data', (s: string) => {
            this.processOutput(s, (line) => {
                this.logError('Error on cargo-watch : {\n' + line + '}\n' );
            });
        });

        this.cargoProcess.on('error', (err: Error) => {
            this.logError('Error on cargo-watch process : {\n' + err.message + '}\n');
        });

        this.logInfo('cargo-watch started.');
    }

    public dispose(): void {
        if (this.diagnosticCollection) {
            this.diagnosticCollection.clear();
            this.diagnosticCollection.dispose();
        }

        if (this.cargoProcess) {
            this.cargoProcess.kill();
            terminate(this.cargoProcess);
        }

        if(this.outputChannel) {
            this.outputChannel.dispose();
        }
    }

    private logInfo(line: string) {
        if (Server.config.cargoWatchOptions.trace === 'verbose') {
            this.outputChannel!.append(line);
        }                
    }

    private logError(line: string) {
        if (Server.config.cargoWatchOptions.trace === 'error' || Server.config.cargoWatchOptions.trace === 'verbose' ) {
            this.outputChannel!.append(line);
        }                
    }

    private parseLine(line: string) {
        if (line.startsWith('[Running')) {
            this.diagnosticCollection!.clear();
            this.statusDisplay!.show();
        }

        if (line.startsWith('[Finished running')) {
            this.statusDisplay!.hide();
        }

        function getLevel(s: string): vscode.DiagnosticSeverity {
            if (s === 'error') {
                return vscode.DiagnosticSeverity.Error;
            }

            if (s.startsWith('warn')) {
                return vscode.DiagnosticSeverity.Warning;
            }

            return vscode.DiagnosticSeverity.Information;
        }

        // cargo-watch itself output non json format
        // Ignore these lines
        let data = null;
        try {
            data = JSON.parse(line.trim());
        } catch (error) {
            return;
        }

        // Only handle compiler-message now
        if (data.reason !== 'compiler-message') {
            return;
        }

        let spans: any[] = data.message.spans;
        spans = spans.filter(o => o.is_primary);

        // We only handle primary span right now.
        if (spans.length > 0) {
            const o = spans[0];

            const rendered = data.message.rendered;
            const level = getLevel(data.message.level);
            const range = new vscode.Range(
                new vscode.Position(o.line_start - 1, o.column_start - 1),
                new vscode.Position(o.line_end - 1, o.column_end - 1)
            );

            const fileName = path.join(vscode.workspace.rootPath!, o.file_name);
            const diagnostic = new vscode.Diagnostic(range, rendered, level);

            diagnostic.source = 'rustc';
            diagnostic.code = data.message.code.code;
            diagnostic.relatedInformation = [];

            const fileUrl = vscode.Uri.file(fileName!);

            const diagnostics: vscode.Diagnostic[] = [
                ...(this.diagnosticCollection!.get(fileUrl) || [])
            ];
            diagnostics.push(diagnostic);

            this.diagnosticCollection!.set(fileUrl, diagnostics);
        }
    }

    private processOutput(chunk: string, cb: (line: string) => void  ) {
        // The stdout is not line based, convert it to line based for proceess.
        this.outBuffer += chunk;
        let eolIndex = this.outBuffer.indexOf('\n');
        while (eolIndex >= 0) {
            // line includes the EOL
            const line = this.outBuffer.slice(0, eolIndex + 1);
            cb(line);
            this.outBuffer = this.outBuffer.slice(eolIndex + 1);

            eolIndex = this.outBuffer.indexOf('\n');
        }
    }
}