-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathparseFile.ts
176 lines (157 loc) · 5.06 KB
/
parseFile.ts
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
// SPDX-FileCopyrightText: Meta Platforms, Inc. and its affiliates
// SPDX-FileCopyrightText: TNG Technology Consulting GmbH <https://www.tngtech.com>
//
// SPDX-License-Identifier: Apache-2.0
import * as fflate from 'fflate';
import fs from 'fs';
import { Options, Validator } from 'jsonschema';
import { Parser, parser } from 'stream-json';
import Asm from 'stream-json/Assembler';
import zlib from 'zlib';
import { INPUT_FILE_NAME, OUTPUT_FILE_NAME } from '../../shared/write-file';
import { getGlobalBackendState } from '../main/globalBackendState';
import {
InvalidDotOpossumFileError,
JsonParsingError,
ParsedOpossumInputAndOutput,
ParsedOpossumInputFile,
ParsedOpossumOutputFile,
} from '../types/types';
import * as OpossumInputFileSchema from './OpossumInputFileSchema.json';
import * as OpossumOutputFileSchema from './OpossumOutputFileSchema.json';
const jsonSchemaValidator = new Validator();
const validationOptions: Options = {
throwError: true,
};
export async function parseOpossumFile(
opossumFilePath: string,
): Promise<
ParsedOpossumInputAndOutput | JsonParsingError | InvalidDotOpossumFileError
> {
let parsedInputData: ParsedOpossumInputFile;
let parsedOutputData: ParsedOpossumOutputFile | null = null;
const zip: fflate.Unzipped = await readZipAsync(opossumFilePath);
if (!zip[INPUT_FILE_NAME]) {
return {
filesInArchive: Object.keys(zip)
.map((fileName) => `'${fileName}'`)
.join(', '),
type: 'invalidDotOpossumFileError',
} satisfies InvalidDotOpossumFileError;
}
getGlobalBackendState().inputFileRaw = zip[INPUT_FILE_NAME];
try {
parsedInputData = JSON.parse(fflate.strFromU8(zip[INPUT_FILE_NAME]));
jsonSchemaValidator.validate(
parsedInputData,
OpossumInputFileSchema,
validationOptions,
);
} catch (err) {
return {
message: `Error: ${opossumFilePath} does not contain a valid input file.\n Original error message: ${err?.toString()}`,
type: 'jsonParsingError',
} satisfies JsonParsingError;
}
if (zip[OUTPUT_FILE_NAME]) {
try {
const outputJson = fflate.strFromU8(zip[OUTPUT_FILE_NAME]);
parsedOutputData = parseOutputJsonContent(outputJson, opossumFilePath);
} catch (err) {
return {
message: `Error: ${opossumFilePath} does not contain a valid output file.\n${err?.toString()}`,
type: 'jsonParsingError',
} satisfies JsonParsingError;
}
}
return {
input: parsedInputData,
output: parsedOutputData,
};
}
async function readZipAsync(opossumFilePath: string): Promise<fflate.Unzipped> {
const originalZipBuffer: Buffer = await new Promise((resolve) => {
fs.readFile(opossumFilePath, (err, data) => {
if (err) {
throw err;
}
resolve(data);
});
});
return new Promise((resolve) => {
fflate.unzip(new Uint8Array(originalZipBuffer), (err, unzipData) => {
if (err) {
throw err;
}
resolve(unzipData);
});
});
}
export function parseInputJsonFile(
resourceFilePath: fs.PathLike,
): Promise<ParsedOpossumInputFile | JsonParsingError> {
let pipeline: Parser;
if (resourceFilePath.toString().endsWith('.json.gz')) {
pipeline = fs
.createReadStream(resourceFilePath)
.pipe(zlib.createGunzip())
.pipe(parser());
} else {
pipeline = fs.createReadStream(resourceFilePath).pipe(parser());
}
let resolveCallback: (
result: ParsedOpossumInputFile | JsonParsingError,
) => void;
const promise: Promise<ParsedOpossumInputFile | JsonParsingError> =
new Promise((resolve) => {
resolveCallback = (opossumInputData): void => resolve(opossumInputData);
});
pipeline.on('error', () => {
resolveCallback({
message: `Error: ${resourceFilePath.toString()} is not a valid input file.`,
type: 'jsonParsingError',
} as JsonParsingError);
});
const asm = Asm.connectTo(pipeline);
asm.on('done', (asm) => {
const opossumInputData = asm.current;
try {
jsonSchemaValidator.validate(
opossumInputData,
OpossumInputFileSchema,
validationOptions,
);
resolveCallback(opossumInputData as ParsedOpossumInputFile);
} catch (err) {
resolveCallback({
message: `Error: ${resourceFilePath.toString()} is not a valid input file.\n${err?.toString()}`,
type: 'jsonParsingError',
} as JsonParsingError);
}
});
return promise;
}
export function parseOutputJsonFile(
attributionFilePath: fs.PathLike,
): ParsedOpossumOutputFile {
const content = fs.readFileSync(attributionFilePath, 'utf-8');
return parseOutputJsonContent(content, attributionFilePath);
}
export function parseOutputJsonContent(
fileContent: string,
filePath: fs.PathLike,
): ParsedOpossumOutputFile {
try {
const jsonContent = JSON.parse(fileContent);
jsonSchemaValidator.validate(
jsonContent,
OpossumOutputFileSchema,
validationOptions,
);
return jsonContent;
} catch (err) {
throw new Error(
`Error: ${filePath.toString()} contains an invalid output file.\n Original error message: ${err?.toString()}`,
);
}
}