-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathimportFromFile.ts
327 lines (299 loc) · 10.5 KB
/
importFromFile.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
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
// SPDX-FileCopyrightText: Meta Platforms, Inc. and its affiliates
// SPDX-FileCopyrightText: TNG Technology Consulting GmbH <https://www.tngtech.com>
// SPDX-FileCopyrightText: Nico Carl <nicocarl@protonmail.com>
//
// SPDX-License-Identifier: Apache-2.0
import { BrowserWindow, dialog } from 'electron';
import fs from 'fs';
import { cloneDeep } from 'lodash';
import { v4 as uuid4 } from 'uuid';
import { EMPTY_PROJECT_CONFIG } from '../../Frontend/shared-constants';
import { AllowedFrontendChannels } from '../../shared/ipc-channels';
import {
Attributions,
ParsedFileContent,
ResourcesToAttributions,
} from '../../shared/shared-types';
import { text } from '../../shared/text';
import { writeFile, writeOpossumFile } from '../../shared/write-file';
import { getGlobalBackendState } from '../main/globalBackendState';
import logger from '../main/logger';
import {
InvalidDotOpossumFileError,
JsonParsingError,
OpossumOutputFile,
ParsedOpossumInputAndOutput,
ParsedOpossumInputFile,
ParsedOpossumOutputFile,
} from '../types/types';
import { getFilePathWithAppendix } from '../utils/getFilePathWithAppendix';
import { isOpossumFileFormat } from '../utils/isOpossumFileFormat';
import {
parseInputJsonFile,
parseOpossumFile,
parseOutputJsonFile,
} from './parseFile';
import {
deserializeAttributions,
getAttributionsToResources,
mergeAttributions,
parseFrequentLicenses,
sanitizeRawBaseUrlsForSources,
sanitizeResourcesToAttributions,
serializeAttributions,
} from './parseInputData';
function isJsonParsingError(object: unknown): object is JsonParsingError {
return (object as JsonParsingError).type === 'jsonParsingError';
}
function isInvalidDotOpossumFileError(
object: unknown,
): object is InvalidDotOpossumFileError {
return (
(object as InvalidDotOpossumFileError).type === 'invalidDotOpossumFileError'
);
}
export async function loadInputAndOutputFromFilePath(
mainWindow: BrowserWindow,
filePath: string,
): Promise<void> {
mainWindow.webContents.send(AllowedFrontendChannels.ResetLoadedFile, {
resetState: true,
});
let parsedInputData: ParsedOpossumInputFile;
let parsedOutputData: ParsedOpossumOutputFile | null = null;
if (isOpossumFileFormat(filePath)) {
logger.info(`Reading file ${filePath}`);
const parsingResult = await parseOpossumFile(filePath);
if (isJsonParsingError(parsingResult)) {
logger.info('Invalid input file');
await getMessageBoxForParsingError(parsingResult.message);
return;
}
if (isInvalidDotOpossumFileError(parsingResult)) {
logger.info('Invalid input file');
mainWindow.webContents.send(AllowedFrontendChannels.FileLoading, {
isLoading: false,
});
await getMessageBoxForInvalidDotOpossumFileError(
parsingResult.filesInArchive,
);
return;
}
parsedInputData = parsingResult.input;
parsedOutputData = parsingResult.output;
} else {
logger.info('Parsing input file');
const parsingResult = await parseInputJsonFile(filePath);
if (isJsonParsingError(parsingResult)) {
logger.info('Invalid input file');
await getMessageBoxForParsingError(parsingResult.message);
return;
}
parsedInputData = parsingResult;
}
logger.info('Sanitizing map of resources to signals');
const unmergedResourcesToExternalAttributions =
sanitizeResourcesToAttributions(
parsedInputData.resources,
parsedInputData.resourcesToAttributions,
);
logger.info('Deserializing signals');
const unmergedExternalAttributions = deserializeAttributions(
parsedInputData.externalAttributions,
);
logger.info('Calculating signals to resources');
const externalAttributionsToResources = getAttributionsToResources(
unmergedResourcesToExternalAttributions,
);
logger.info('Merging similar signals');
const [externalAttributions, resourcesToExternalAttributions] =
mergeAttributions({
attributions: unmergedExternalAttributions,
resourcesToAttributions: unmergedResourcesToExternalAttributions,
attributionsToResources: externalAttributionsToResources,
});
logger.info('Parsing frequent licenses from input');
const frequentLicenses = parseFrequentLicenses(
parsedInputData.frequentLicenses,
);
if (parsedOutputData === null) {
logger.info('Creating output file');
if (isOpossumFileFormat(filePath)) {
parsedOutputData = await createOutputInOpossumFile(
filePath,
externalAttributions,
resourcesToExternalAttributions,
parsedInputData.metadata.projectId,
);
} else {
const outputJsonPath = getFilePathWithAppendix(
filePath,
'_attributions.json',
);
const inputFileMD5Checksum = getGlobalBackendState().inputFileChecksum;
parsedOutputData = await parseOrCreateOutputJsonFile(
outputJsonPath,
externalAttributions,
resourcesToExternalAttributions,
parsedInputData.metadata.projectId,
inputFileMD5Checksum,
);
}
}
logger.info('Calculating attributions to resources');
const manualAttributionsToResources = getAttributionsToResources(
parsedOutputData.resourcesToAttributions,
);
logger.info('Deserializing attributions');
const manualAttributions = deserializeAttributions(
parsedOutputData.manualAttributions,
externalAttributions,
);
logger.info('Sending data to user interface');
mainWindow.webContents.send(AllowedFrontendChannels.FileLoaded, {
metadata: parsedInputData.metadata,
resources: parsedInputData.resources,
config: parsedInputData.config ?? EMPTY_PROJECT_CONFIG,
manualAttributions: {
attributions: manualAttributions,
resourcesToAttributions: parsedOutputData.resourcesToAttributions,
attributionsToResources: manualAttributionsToResources,
},
externalAttributions: {
attributions: externalAttributions,
resourcesToAttributions: resourcesToExternalAttributions,
attributionsToResources: externalAttributionsToResources,
},
frequentLicenses,
resolvedExternalAttributions: new Set(
parsedOutputData.resolvedExternalAttributions,
),
attributionBreakpoints: new Set(parsedInputData.attributionBreakpoints),
filesWithChildren: new Set(parsedInputData.filesWithChildren),
baseUrlsForSources: sanitizeRawBaseUrlsForSources(
parsedInputData.baseUrlsForSources,
),
externalAttributionSources:
parsedInputData.externalAttributionSources ?? {},
} satisfies ParsedFileContent);
logger.info('Finalizing global state');
getGlobalBackendState().projectTitle = parsedInputData.metadata.projectTitle;
getGlobalBackendState().projectId = parsedInputData.metadata.projectId;
}
async function createOutputInOpossumFile(
filePath: string,
externalAttributions: Attributions,
resourcesToExternalAttributions: ResourcesToAttributions,
projectId: string,
): Promise<ParsedOpossumOutputFile> {
logger.info('Preparing output');
const attributionJSON = createJsonOutputFile(
externalAttributions,
resourcesToExternalAttributions,
projectId,
);
await writeOpossumFile({
path: filePath,
input: getGlobalBackendState().inputFileRaw,
output: attributionJSON,
});
logger.info('Parsing output');
const parsingResult = (await parseOpossumFile(
filePath,
)) as ParsedOpossumInputAndOutput;
return parsingResult.output as ParsedOpossumOutputFile;
}
async function parseOrCreateOutputJsonFile(
filePath: string,
externalAttributions: Attributions,
resourcesToExternalAttributions: ResourcesToAttributions,
projectId: string,
inputFileMD5Checksum?: string,
): Promise<ParsedOpossumOutputFile> {
if (!fs.existsSync(filePath)) {
logger.info('Preparing output');
const attributionJSON = createJsonOutputFile(
externalAttributions,
resourcesToExternalAttributions,
projectId,
inputFileMD5Checksum,
);
await writeFile({ path: filePath, content: attributionJSON });
}
logger.info('Parsing output');
return parseOutputJsonFile(filePath);
}
function createJsonOutputFile(
externalAttributions: Attributions,
resourcesToExternalAttributions: ResourcesToAttributions,
projectId: string,
inputFileMD5Checksum?: string,
): OpossumOutputFile {
const externalAttributionsCopy = cloneDeep(externalAttributions);
const manualAttributions: Attributions = {};
const manualAttributionIdsToExternalAttributionIds: {
[attributionId: string]: string;
} = {};
const manualAttributionIds = new Set<string>();
for (const attributionId of Object.keys(externalAttributionsCopy)) {
const packageInfo = externalAttributionsCopy[attributionId];
if (packageInfo.preSelected) {
delete packageInfo.source;
delete packageInfo.preferred;
delete packageInfo.preferredOverOriginIds;
const newUUID = uuid4();
manualAttributions[newUUID] = packageInfo;
manualAttributionIdsToExternalAttributionIds[attributionId] = newUUID;
manualAttributionIds.add(attributionId);
}
}
const resourcesToAttributions: ResourcesToAttributions = {};
for (const resourceId of Object.keys(resourcesToExternalAttributions)) {
const attributionIds = resourcesToExternalAttributions[resourceId];
const filteredAttributionIds = attributionIds.filter((attributionId) =>
manualAttributionIds.has(attributionId),
);
if (filteredAttributionIds.length) {
resourcesToAttributions[resourceId] = filteredAttributionIds.map(
(attributionId) =>
manualAttributionIdsToExternalAttributionIds[attributionId],
);
}
}
return {
metadata: {
projectId,
fileCreationDate: String(Date.now()),
inputFileMD5Checksum,
},
manualAttributions: serializeAttributions(manualAttributions),
resourcesToAttributions,
resolvedExternalAttributions: [],
};
}
export async function getMessageBoxForParsingError(
errorMessage: string,
): Promise<void> {
await dialog.showMessageBox({
type: 'error',
buttons: ['OK'],
defaultId: 0,
title: 'Parsing Error',
message: 'Error parsing the input file.',
detail: `${errorMessage}\n${text.errorBoundary.outdatedAppVersion}`,
});
}
export async function getMessageBoxForInvalidDotOpossumFileError(
filesInArchive: string,
): Promise<void> {
await dialog.showMessageBox({
type: 'error',
buttons: ['OK'],
defaultId: 0,
title: 'Invalid File Error',
message: "Error loading '.opossum' file.",
detail:
"The '.opossum' file is invalid as it does not contain an 'input.json'. " +
`Actual files in the archive: ${filesInArchive}.`,
});
}