Skip to content

Commit 1d1cdbb

Browse files
committed
chore: refactor usage of promises into async/await
1 parent 596e629 commit 1d1cdbb

File tree

8 files changed

+147
-256
lines changed

8 files changed

+147
-256
lines changed

src/config.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ class Config {
153153
* Authorizes the RHDA (Red Hat Dependency Analytics) service.
154154
* @param context The extension context for authorization.
155155
*/
156-
async authorizeRHDA(context): Promise<void> {
156+
async authorizeRHDA(context: vscode.ExtensionContext): Promise<void> {
157157
this.telemetryId = await getTelemetryId(context);
158158
await this.setProcessEnv();
159159
}
@@ -214,7 +214,6 @@ class Config {
214214
} else {
215215
console.error(errorMsg);
216216
}
217-
218217
}
219218
}
220219
}

src/exhortServices.ts

Lines changed: 28 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -12,36 +12,29 @@ import { IImageRef, IOptions } from './imageAnalysis';
1212
* @param options - The options for running image analysis.
1313
* @returns A Promise resolving to the analysis response in HTML format.
1414
*/
15-
function imageAnalysisService(images: IImageRef[], options: IOptions): Promise<any> {
16-
return new Promise<any>(async (resolve, reject) => {
17-
const jarPath = `${__dirname}/../javaApiAdapter/exhort-java-api-adapter-1.0-SNAPSHOT-jar-with-dependencies.jar`;
18-
const reportType = 'html';
19-
let parameters = '';
20-
let properties = '';
15+
async function imageAnalysisService(images: IImageRef[], options: IOptions): Promise<any> {
16+
const jarPath = `${__dirname}/../javaApiAdapter/exhort-java-api-adapter-1.0-SNAPSHOT-jar-with-dependencies.jar`;
17+
const reportType = 'html';
18+
let parameters = '';
19+
let properties = '';
2120

22-
images.forEach(image => {
23-
if (image.platform) {
24-
parameters += ` ${image.image}^^${image.platform}`;
25-
} else {
26-
parameters += ` ${image.image}`;
27-
}
28-
});
29-
30-
for (const setting in options) {
31-
if (options[setting]) {
32-
properties += ` -D${setting}=${options[setting]}`;
33-
}
21+
images.forEach(image => {
22+
if (image.platform) {
23+
parameters += ` ${image.image}^^${image.platform}`;
24+
} else {
25+
parameters += ` ${image.image}`;
3426
}
27+
});
3528

36-
try {
37-
const result = execSync(`java${properties} -jar ${jarPath} ${reportType}${parameters}`, {
38-
maxBuffer: 1000 * 1000 * 10, // 10 MB
39-
});
40-
resolve(result.toString());
41-
} catch (error) {
42-
reject(error);
29+
for (const setting in options) {
30+
if (options[setting]) {
31+
properties += ` -D${setting}=${options[setting]}`;
4332
}
44-
});
33+
}
34+
35+
return execSync(`java${properties} -jar ${jarPath} ${reportType}${parameters}`, {
36+
maxBuffer: 1000 * 1000 * 10, // 10 MB
37+
}).toString();
4538
}
4639

4740
/**
@@ -50,16 +43,9 @@ function imageAnalysisService(images: IImageRef[], options: IOptions): Promise<a
5043
* @param options Additional options for the analysis.
5144
* @returns A promise resolving to the stack analysis report in HTML format.
5245
*/
53-
function stackAnalysisService(pathToManifest: string, options: object): Promise<any> {
54-
return new Promise<any>(async (resolve, reject) => {
55-
try {
56-
// Get stack analysis in HTML format
57-
const stackAnalysisReportHtml = await exhort.stackAnalysis(pathToManifest, true, options);
58-
resolve(stackAnalysisReportHtml);
59-
} catch (error) {
60-
reject(error);
61-
}
62-
});
46+
async function stackAnalysisService(pathToManifest: string, options: object): Promise<string> {
47+
// Get stack analysis in HTML format
48+
return await exhort.stackAnalysis(pathToManifest, true, options);
6349
}
6450

6551
/**
@@ -68,32 +54,21 @@ function stackAnalysisService(pathToManifest: string, options: object): Promise<
6854
* @param source The source for which the token is being validated.
6955
* @returns A promise resolving after validating the token.
7056
*/
71-
async function tokenValidationService(options, source): Promise<string> {
57+
async function tokenValidationService(options: object, source: string): Promise<string | undefined> {
7258
try {
73-
7459
// Get token validation status code
7560
const tokenValidationStatus = await exhort.validateToken(options);
7661

77-
if (
78-
tokenValidationStatus === 200
79-
) {
62+
if (tokenValidationStatus === 200) {
8063
vscode.window.showInformationMessage(`${source} token validated successfully`);
8164
return;
82-
} else if (
83-
tokenValidationStatus === 400
84-
) {
65+
} else if (tokenValidationStatus === 400) {
8566
return `Missing token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`;
86-
} else if (
87-
tokenValidationStatus === 401
88-
) {
67+
} else if (tokenValidationStatus === 401) {
8968
return `Invalid token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`;
90-
} else if (
91-
tokenValidationStatus === 403
92-
) {
69+
} else if (tokenValidationStatus === 403) {
9370
return `Forbidden. The token does not have permissions. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`;
94-
} else if (
95-
tokenValidationStatus === 429
96-
) {
71+
} else if (tokenValidationStatus === 429) {
9772
return `Too many requests. Rate limit exceeded. Please try again in a little while. Status: ${tokenValidationStatus}`;
9873
} else {
9974
return `Failed to validate token. Status: ${tokenValidationStatus}`;

src/extension.ts

Lines changed: 7 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -81,26 +81,6 @@ export function activate(context: vscode.ExtensionContext) {
8181
}
8282
);
8383

84-
// const disposableSetSnykToken = vscode.commands.registerCommand(
85-
// commands.SET_SNYK_TOKEN_COMMAND,
86-
// async () => {
87-
// const token = await vscode.window.showInputBox({
88-
// prompt: 'Please enter your Snyk Token:',
89-
// placeHolder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
90-
// password: true,
91-
// validateInput: validateSnykToken
92-
// });
93-
94-
// if (token === undefined) {
95-
// return;
96-
// } else if (token === '') {
97-
// await globalConfig.clearSnykToken(true);
98-
// } else {
99-
// await globalConfig.setSnykToken(token);
100-
// }
101-
// }
102-
// );
103-
10484
registerStackAnalysisCommands(context);
10585

10686
globalConfig.authorizeRHDA(context)
@@ -157,8 +137,7 @@ export function activate(context: vscode.ExtensionContext) {
157137
if (selection === PromptText.FULL_STACK_PROMPT_TEXT) {
158138
record(context, TelemetryActions.vulnerabilityReportPopupOpened, { manifest: fileName, fileName: fileName });
159139
vscode.commands.executeCommand(commands.STACK_ANALYSIS_COMMAND, filePath);
160-
}
161-
else {
140+
} else {
162141
record(context, TelemetryActions.vulnerabilityReportPopupIgnored, { manifest: fileName, fileName: fileName });
163142
}
164143
};
@@ -194,30 +173,20 @@ export function activate(context: vscode.ExtensionContext) {
194173
})
195174
.catch(error => {
196175
vscode.window.showErrorMessage(`Failed to Authorize Red Hat Dependency Analytics extension: ${error.message}`);
197-
throw (error);
176+
throw error;
198177
});
199178

200179
vscode.workspace.onDidChangeConfiguration(() => {
201180
globalConfig.loadData();
202181
});
203-
204-
// context.secrets.onDidChange(async (e) => {
205-
// if (e.key === SNYK_TOKEN_KEY) {
206-
// const token = await globalConfig.getSnykToken();
207-
// lspClient.sendNotification('snykTokenModified', token);
208-
// }
209-
// });
210182
}
211183

212184
/**
213185
* Deactivates the extension.
214186
* @returns A `Thenable` for void.
215187
*/
216188
export function deactivate(): Thenable<void> {
217-
if (!lspClient) {
218-
return undefined;
219-
}
220-
return lspClient.stop();
189+
return lspClient?.stop();
221190
}
222191

223192
/**
@@ -263,10 +232,10 @@ function redirectToRedHatCatalog() {
263232
* Shows a notification regarding Red Hat Dependency Analytics recommendations.
264233
*/
265234
function showRHRepositoryRecommendationNotification() {
266-
const msg = `Important: If you apply Red Hat Dependency Analytics recommendations,
267-
make sure the Red Hat GA Repository (${REDHAT_MAVEN_REPOSITORY}) has been added to your project configuration.
268-
This ensures that the applied dependencies work correctly.
269-
Learn how to add the repository: [Click here](${REDHAT_MAVEN_REPOSITORY_DOCUMENTATION_URL})`;
235+
const msg = 'Important: If you apply Red Hat Dependency Analytics recommendations, ' +
236+
`make sure the Red Hat GA Repository (${REDHAT_MAVEN_REPOSITORY}) has been added to your project configuration. ` +
237+
'This ensures that the applied dependencies work correctly. ' +
238+
`Learn how to add the repository: [Click here](${REDHAT_MAVEN_REPOSITORY_DOCUMENTATION_URL})`;
270239
vscode.window.showWarningMessage(msg);
271240
}
272241

src/imageAnalysis.ts

Lines changed: 29 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class DockerImageAnalysis implements IImageAnalysis {
7878
args: Map<string, string> = new Map<string, string>();
7979
images: IImageRef[] = [];
8080
imageAnalysisReportHtml: string = '';
81+
filePath: string
8182

8283
/**
8384
* Regular expression for matching 'FROM' statements.
@@ -101,20 +102,18 @@ class DockerImageAnalysis implements IImageAnalysis {
101102

102103
constructor(filePath: string) {
103104
const lines = this.parseTxtDoc(filePath);
104-
105+
this.filePath = filePath
105106
this.images = this.collectImages(lines);
106107
}
107108

108109
parseTxtDoc(filePath: string): string[] {
109110
try {
110111
const contentBuffer = fs.readFileSync(filePath);
111-
112112
const contentString = contentBuffer.toString('utf-8');
113-
114113
return contentString.split('\n');
115114
} catch (err) {
116115
updateCurrentWebviewPanel('error');
117-
throw (err);
116+
throw err;
118117
}
119118
}
120119

@@ -179,43 +178,29 @@ class DockerImageAnalysis implements IImageAnalysis {
179178
}
180179

181180
async runImageAnalysis() {
182-
try {
183-
return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => {
184-
return new Promise<void>(async (resolve, reject) => {
185-
p.report({
186-
message: StatusMessages.WIN_ANALYZING_DEPENDENCIES
187-
});
188-
189-
// execute image analysis
190-
await imageAnalysisService(this.images, this.options)
191-
.then(async (resp) => {
192-
p.report({
193-
message: StatusMessages.WIN_GENERATING_DEPENDENCIES
194-
});
195-
196-
updateCurrentWebviewPanel(resp);
197-
198-
p.report({
199-
message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS
200-
});
201-
202-
this.imageAnalysisReportHtml = resp;
203-
204-
resolve();
205-
})
206-
.catch(err => {
207-
p.report({
208-
message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS
209-
});
210-
211-
reject(err);
212-
});
213-
});
214-
});
215-
} catch (err) {
216-
updateCurrentWebviewPanel('error');
217-
throw (err);
218-
}
181+
return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => {
182+
p.report({ message: StatusMessages.WIN_ANALYZING_DEPENDENCIES });
183+
184+
try {
185+
186+
// execute image analysis
187+
const promise = imageAnalysisService(this.images, this.options)
188+
p.report({ message: StatusMessages.WIN_GENERATING_DEPENDENCIES });
189+
190+
const resp = await promise;
191+
updateCurrentWebviewPanel(resp);
192+
193+
p.report({ message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS });
194+
195+
this.imageAnalysisReportHtml = resp;
196+
} catch (error) {
197+
p.report({ message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS });
198+
199+
updateCurrentWebviewPanel('error');
200+
201+
throw error
202+
}
203+
});
219204
}
220205
}
221206

@@ -225,13 +210,9 @@ class DockerImageAnalysis implements IImageAnalysis {
225210
* @returns A Promise resolving to an Analysis Report HTML.
226211
*/
227212
async function executeDockerImageAnalysis(filePath: string): Promise<string> {
228-
try {
229-
const dockerImageAnalysis = new DockerImageAnalysis(filePath);
230-
await dockerImageAnalysis.runImageAnalysis();
231-
return dockerImageAnalysis.imageAnalysisReportHtml;
232-
} catch (error) {
233-
throw (error);
234-
}
213+
const dockerImageAnalysis = new DockerImageAnalysis(filePath);
214+
await dockerImageAnalysis.runImageAnalysis();
215+
return dockerImageAnalysis.imageAnalysisReportHtml;
235216
}
236217

237218
export { executeDockerImageAnalysis, IImageRef, IOptions };

src/redhatTelemetry.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ async function startUp(context: vscode.ExtensionContext) {
6666
* @param context The extension context.
6767
* @returns A promise resolving to the telemetry ID.
6868
*/
69-
async function getTelemetryId(context) {
69+
async function getTelemetryId(context: vscode.ExtensionContext) {
7070
const redhatService = await getRedHatService(context);
7171
const redhatIdProvider = await redhatService.getIdProvider();
7272
const telemetryId = await redhatIdProvider.getRedHatUUID();

0 commit comments

Comments
 (0)