Skip to content
Snippets Groups Projects
Commit 2125ae99 authored by michael.minelli's avatar michael.minelli
Browse files

Typescript => ESLint

parent ae9868bb
Branches
Tags
No related merge requests found
Showing
with 81 additions and 80 deletions
Subproject commit 4d703a2dd39ec0c2b71bbbbda8900588c4e360bd Subproject commit ffc5d65f9f0f0e825688177425e526131aa84631
// Read from the .env file // Read from the .env file
// ATTENTION : This lines MUST be the first of this file (except for the path import) // ATTENTION : These lines MUST be the first of this file (except for the path import)
const path = require('node:path'); import path = require('node:path');
const myEnv = require('dotenv').config({ import myEnv = require('dotenv');
import dotenvExpand = require('dotenv-expand');
dotenvExpand.expand(myEnv.config({
path : path.join(__dirname, '../.env'), path : path.join(__dirname, '../.env'),
DOTENV_KEY: 'dotenv://:key_fc323d8e0a02349342f1c6a119bb38495958ce3a43a87d19a3f674b7e2896dcb@dotenv.local/vault/.env.vault?environment=development' DOTENV_KEY: 'dotenv://:key_fc323d8e0a02349342f1c6a119bb38495958ce3a43a87d19a3f674b7e2896dcb@dotenv.local/vault/.env.vault?environment=development'
}); }));
require('dotenv-expand').expand(myEnv);
require('./shared/helpers/TypeScriptExtensions'); // ATTENTION : This line MUST be the second of this file require('./shared/helpers/TypeScriptExtensions'); // ATTENTION : This line MUST be the second of this file
...@@ -15,4 +19,5 @@ import HttpManager from './managers/HttpManager'; ...@@ -15,4 +19,5 @@ import HttpManager from './managers/HttpManager';
HttpManager.registerAxiosInterceptor(); HttpManager.registerAxiosInterceptor();
new CommanderApp(); new CommanderApp();
\ No newline at end of file
...@@ -10,13 +10,13 @@ abstract class CommanderCommand { ...@@ -10,13 +10,13 @@ abstract class CommanderCommand {
this.defineCommand(); this.defineCommand();
this.defineSubCommands(); this.defineSubCommands();
}; }
protected abstract defineCommand(): void; protected abstract defineCommand(): void;
protected defineSubCommands() {} protected defineSubCommands() {}
protected abstract commandAction(...args: Array<any>): Promise<void>; protected abstract commandAction(...args: Array<unknown>): Promise<void>;
} }
......
...@@ -20,7 +20,7 @@ class AssignmentCommand extends CommanderCommand { ...@@ -20,7 +20,7 @@ class AssignmentCommand extends CommanderCommand {
AssignmentUnpublishCommand.registerOnCommand(this.command); AssignmentUnpublishCommand.registerOnCommand(this.command);
} }
protected async commandAction(options: any): Promise<void> { } protected async commandAction(): Promise<void> { }
} }
......
import CommanderCommand from '../../CommanderCommand'; import CommanderCommand from '../../CommanderCommand';
import Config from '../../../config/Config'; import Config from '../../../config/Config';
import ora from 'ora'; import ora from 'ora';
import util from 'util';
import { exec } from 'child_process';
import chalk from 'chalk'; import chalk from 'chalk';
import AssignmentValidator from '../../../sharedByClients/helpers/Dojo/AssignmentValidator'; import AssignmentValidator from '../../../sharedByClients/helpers/Dojo/AssignmentValidator';
import ClientsSharedAssignmentHelper from '../../../sharedByClients/helpers/Dojo/ClientsSharedAssignmentHelper'; import ClientsSharedAssignmentHelper from '../../../sharedByClients/helpers/Dojo/ClientsSharedAssignmentHelper';
const execAsync = util.promisify(exec);
class AssignmentCheckCommand extends CommanderCommand { class AssignmentCheckCommand extends CommanderCommand {
protected commandName: string = 'check'; protected commandName: string = 'check';
...@@ -76,13 +71,13 @@ class AssignmentCheckCommand extends CommanderCommand { ...@@ -76,13 +71,13 @@ class AssignmentCheckCommand extends CommanderCommand {
} }
}); });
assignmentValidator.events.on('finished', (success: boolean, exitCode: number) => { assignmentValidator.events.on('finished', (success: boolean) => {
success ? resolve() : reject(); success ? resolve() : reject();
}); });
assignmentValidator.run(true); assignmentValidator.run(true);
}); });
} catch ( error ) { } } catch ( error ) { /* empty */ }
ClientsSharedAssignmentHelper.displayExecutionResults(assignmentValidator, `The assignment is ready to be pushed.`, { ClientsSharedAssignmentHelper.displayExecutionResults(assignmentValidator, `The assignment is ready to be pushed.`, {
INFO : chalk.bold, INFO : chalk.bold,
......
...@@ -22,7 +22,7 @@ class AssignmentCreateCommand extends CommanderCommand { ...@@ -22,7 +22,7 @@ class AssignmentCreateCommand extends CommanderCommand {
.action(this.commandAction.bind(this)); .action(this.commandAction.bind(this));
} }
protected async commandAction(options: any): Promise<void> { protected async commandAction(options: { name: string, template?: string, members_id?: Array<number>, members_username?: Array<string> }): Promise<void> {
let members!: Array<GitlabUser> | false; let members!: Array<GitlabUser> | false;
let templateIdOrNamespace: string | null = null; let templateIdOrNamespace: string | null = null;
......
...@@ -16,7 +16,7 @@ class ExerciseCommand extends CommanderCommand { ...@@ -16,7 +16,7 @@ class ExerciseCommand extends CommanderCommand {
ExerciseRunCommand.registerOnCommand(this.command); ExerciseRunCommand.registerOnCommand(this.command);
} }
protected async commandAction(options: any): Promise<void> { } protected async commandAction(): Promise<void> { }
} }
......
...@@ -21,7 +21,7 @@ class ExerciseCreateCommand extends CommanderCommand { ...@@ -21,7 +21,7 @@ class ExerciseCreateCommand extends CommanderCommand {
.action(this.commandAction.bind(this)); .action(this.commandAction.bind(this));
} }
protected async commandAction(options: any): Promise<void> { protected async commandAction(options: { assignment: string, members_id?: Array<number>, members_username?: Array<string> }): Promise<void> {
let members!: Array<GitlabUser> | false; let members!: Array<GitlabUser> | false;
let assignment!: Assignment | undefined; let assignment!: Assignment | undefined;
......
...@@ -188,13 +188,13 @@ class ExerciseRunCommand extends CommanderCommand { ...@@ -188,13 +188,13 @@ class ExerciseRunCommand extends CommanderCommand {
} }
}); });
exerciseDockerCompose.events.on('finished', (success: boolean, exitCode: number) => { exerciseDockerCompose.events.on('finished', (success: boolean) => {
success ? resolve() : reject(); success ? resolve() : reject();
}); });
exerciseDockerCompose.run(true); exerciseDockerCompose.run(true);
}); });
} catch ( error ) { } } catch ( error ) { /* empty */ }
fs.rmSync(composeOverridePath, { force: true }); fs.rmSync(composeOverridePath, { force: true });
fs.writeFileSync(this.fileComposeLogs, exerciseDockerCompose.allLogs); fs.writeFileSync(this.fileComposeLogs, exerciseDockerCompose.allLogs);
......
...@@ -18,7 +18,7 @@ class SessionCommand extends CommanderCommand { ...@@ -18,7 +18,7 @@ class SessionCommand extends CommanderCommand {
SessionTestCommand.registerOnCommand(this.command); SessionTestCommand.registerOnCommand(this.command);
} }
protected async commandAction(options: any): Promise<void> { } protected async commandAction(): Promise<void> { }
} }
......
...@@ -17,9 +17,7 @@ class SessionLoginCommand extends CommanderCommand { ...@@ -17,9 +17,7 @@ class SessionLoginCommand extends CommanderCommand {
try { try {
console.log(chalk.cyan('Please wait while we login you into Dojo...')); console.log(chalk.cyan('Please wait while we login you into Dojo...'));
await SessionManager.login(options.cli); await SessionManager.login(options.cli);
} catch ( error ) { } catch ( error ) { /* empty */ }
}
} }
} }
......
...@@ -14,7 +14,7 @@ class SessionLogoutCommand extends CommanderCommand { ...@@ -14,7 +14,7 @@ class SessionLogoutCommand extends CommanderCommand {
.action(this.commandAction.bind(this)); .action(this.commandAction.bind(this));
} }
protected async commandAction(options: any): Promise<void> { protected async commandAction(options: { force: boolean }): Promise<void> {
if ( !options.force ) { if ( !options.force ) {
const confirm: boolean = (await inquirer.prompt({ const confirm: boolean = (await inquirer.prompt({
name : 'confirm', name : 'confirm',
......
...@@ -10,7 +10,7 @@ class LocalConfigFile { ...@@ -10,7 +10,7 @@ class LocalConfigFile {
return `${ Config.localConfig.folder }/${ this.filename }`; return `${ Config.localConfig.folder }/${ this.filename }`;
} }
private _config: { [key: string]: any } = {}; private _config: { [key: string]: unknown } = {};
loadConfig() { loadConfig() {
if ( !fs.existsSync(this.configPath) ) { if ( !fs.existsSync(this.configPath) ) {
...@@ -26,7 +26,7 @@ class LocalConfigFile { ...@@ -26,7 +26,7 @@ class LocalConfigFile {
} }
} }
getParam(key: string): any | null { getParam(key: string): unknown | null {
const value = key in this._config ? this._config[key] : null; const value = key in this._config ? this._config[key] : null;
if ( value === null ) { if ( value === null ) {
return null; return null;
...@@ -37,8 +37,8 @@ class LocalConfigFile { ...@@ -37,8 +37,8 @@ class LocalConfigFile {
} }
} }
setParam(key: string, value: any): void { setParam(key: string, value: unknown): void {
let previousValue = this.getParam(key); const previousValue = this.getParam(key);
if ( JSON5.stringify(previousValue) === JSON5.stringify(value) ) { if ( JSON5.stringify(previousValue) === JSON5.stringify(value) ) {
return; return;
} }
......
...@@ -4,7 +4,7 @@ import GitlabManager from '../managers/GitlabManager'; ...@@ -4,7 +4,7 @@ import GitlabManager from '../managers/GitlabManager';
class AccessesHelper { class AccessesHelper {
async checkStudent(): Promise<boolean> { async checkStudent(): Promise<boolean> {
let sessionResult = await SessionManager.testSession(true, [ 'student' ]); const sessionResult = await SessionManager.testSession(true, [ 'student' ]);
if ( !sessionResult ) { if ( !sessionResult ) {
return false; return false;
...@@ -14,7 +14,7 @@ class AccessesHelper { ...@@ -14,7 +14,7 @@ class AccessesHelper {
} }
async checkTeachingStaff(): Promise<boolean> { async checkTeachingStaff(): Promise<boolean> {
let sessionResult = await SessionManager.testSession(true, [ 'teachingStaff' ]); const sessionResult = await SessionManager.testSession(true, [ 'teachingStaff' ]);
if ( !sessionResult || !sessionResult.teachingStaff ) { if ( !sessionResult || !sessionResult.teachingStaff ) {
return false; return false;
...@@ -22,6 +22,6 @@ class AccessesHelper { ...@@ -22,6 +22,6 @@ class AccessesHelper {
return (await GitlabManager.testToken(true)).every(result => result); return (await GitlabManager.testToken(true)).every(result => result);
} }
}; }
export default new AccessesHelper(); export default new AccessesHelper();
\ No newline at end of file
...@@ -107,7 +107,7 @@ class DojoBackendManager { ...@@ -107,7 +107,7 @@ class DojoBackendManager {
if ( error.response.status === StatusCodes.CONFLICT ) { if ( error.response.status === StatusCodes.CONFLICT ) {
spinner.fail(`The assignment name is already used. Please choose another one.`); spinner.fail(`The assignment name is already used. Please choose another one.`);
} else { } else {
if ( (error.response.data as DojoBackendResponse<any>).code === DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR ) { if ( (error.response.data as DojoBackendResponse<unknown>).code === DojoStatusCode.ASSIGNMENT_CREATION_GITLAB_ERROR ) {
spinner.fail(`Assignment creation error: An unknown error occurred while creating the assignment on Gitlab. Please try again later or contact an administrator.`); spinner.fail(`Assignment creation error: An unknown error occurred while creating the assignment on Gitlab. Please try again later or contact an administrator.`);
} else { } else {
spinner.fail(`Assignment creation error: An unknown error occurred while creating the assignment on Dojo server. Please try again later or contact an administrator.`); spinner.fail(`Assignment creation error: An unknown error occurred while creating the assignment on Dojo server. Please try again later or contact an administrator.`);
...@@ -145,7 +145,7 @@ class DojoBackendManager { ...@@ -145,7 +145,7 @@ class DojoBackendManager {
if ( error.response.status === StatusCodes.CONFLICT ) { if ( error.response.status === StatusCodes.CONFLICT ) {
spinner.fail(`You've already reached the max number of exercise of this assignment.`); spinner.fail(`You've already reached the max number of exercise of this assignment.`);
} else { } else {
if ( (error.response.data as DojoBackendResponse<any>).code === DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR ) { if ( (error.response.data as DojoBackendResponse<unknown>).code === DojoStatusCode.EXERCISE_CREATION_GITLAB_ERROR ) {
spinner.fail(`Exercise creation error: An unknown error occurred while creating the exercise on Gitlab. Please try again later or contact an administrator.`); spinner.fail(`Exercise creation error: An unknown error occurred while creating the exercise on Gitlab. Please try again later or contact an administrator.`);
} else { } else {
spinner.fail(`Exercise creation error: An unknown error occurred while creating the exercise on Dojo server. Please try again later or contact an administrator.`); spinner.fail(`Exercise creation error: An unknown error occurred while creating the exercise on Dojo server. Please try again later or contact an administrator.`);
......
...@@ -3,6 +3,7 @@ import ora from 'ora'; ...@@ -3,6 +3,7 @@ import ora from 'ora';
import GitlabUser from '../shared/types/Gitlab/GitlabUser'; import GitlabUser from '../shared/types/Gitlab/GitlabUser';
import GitlabRoute from '../shared/types/Gitlab/GitlabRoute'; import GitlabRoute from '../shared/types/Gitlab/GitlabRoute';
import SharedConfig from '../shared/config/SharedConfig'; import SharedConfig from '../shared/config/SharedConfig';
import GitlabRepository from '../shared/types/Gitlab/GitlabRepository';
class GitlabManager { class GitlabManager {
...@@ -15,7 +16,7 @@ class GitlabManager { ...@@ -15,7 +16,7 @@ class GitlabManager {
ora('Checking Gitlab token: ').start().info(); ora('Checking Gitlab token: ').start().info();
} }
let result: [ boolean, boolean ] = [ false, false ]; const result: [ boolean, boolean ] = [ false, false ];
type NotificationSettings = { level: string } type NotificationSettings = { level: string }
...@@ -84,7 +85,7 @@ class GitlabManager { ...@@ -84,7 +85,7 @@ class GitlabManager {
return axios.get(this.getApiUrl(GitlabRoute.NOTIFICATION_SETTINGS)); return axios.get(this.getApiUrl(GitlabRoute.NOTIFICATION_SETTINGS));
} }
public setNotificationSettings(newSettings: any) { public setNotificationSettings(newSettings: Record<string, string>) {
return axios.put(this.getApiUrl(GitlabRoute.NOTIFICATION_SETTINGS), { params: new URLSearchParams(newSettings) }); return axios.put(this.getApiUrl(GitlabRoute.NOTIFICATION_SETTINGS), { params: new URLSearchParams(newSettings) });
} }
...@@ -98,7 +99,7 @@ class GitlabManager { ...@@ -98,7 +99,7 @@ class GitlabManager {
if ( verbose ) { if ( verbose ) {
spinner.start(); spinner.start();
} }
const params: any = {}; const params: { [key: string]: unknown } = {};
params[paramName] = param; params[paramName] = param;
const user = await axios.get<Array<GitlabUser>>(this.getApiUrl(GitlabRoute.USERS_GET), { params: params }); const user = await axios.get<Array<GitlabUser>>(this.getApiUrl(GitlabRoute.USERS_GET), { params: params });
...@@ -128,19 +129,19 @@ class GitlabManager { ...@@ -128,19 +129,19 @@ class GitlabManager {
return await this.getGitlabUsers(usernames, 'search', verbose, verboseIndent); return await this.getGitlabUsers(usernames, 'search', verbose, verboseIndent);
} }
public async getRepository(repoId: number): Promise<any> { public async getRepository(repoId: number): Promise<GitlabRepository> {
return await axios.get(this.getApiUrl(GitlabRoute.REPOSITORY_GET).replace('{{id}}', repoId.toString())); return await axios.get(this.getApiUrl(GitlabRoute.REPOSITORY_GET).replace('{{id}}', repoId.toString()));
} }
public async fetchMembers(options: any): Promise<Array<GitlabUser> | false> { public async fetchMembers(options: { members_id?: Array<number>, members_username?: Array<string> }): Promise<Array<GitlabUser> | false> {
if ( options.members_id || options.members_username ) { if ( options.members_id || options.members_username ) {
ora('Checking Gitlab members:').start().info(); ora('Checking Gitlab members:').start().info();
} }
let members: Array<GitlabUser> = []; let members: Array<GitlabUser> = [];
async function getMembers<T>(context: any, functionName: string, paramsToSearch: Array<T>): Promise<boolean> { async function getMembers<T>(context: unknown, functionName: string, paramsToSearch: Array<T>): Promise<boolean> {
const result = await (context[functionName] as (arg: Array<T>, verbose: boolean, verboseIndent: number) => Promise<Array<GitlabUser | undefined>>)(paramsToSearch, true, 8); const result = await ((context as { [functionName: string]: (arg: Array<T>, verbose: boolean, verboseIndent: number) => Promise<Array<GitlabUser | undefined>> })[functionName])(paramsToSearch, true, 8);
if ( result.every(user => user) ) { if ( result.every(user => user) ) {
members = members.concat(result as Array<GitlabUser>); members = members.concat(result as Array<GitlabUser>);
......
import axios, { AxiosRequestHeaders } from 'axios'; import axios, { AxiosError, AxiosRequestHeaders } from 'axios';
import SessionManager from './SessionManager'; import SessionManager from './SessionManager';
import FormData from 'form-data'; import FormData from 'form-data';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
...@@ -84,17 +84,19 @@ class HttpManager { ...@@ -84,17 +84,19 @@ class HttpManager {
await SessionManager.refreshTokens(); await SessionManager.refreshTokens();
return axios(originalConfig); return axios(originalConfig);
} catch ( _error: any ) { } catch ( error: unknown ) {
if ( _error.response && _error.response.data ) { if ( error instanceof AxiosError ) {
return Promise.reject(_error.response.data); if ( error.response && error.response.data ) {
return Promise.reject(error.response.data);
}
} }
return Promise.reject(_error); return Promise.reject(error);
} }
} }
if ( error.response.status === StatusCodes.METHOD_NOT_ALLOWED && isFromApi && error.response.data ) { if ( error.response.status === StatusCodes.METHOD_NOT_ALLOWED && isFromApi && error.response.data ) {
const data: DojoBackendResponse<{}> = error.response.data; const data: DojoBackendResponse<void> = error.response.data;
switch ( data.code ) { switch ( data.code ) {
case DojoStatusCode.CLIENT_NOT_SUPPORTED: case DojoStatusCode.CLIENT_NOT_SUPPORTED:
......
...@@ -36,7 +36,7 @@ class LoginServer { ...@@ -36,7 +36,7 @@ class LoginServer {
}; };
if ( req.url?.match(Config.login.server.route) ) { if ( req.url?.match(Config.login.server.route) ) {
let urlParts = req.url.split('='); const urlParts = req.url.split('=');
if ( urlParts.length > 0 ) { if ( urlParts.length > 0 ) {
this.events.emit('code', urlParts[1]); this.events.emit('code', urlParts[1]);
...@@ -84,7 +84,7 @@ class SessionManager { ...@@ -84,7 +84,7 @@ class SessionManager {
} }
get apiToken(): string { get apiToken(): string {
const apisToken = this.configFile.getParam(LocalConfigKeys.APIS_TOKEN); const apisToken = this.configFile.getParam(LocalConfigKeys.APIS_TOKEN) as null | { [key: string]: string };
if ( apisToken !== null && ClientsSharedConfig.apiURL in apisToken ) { if ( apisToken !== null && ClientsSharedConfig.apiURL in apisToken ) {
return apisToken[ClientsSharedConfig.apiURL]; return apisToken[ClientsSharedConfig.apiURL];
...@@ -94,7 +94,7 @@ class SessionManager { ...@@ -94,7 +94,7 @@ class SessionManager {
} }
set apiToken(token: string) { set apiToken(token: string) {
let apisToken = this.configFile.getParam(LocalConfigKeys.APIS_TOKEN); let apisToken = this.configFile.getParam(LocalConfigKeys.APIS_TOKEN) as null | { [key: string]: string };
if ( apisToken === null ) { if ( apisToken === null ) {
apisToken = {}; apisToken = {};
} }
...@@ -113,7 +113,7 @@ class SessionManager { ...@@ -113,7 +113,7 @@ class SessionManager {
} }
get gitlabCredentials(): DojoGitlabCredentials { get gitlabCredentials(): DojoGitlabCredentials {
return this.configFile.getParam(LocalConfigKeys.GITLAB); return this.configFile.getParam(LocalConfigKeys.GITLAB) as DojoGitlabCredentials;
} }
set gitlabCredentials(credentials: DojoGitlabCredentials) { set gitlabCredentials(credentials: DojoGitlabCredentials) {
...@@ -216,7 +216,7 @@ class SessionManager { ...@@ -216,7 +216,7 @@ class SessionManager {
gitlabCode = await this.getGitlabCodeFromHeadlessEnvironment(); gitlabCode = await this.getGitlabCodeFromHeadlessEnvironment();
} }
let gitlabTokensSpinner = ora({ const gitlabTokensSpinner = ora({
text : 'Retrieving gitlab tokens', text : 'Retrieving gitlab tokens',
indent: 4 indent: 4
}).start(); }).start();
...@@ -239,7 +239,7 @@ class SessionManager { ...@@ -239,7 +239,7 @@ class SessionManager {
} }
ora(`Login to Dojo backend:`).start().info(); ora(`Login to Dojo backend:`).start().info();
let dojoLoginSpinner = ora({ const dojoLoginSpinner = ora({
text : 'Login to Dojo backend', text : 'Login to Dojo backend',
indent: 4 indent: 4
}).start(); }).start();
...@@ -256,7 +256,7 @@ class SessionManager { ...@@ -256,7 +256,7 @@ class SessionManager {
} }
async refreshTokens() { async refreshTokens() {
let gitlabTokens = await DojoBackendManager.refreshTokens(this.gitlabCredentials.refreshToken!); const gitlabTokens = await DojoBackendManager.refreshTokens(this.gitlabCredentials.refreshToken!);
this.gitlabCredentials = { this.gitlabCredentials = {
refreshToken: gitlabTokens.refresh_token, refreshToken: gitlabTokens.refresh_token,
...@@ -274,7 +274,7 @@ class SessionManager { ...@@ -274,7 +274,7 @@ class SessionManager {
checkPermissions(verbose: boolean = true, indent: number = 8, checkPermissions: Array<string> | null = []): Permissions { checkPermissions(verbose: boolean = true, indent: number = 8, checkPermissions: Array<string> | null = []): Permissions {
const hasPermission = (permissionPredicate: () => boolean, verboseText: string): boolean => { const hasPermission = (permissionPredicate: () => boolean, verboseText: string): boolean => {
let isAllowed: boolean = this.profile !== undefined && permissionPredicate(); const isAllowed: boolean = this.profile !== undefined && permissionPredicate();
if ( verbose ) { if ( verbose ) {
const spinner: ora.Ora = ora({ const spinner: ora.Ora = ora({
......
Subproject commit 4a5eb68209ae9204b6d4cc8020bd62cf6a5be989 Subproject commit 101cc26895eb0b5fe97e03bb96039e0cddd94391
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment