From f71ba88e29e8a54f8d6e728a9a4653fc76e0a67e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me>
Date: Wed, 9 Aug 2023 23:04:58 +0200
Subject: [PATCH] Step 8: Modify the display of the result

---
 ExerciceChecker/src/app.ts | 65 +++++++++++++++++++++++++++-----------
 1 file changed, 46 insertions(+), 19 deletions(-)

diff --git a/ExerciceChecker/src/app.ts b/ExerciceChecker/src/app.ts
index d96029a..f637a11 100644
--- a/ExerciceChecker/src/app.ts
+++ b/ExerciceChecker/src/app.ts
@@ -4,6 +4,7 @@ const path = require('node:path');
 require('dotenv').config({ path: path.join(__dirname, '../.env') });
 require('./shared/helpers/TypeScriptExtensions'); // ATTENTION : This line MUST be the second of this file
 
+import boxen                from 'boxen';
 import RecursiveFilesStats  from './shared/helpers/recursiveFilesStats/RecursiveFilesStats';
 import Toolbox              from './shared/helpers/Toolbox';
 import ExerciceHelper       from './shared/helpers/ExerciceHelper';
@@ -23,6 +24,11 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
 
     HttpManager.registerAxiosInterceptor();
 
+    const chalkInfo: chalk.Chalk = chalk.blue;
+    const chalkError: chalk.Chalk = chalk.red;
+    const chalkSuccess: chalk.Chalk = chalk.green;
+    const chalkFailure: chalk.Chalk = chalk.red;
+
     console.log(chalk.bgBlue.black.bold('DOJO EXERCICE CHECKER'));
 
     /*
@@ -30,10 +36,10 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
      -   Read the dojo enonce file from the enonce repository
      -   Download immutables files (maybe throw or show an error if the files have been modified ?)
      */
-    console.log(chalk.green('- Checking the exercice\'s enonce and his immutable files'));
+    console.log(chalkInfo(`- Checking the exercice's enonce and his immutable files`));
     const exerciceEnonce = await DojoBackendManager.getExerciceEnonce();
     if ( !exerciceEnonce ) {
-        console.error(chalk.red(`X Error while getting the exercice's enonce`));
+        console.error(chalkError(`X Error while getting the exercice's enonce`));
         process.exit(ExerciceCheckerError.EXERCICE_ENONCE_GET_ERROR);
     }
 
@@ -50,7 +56,7 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
      - Run docker-compose file
      - Get logs from linked services
      */
-    console.log(chalk.green('- Run docker compose file'));
+    console.log(chalkInfo('- Run docker compose file'));
     const dockerComposeOverride = fs.readFileSync(path.join(__dirname, '../assets/docker-compose-override.yml'), 'utf8').replace('{{VOLUME_NAME}}', exerciceEnonce.enonceFile.result.volume).replace('{{MOUNT_PATH}}', Config.folders.resultsExercice);
     fs.writeFileSync(`${ Config.folders.project }/docker-compose-override.yml`, dockerComposeOverride);
 
@@ -84,35 +90,36 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
             resolve([ code ?? ExerciceCheckerError.DOCKER_COMPOSE_UP_ERROR, logs ]);
         });
     });
