1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00
programming-challenges/cli/commands/search/index.ts

62 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

import path from "node:path"
import fs from "node:fs"
2023-01-05 18:29:07 +01:00
import { Command, Option } from "clipanion"
import * as typanion from "typanion"
import chalk from "chalk"
2023-01-05 18:29:07 +01:00
import { template } from "../../services/Template.js"
import { Challenge } from "../../services/Challenge.js"
2023-01-05 18:29:07 +01:00
export class SearchCommand extends Command {
public static override paths = [["search"]]
2023-01-05 18:29:07 +01:00
2023-01-10 23:15:36 +01:00
public static override usage = {
description: "Search challenges in the programming language specified.",
2023-01-05 18:29:07 +01:00
}
public solved = Option.Boolean("--solved", false, {
2023-01-05 18:29:07 +01:00
description:
"Challenges which have already been solved (at least with one solution).",
2023-01-05 18:29:07 +01:00
})
public programmingLanguage = Option.String("--language", {
description: "The programming language used to solve the challenge.",
2023-01-05 18:29:07 +01:00
required: true,
validator: typanion.isString(),
2023-01-05 18:29:07 +01:00
})
2023-01-10 23:15:36 +01:00
public async execute(): Promise<number> {
2023-01-05 18:29:07 +01:00
try {
await template.verifySupportedProgrammingLanguage(
this.programmingLanguage,
2023-01-05 18:29:07 +01:00
)
const challenges = await Challenge.getChallenges()
const challengesResult: Challenge[] = []
for (const challenge of challenges) {
const solutionsPath = path.join(challenge.path, "solutions")
2023-01-05 18:29:07 +01:00
const solutions = await fs.promises.readdir(solutionsPath)
if (
(!this.solved && !solutions.includes(this.programmingLanguage)) ||
(this.solved && solutions.includes(this.programmingLanguage))
) {
challengesResult.push(challenge)
}
}
const message = this.solved
? "Challenges already solved"
: "Challenges not yet solved"
2023-01-05 18:29:07 +01:00
console.log(`${message} in ${chalk.bold(this.programmingLanguage)}:`)
for (const challenge of challengesResult) {
console.log(` - ${challenge.name}`)
}
return 0
} catch (error) {
if (error instanceof Error) {
console.error(`${chalk.bold.red("Error:")} ${error.message}`)
2023-01-05 18:29:07 +01:00
}
return 1
}
}
}