-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathLanguageServer.spec.ts
More file actions
1803 lines (1557 loc) · 68.7 KB
/
LanguageServer.spec.ts
File metadata and controls
1803 lines (1557 loc) · 68.7 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { expect } from './chai-config.spec';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import type { ConfigurationItem, DidChangeWatchedFilesParams, Location, PublishDiagnosticsParams, WorkspaceFolder } from 'vscode-languageserver';
import { FileChangeType } from 'vscode-languageserver';
import { Deferred } from './deferred';
import { CustomCommands, LanguageServer } from './LanguageServer';
import { createSandbox } from 'sinon';
import { standardizePath as s, util } from './util';
import { TextDocument } from 'vscode-languageserver-textdocument';
import type { Program } from './Program';
import * as assert from 'assert';
import type { PartialDiagnostic } from './testHelpers.spec';
import { createInactivityStub, expectZeroDiagnostics, normalizeDiagnostics, trim } from './testHelpers.spec';
import { isBrsFile, isLiteralString } from './astUtils/reflection';
import { createVisitor, WalkMode } from './astUtils/visitors';
import { tempDir, rootDir } from './testHelpers.spec';
import { URI } from 'vscode-uri';
import { BusyStatusTracker } from './BusyStatusTracker';
import type { BscFile } from './interfaces';
import type { Project } from './lsp/Project';
import { LogLevel, Logger, createLogger } from './logging';
import { DiagnosticMessages } from './DiagnosticMessages';
import { standardizePath } from 'roku-deploy';
import undent from 'undent';
import { ProjectManager } from './lsp/ProjectManager';
import type { WorkspaceConfig } from './lsp/ProjectManager';
const sinon = createSandbox();
const workspacePath = rootDir;
const enableThreadingDefault = LanguageServer.enableThreadingDefault;
describe('LanguageServer', () => {
let server: LanguageServer;
let program: Program;
let workspaceFolders: string[] = [];
let connection = {
onInitialize: () => null,
onInitialized: () => null,
onDidChangeConfiguration: () => null,
onDidChangeWatchedFiles: () => null,
onCompletion: () => null,
onCompletionResolve: () => null,
onDocumentSymbol: () => null,
onWorkspaceSymbol: () => null,
onDefinition: () => null,
onSignatureHelp: () => null,
onReferences: () => null,
onHover: () => null,
listen: () => null,
sendNotification: () => null,
sendDiagnostics: () => null,
onExecuteCommand: () => null,
onCodeAction: () => null,
onDidOpenTextDocument: () => null,
onDidChangeTextDocument: () => null,
onDidCloseTextDocument: () => null,
onWillSaveTextDocument: () => null,
onWillSaveTextDocumentWaitUntil: () => null,
onDidSaveTextDocument: () => null,
onRequest: () => null,
workspace: {
getWorkspaceFolders: () => {
return workspaceFolders.map(
x => ({
uri: getFileProtocolPath(x),
name: path.basename(x)
})
);
},
getConfiguration: () => {
return {};
},
onDidChangeWorkspaceFolders: () => { }
},
tracer: {
log: () => { }
},
client: {
register: () => Promise.resolve()
}
};
beforeEach(() => {
sinon.restore();
fsExtra.emptyDirSync(tempDir);
server = new LanguageServer();
server['busyStatusTracker'] = new BusyStatusTracker();
workspaceFolders = [workspacePath];
LanguageServer.enableThreadingDefault = false;
//mock the connection stuff
sinon.stub(server as any, 'establishConnection').callsFake(() => {
return connection;
});
server['hasConfigurationCapability'] = true;
});
afterEach(() => {
sinon.restore();
fsExtra.emptyDirSync(tempDir);
server['dispose']();
LanguageServer.enableThreadingDefault = enableThreadingDefault;
});
function addXmlFile(name: string, additionalXmlContents = '') {
const filePath = `components/${name}.xml`;
const contents = `<?xml version="1.0" encoding="utf-8"?>
<component name="${name}" extends="Group">
${additionalXmlContents}
<script type="text/brightscript" uri="${name}.brs" />
</component>`;
return program.setFile(filePath, contents);
}
function addScriptFile(name: string, contents: string, extension = 'brs') {
const filePath = s`components/${name}.${extension}`;
const file = program.setFile(filePath, contents);
if (file) {
const document = TextDocument.create(util.pathToUri(file.srcPath), 'brightscript', 1, contents);
(server['documents']['_syncedDocuments'] as Map<string, TextDocument>).set(document.uri, document);
return document;
}
}
it('does not cause infinite loop of project creation', async () => {
//add a project with a files array that includes (and then excludes) a file
fsExtra.outputFileSync(s`${rootDir}/bsconfig.json`, JSON.stringify({
files: ['source/**/*', '!source/**/*.spec.bs']
}));
server['run']();
function setSyncedDocument(srcPath: string, text: string, version = 1) {
//force an open text document
const document = TextDocument.create(util.pathToUri(
util.standardizePath(srcPath
)
), 'brightscript', 1, `sub main()\nend sub`);
(server['documents']['_syncedDocuments'] as Map<string, TextDocument>).set(document.uri, document);
}
//wait for the projects to finish loading up
await server['syncProjects']();
//this bug was causing an infinite async loop of new project creations. So monitor the creation of new projects for evaluation later
const { stub, promise: createProjectsSettled } = createInactivityStub(ProjectManager.prototype as any, 'constructProject', 400, sinon);
setSyncedDocument(s`${rootDir}/source/lib1.spec.bs`, 'sub lib1()\nend sub');
setSyncedDocument(s`${rootDir}/source/lib2.spec.bs`, 'sub lib2()\nend sub');
// open a file that is excluded by the project, so it should trigger a standalone project.
await server['onTextDocumentDidChangeContent']({
document: TextDocument.create(util.pathToUri(s`${rootDir}/source/lib1.spec.bs`), 'brightscript', 1, `sub main()\nend sub`)
});
//wait for the "create projects" deferred debounce to settle
await createProjectsSettled;
//test passes if we've only made 2 new projects (one for each of the standalone projects)
expect(stub.callCount).to.eql(2);
});
describe('onDidChangeConfiguration', () => {
async function doTest(startingConfigs: WorkspaceConfig[], endingConfigs: WorkspaceConfig[]) {
(server as any)['connection'] = connection;
server['workspaceConfigsCache'] = new Map(startingConfigs.map(x => [x.workspaceFolder, x]));
const stub = sinon.stub(server as any, 'getWorkspaceConfigs').returns(Promise.resolve(endingConfigs));
await server.onDidChangeConfiguration({ settings: {} });
stub.restore();
}
it('does not reload project when: no projects are present before and after', async () => {
const stub = sinon.stub(server as any, 'syncProjects').callsFake(() => Promise.resolve());
await doTest([], []);
expect(stub.called).to.be.false;
});
it('does not reload project when: 1 project is unchanged', async () => {
const stub = sinon.stub(server as any, 'syncProjects').callsFake(() => Promise.resolve());
await doTest([{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}], [{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}]);
expect(stub.called).to.be.false;
});
it('reloads project when adding new project', async () => {
const stub = sinon.stub(server as any, 'syncProjects').callsFake(() => Promise.resolve());
await doTest([], [{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}]);
expect(stub.called).to.be.true;
});
it('reloads project when deleting a project', async () => {
const stub = sinon.stub(server as any, 'syncProjects').callsFake(() => Promise.resolve());
await doTest([{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}, {
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: s`${tempDir}/project2`,
excludePatterns: []
}], [{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}]);
expect(stub.called).to.be.true;
});
it('reloads project when changing specific settings', async () => {
const stub = sinon.stub(server as any, 'syncProjects').callsFake(() => Promise.resolve());
await doTest([{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'trace'
},
workspaceFolder: workspacePath,
excludePatterns: []
}], [{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}]);
expect(stub.called).to.be.true;
});
});
describe('sendDiagnostics', () => {
it('dedupes diagnostics found at same location from multiple projects', async () => {
fsExtra.outputFileSync(s`${rootDir}/common/lib.brs`, `
sub test()
print alpha 'variable does not exist
end sub
`);
fsExtra.outputFileSync(s`${rootDir}/project1/bsconfig.json`, JSON.stringify({
rootDir: s`${rootDir}/project1`,
files: [{
src: `../common/lib.brs`,
dest: 'source/lib.brs'
}]
}));
fsExtra.outputFileSync(s`${rootDir}/project2/bsconfig.json`, JSON.stringify({
rootDir: s`${rootDir}/project2`,
files: [{
src: `../common/lib.brs`,
dest: 'source/lib.brs'
}]
}));
server['connection'] = connection as any;
let sendDiagnosticsDeferred = new Deferred<any>();
let stub = sinon.stub(server['connection'], 'sendDiagnostics').callsFake(async (arg) => {
sendDiagnosticsDeferred.resolve(arg);
return sendDiagnosticsDeferred.promise;
});
await server['syncProjects']();
await sendDiagnosticsDeferred.promise;
expect(stub.getCall(0).args?.[0]?.diagnostics).to.be.lengthOf(1);
});
});
describe('project-activate', () => {
it('should sync all open document changes to all projects', async () => {
//force an open text document
const srcPath = s`${rootDir}/source/main.brs`;
const document = TextDocument.create(util.pathToUri(srcPath), 'brightscript', 1, `sub main()\nend sub`);
(server['documents']['_syncedDocuments'] as Map<string, TextDocument>).set(document.uri, document);
const deferred = new Deferred();
const stub = sinon.stub(server['projectManager'], 'handleFileChanges').callsFake(() => {
deferred.resolve();
return Promise.resolve();
});
server['projectManager']['emit']('project-activate', {
project: server['projectManager'].projects[0]
});
await deferred.promise;
expect(
stub.getCalls()[0].args[0].map(x => ({
srcPath: x.srcPath,
fileContents: x.fileContents
}))
).to.eql([{
srcPath: srcPath,
fileContents: document.getText()
}]);
});
it('handles when there were no open documents', () => {
server['projectManager']['emit']('project-activate', {
project: {
projectNumber: 1
}
} as any);
//we can't really test this, but it helps with code coverage...
});
});
describe('syncProjects', () => {
it('loads workspace as project', async () => {
server.run();
expect(server['projectManager'].projects).to.be.lengthOf(0);
fsExtra.ensureDirSync(workspacePath);
await server['syncProjects']();
//no child bsconfig.json files, use the workspacePath
expect(
server['projectManager'].projects.map(x => x.projectPath)
).to.eql([
workspacePath
]);
fsExtra.outputJsonSync(s`${workspacePath}/project1/bsconfig.json`, {});
fsExtra.outputJsonSync(s`${workspacePath}/project2/bsconfig.json`, {});
await server['syncProjects']();
//2 child bsconfig.json files. Use those folders as projects, and don't use workspacePath
expect(
server['projectManager'].projects.map(x => x.projectPath).sort()
).to.eql([
s`${workspacePath}/project1`,
s`${workspacePath}/project2`
]);
fsExtra.removeSync(s`${workspacePath}/project2/bsconfig.json`);
await server['syncProjects']();
//1 child bsconfig.json file. Still don't use workspacePath
expect(
server['projectManager'].projects.map(x => x.projectPath)
).to.eql([
s`${workspacePath}/project1`
]);
fsExtra.removeSync(s`${workspacePath}/project1/bsconfig.json`);
await server['syncProjects']();
//back to no child bsconfig.json files. use workspacePath again
expect(
server['projectManager'].projects.map(x => x.projectPath)
).to.eql([
workspacePath
]);
});
it('ignores bsconfig.json files from vscode ignored paths', async () => {
const mapItem = (item: ConfigurationItem) => {
if (item.section === 'files') {
return {
exclude: {
'**/vendor': true
}
};
} else if (item.section === 'search') {
return {
exclude: {
'**/temp': true
}
};
} else {
return {};
}
};
server.run();
sinon.stub(server['connection'].workspace, 'getConfiguration').callsFake(
// @ts-expect-error Sinon incorrectly infers the type of this function
(items: any) => {
if (typeof items === 'string') {
return Promise.resolve({});
}
if (Array.isArray(items)) {
return Promise.resolve(items.map(mapItem));
}
return Promise.resolve(mapItem(items));
}
);
await server.onInitialized();
fsExtra.outputJsonSync(s`${workspacePath}/vendor/someProject/bsconfig.json`, {});
fsExtra.outputJsonSync(s`${workspacePath}/temp/someProject/bsconfig.json`, {});
//it always ignores node_modules
fsExtra.outputJsonSync(s`${workspacePath}/node_modules/someProject/bsconfig.json`, {});
await server['syncProjects']();
//no child bsconfig.json files, use the workspacePath
expect(
server['projectManager'].projects.map(x => x.projectPath)
).to.eql([
workspacePath
]);
});
it('does not produce duplicate projects when subdir and parent dir are opened as workspace folders', async () => {
fsExtra.outputJsonSync(s`${tempDir}/root/bsconfig.json`, {});
fsExtra.outputJsonSync(s`${tempDir}/root/subdir/bsconfig.json`, {});
workspaceFolders = [
s`${tempDir}/root`,
s`${tempDir}/root/subdir`
];
server.run();
await server['syncProjects']();
expect(
server['projectManager'].projects.map(x => x.projectPath).sort()
).to.eql([
s`${tempDir}/root`,
s`${tempDir}/root/subdir`
]);
});
it('finds nested roku-like dirs', async () => {
fsExtra.outputFileSync(s`${tempDir}/project1/manifest`, '');
fsExtra.outputFileSync(s`${tempDir}/project1/source/main.brs`, '');
fsExtra.outputFileSync(s`${tempDir}/sub/dir/project2/manifest`, '');
fsExtra.outputFileSync(s`${tempDir}/sub/dir/project2/source/main.bs`, '');
//does not match folder with manifest without a sibling ./source folder
fsExtra.outputFileSync(s`${tempDir}/project3/manifest`, '');
workspaceFolders = [
s`${tempDir}/`
];
server.run();
await server['syncProjects']();
expect(
server['projectManager'].projects.map(x => x.projectPath).sort()
).to.eql([
s`${tempDir}/project1`,
s`${tempDir}/sub/dir/project2`
]);
});
});
describe('onInitialize', () => {
it('sets capabilities', async () => {
server['hasConfigurationCapability'] = false;
server['clientHasWorkspaceFolderCapability'] = false;
await server.onInitialize({
capabilities: {
workspace: {
configuration: true,
workspaceFolders: true
}
}
} as any);
expect(server['hasConfigurationCapability']).to.be.true;
expect(server['clientHasWorkspaceFolderCapability']).to.be.true;
});
});
describe('onInitialized', () => {
it('registers workspaceFolders change listener', async () => {
server['connection'] = connection as any;
const deferred = new Deferred();
sinon.stub(server['connection']['workspace'], 'onDidChangeWorkspaceFolders').callsFake((() => {
deferred.resolve();
}) as any);
server['hasConfigurationCapability'] = false;
server['clientHasWorkspaceFolderCapability'] = true;
await server.onInitialized();
//if the promise resolves, we know the function was called
await deferred.promise;
});
});
describe('syncLogLevel', () => {
beforeEach(() => {
//disable logging for these tests
sinon.stub(Logger.prototype, 'write').callsFake(() => { });
});
it('uses a default value when no workspace or projects are present', async () => {
server.run();
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.log);
});
it('recovers when workspace sends unsupported value', async () => {
server.run();
sinon.stub(server as any, 'getClientConfiguration').returns(Promise.resolve({
languageServer: {
logLevel: 'not-valid'
}
}));
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.log);
});
it('uses logLevel from workspace', async () => {
server.run();
sinon.stub(server as any, 'getClientConfiguration').returns(Promise.resolve({
languageServer: {
logLevel: 'trace'
}
}));
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.trace);
});
it('uses the higher-verbosity logLevel from multiple workspaces', async () => {
server.run();
//mock multiple workspaces
sinon.stub(server['connection'].workspace, 'getWorkspaceFolders').returns(Promise.resolve([
{
name: 'workspace1',
uri: getFileProtocolPath(s`${tempDir}/project1`)
},
{
name: 'workspace1',
uri: getFileProtocolPath(s`${tempDir}/project2`)
}
]));
sinon.stub(server as any, 'getClientConfiguration').onFirstCall().returns(Promise.resolve({
languageServer: {
logLevel: 'trace'
}
})).onSecondCall().returns(Promise.resolve({
languageServer: {
logLevel: 'info'
}
}));
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.trace);
});
it('uses valid workspace value when one of them is invalid', async () => {
server.run();
//mock multiple workspaces
sinon.stub(server['connection'].workspace, 'getWorkspaceFolders').returns(Promise.resolve([
{
name: 'workspace1',
uri: getFileProtocolPath(s`${tempDir}/project1`)
},
{
name: 'workspace1',
uri: getFileProtocolPath(s`${tempDir}/project2`)
}
]));
sinon.stub(server as any, 'getClientConfiguration').onFirstCall().returns(Promise.resolve({
languageServer: {
logLevel: 'trace1'
}
})).onSecondCall().returns(Promise.resolve({
languageServer: {
logLevel: 'info'
}
}));
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.info);
});
it('uses value from projects when not found in workspace', async () => {
server.run();
//mock multiple workspaces
sinon.stub(server['connection'].workspace, 'getWorkspaceFolders').returns(Promise.resolve([{
name: 'workspace1',
uri: getFileProtocolPath(s`${tempDir}/project2`)
}]));
server['projectManager'].projects.push({
logger: createLogger({
logLevel: LogLevel.info
}),
projectNumber: 2
} as any);
await server['syncLogLevel']();
expect(server.logger.logLevel).to.eql(LogLevel.info);
});
});
describe('rebuildPathFilterer', () => {
let workspaceConfigs: WorkspaceConfig[] = [];
beforeEach(() => {
workspaceConfigs = [
{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: workspacePath,
excludePatterns: []
}
];
server['connection'] = connection as any;
sinon.stub(server as any, 'getWorkspaceConfigs').callsFake(() => Promise.resolve(workspaceConfigs));
});
it('allows files from dist by default', async () => {
const filterer = await server['rebuildPathFilterer']();
//certain files are allowed through by default
expect(
filterer.filter([
s`${rootDir}/manifest`,
s`${rootDir}/dist/file.brs`,
s`${rootDir}/source/file.brs`
])
).to.eql([
s`${rootDir}/manifest`,
s`${rootDir}/dist/file.brs`,
s`${rootDir}/source/file.brs`
]);
});
it('filters out some standard locations by default', async () => {
const filterer = await server['rebuildPathFilterer']();
expect(
filterer.filter([
s`${workspacePath}/node_modules/file.brs`,
s`${workspacePath}/.git/file.brs`,
s`${workspacePath}/out/file.brs`,
s`${workspacePath}/.roku-deploy-staging/file.brs`
])
).to.eql([]);
});
it('properly handles a .gitignore list', async () => {
fsExtra.outputFileSync(s`${workspacePath}/.gitignore`, undent`
dist/
`);
const filterer = await server['rebuildPathFilterer']();
//filters files that appear in a .gitignore list
expect(
filterer.filter([
s`${workspacePath}/src/source/file.brs`,
//this file should be excluded
s`${workspacePath}/dist/source/file.brs`
])
).to.eql([
s`${workspacePath}/src/source/file.brs`
]);
});
it('does not crash for path outside of workspaceFolder', async () => {
fsExtra.outputFileSync(s`${workspacePath}/.gitignore`, undent`
dist/
`);
const filterer = await server['rebuildPathFilterer']();
//filters files that appear in a .gitignore list
expect(
filterer.filter([
s`${workspacePath}/../flavor1/src/source/file.brs`
])
).to.eql([
//since the path is outside the workspace, it does not match the .gitignore patter, and thus is not excluded
s`${workspacePath}/../flavor1/src/source/file.brs`
]);
});
it('a gitignore file from any workspace will apply to all workspaces', async () => {
workspaceConfigs = [{
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: s`${tempDir}/flavor1`,
excludePatterns: []
}, {
bsconfigPath: undefined,
languageServer: {
enableThreading: false,
enableDiscovery: true,
logLevel: 'info'
},
workspaceFolder: s`${tempDir}/flavor2`,
excludePatterns: []
}];
fsExtra.outputFileSync(s`${workspaceConfigs[0].workspaceFolder}/.gitignore`, undent`
dist/
`);
fsExtra.outputFileSync(s`${workspaceConfigs[1].workspaceFolder}/.gitignore`, undent`
out/
`);
const filterer = await server['rebuildPathFilterer']();
//filters files that appear in a .gitignore list
expect(
filterer.filter([
//included files
s`${workspaceConfigs[0].workspaceFolder}/src/source/file.brs`,
s`${workspaceConfigs[1].workspaceFolder}/src/source/file.brs`,
//excluded files
s`${workspaceConfigs[0].workspaceFolder}/dist/source/file.brs`,
s`${workspaceConfigs[1].workspaceFolder}/out/source/file.brs`
])
).to.eql([
s`${workspaceConfigs[0].workspaceFolder}/src/source/file.brs`,
s`${workspaceConfigs[1].workspaceFolder}/src/source/file.brs`
]);
});
it('does not erase project-specific filters', async () => {
let filterer = await server['rebuildPathFilterer']();
const files = [
s`${rootDir}/node_modules/one/file.xml`,
s`${rootDir}/node_modules/two.bs`,
s`${rootDir}/node_modules/three/dist/lib.bs`
];
//all node_modules files are filtered out by default, unless included in an includeList
expect(filterer.filter(files)).to.eql([]);
//register two specific node_module folders to include
filterer.registerIncludeList(rootDir, ['node_modules/one/**/*', 'node_modules/two.bs']);
//unless included in an includeList
expect(filterer.filter(files)).to.eql([
s`${rootDir}/node_modules/one/file.xml`,
s`${rootDir}/node_modules/two.bs`
//three should still be excluded
]);
//rebuild the path filterer, make sure the project's includeList is still retained
filterer = await server['rebuildPathFilterer']();
expect(filterer.filter(files)).to.eql([
//one and two should still make it through the filter unscathed
s`${rootDir}/node_modules/one/file.xml`,
s`${rootDir}/node_modules/two.bs`
//three should still be excluded
]);
});
it('a removed project includeList gets unregistered', async () => {
let filterer = await server['rebuildPathFilterer']();
const files = [
s`${rootDir}/project1/node_modules/one/file.xml`,
s`${rootDir}/project1/node_modules/two.bs`,
s`${rootDir}/project1/node_modules/three/dist/lib.bs`
];
//all node_modules files are filtered out by default, unless included in an includeList
expect(filterer.filter(files)).to.eql([]);
//register a new project that references a file from node_modules
fsExtra.outputFileSync(s`${rootDir}/project1/bsconfig.json`, JSON.stringify({
files: ['node_modules/one/file.xml']
}));
await server['syncProjects']();
//one should be included because the project references it
expect(filterer.filter(files)).to.eql([
s`${rootDir}/project1/node_modules/one/file.xml`
]);
//delete the project's bsconfig.json and sync again (thus destroying the project)
fsExtra.removeSync(s`${rootDir}/project1/bsconfig.json`);
await server['syncProjects']();
//the project's pathFilterer pattern has been unregistered
expect(filterer.filter(files)).to.eql([]);
});
});
describe('onDidChangeWatchedFiles', () => {
it('does not trigger revalidates when changes are in files which are not tracked', async () => {
server.run();
const externalDir = s`${tempDir}/not_app_dir`;
fsExtra.outputJsonSync(s`${externalDir}/bsconfig.json`, {});
fsExtra.outputFileSync(s`${externalDir}/source/main.brs`, '');
fsExtra.outputFileSync(s`${externalDir}/source/lib.brs`, '');
await server['syncProjects']();
const stub2 = sinon.stub((server['projectManager'].projects[0] as Project)['builder'].program, 'setFile');
await server['onDidChangeWatchedFiles']({
changes: [{
type: FileChangeType.Created,
uri: getFileProtocolPath(externalDir)
}]
} as DidChangeWatchedFilesParams);
expect(
stub2.getCalls()
).to.be.empty;
});
it('rebuilds the path filterer when certain files are changed', async () => {
sinon.stub(server['projectManager'], 'handleFileChanges').callsFake(() => Promise.resolve());
(server as any)['connection'] = connection;
async function test(filePath: string, expected = true) {
const stub = sinon.stub(server as any, 'rebuildPathFilterer');
await server['onDidChangeWatchedFiles']({
changes: [{
type: FileChangeType.Changed,
uri: util.pathToUri(filePath)
}]
} as DidChangeWatchedFilesParams);
expect(
stub.getCalls().length
).to.eql(expected ? 1 : 0);
stub.restore();
}
await test(s`${rootDir}/bsconfig.json`);
await test(s`${rootDir}/sub/dir/bsconfig.json`);
await test(s`${rootDir}/.vscode/settings.json`);
await test(s`${rootDir}/.gitignore`);
await test(s`${rootDir}/sub/dir/.two/.gitignore`);
await test(s`${rootDir}/source/main.brs`, false);
});
it('excludes explicit workspaceFolder paths', async () => {
(server as any).connection = connection;
sinon.stub(server['connection'].workspace, 'getWorkspaceFolders').returns(Promise.resolve([{
name: 'workspace1',
uri: util.pathToUri(s`${tempDir}/project1`)
} as WorkspaceFolder]));
const stub = sinon.stub(server['projectManager'], 'handleFileChanges').callsFake(() => Promise.resolve());
await server['onDidChangeWatchedFiles']({
changes: [{
type: FileChangeType.Created,
uri: util.pathToUri(s`${tempDir}/project1`)
}]
} as DidChangeWatchedFilesParams);
//it did not send along the workspace folder itself
expect(
stub.getCalls()[0].args[0]
).to.eql([]);
});
});
describe('onDocumentClose', () => {
it('calls handleFileClose', async () => {
const stub = sinon.stub(server['projectManager'], 'handleFileClose').callsFake((() => { }) as any);
await server['onDocumentClose']({
document: {
uri: util.pathToUri(s`${rootDir}/source/main.brs`)
} as any
});
expect(stub.args[0][0].srcPath).to.eql(s`${rootDir}/source/main.brs`);
});
});
describe('onSignatureHelp', () => {
let callDocument: TextDocument;
let importingXmlFile: BscFile;
const functionFileBaseName = 'buildAwesome';
const funcDefinitionLine = 'function buildAwesome(confirm = true as Boolean)';
beforeEach(async () => {
server['connection'] = server['establishConnection']();
await server['syncProjects']();
program = (server['projectManager'].projects[0] as Project)['builder'].program;
const name = `CallComponent`;
callDocument = addScriptFile(name, `
sub init()
shouldBuildAwesome = true
if shouldBuildAwesome then
buildAwesome()
else
m.buildAwesome()
end if
end sub
`)!;
importingXmlFile = addXmlFile(name, `<script type="text/brightscript" uri="${functionFileBaseName}.bs" />`);
});
it('should return the expected signature info when documentation is included', async () => {
const funcDescriptionComment = '@description Builds awesome for you';
const funcReturnComment = '@return {Integer} The key to everything';
addScriptFile(functionFileBaseName, `
' /**
' * ${funcDescriptionComment}
' * ${funcReturnComment}
' */
${funcDefinitionLine}
return 42
end function
`, 'bs');
const result = await server['onSignatureHelp']({
textDocument: {
uri: callDocument.uri
},
position: util.createPosition(4, 37)
});
expect(result.signatures).to.not.be.empty;
const signature = result.signatures[0];
expect(signature.label).to.equal(funcDefinitionLine);
expect(signature.documentation).to.include(funcDescriptionComment);
expect(signature.documentation).to.include(funcReturnComment);
});
it('should work if used on a property value', async () => {
addScriptFile(functionFileBaseName, `
${funcDefinitionLine}
return 42
end function