Skip to content

Commit 4f83ff8

Browse files
atypon code clean up
1 parent 864365f commit 4f83ff8

File tree

11 files changed

+125
-33
lines changed

11 files changed

+125
-33
lines changed

src/commander/exec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import which from 'which'
33
import { Context } from '../types.js'
44
import { color, Listr, ListrDefaultRendererLogLevels } from 'listr2'
55
import startServer from '../tasks/startServer.js'
6-
import auth from '../tasks/auth.js'
6+
import authExec from '../tasks/authExec.js'
77
import ctxInit from '../lib/ctx.js'
88
import getGitInfo from '../tasks/getGitInfo.js'
9-
import createBuild from '../tasks/createBuild.js'
9+
import createBuildExec from '../tasks/createBuildExec.js'
1010
import exec from '../tasks/exec.js'
1111
import processSnapshots from '../tasks/processSnapshot.js'
1212
import finalizeBuild from '../tasks/finalizeBuild.js'
@@ -39,10 +39,10 @@ command
3939

4040
let tasks = new Listr<Context>(
4141
[
42-
auth(ctx),
42+
authExec(ctx),
4343
startServer(ctx),
4444
getGitInfo(ctx),
45-
createBuild(ctx),
45+
createBuildExec(ctx),
4646
exec(ctx),
4747
processSnapshots(ctx),
4848
finalizeBuild(ctx)

src/lib/ctx.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export default (options: Record<string, string>): Context => {
9898
delayedUpload: config.delayedUpload ?? false,
9999
useGlobalCache: config.useGlobalCache ?? false,
100100
ignoreHTTPSErrors: config.ignoreHTTPSErrors ?? false,
101+
skipBuildCreation: config.skipBuildCreation ?? false
101102
},
102103
uploadFilePath: '',
103104
webStaticConfig: [],

src/lib/schemaValidation.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,9 @@ const ConfigSchema = {
168168
useGlobalCache: {
169169
type: "boolean",
170170
errorMessage: "Invalid config; useGlobalCache must be true/false"
171+
skipBuildCreation: {
172+
type: "boolean",
173+
errorMessage: "Invalid config; skipBuildCreation must be true/false"
171174
},
172175
},
173176
anyOf: [

src/lib/server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,16 @@ export default async (ctx: Context): Promise<FastifyInstance<Server, IncomingMes
5555
// If not cached, fetch from API and cache it
5656
try {
5757
let fetchedCapabilitiesResp = await ctx.client.getSmartUICapabilities(sessionId, ctx.config, ctx.git, ctx.log);
58-
ctx.sessionCapabilitiesMap.set(sessionId, fetchedCapabilitiesResp);
5958
capsBuildId = fetchedCapabilitiesResp?.buildId || ''
6059
console.log(JSON.stringify(fetchedCapabilitiesResp))
6160

6261
if (capsBuildId) {
62+
ctx.sessionCapabilitiesMap.set(sessionId, fetchedCapabilitiesResp);
6363
ctx.sessionToBuildMap.set(sessionId, capsBuildId);
6464
ctx.buildToProjectTokenMap.set(capsBuildId, fetchedCapabilitiesResp?.projectToken || '');
6565
}
6666
} catch (error: any) {
67-
console.log(`Failed to fetch capabilities for sessionId ${sessionId}: ${error.message}`);
67+
// console.log(`Failed to fetch capabilities for sessionId ${sessionId}: ${error.message}`);
6868
}
6969
}
7070
}

src/lib/snapshotQueue.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -327,11 +327,23 @@ export default class Queue {
327327
if (useCapsBuildId) {
328328
await this.ctx.client.uploadSnapshotForCaps(this.ctx, processedSnapshot, capsBuildId, capsProjectToken);
329329
// Increment snapshot count for the specific buildId
330-
const currentCount = this.ctx.buildToSnapshotCountMap.get(capsBuildId) || 0;
331-
this.ctx.buildToSnapshotCountMap.set(capsBuildId, currentCount + 1);
330+
const cachedCapabilities = this.ctx.sessionCapabilitiesMap.get(sessionId);
331+
const currentCount = cachedCapabilities?.snapshotCount || 0; // Get the current snapshot count for sessionId
332+
cachedCapabilities.snapshotCount = currentCount + 1; // Increment snapshot count
333+
this.ctx.sessionCapabilitiesMap.set(sessionId, cachedCapabilities);
332334
} else {
333335
if (!this.ctx.build?.id) {
334-
throw new Error('Build ID is empty');
336+
if (this.ctx.authenticatedInitially) {
337+
let resp = await this.ctx.client.createBuild(this.ctx.git, this.ctx.config, this.ctx.log, this.ctx.build.name);
338+
this.ctx.build = {
339+
id: resp.data.buildId,
340+
name: resp.data.buildName,
341+
url: resp.data.buildURL,
342+
baseline: resp.data.baseline,
343+
}
344+
} else {
345+
throw new Error('SmartUI capabilities are missing in env variables or in driver capabilities');
346+
}
335347
}
336348
await this.ctx.client.uploadSnapshot(this.ctx, processedSnapshot);
337349
this.ctx.totalSnapshots++;

src/tasks/auth.ts

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,15 @@ export default (ctx: Context): ListrTask<Context, ListrRendererFactory, ListrRen
1010
updateLogContext({task: 'auth'});
1111

1212
try {
13-
if ( !ctx.env.PROJECT_NAME && !ctx.env.PROJECT_TOKEN ) {
14-
ctx.authenticatedInitially = false
15-
task.output = chalk.gray(`Empty PROJECT_TOKEN and PROJECT_NAME. Skipping authentication. Expecting SmartUI Capabilities in driver!`)
16-
task.title = 'Skipped Authentication with SmartUI';
17-
} else {
18-
const authResult = await ctx.client.auth(ctx.log, ctx.env);
19-
if (authResult === 2) {
20-
task.output = chalk.gray(`New project '${ctx.env.PROJECT_NAME}' created successfully`);
21-
} else if (authResult === 0) {
22-
task.output = chalk.gray(`Using existing project token '******#${ctx.env.PROJECT_TOKEN.split('#').pop()}'`);
23-
} else if (authResult === 1) {
24-
task.output = chalk.gray(`Using existing project '${ctx.env.PROJECT_NAME}'`);
25-
}
26-
ctx.authenticatedInitially = true
27-
task.title = 'Authenticated with SmartUI';
13+
const authResult = await ctx.client.auth(ctx.log, ctx.env);
14+
if (authResult === 2) {
15+
task.output = chalk.gray(`New project '${ctx.env.PROJECT_NAME}' created successfully`);
16+
} else if (authResult === 0) {
17+
task.output = chalk.gray(`Using existing project token '******#${ctx.env.PROJECT_TOKEN.split('#').pop()}'`);
18+
} else if (authResult === 1) {
19+
task.output = chalk.gray(`Using existing project '${ctx.env.PROJECT_NAME}'`);
2820
}
21+
task.title = 'Authenticated with SmartUI';
2922
} catch (error: any) {
3023
ctx.log.debug(error);
3124
task.output = chalk.gray(error.message);

src/tasks/authExec.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { ListrTask, ListrRendererFactory } from 'listr2'
2+
import { Context } from '../types.js'
3+
import chalk from 'chalk'
4+
import { updateLogContext } from '../lib/logger.js'
5+
6+
export default (ctx: Context): ListrTask<Context, ListrRendererFactory, ListrRendererFactory> => {
7+
return {
8+
title: `Authenticating with SmartUI`,
9+
task: async (ctx, task): Promise<void> => {
10+
updateLogContext({task: 'auth'});
11+
12+
try {
13+
if ( !ctx.env.PROJECT_NAME && !ctx.env.PROJECT_TOKEN ) {
14+
ctx.authenticatedInitially = false
15+
task.output = chalk.gray(`Empty PROJECT_TOKEN and PROJECT_NAME. Skipping authentication. Expecting SmartUI Capabilities in driver!`)
16+
task.title = 'Skipped Authentication with SmartUI';
17+
} else {
18+
const authResult = await ctx.client.auth(ctx.log, ctx.env);
19+
if (authResult === 2) {
20+
task.output = chalk.gray(`New project '${ctx.env.PROJECT_NAME}' created successfully`);
21+
} else if (authResult === 0) {
22+
task.output = chalk.gray(`Using existing project token '******#${ctx.env.PROJECT_TOKEN.split('#').pop()}'`);
23+
} else if (authResult === 1) {
24+
task.output = chalk.gray(`Using existing project '${ctx.env.PROJECT_NAME}'`);
25+
}
26+
ctx.authenticatedInitially = true
27+
task.title = 'Authenticated with SmartUI';
28+
}
29+
} catch (error: any) {
30+
ctx.log.debug(error);
31+
task.output = chalk.gray(error.message);
32+
throw new Error('Authentication failed');
33+
}
34+
},
35+
rendererOptions: { persistentOutput: true }
36+
}
37+
}

src/tasks/createBuild.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ export default (ctx: Context): ListrTask<Context, ListrRendererFactory, ListrRen
2424
task.output = chalk.gray(`Empty PROJECT_TOKEN and PROJECT_NAME. Skipping Creation of Build!`)
2525
task.title = 'Skipped SmartUI build creation'
2626
}
27+
task.output = chalk.gray(`build id: ${resp.data.buildId}`);
28+
task.title = 'SmartUI build created'
2729
} catch (error: any) {
2830
ctx.log.debug(error);
2931
task.output = chalk.gray(error.message);

src/tasks/createBuildExec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { ListrTask, ListrRendererFactory } from 'listr2';
2+
import { Context } from '../types.js'
3+
import chalk from 'chalk';
4+
import { updateLogContext } from '../lib/logger.js';
5+
6+
export default (ctx: Context): ListrTask<Context, ListrRendererFactory, ListrRendererFactory> => {
7+
return {
8+
title: `Creating SmartUI build`,
9+
task: async (ctx, task): Promise<void> => {
10+
updateLogContext({task: 'createBuild'});
11+
12+
try {
13+
if (ctx.authenticatedInitially && !ctx.config.skipBuildCreation) {
14+
let resp = await ctx.client.createBuild(ctx.git, ctx.config, ctx.log, ctx.build.name);
15+
ctx.build = {
16+
id: resp.data.buildId,
17+
name: resp.data.buildName,
18+
url: resp.data.buildURL,
19+
baseline: resp.data.baseline,
20+
}
21+
task.output = chalk.gray(`build id: ${resp.data.buildId}`);
22+
task.title = 'SmartUI build created'
23+
} else {
24+
task.output = chalk.gray(`Empty PROJECT_TOKEN and PROJECT_NAME. Skipping Creation of Build!`)
25+
task.title = 'Skipped SmartUI build creation'
26+
}
27+
} catch (error: any) {
28+
ctx.log.debug(error);
29+
task.output = chalk.gray(error.message);
30+
throw new Error('SmartUI build creation failed');
31+
}
32+
},
33+
rendererOptions: { persistentOutput: true }
34+
}
35+
}

src/tasks/finalizeBuild.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,20 +21,28 @@ export default (ctx: Context): ListrTask<Context, ListrRendererFactory, ListrRen
2121
task.output = chalk.gray(error.message);
2222
throw new Error('Finalize build failed');
2323
}
24+
let buildUrls = `build url: ${ctx.build.url}\n`;
2425

25-
for (const [buildId, totalSnapshots] of ctx.buildToSnapshotCountMap.entries()) {
26-
26+
for (const [sessionId, capabilities] of ctx.sessionCapabilitiesMap.entries()) {
2727
try {
28-
// Fetch projectToken from buildToProjectTokenMap
29-
const projectToken = ctx.buildToProjectTokenMap?.get(buildId) || '';
30-
await ctx.client.finalizeBuildForCapsWithToken(buildId, totalSnapshots, projectToken, ctx.log);
28+
const buildId = capabilities?.buildId || '';
29+
const projectToken = capabilities?.projectToken || '';
30+
const totalSnapshots = capabilities?.snapshotCount || 0;
31+
const sessionBuildUrl = capabilities?.buildURL || '';
32+
const testId = capabilities?.id || '';
33+
34+
if (buildId && projectToken) {
35+
await ctx.client.finalizeBuildForCapsWithToken(buildId, totalSnapshots, projectToken, ctx.log);
36+
}
37+
38+
if (testId) {
39+
buildUrls += `TestId ${testId}: ${sessionBuildUrl}\n`;
40+
}
3141
} catch (error: any) {
32-
ctx.log.debug(`Error finalizing build ${buildId}: ${error.message}`);
42+
ctx.log.debug(`Error finalizing build for session ${sessionId}: ${error.message}`);
3343
}
3444
}
35-
36-
37-
task.output = chalk.gray(`build url: ${ctx.build.url}`);
45+
task.output = chalk.gray(buildUrls);
3846
task.title = 'Finalized build';
3947

4048
// cleanup and upload logs

0 commit comments

Comments
 (0)