-    if ( containerExitStatus[0] === ExerciceCheckerError.DOCKER_COMPOSE_UP_ERROR ) {
-        console.error(chalk.red(`X Error while running the docker compose file`));
-        process.exit(containerExitStatus[0]);
+    const containerExitCode = containerExitStatus[0];
+    if ( containerExitCode === ExerciceCheckerError.DOCKER_COMPOSE_UP_ERROR ) {
+        console.error(chalkError(`X Error while running the docker compose file`));
+        process.exit(containerExitCode);
     }
     fs.writeFileSync(`${ Config.folders.resultsDojo }/dockerComposeLogs.txt`, containerExitStatus[1]);
 
-    console.log(chalk.green('- Acquire logs of linked services'));
+    console.log(chalkInfo('- Acquire logs of linked services'));
     try {
         await execAsync(`${ changeDirectoryCommand };${ dockerComposeCommand } logs --timestamps >> ${ Config.folders.resultsDojo }/dockerComposeLogs.txt`);
     } catch ( error ) {
-        console.error(chalk.red(`X Error while getting the linked services logs`));
+        console.error(chalkError(`X Error while getting the linked services logs`));
         process.exit(ExerciceCheckerError.DOCKER_COMPOSE_LOGS_ERROR);
     }
 
 
     // Step 6: Check content requirements and content size
-    console.log(chalk.green('- Validating results folder size'));
+    console.log(chalkInfo('- Validating results folder size'));
     const resultsFolderSize = await Toolbox.fs.getTotalSize(Config.folders.resultsExercice);
     if ( resultsFolderSize > Config.resultsFolderMaxSizeInBytes ) {
-        console.error(chalk.red(`X Results folder size is too big (bigger than ${ Config.resultsFolderMaxSizeInBytes / 1000000 })`));
+        console.error(chalkError(`X Results folder size is too big (bigger than ${ Config.resultsFolderMaxSizeInBytes / 1000000 })`));
         process.exit(ExerciceCheckerError.EXERCICE_RESULTS_FOLDER_TOO_BIG);
     }
 
-    console.log(chalk.green('- Checking results file'));
+    console.log(chalkInfo('- Checking results file'));
     const resultsFileOriginPath = path.join(Config.folders.resultsExercice, Config.filenames.results);
     const resultsFilePath = path.join(Config.folders.resultsDojo, Config.filenames.results);
 
     if ( !fs.existsSync(resultsFileOriginPath) ) {
-        console.error(chalk.red(`X Results file not found.`));
+        console.error(chalkError(`X Results file not found.`));
         process.exit(ExerciceCheckerError.EXERCICE_RESULTS_FILE_NOT_FOUND);
     }
 
@@ -121,14 +128,15 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
     const validationResults = ExerciceHelper.validateResultFile(resultsFilePath);
 
     if ( !validationResults.isValid ) {
-        console.error(chalk.red(`X Results file is not valid. Here are the errors :`));
-        console.error(chalk.red(JSON.stringify(validationResults.errors)));
+        console.error(chalkError(`X Results file is not valid. Here are the errors :`));
+        console.error(chalkError(JSON.stringify(validationResults.errors)));
         process.exit(ExerciceCheckerError.EXERCICE_RESULTS_FILE_SCHEMA_NOT_VALID);
     }
 
+
     // Step 7: Upload and show the results
     try {
-        console.log(chalk.green(`- Uploading results to the dojo server`));
+        console.log(chalkInfo(`- Uploading results to the dojo server`));
         const commit: any = {};
         Toolbox.getKeysWithPrefix(process.env, 'CI_COMMIT_').forEach(key => {
             commit[Toolbox.snakeToCamel(key.replace('CI_COMMIT_', ''))] = process.env[key];
@@ -139,16 +147,35 @@ import ArchiveHelper        from './shared/helpers/ArchiveHelper';
             liteStats               : true
         });
 
-        await DojoBackendManager.sendResults(containerExitStatus[0], commit, validationResults.results!, files, await ArchiveHelper.getBase64(Config.folders.resultsVolume));
+        await DojoBackendManager.sendResults(containerExitCode, commit, validationResults.results!, files, await ArchiveHelper.getBase64(Config.folders.resultsVolume));
     } catch ( error ) {
-        console.error(chalk.red(`X Error while uploading the results`));
+        console.error(chalkError(`X Error while uploading the results`));
         console.error(JSON.stringify(error));
         process.exit(ExerciceCheckerError.UPLOAD);
     }
 
 
     // Step 8: Exit with container exit code
-    console.log(chalk.green(`- Good bye (container's exit code : ${ containerExitStatus[0] })`));
-    process.exit(containerExitStatus[0]);
+    const finalLogGlobalResult = `${ chalkInfo('Global result') } : ${ containerExitCode === 0 ? chalkSuccess('✅ Success') : chalkFailure('❌ Failure') }`;
+
+    const finalLogExecutionExitCode = `${ chalkInfo('Execution exit code') } : ${ (containerExitCode == 0 ? chalkSuccess : chalkError)(containerExitCode) }`;
+
+    const finalLogResultNumbers = validationResults.results!.successfulTests || validationResults.results!.failedTests ? `\n\n${ chalkSuccess('Tests passed') } : ${ validationResults.results!.successfulTests ?? '--' }\n${ chalkError('Tests failed') } : ${ validationResults.results!.failedTests ?? '--' }` : '';
+
+    const finalLogSuccessResultDetails = (validationResults.results!.successfulTestsList ?? []).map(testName => `- ✅ ${ testName }`).join('\n');
+    const finalLogFailedResultDetails = (validationResults.results!.failedTestsList ?? []).map(testName => `- ❌ ${ testName }`).join('\n');
+    const finalLogResultDetails = validationResults.results!.successfulTestsList || validationResults.results!.failedTestsList ? `\n\n${ chalkInfo('Tests') } :${ finalLogSuccessResultDetails != '' ? '\n' + finalLogSuccessResultDetails : '' }${ finalLogFailedResultDetails != '' ? '\n' + finalLogFailedResultDetails : '' }` : '';
+
+    console.log(boxen(`${ finalLogGlobalResult }\n\n${ finalLogExecutionExitCode }${ finalLogResultNumbers }${ finalLogResultDetails }`, {
+        title         : 'Results',
+        titleAlignment: 'center',
+        borderColor   : 'yellow',
+        borderStyle   : 'bold',
+        margin        : 1,
+        padding       : 1,
+        textAlignment : 'left'
+    }));
+
+    process.exit(containerExitCode);
 })();
 
-- 
GitLab