-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathactivateDaffodilDebug.ts
More file actions
928 lines (836 loc) · 29.6 KB
/
Copy pathactivateDaffodilDebug.ts
File metadata and controls
928 lines (836 loc) · 29.6 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict'
import * as fs from 'fs'
import * as path from 'path'
import * as vscode from 'vscode'
import * as infoset from '../infoset'
import * as launchWizard from '../launchWizard/launchWizard'
import * as dfdlLang from '../language/dfdl'
import * as dfdlExt from '../language/semantics/dfdlExt'
import * as dataEditClient from '../dataEditor'
import * as tdmlEditor from '../tdmlEditor'
import * as rootCompletion from '../rootCompletion'
import { tmpdir } from 'os'
import JSZip from 'jszip'
import { rm } from 'node:fs/promises'
import { getTunables } from './extension'
import {
CancellationToken,
DebugConfiguration,
ProviderResult,
WorkspaceFolder,
} from 'vscode'
import { getDataFileFromFolder, getDebugger } from '../daffodilDebugger'
import { getConfig, getCurrentConfig, getTDMLTestCaseItems } from '../utils'
import { FileAccessor } from './daffodilRuntime'
import { TDMLConfig } from '../classes/tdmlConfig'
import { handleDebugEvent } from './daffodilEvent'
import { InlineDebugAdapterFactory } from './extension'
import {
appendTestCase,
readTDMLFileContents,
getTmpTDMLFilePath,
copyTestCase,
TMP_TDML_FILENAME,
} from '../tdmlEditor/utilities/tdmlXmlUtils'
import xmlFormat from 'xml-formatter'
import { CommandsProvider } from '../views/commands'
import * as daffodilDebugErrors from './daffodilDebugErrors'
import { TDMLProvider } from '../tdmlEditor/TDMLProvider'
import { getTestCaseDisplayData } from '../tdmlEditor/utilities/tdmlXmlUtils'
export const outputChannel: vscode.OutputChannel =
vscode.window.createOutputChannel('Daffodil')
async function createDirectory(directoryPath: string): Promise<void> {
try {
await fs.promises.mkdir(directoryPath, { recursive: true })
console.log(`Directory created successfully at ${directoryPath}`)
} catch (error) {
console.error(`Error creating directory:`, error)
throw error
}
}
async function copyFileAsync(src: string, dest: string): Promise<void> {
try {
// Ensure directory exists first
await fs.promises.mkdir(path.dirname(dest), { recursive: true })
await fs.promises.copyFile(src, dest)
console.log(`'${src}' was copied to '${dest}'`)
} catch (err) {
console.error('Error copying file:', err)
// Propagate the error so callers awaiting this function observe failures
throw err
}
}
/** Method to file path for schema and data
* Details:
* Required so that the vscode api commands:
* - extension.dfdl-debug.getSchemaName
* - extension.dfdl-debug.getDataName
* can be sent a file instead of always opening up a prompt.
* Always makes it so the vscode api commands above are able
* to be tested inside of the test suite
*/
async function getFile(fileRequested, label, title) {
let file = ''
if (fileRequested && fs.existsSync(fileRequested)) {
file = fileRequested
} else if (fileRequested && !fs.existsSync(fileRequested)) {
file = ''
} else {
file = await vscode.window
.showOpenDialog({
canSelectMany: false,
openLabel: label,
canSelectFiles: true,
canSelectFolders: false,
title: title,
})
.then((fileUri) => {
if (fileUri && fileUri[0]) {
let path = fileUri[0].fsPath
return normalizePath(path)
}
return ''
})
}
return file
}
// Method to normalize the drive letter in a Windows path to a capital letter
// Even when using Windows, when sending a path to the backend that will be used
// to determine the source file for breakpoints/debugging, it must be case-sensitive
function normalizePath(path: string): string {
if (
process.platform === 'win32' &&
path.length > 2 &&
path.charCodeAt(0) > 97 &&
path.charCodeAt(0) <= 122 &&
path.charAt(1) === ':'
)
return path.charAt(0).toUpperCase() + path.slice(1)
return path
}
/**
* Configures the file path string of an intended TDML save file if the
* extension is malformed.
* @param pathStr
* @returns file path string with a valid TDML file extension.
*/
function validateTDMLFilePath(pathStr: string): string {
// Create capture groups for the path
// Capture Group 2 will be all valid extensions potentially chained at the end of the path
// Capture Group 1 will be the rest of the filename (before the valid extensions)
const matches = pathStr.match(/(^.*?)((\.tdml|\.tdml\.xml)*)$/i)
if (matches) {
// We want to grab the first valid extension found from the previous regex's Capture Group 2
// and append that to the filename with TDML extensions stripped (previous regex's Capture Group 1)
const extMatches = matches[2].match(/^\.tdml.xml|^\.tdml/i)
return extMatches ? matches[1] + extMatches : matches[1] + '.tdml'
}
return pathStr + '.tdml'
}
/** Method to show dialog to save TDML file
* Details:
* Required so that the vscode api commands:
* - extension.dfdl-debug.getValidatedTDMLCopyPath
* can be sent a file instead of always opening up a prompt.
*/
async function showTDMLSaveDialog(fileRequested, label, title) {
let file = await vscode.window.showSaveDialog({
saveLabel: label,
title: title,
filters: {
TDML: ['tdml', 'tdml.xml'],
},
defaultUri: fileRequested,
})
if (!file) {
vscode.window.showErrorMessage('No output TDML filename provided')
return
}
return validateTDMLFilePath(normalizePath(file.fsPath))
}
// Function for setting up the commands for Run and Debug file
async function createDebugRunFileConfigs(
resource: vscode.Uri,
runOrDebug: String,
tdmlAction: string | undefined,
runLast = false
) {
let targetResource: vscode.Uri | undefined = resource
let noDebug = runOrDebug === 'run'
if (!targetResource) {
if (vscode.window.activeTextEditor) {
targetResource = vscode.window.activeTextEditor.document.uri
} else {
const tdmlUri = TDMLProvider.getDocumentUri()
if (tdmlUri) {
targetResource = tdmlUri
}
}
}
if (targetResource) {
const normalizedResource = normalizePath(targetResource.fsPath)
let infosetFile = `${
path.basename(normalizedResource).split('.')[0]
}-infoset.xml`
vscode.window.showInformationMessage(infosetFile)
let currentConfig = getCurrentConfig()
if (runLast && currentConfig) {
vscode.debug.startDebugging(undefined, currentConfig, {
noDebug: noDebug,
})
} else {
var tdmlConfig: TDMLConfig | undefined = undefined
var newData: string | undefined = undefined
var newSchema: string | undefined = normalizedResource
if (tdmlAction) {
tdmlConfig = { action: tdmlAction }
if (tdmlAction === 'execute') {
tdmlConfig.path = normalizedResource
newData = undefined
newSchema = undefined
}
}
const config = getConfig({
name: 'Run File',
request: 'launch',
type: 'dfdl',
schema: {
path: newSchema,
rootName: null,
rootNamespace: null,
},
data: newData,
infosetFormat: 'xml',
infosetOutput: {
type: 'file',
path: '${workspaceFolder}/' + infosetFile,
},
...(tdmlConfig && { tdmlConfig: tdmlConfig }),
})
vscode.debug.startDebugging(undefined, config, { noDebug: noDebug })
}
}
}
function setupViews(context: vscode.ExtensionContext) {
new CommandsProvider().register(context)
}
export function activateDaffodilDebug(
context: vscode.ExtensionContext,
factory?: vscode.DebugAdapterDescriptorFactory
) {
setupViews(context)
context.subscriptions.push(
vscode.commands.registerCommand('getContext', () => context)
)
context.subscriptions.push(
vscode.commands.registerCommand(
'extension.dfdl-debug.runEditorContents',
(resource: vscode.Uri) => {
createDebugRunFileConfigs(resource, 'run', undefined)
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.debugEditorContents',
(resource: vscode.Uri) => {
createDebugRunFileConfigs(resource, 'debug', undefined)
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.debugLastEditorContents',
(resource: vscode.Uri) => {
createDebugRunFileConfigs(resource, 'debug', undefined, true)
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.appendTDML',
async (resource: vscode.Uri) => {
if (!fs.existsSync(getTmpTDMLFilePath())) {
vscode.window.showErrorMessage(
`TDML ERROR: Test suite not found. Ensure that the TDML action is set to "generate" for your DFDL debugging launch configuration before appending.`
)
console.error(
`TDML ERROR: Test suite not found. ${TMP_TDML_FILENAME} was not found in ${tmpdir()} for Append TDML operation.`
)
return
}
let targetResource = resource
if (!targetResource) {
if (vscode.window.activeTextEditor) {
targetResource = vscode.window.activeTextEditor.document.uri
} else {
const tdmlUri = TDMLProvider.getDocumentUri()
if (tdmlUri) {
targetResource = tdmlUri
}
}
}
if (targetResource) {
appendTestCase(getTmpTDMLFilePath(), targetResource.fsPath)
.then((appendedBuffer) => {
fs.writeFileSync(targetResource.fsPath, xmlFormat(appendedBuffer))
})
.catch((reason) => {
// Not sure if we need to do something different/more here
console.log(reason)
})
}
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.executeTDML',
(resource: vscode.Uri) => {
createDebugRunFileConfigs(resource, 'debug', 'execute')
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.createTDML',
async (_) => {
if (!fs.existsSync(getTmpTDMLFilePath())) {
vscode.window.showErrorMessage(
`TDML ERROR: Test suite not found. Ensure that the TDML action is set to "generate" for your DFDL debugging launch configuration before copying.`
)
console.error(
`TDML ERROR: Test suite not found. ${TMP_TDML_FILENAME} was not found in ${tmpdir()} for Copy TDML operation.`
)
return
}
// Ask for destination path
// Copy file in /tmp to destination path
// TDMLConfig.path should not be used here because that only matters when sending to the server
// We could make it so that if someone wants to specify the path and set the action to 'copy', but
// that doesn't make a whole lot of sense.
let targetResource = await vscode.commands.executeCommand(
'extension.dfdl-debug.getValidatedTDMLCopyPath'
)
// Is there a better way of error checking this?
if (targetResource) {
copyTestCase(
getTmpTDMLFilePath(),
targetResource as unknown as string
)
.then((copiedBuffer) => {
fs.writeFileSync(
targetResource as unknown as string,
xmlFormat(copiedBuffer)
)
})
.catch((reason) => {
// Not sure if we need to do something different/more here
console.log(reason)
})
}
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.zipTDML',
async (resource: vscode.Uri) => {
let targetResource: vscode.Uri | undefined = resource
if (vscode.window.activeTextEditor) {
targetResource = vscode.window.activeTextEditor.document.uri
} else {
const tdmlUri = TDMLProvider.getDocumentUri()
if (tdmlUri) {
targetResource = tdmlUri
}
}
const resolvedResource = targetResource
// create temp zip folder
let tmpDir = path.dirname(getTmpTDMLFilePath())
const zipDir = path.posix.join(tmpDir, '_zipdir')
await createDirectory(zipDir)
// copy TDML file to zip folder
await copyFileAsync(
resolvedResource.fsPath,
path.posix.join(zipDir, path.basename(resolvedResource.fsPath))
)
// read TDML file to see what files are required...
await readTDMLFileContents(
path.posix.join(zipDir, path.basename(resolvedResource.fsPath))
).then(async (xmlBuffer) => {
await getTestCaseDisplayData(xmlBuffer).then(
async (testSuiteData) => {
// Use for..of so we can await async operations (createDirectory, copies, etc.)
for (const testCase of testSuiteData.testCases) {
// create subdir for testcase and wait for it to complete
const testCaseDir = path.posix.join(
zipDir,
testCase.testCaseName
)
await createDirectory(testCaseDir)
// copy schema file
let xsdFile = testCase.testCaseModel
let xsdFileSrc = path.posix.join(
path.dirname(resolvedResource.fsPath),
xsdFile
)
let xsdFileDest = path.posix.join(
testCaseDir,
path.basename(xsdFile)
)
await copyFileAsync(xsdFileSrc, xsdFileDest)
// edit path in copied TDML file
let updatedBuffer = xmlBuffer.replace(
`model="${xsdFile}"`,
`model="${path.posix.join(testCase.testCaseName, path.basename(xsdFile))}"`
)
xmlBuffer = updatedBuffer
// copy data file
for (const dataDocuments of testCase.dataDocuments) {
const dataFile = path.basename(dataDocuments.trim())
const dataFileSrc = path.posix.join(
path.dirname(resolvedResource.fsPath),
dataDocuments.trim()
)
const dataFileDest = path.posix.join(
testCaseDir,
path.basename(dataFile)
)
await copyFileAsync(dataFileSrc, dataFileDest)
// edit path in copied TDML file
xmlBuffer = xmlBuffer.replace(
dataDocuments.trim(),
path.posix.join(testCase.testCaseName, dataFile)
)
}
// copy infoset files (await each copy)
for (const dfdlInfosets of testCase.dfdlInfosets) {
const infoFile = path.basename(dfdlInfosets.trim())
const infoSrc = path.posix.join(
path.dirname(resolvedResource.fsPath),
dfdlInfosets.trim()
)
const infoDest = path.posix.join(
testCaseDir,
path.basename(dfdlInfosets.trim())
)
await copyFileAsync(infoSrc, infoDest)
// edit path in copied TDML file
xmlBuffer = xmlBuffer.replace(
dfdlInfosets.trim(),
path.posix.join(testCase.testCaseName, infoFile)
)
}
}
}
)
// write updated info back to TDML file
try {
// Synchronously writes data to a file, replacing it if it already exists
fs.writeFileSync(
path.posix.join(zipDir, path.basename(resolvedResource.fsPath)),
xmlBuffer,
{ encoding: 'utf8' }
)
console.log('Updated schema file written successfully')
} catch (err) {
console.error('Error writing updated schema file:', err)
}
})
// zip folders
const zip = new JSZip()
// Add the folder content recursively
console.log('adding folder to zip')
addFolderToZip(zipDir, zip)
// Generate, save, and then clean up
let targetZip = targetResource.fsPath.replace(/tdml$/, 'tdml.zip')
try {
const content = await zip.generateAsync({ type: 'nodebuffer' })
fs.writeFileSync(targetZip, content)
console.log(`Zip file written successfully: '${targetZip}'`)
vscode.window.showInformationMessage(
`Zip file successfully created: '${targetZip}'`
)
await rm(zipDir, { recursive: true, force: true })
console.log(`Temp directory successfully removed: '${zipDir}'`)
} catch (err) {
console.error(
`Error while creating zip file '${targetZip}' or deleting temp directory '${zipDir}': ${err}`
)
vscode.window.showErrorMessage(
`Failed to create zip file: '${targetZip}'`
)
}
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.toggleFormatting',
(_) => {
const ds = vscode.debug.activeDebugSession
if (ds) {
ds.customRequest('toggleFormatting')
}
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.getSchemaName',
async (fileRequested = null) => {
// Open native file explorer to allow user to select data file from anywhere on their machine
const retVal = await getFile(
fileRequested,
'Select DFDL schema to debug',
'Select DFDL schema to debug'
)
if (!retVal)
vscode.window.showInformationMessage(
'Invalid DFDL schema path selected'
)
return retVal
}
),
vscode.commands.registerCommand(
'extension.dfdl-debug.getDataName',
async (fileRequested = null) => {
// Open native file explorer to allow user to select data file from anywhere on their machine
const retVal = await getFile(
fileRequested,
'Select input data file to debug',
'Select input data file to debug'
)
if (!retVal)
vscode.window.showInformationMessage(
'Invalid data file path selected'
)
return retVal
}
),
vscode.commands.registerCommand('extension.dfdl-debug.showLogs', () => {
outputChannel.show(true)
})
)
context.subscriptions.push(
vscode.commands.registerCommand(
'extension.dfdl-debug.getValidatedTDMLPath',
async (fileRequested = null) => {
// Open native file explorer to allow user to select data file from anywhere on their machine
const retVal = await getFile(
fileRequested,
'Select TDML File',
'Select TDML File'
)
if (!retVal)
vscode.window.showInformationMessage('Invalid TDML Path selected')
return retVal
}
)
)
context.subscriptions.push(
vscode.commands.registerCommand(
'extension.dfdl-debug.getValidatedTDMLCopyPath',
async (fileRequested = null) => {
// Open native file explorer to allow user to select data file from anywhere on their machine
if (fileRequested && fs.existsSync(fileRequested)) {
return fileRequested
} else if (fileRequested && !fs.existsSync(fileRequested)) {
return ''
} else {
return await showTDMLSaveDialog(
fileRequested,
'Save TDML File',
'Save TDML File'
)
}
}
)
)
context.subscriptions.push(
vscode.commands.registerCommand(
'extension.dfdl-debug.getTDMLName',
async (tdmlConfigPath) => {
// get test case name options for dropdown
const test_case_names: string[] = getTDMLTestCaseItems(tdmlConfigPath)
if (test_case_names.length == 0) {
vscode.window.showInformationMessage(
'No test cases found in TDML file.'
)
return
}
// Await showQuickPick directly and return the result
const retVal = await vscode.window.showQuickPick(test_case_names, {
placeHolder: 'Test Case Name',
})
if (!retVal)
vscode.window.showInformationMessage('Invalid TDML Name selected')
return retVal
}
)
)
// register a configuration provider for 'dfdl' debug type
const provider = new DaffodilConfigurationProvider(context)
context.subscriptions.push(
// register a configuration provider for 'dfdl' debug type
vscode.debug.registerDebugConfigurationProvider('dfdl', provider),
// register a dynamic configuration provider for 'dfdl' debug type
vscode.debug.registerDebugConfigurationProvider(
'dfdl',
{
provideDebugConfigurations(
folder: WorkspaceFolder | undefined
): ProviderResult<DebugConfiguration[]> {
if (!vscode.workspace.workspaceFolders) {
return [
getConfig({
name: 'Daffodil Launch',
request: 'launch',
type: 'dfdl',
schema: {
path: '${file}',
rootName: null,
rootNamespace: null,
},
data: '${command:AskForDataName}',
debugServer: false,
infosetFormat: 'xml',
infosetOutput: {
type: 'file',
path: '${file}-infoset.xml',
},
}),
]
}
let targetResource = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.document.uri
: vscode.workspace.workspaceFolders[0].uri
let infosetFile = `${
path.basename(targetResource.fsPath).split('.')[0]
}-infoset.xml`
return [
getConfig({
name: 'Daffodil Launch',
request: 'launch',
type: 'dfdl',
schema: {
path: '${file}',
rootName: null,
rootNamespace: null,
},
data: '${command:AskForDataName}',
debugServer: false,
infosetFormat: 'xml',
infosetOutput: {
type: 'file',
path: '${workspaceFolder}/' + infosetFile,
},
}),
]
},
},
vscode.DebugConfigurationProviderTriggerKind.Dynamic
)
)
if (!factory) {
factory = new InlineDebugAdapterFactory(context)
}
context.subscriptions.push(
vscode.debug.registerDebugAdapterDescriptorFactory('dfdl', factory)
)
if ('dispose' in factory) {
context.subscriptions.push(factory as vscode.Disposable)
}
context.subscriptions.push(
// override VS Code's default implementation of the debug hover
vscode.languages.registerEvaluatableExpressionProvider('xml', {
provideEvaluatableExpression(
document: vscode.TextDocument,
position: vscode.Position
): vscode.ProviderResult<vscode.EvaluatableExpression> {
const wordRange = document.getWordRangeAtPosition(position)
return wordRange
? new vscode.EvaluatableExpression(wordRange)
: undefined
},
}),
// override VS Code's default implementation of the "inline values" feature"
vscode.languages.registerInlineValuesProvider('xml', {
provideInlineValues(
document: vscode.TextDocument,
viewport: vscode.Range,
context: vscode.InlineValueContext
): vscode.ProviderResult<vscode.InlineValue[]> {
const allValues: vscode.InlineValue[] = []
for (
let l = viewport.start.line;
l <= context.stoppedLocation.end.line;
l++
) {
const line = document.lineAt(l)
var regExp = /local_[ifso]/gi // match variables of the form local_i, local_f, Local_i, LOCAL_S...
do {
var m = regExp.exec(line.text)
if (m) {
const varName = m[0]
const varRange = new vscode.Range(
l,
m.index,
l,
m.index + varName.length
)
// value found via variable lookup
allValues.push(
new vscode.InlineValueVariableLookup(varRange, varName, false)
)
}
} while (m)
}
return allValues
},
})
)
context.subscriptions.push(
vscode.debug.onDidReceiveDebugSessionCustomEvent(handleDebugEvent)
)
dfdlLang.activate(context)
dfdlExt.activate(context)
infoset.activate(context)
dataEditClient.activate(context)
launchWizard.activate(context)
tdmlEditor.activate(context)
rootCompletion.activate(context)
daffodilDebugErrors.activate()
}
class DaffodilConfigurationProvider
implements vscode.DebugConfigurationProvider
{
context: vscode.ExtensionContext
constructor(context: vscode.ExtensionContext) {
this.context = context
}
/**
* Massage a debug configuration just before a debug session is being launched,
* e.g. add all missing attributes to the debug configuration.
*/
async resolveDebugConfiguration(
folder: WorkspaceFolder | undefined,
config: DebugConfiguration,
token?: CancellationToken
): Promise<DebugConfiguration | undefined> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
config = getConfig({ name: 'Launch', request: 'launch', type: 'dfdl' })
}
// default schema path and data paths to ask for file prompts if they are null, undefined, or '' in launch.json config
config = {
...config,
schema: {
...config.schema,
path: config.schema?.path || '${command:AskForSchemaName}',
},
data: config.data || '${command:AskForDataName}',
}
const validTunables = getTunables(this.context)
const currentTunables = config.tunables ?? {}
const invalidTunables = Object.keys(currentTunables).filter(
(name) => !(name in validTunables)
)
const invalidValues = Object.entries(currentTunables)
.filter(([name, value]) => {
if (!(name in validTunables)) {
return false
}
const type = validTunables[name]
switch (type) {
case 'boolean':
return value !== 'true' && value !== 'false'
case 'number':
return isNaN(Number(value))
case 'string':
return typeof value !== 'string'
default:
return false
}
})
.map(([name]) => name)
const invalid = [...invalidTunables, ...invalidValues]
if (invalid.length > 0) {
const messages = [
...invalidTunables.map((name) => `${name} (invalid tunable)`),
...invalidValues.map((name) => `${name} (invalid value)`),
]
const choice = await vscode.window.showWarningMessage(
`Invalid tunables found:\n\n${messages.join('\n')}`,
{ modal: true },
'Ignore Invalid Tunables'
)
if (choice !== 'Ignore Invalid Tunables') {
return undefined
}
config.tunables = { ...config.tunables }
for (const invalidTunable of invalid) {
delete config.tunables[invalidTunable]
}
}
let dataFolder = config.data
if (
dataFolder.includes('${workspaceFolder}') &&
vscode.workspace.workspaceFolders &&
dataFolder.split('.').length === 1
) {
dataFolder = vscode.workspace.workspaceFolders[0].uri.fsPath
}
if (
!dataFolder.includes('${command:AskForSchemaName}') &&
!dataFolder.includes('${command:AskForDataName}') &&
!dataFolder.includes('${workspaceFolder}') &&
config.tdmlConfig?.action !== 'execute' &&
vscode.workspace.workspaceFolders &&
dataFolder !== vscode.workspace.workspaceFolders[0].uri.fsPath &&
dataFolder.split('.').length === 1 &&
fs.lstatSync(dataFolder).isDirectory()
) {
return getDataFileFromFolder(dataFolder).then((dataFile) => {
config.data = dataFile
return getDebugger(this.context, config).then((_) => {
return getCurrentConfig()
})
})
}
return getDebugger(this.context, config).then((_) => {
return getCurrentConfig()
})
}
}
export const workspaceFileAccessor: FileAccessor = {
async readFile(path: string) {
try {
const uri = vscode.Uri.file(path)
const bytes = await vscode.workspace.fs.readFile(uri)
const contents = Buffer.from(bytes).toString('utf8')
return contents
} catch (e) {
try {
const uri = vscode.Uri.parse(path)
const bytes = await vscode.workspace.fs.readFile(uri)
const contents = Buffer.from(bytes).toString('utf8')
return contents
} catch (e) {
return `cannot read '${path}'`
}
}
},
}
/**
* Recursively adds files and folders to a JSZip instance.
* @param dirPath The folder to add
* @param zip The JSZip instance
*/
function addFolderToZip(dirPath: string, zip: JSZip) {
const files = fs.readdirSync(dirPath)
for (const file of files) {
const filePath = path.posix.join(dirPath, file)
const stats = fs.statSync(filePath)
if (stats.isDirectory()) {
// Create a subfolder in the ZIP and recurse
const subFolder = zip.folder(file)
if (subFolder) {
addFolderToZip(filePath, subFolder)
}
} else {
// Read file data and add to current zip/folder
const fileData = fs.readFileSync(filePath)
zip.file(file, fileData)
}
}
}