1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-07-18 02:20:12 +02:00
programming-challenges/cli/commands/run/solution.ts

77 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-08-30 15:48:07 +02:00
import path from 'node:path'
import fs from 'node:fs'
import { Command, Option } from 'clipanion'
import * as typanion from 'typanion'
import chalk from 'chalk'
import { isExistingPath } from '../../utils/isExistingPath.js'
import { template } from '../../services/Template.js'
import { Solution } from '../../services/Solution.js'
2022-09-22 16:16:21 +02:00
import { TemporaryFolder } from '../../services/TemporaryFolder.js'
2022-08-30 15:48:07 +02:00
export class RunSolutionCommand extends Command {
2023-01-10 23:15:36 +01:00
public static override paths = [['run', 'solution']]
2022-08-30 15:48:07 +02:00
2023-01-10 23:15:36 +01:00
public static override usage = {
2022-08-30 15:48:07 +02:00
description: 'Run the solution with the given `input.txt` file.'
}
public programmingLanguage = Option.String('--language', {
description: 'The programming language used to solve the challenge.',
required: true,
validator: typanion.isString()
})
public challenge = Option.String('--challenge', {
description: 'The challenge name where you want to run your solution.',
required: true,
validator: typanion.isString()
})
public solutionName = Option.String('--solution', {
description: 'The solution name to run.',
required: true,
validator: typanion.isString()
})
public inputPathUser = Option.String('--input-path', {
description: 'The input file path to use.',
required: true,
validator: typanion.isString()
})
public output = Option.Boolean('--output', false, {
description: 'Display the output of the solution.'
})
2023-01-10 23:15:36 +01:00
public async execute(): Promise<number> {
2022-08-30 15:48:07 +02:00
console.log()
try {
2022-09-22 16:16:21 +02:00
await TemporaryFolder.cleanAll()
2022-08-30 15:48:07 +02:00
await template.verifySupportedProgrammingLanguage(
this.programmingLanguage
)
const solution = await Solution.get({
name: this.solutionName,
challengeName: this.challenge,
programmingLanguageName: this.programmingLanguage
})
const inputPath = path.resolve(process.cwd(), this.inputPathUser)
if (!(await isExistingPath(inputPath))) {
throw new Error(`The \`input-path\` doesn't exist: ${inputPath}.`)
}
const input = await fs.promises.readFile(inputPath, { encoding: 'utf-8' })
await solution.run(input, this.output)
2022-09-22 16:16:21 +02:00
await TemporaryFolder.cleanAll()
2022-08-30 15:48:07 +02:00
return 0
} catch (error) {
if (error instanceof Error) {
console.error(`${chalk.bold.red('Error:')} ${error.message}`)
}
2022-09-22 16:16:21 +02:00
await TemporaryFolder.cleanAll()
2022-08-30 15:48:07 +02:00
return 1
}
}
}