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

feat: usage of ESM modules imports (instead of CommonJS) (#14)

This commit is contained in:
Divlo 2022-04-23 18:41:14 +02:00 committed by GitHub
parent c502c17e7c
commit 104c61935a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 6623 additions and 5171 deletions

View File

@ -5,11 +5,11 @@
"project": "./tsconfig.json"
},
"env": {
"node": true,
"jest": true
"node": true
},
"rules": {
"import/extensions": ["error", "always"],
"unicorn/prevent-abbreviations": "error"
"unicorn/prevent-abbreviations": "error",
"unicorn/prefer-node-protocol": "error"
}
}

View File

@ -9,8 +9,9 @@ on:
jobs:
test-solutions:
runs-on: 'ubuntu-latest'
timeout-minutes: 30
steps:
- uses: 'actions/checkout@v2'
- uses: 'actions/checkout@v3.0.0'
with:
fetch-depth: 0
@ -20,7 +21,7 @@ jobs:
SKIP_LOGIN: true
- name: 'Use Node.js'
uses: 'actions/setup-node@v2.5.1'
uses: 'actions/setup-node@v3.0.0'
with:
node-version: 'lts/*'
cache: 'npm'

View File

@ -10,10 +10,10 @@ jobs:
lint:
runs-on: 'ubuntu-latest'
steps:
- uses: 'actions/checkout@v2'
- uses: 'actions/checkout@v3.0.0'
- name: 'Use Node.js'
uses: 'actions/setup-node@v2.5.1'
uses: 'actions/setup-node@v3.0.0'
with:
node-version: 'lts/*'
cache: 'npm'
@ -29,10 +29,10 @@ jobs:
build:
runs-on: 'ubuntu-latest'
steps:
- uses: 'actions/checkout@v2'
- uses: 'actions/checkout@v3.0.0'
- name: 'Use Node.js'
uses: 'actions/setup-node@v2.5.1'
uses: 'actions/setup-node@v3.0.0'
with:
node-version: 'lts/*'
cache: 'npm'
@ -46,7 +46,7 @@ jobs:
test:
runs-on: 'ubuntu-latest'
steps:
- uses: 'actions/checkout@v2'
- uses: 'actions/checkout@v3.0.0'
- name: 'Use Docker'
uses: 'actions-hub/docker/cli@master'
@ -54,7 +54,7 @@ jobs:
SKIP_LOGIN: true
- name: 'Use Node.js'
uses: 'actions/setup-node@v2.5.1'
uses: 'actions/setup-node@v3.0.0'
with:
node-version: 'lts/*'
cache: 'npm'
@ -62,5 +62,8 @@ jobs:
- name: 'Install'
run: 'npm install'
- name: 'Build'
run: 'npm run build'
- name: 'Test'
run: 'npm run test'

1
.gitignore vendored
View File

@ -16,6 +16,7 @@ bin
# testing
coverage
.nyc_output
# editors
.vscode

2
.swcrc
View File

@ -13,7 +13,7 @@
"loose": true
},
"module": {
"type": "commonjs",
"type": "es6",
"strict": false,
"strictMode": true,
"lazy": false,

9
.taprc Normal file
View File

@ -0,0 +1,9 @@
ts: false
jsx: false
flow: false
check-coverage: false
coverage: false
timeout: 60000
files:
- 'build/**/*.test.js'

View File

@ -17,7 +17,7 @@ void print_couple(int* numbers, size_t couple_length) {
int main() {
size_t couple_length;
scanf("%ld\n", &couple_length);
scanf("%lu\n", &couple_length);
char* string = input();
char* token = strtok(string, " ; ");
size_t numbers_length = 1;

View File

@ -16,7 +16,7 @@ char* convert_from_base_10_to_base(unsigned long number, unsigned int base) {
if (number == 0) {
return "0";
}
int remainders[64] = {};
int remainders[64];
int index = 0;
while (number > 0) {
remainders[index] = number % base;

View File

@ -1,9 +1,10 @@
#include <cstdlib>
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << "Hello, " + line + "!" << std::endl;
}
return 0;
std::string line;
std::getline(std::cin, line);
std::cout << "Hello, " + line + "!\n";
return EXIT_SUCCESS;
}

View File

@ -0,0 +1,7 @@
# sorting-algorithms/python/bubble-sort
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.
| Algorithm | Best Case | Average Case | Worst Case |
| ----------------------------------------------------------- | ----------- | ------------ | ----------- |
| [Bubble sort](https://wikipedia.org/wiki/Bubble_sort) | O(n) | O(n²) | O(n²) |

View File

@ -0,0 +1,24 @@
from typing import List
import sys
def bubble_sort(numbersInput: List[int]) -> List[int]:
numbers = list(numbersInput)
length = len(numbers)
for index_1 in range(length):
for index_2 in range(length - index_1 - 1):
if numbers[index_2] > numbers[index_2 + 1]:
temporary = numbers[index_2]
numbers[index_2] = numbers[index_2 + 1]
numbers[index_2 + 1] = temporary
return numbers
numbers: List[int] = []
for value in sys.stdin:
numbers.append(int(value.rstrip('\n')))
numbers = numbers[1:]
sorted_numbers = bubble_sort(numbers)
for number in sorted_numbers:
print(number)

View File

@ -0,0 +1,7 @@
# sorting-algorithms/python/insertion-sort
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.
| Algorithm | Best Case | Average Case | Worst Case |
| ----------------------------------------------------------- | ----------- | ------------ | ----------- |
| [Insertion sort](https://wikipedia.org/wiki/Insertion_sort) | O(n) | O(n²) | O(n²) |

View File

@ -0,0 +1,24 @@
from typing import List
import sys
def insertion_sort(numbersInput: List[int]) -> List[int]:
numbers = list(numbersInput)
for index_1 in range(1, len(numbers)):
current = numbers[index_1]
index_2 = index_1 - 1
while index_2 >= 0 and numbers[index_2] > current:
numbers[index_2 + 1] = numbers[index_2]
index_2 -= 1
numbers[index_2 + 1] = current
return numbers
numbers: List[int] = []
for value in sys.stdin:
numbers.append(int(value.rstrip('\n')))
numbers = numbers[1:]
sorted_numbers = insertion_sort(numbers)
for number in sorted_numbers:
print(number)

View File

@ -15,7 +15,7 @@ char* triangle_type(int triangle_sides[3]) {
}
int main() {
int triangle_sides[3] = {};
int triangle_sides[3];
for (size_t index = 0; index < 3; index++) {
scanf("%d", &triangle_sides[index]);
}

View File

@ -1,3 +0,0 @@
import { Docker } from '../services/Docker.js'
jest.setTimeout(Docker.MAXIMUM_TIMEOUT_MILLISECONDS)

View File

@ -2,9 +2,11 @@ import { PassThrough } from 'node:stream'
import path from 'node:path'
import fs from 'node:fs'
import tap from 'tap'
import sinon from 'sinon'
import fsMock from 'mock-fs'
import chalk from 'chalk'
import getStream from 'get-stream'
import fsMock from 'mock-fs'
import date from 'date-and-time'
import { cli } from '../../../cli.js'
@ -16,8 +18,8 @@ const challenge = 'aaaa-test-jest'
const inputChallenge = `--challenge=${challenge}`
const inputGitHubUser = `--github-user=${githubUser}`
describe('programming-challenges generate challenge', () => {
beforeEach(() => {
await tap.test('programming-challenges generate challenge', async (t) => {
t.beforeEach(() => {
fsMock(
{
[process.cwd()]: fsMock.load(process.cwd(), { recursive: true })
@ -26,13 +28,14 @@ describe('programming-challenges generate challenge', () => {
)
})
afterEach(() => {
t.afterEach(() => {
fsMock.restore()
jest.clearAllMocks()
sinon.restore()
})
it('succeeds and generate the new challenge', async () => {
console.log = jest.fn()
await t.test('succeeds and generate the new challenge', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const dateString = date.format(new Date(), 'D MMMM Y', true)
const stream = new PassThrough()
const exitCode = await cli.run(
@ -44,14 +47,20 @@ describe('programming-challenges generate challenge', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
t.equal(exitCode, 0)
const challengePath = path.join(process.cwd(), 'challenges', challenge)
const readmePath = path.join(challengePath, 'README.md')
const readmeContent = await fs.promises.readFile(readmePath, { encoding: 'utf-8' })
const successMessage = `${chalk.bold.green('Success:')} created the new challenge at ${challengePath}.`
expect(console.log).toHaveBeenCalledWith(successMessage)
expect(await isExistingPath(challengePath)).toBeTruthy()
expect(readmeContent).toMatch(`# ${challenge}
const readmeContent = await fs.promises.readFile(readmePath, {
encoding: 'utf-8'
})
const successMessage = `${chalk.bold.green(
'Success:'
)} created the new challenge at ${challengePath}.`
t.equal(consoleLogSpy.calledWith(successMessage), true)
t.equal(await isExistingPath(challengePath), true)
t.equal(
readmeContent,
`# ${challenge}
Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
@ -62,10 +71,11 @@ Description of the challenge...
## Examples
See the \`test\` folder for examples of input/output.
`)
`
)
})
it('fails without options', async () => {
await t.test('fails without options', async (t) => {
const stream = new PassThrough()
const promise = getStream(stream)
const exitCode = await cli.run(input, {
@ -74,13 +84,14 @@ See the \`test\` folder for examples of input/output.
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
const output = await promise
expect(output).toContain('Unknown Syntax Error')
t.match(output, 'Unknown Syntax Error')
})
it('fails with already existing challenge', async () => {
console.error = jest.fn()
await t.test('fails with already existing challenge', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, '--challenge=hello-world', inputGitHubUser],
@ -90,15 +101,19 @@ See the \`test\` folder for examples of input/output.
stderr: stream
}
)
expect(console.error).toHaveBeenCalledWith(
`${chalk.bold.red('Error:')} The challenge already exists: hello-world.`
)
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red('Error:')} The challenge already exists: hello-world.`
),
true
)
})
it('fails with invalid challenge name', async () => {
console.error = jest.fn()
await t.test('fails with invalid challenge name', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, '--challenge=hEllO-world', inputGitHubUser],
@ -109,9 +124,12 @@ See the \`test\` folder for examples of input/output.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red('Error:')} Invalid challenge name.`
),
true
)
})
})

View File

@ -2,9 +2,11 @@ import { PassThrough } from 'node:stream'
import path from 'node:path'
import fs from 'node:fs'
import tap from 'tap'
import sinon from 'sinon'
import fsMock from 'mock-fs'
import chalk from 'chalk'
import getStream from 'get-stream'
import fsMock from 'mock-fs'
import date from 'date-and-time'
import { cli } from '../../../cli.js'
@ -20,8 +22,8 @@ const inputGitHubUser = `--github-user=${githubUser}`
const inputLanguage = `--language=${language}`
const inputSolution = `--solution=${solution}`
describe('programming-challenges generate solution', () => {
beforeEach(() => {
await tap.test('programming-challenges generate solution', async (t) => {
t.beforeEach(() => {
fsMock(
{
[process.cwd()]: fsMock.load(process.cwd(), { recursive: true })
@ -30,13 +32,14 @@ describe('programming-challenges generate solution', () => {
)
})
afterEach(() => {
t.afterEach(() => {
fsMock.restore()
jest.clearAllMocks()
sinon.restore()
})
it('succeeds and generate the new solution', async () => {
console.log = jest.fn()
await t.test('succeeds and generate the new solution', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const dateString = date.format(new Date(), 'D MMMM Y', true)
const stream = new PassThrough()
const exitCode = await cli.run(
@ -48,26 +51,47 @@ describe('programming-challenges generate solution', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
const solutionPath = path.join(process.cwd(), 'challenges', challenge, 'solutions', language, solution)
t.equal(exitCode, 0)
const solutionPath = path.join(
process.cwd(),
'challenges',
challenge,
'solutions',
language,
solution
)
const readmePath = path.join(solutionPath, 'README.md')
const readmeContent = await fs.promises.readFile(readmePath, { encoding: 'utf-8' })
const successMessage = `${chalk.bold.green('Success:')} created the new solution at ${solutionPath}.`
expect(console.log).toHaveBeenCalledWith(successMessage)
expect(await isExistingPath(solutionPath)).toBeTruthy()
expect(readmeContent).toMatch(`# ${challenge}/${language}/${solution}
const readmeContent = await fs.promises.readFile(readmePath, {
encoding: 'utf-8'
})
const successMessage = `${chalk.bold.green(
'Success:'
)} created the new solution at ${solutionPath}.`
t.equal(consoleLogSpy.calledWith(successMessage), true)
t.equal(await isExistingPath(solutionPath), true)
t.equal(
readmeContent,
`# ${challenge}/${language}/${solution}
Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
`)
`
)
})
it("fails with challenges that doesn't exist", async () => {
console.error = jest.fn()
await t.test("fails with challenges that doesn't exist", async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidChallenge = 'aaa-jest-challenge'
const inputInvalidChallenge = `--challenge=${invalidChallenge}`
const exitCode = await cli.run(
[...input, inputInvalidChallenge, inputGitHubUser, inputLanguage, inputSolution],
[
...input,
inputInvalidChallenge,
inputGitHubUser,
inputLanguage,
inputSolution
],
{
stdin: process.stdin,
stdout: stream,
@ -75,19 +99,30 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ` The challenge doesn't exist yet: ${invalidChallenge}.`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
` The challenge doesn't exist yet: ${invalidChallenge}.`
),
true
)
})
it('fails with solution that already exist', async () => {
console.error = jest.fn()
await t.test('fails with solution that already exist', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidSolution = 'function'
const inputInvalidSolution = `--solution=${invalidSolution}`
const exitCode = await cli.run(
[...input, inputChallenge, inputGitHubUser, inputLanguage, inputInvalidSolution],
[
...input,
inputChallenge,
inputGitHubUser,
inputLanguage,
inputInvalidSolution
],
{
stdin: process.stdin,
stdout: stream,
@ -95,19 +130,30 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ` The solution already exists: ${invalidSolution}.`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
` The solution already exists: ${invalidSolution}.`
),
true
)
})
it('fails with invalid language', async () => {
console.error = jest.fn()
await t.test('fails with invalid language', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidLanguage = 'invalid'
const inputInvalidLanguage = `--language=${invalidLanguage}`
const exitCode = await cli.run(
[...input, inputChallenge, inputGitHubUser, inputSolution, inputInvalidLanguage],
[
...input,
inputChallenge,
inputGitHubUser,
inputSolution,
inputInvalidLanguage
],
{
stdin: process.stdin,
stdout: stream,
@ -115,13 +161,17 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ' This programming language is not supported yet.'
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
' This programming language is not supported yet.'
),
true
)
})
it('fails without options', async () => {
await t.test('fails without options', async () => {
const stream = new PassThrough()
const promise = getStream(stream)
const exitCode = await cli.run(input, {
@ -130,8 +180,8 @@ Created by [@${githubUser}](https://github.com/${githubUser}) on ${dateString}.
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
t.equal(exitCode, 1)
const output = await promise
expect(output).toContain('Unknown Syntax Error')
t.match(output, 'Unknown Syntax Error')
})
})

View File

@ -1,5 +1,7 @@
import { PassThrough } from 'node:stream'
import tap from 'tap'
import sinon from 'sinon'
import chalk from 'chalk'
import { cli } from '../../../cli.js'
@ -13,13 +15,14 @@ const inputChallenge = `--challenge=${challenge}`
const inputLanguage = `--language=${language}`
const inputSolution = `--solution=${solution}`
describe('programming-challenges run test', () => {
afterEach(() => {
jest.clearAllMocks()
await tap.test('programming-challenges run test', async (t) => {
t.afterEach(() => {
sinon.restore()
})
it('succeeds', async () => {
console.log = jest.fn()
await t.test('succeeds', async (t) => {
sinon.stub(console, 'log').value(() => {})
const consoleLogSpy = sinon.spy(console, 'log')
const stream = new PassThrough()
const exitCode = await cli.run(
[...input, inputChallenge, inputSolution, inputLanguage],
@ -30,14 +33,25 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(0)
expect(console.log).toHaveBeenNthCalledWith(2, `${chalk.bold('Name:')} ${challenge}/${language}/${solution}\n`)
expect(console.log).toHaveBeenNthCalledWith(4, `${chalk.bold('Tests:')} ${chalk.bold.green('3 passed')}, 3 total`)
expect(console.log).toHaveBeenNthCalledWith(6, Test.SUCCESS_MESSAGE)
t.equal(exitCode, 0)
t.equal(
consoleLogSpy.calledWith(
`${chalk.bold('Name:')} ${challenge}/${language}/${solution}\n`
),
true
)
t.equal(
consoleLogSpy.calledWith(
`${chalk.bold('Tests:')} ${chalk.bold.green('3 passed')}, 3 total`
),
true
)
t.equal(consoleLogSpy.calledWith(Test.SUCCESS_MESSAGE), true)
})
it("fails with solution that doesn't exist", async () => {
console.error = jest.fn()
await t.test("fails with solution that doesn't exist", async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidSolution = 'invalid'
const inputInvalidSolution = `--solution=${invalidSolution}`
@ -50,14 +64,18 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') + ' The solution was not found.'
),
true
)
})
it('fails with invalid language', async () => {
console.error = jest.fn()
await t.test('fails with invalid language', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const invalidLanguage = 'invalid'
const inputInvalidLanguage = `--language=${invalidLanguage}`
@ -70,14 +88,19 @@ describe('programming-challenges run test', () => {
}
)
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
chalk.bold.red('Error:') + ' This programming language is not supported yet.'
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
chalk.bold.red('Error:') +
' This programming language is not supported yet.'
),
true
)
})
it('fails without options', async () => {
console.error = jest.fn()
await t.test('fails without options', async (t) => {
sinon.stub(console, 'error').value(() => {})
const consoleErrorSpy = sinon.spy(console, 'error')
const stream = new PassThrough()
const exitCode = await cli.run(input, {
stdin: process.stdin,
@ -85,9 +108,14 @@ describe('programming-challenges run test', () => {
stderr: stream
})
stream.end()
expect(exitCode).toEqual(1)
expect(console.error).toHaveBeenCalledWith(
`${chalk.bold.red('Error:')} You must specify all the options (\`--challenge\`, \`--solution\`, \`--language\`).`
t.equal(exitCode, 1)
t.equal(
consoleErrorSpy.calledWith(
`${chalk.bold.red(
'Error:'
)} You must specify all the options (\`--challenge\`, \`--solution\`, \`--language\`).`
),
true
)
})
})

View File

@ -5,7 +5,4 @@ import { cli } from './cli.js'
const [, , ...arguments_] = process.argv
cli.runExit(arguments_, Cli.defaultContext).catch(() => {
console.error('Error occurred...')
process.exit(1)
})
await cli.runExit(arguments_, Cli.defaultContext)

View File

@ -1,5 +1,5 @@
import path from 'node:path'
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import validateProjectName from 'validate-npm-package-name'
@ -21,7 +21,7 @@ export class Challenge implements ChallengeOptions {
constructor (options: ChallengeOptions) {
const { name } = options
this.name = name
this.path = path.join(__dirname, '..', '..', 'challenges', name)
this.path = fileURLToPath(new URL(`../../challenges/${name}`, import.meta.url))
}
static async generate (options: GenerateChallengeOptions): Promise<Challenge> {

View File

@ -1,4 +1,4 @@
import execa from 'execa'
import { execaCommand } from 'execa'
import ora from 'ora'
import ms from 'ms'
@ -11,7 +11,7 @@ export class Docker {
public async build (): Promise<void> {
const loader = ora('Building the Docker image').start()
try {
await execa.command(`docker build --tag=${Docker.CONTAINER_TAG} ./`)
await execaCommand(`docker build --tag=${Docker.CONTAINER_TAG} ./`)
loader.stop()
} catch (error) {
loader.fail()
@ -20,7 +20,7 @@ export class Docker {
}
public async run (input: string): Promise<string> {
const subprocess = execa.command(
const subprocess = execaCommand(
`docker run --interactive --rm ${Docker.CONTAINER_TAG}`,
{
input

View File

@ -1,4 +1,4 @@
import execa from 'execa'
import { execaCommand } from 'execa'
import { Challenge } from './Challenge.js'
import { Solution } from './Solution.js'
@ -35,7 +35,7 @@ export class GitAffected implements GitAffectedOptions {
head: string
): Promise<string[]> {
try {
const { stdout } = await execa.command(
const { stdout } = await execaCommand(
`git diff --name-only --relative ${base} ${head}`
)
return this.parseGitOutput(stdout)
@ -50,7 +50,7 @@ export class GitAffected implements GitAffectedOptions {
public async getLatestPushedCommit (): Promise<string> {
const latestCommit = this.isContinuousIntegration ? '~1' : ''
const { stdout } = await execa.command(`git rev-parse origin/master${latestCommit}`)
const { stdout } = await execaCommand(`git rev-parse origin/master${latestCommit}`)
return stdout
}

View File

@ -1,3 +1,4 @@
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'node:fs'
@ -122,12 +123,7 @@ export class Solution implements SolutionOptions {
static async getManyByProgrammingLanguages (programmingLanguages?: string[]): Promise<Solution[]> {
const languages = programmingLanguages ?? await template.getProgrammingLanguages()
const challengesPath = path.join(
__dirname,
'..',
'..',
'challenges'
)
const challengesPath = fileURLToPath(new URL('../../challenges', import.meta.url))
const challenges = await fs.promises.readdir(challengesPath)
const paths: string[] = []
for (const challenge of challenges) {

View File

@ -1,12 +1,15 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import { replaceInFile } from 'replace-in-file'
import replaceInFileDefault from 'replace-in-file'
import date from 'date-and-time'
import { copyDirectory } from '../utils/copyDirectory.js'
const TEMPLATE_PATH = path.join(__dirname, '..', '..', 'templates')
const { replaceInFile } = replaceInFileDefault
const TEMPLATE_PATH = fileURLToPath(new URL('../../templates', import.meta.url))
const TEMPLATE_DOCKER_PATH = path.join(TEMPLATE_PATH, 'docker')
const TEMPLATE_CHALLENGE_PATH = path.join(TEMPLATE_PATH, 'challenge')
const TEMPLATE_SOLUTION_PATH = path.join(TEMPLATE_PATH, 'solution')
@ -48,7 +51,9 @@ class Template {
return description
}
private async replaceInDestination (options: ReplaceInDestinationOptions): Promise<void> {
private async replaceInDestination(
options: ReplaceInDestinationOptions
): Promise<void> {
const { name, description, destination } = options
const readmePath = path.join(destination, 'README.md')
await replaceInFile({
@ -70,8 +75,17 @@ class Template {
}
public async solution(options: TemplateSolutionOptions): Promise<void> {
const { destination, githubUser, name, challengeName, programmingLanguageName } = options
const templateLanguagePath = path.join(TEMPLATE_SOLUTION_PATH, programmingLanguageName)
const {
destination,
githubUser,
name,
challengeName,
programmingLanguageName
} = options
const templateLanguagePath = path.join(
TEMPLATE_SOLUTION_PATH,
programmingLanguageName
)
await this.verifySupportedProgrammingLanguage(programmingLanguageName)
await fs.promises.mkdir(destination, { recursive: true })
await copyDirectory(templateLanguagePath, destination)
@ -95,10 +109,12 @@ class Template {
public async getProgrammingLanguages(): Promise<string[]> {
const languages = await fs.promises.readdir(TEMPLATE_SOLUTION_PATH)
return languages.filter(language => language !== 'base')
return languages.filter((language) => language !== 'base')
}
public async verifySupportedProgrammingLanguage (language: string): Promise<void> {
public async verifySupportedProgrammingLanguage(
language: string
): Promise<void> {
const languages = await this.getProgrammingLanguages()
if (!languages.includes(language)) {
throw new Error('This programming language is not supported yet.')

View File

@ -1,23 +1,26 @@
import tap from 'tap'
import { Challenge } from '../Challenge.js'
import { GitAffected } from '../GitAffected.js'
import { Solution } from '../Solution.js'
const gitAffected = new GitAffected({ isContinuousIntegration: false })
describe('services/GitAffected - parseGitOutput', () => {
it('returns the right output array', () => {
expect(gitAffected.parseGitOutput('1.txt\n 2.txt ')).toEqual(['1.txt', '2.txt'])
await tap.test('services/GitAffected', async (t) => {
await t.test('parseGitOutput', async (t) => {
await t.test('returns the right output array', async (t) => {
t.same(gitAffected.parseGitOutput('1.txt\n 2.txt '), ['1.txt', '2.txt'])
})
})
describe('services/GitAffected - getAffectedSolutionsFromFiles', () => {
it('returns the affected solutions', async () => {
await t.test('getAffectedSolutionsFromFiles', async (t) => {
await t.test('returns the affected solutions', async (t) => {
const files = [
'challenges/hello-world/solutions/javascript/function/solution.js',
'challenges/is-palindrome/solutions/c/function/input.c'
]
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions).toEqual([
t.same(solutions, [
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
@ -31,74 +34,92 @@ describe('services/GitAffected - getAffectedSolutionsFromFiles', () => {
])
})
it('returns the affected solutions from Dockerfile changes', async () => {
await t.test(
'returns the affected solutions from Dockerfile changes',
async (t) => {
const files = ['templates/docker/javascript/Dockerfile']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
expect(solutions[1]).toEqual(
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
})
}
)
it('returns the affected solutions from Docker template changes', async () => {
await t.test(
'returns the affected solutions from Docker template changes',
async (t) => {
const files = ['templates/docker/javascript/package.json']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'camel-case' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
expect(solutions[1]).toEqual(
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'first-non-repeating-character' }),
name: 'function',
programmingLanguageName: 'javascript'
})
)
})
}
)
it('returns the affected solutions from input/output files', async () => {
await t.test(
'returns the affected solutions from input/output files',
async (t) => {
const files = ['challenges/hello-world/test/1/input.txt']
const solutions = await gitAffected.getAffectedSolutionsFromFiles(files)
expect(solutions[0]).toEqual(
t.same(
solutions[0],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'c'
})
)
expect(solutions[1]).toEqual(
t.same(
solutions[1],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cpp'
})
)
expect(solutions[2]).toEqual(
t.same(
solutions[2],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'cs'
})
)
expect(solutions[3]).toEqual(
t.same(
solutions[3],
new Solution({
challenge: new Challenge({ name: 'hello-world' }),
name: 'function',
programmingLanguageName: 'dart'
})
)
}
)
})
})

View File

@ -1,43 +1,39 @@
import fs from 'node:fs'
import tap from 'tap'
import fsMock from 'mock-fs'
import { copyDirectory } from '../copyDirectory.js'
describe('utils/copyDirectory', () => {
afterEach(() => {
await tap.test('utils/copyDirectory', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('copy the files', async () => {
await t.test('copy the files', async (t) => {
fsMock({
'/source': {
'default.png': '',
'index.ts': '',
'.npmignore': ''
'index.ts': ''
},
'/destination': {}
}, { createCwd: false })
})
let destinationDirectoryContent = await fs.promises.readdir('/destination')
let sourceDirectoryContent = await fs.promises.readdir('/source')
expect(destinationDirectoryContent.length).toEqual(0)
expect(sourceDirectoryContent.length).toEqual(3)
t.equal(destinationDirectoryContent.length, 0)
t.equal(sourceDirectoryContent.length, 2)
await copyDirectory('/source', '/destination')
destinationDirectoryContent = await fs.promises.readdir('/destination')
sourceDirectoryContent = await fs.promises.readdir('/source')
expect(destinationDirectoryContent.length).toEqual(3)
expect(sourceDirectoryContent.length).toEqual(3)
expect(destinationDirectoryContent).toEqual(
expect.arrayContaining(['default.png', 'index.ts', '.npmignore'])
)
expect(sourceDirectoryContent).toEqual(
expect.arrayContaining(['default.png', 'index.ts', '.npmignore'])
)
t.equal(destinationDirectoryContent.length, 2)
t.equal(sourceDirectoryContent.length, 2)
t.strictSame(destinationDirectoryContent, ['default.png', 'index.ts'])
t.strictSame(sourceDirectoryContent, ['default.png', 'index.ts'])
})
it('copy the files and folders recursively', async () => {
await t.test('copy the files and folders recursively', async (t) => {
fsMock({
'/source': {
'random-folder': {
@ -46,11 +42,10 @@ describe('utils/copyDirectory', () => {
'mycode.ts': ''
}
},
'index.ts': '',
'.npmignore': ''
'index.ts': ''
},
'/destination': {}
}, { createCwd: false })
})
let destinationDirectoryContent = await fs.promises.readdir('/destination')
let sourceDirectoryContent = await fs.promises.readdir('/source')
@ -58,33 +53,27 @@ describe('utils/copyDirectory', () => {
let secondRandomFolderContent = await fs.promises.readdir(
'/source/random-folder/second-random-folder'
)
expect(randomFolderContent.length).toEqual(2)
expect(secondRandomFolderContent.length).toEqual(1)
expect(destinationDirectoryContent.length).toEqual(0)
expect(sourceDirectoryContent.length).toEqual(3)
t.equal(randomFolderContent.length, 2)
t.equal(secondRandomFolderContent.length, 1)
t.equal(destinationDirectoryContent.length, 0)
t.equal(sourceDirectoryContent.length, 2)
await copyDirectory('/source', '/destination')
destinationDirectoryContent = await fs.promises.readdir('/destination')
sourceDirectoryContent = await fs.promises.readdir('/source')
randomFolderContent = await fs.promises.readdir('/destination/random-folder')
randomFolderContent = await fs.promises.readdir(
'/destination/random-folder'
)
secondRandomFolderContent = await fs.promises.readdir(
'/destination/random-folder/second-random-folder'
)
expect(destinationDirectoryContent.length).toEqual(3)
expect(sourceDirectoryContent.length).toEqual(3)
expect(destinationDirectoryContent).toEqual(
expect.arrayContaining(['random-folder', 'index.ts', '.npmignore'])
)
expect(sourceDirectoryContent).toEqual(
expect.arrayContaining(['random-folder', 'index.ts', '.npmignore'])
)
expect(randomFolderContent.length).toEqual(2)
expect(secondRandomFolderContent.length).toEqual(1)
expect(randomFolderContent).toEqual(
expect.arrayContaining(['default.png', 'second-random-folder'])
)
expect(secondRandomFolderContent).toEqual(
expect.arrayContaining(['mycode.ts'])
)
t.equal(destinationDirectoryContent.length, 2)
t.equal(sourceDirectoryContent.length, 2)
t.strictSame(destinationDirectoryContent, ['index.ts', 'random-folder'])
t.strictSame(sourceDirectoryContent, ['index.ts', 'random-folder'])
t.equal(randomFolderContent.length, 2)
t.equal(secondRandomFolderContent.length, 1)
t.strictSame(randomFolderContent, ['default.png', 'second-random-folder'])
t.strictSame(secondRandomFolderContent, ['mycode.ts'])
})
})

View File

@ -1,6 +1,7 @@
import fs from 'node:fs'
import fsMock from 'mock-fs'
import tap from 'tap'
import {
TEMPORARY_PATH,
@ -8,20 +9,30 @@ import {
} from '../createTemporaryEmptyFolder.js'
import { isExistingPath } from '../isExistingPath.js'
describe('utils/createTemporaryEmptyFolder', () => {
afterEach(() => {
await tap.test('utils/createTemporaryEmptyFolder', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('should remove and create again the temporary folder', async () => {
await t.test('should create the temporary folder', async (t) => {
fsMock({})
t.equal(await isExistingPath(TEMPORARY_PATH), false)
await createTemporaryEmptyFolder()
t.equal(await isExistingPath(TEMPORARY_PATH), true)
})
await t.test(
'should remove and create again the temporary folder',
async (t) => {
fsMock({
[TEMPORARY_PATH]: {
'file.txt': ''
}
}, { createCwd: false })
expect(await isExistingPath(TEMPORARY_PATH)).toBeTruthy()
expect((await fs.promises.readdir(TEMPORARY_PATH)).length).toEqual(1)
})
t.equal(await isExistingPath(TEMPORARY_PATH), true)
t.equal((await fs.promises.readdir(TEMPORARY_PATH)).length, 1)
await createTemporaryEmptyFolder()
expect((await fs.promises.readdir(TEMPORARY_PATH)).length).toEqual(0)
})
t.equal((await fs.promises.readdir(TEMPORARY_PATH)).length, 0)
}
)
})

View File

@ -1,23 +1,24 @@
import fsMock from 'mock-fs'
import tap from 'tap'
import { isExistingPath } from '../isExistingPath.js'
describe('utils/isExistingFile', () => {
afterEach(() => {
await tap.test('utils/isExistingPath', async (t) => {
t.afterEach(() => {
fsMock.restore()
})
it('should return true if the file exists', async () => {
await t.test('should return true if the file exists', async () => {
fsMock({
'/file.txt': ''
}, { createCwd: false })
expect(await isExistingPath('/file.txt')).toBeTruthy()
})
t.equal(await isExistingPath('/file.txt'), true)
})
it("should return false if the file doesn't exists", async () => {
await t.test("should return false if the file doesn't exists", async () => {
fsMock({
'/file.txt': ''
}, { createCwd: false })
expect(await isExistingPath('/randomfile.txt')).toBeFalsy()
})
t.equal(await isExistingPath('/randomfile.txt'), false)
})
})

View File

@ -1,13 +1,14 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import { isExistingPath } from '../utils/isExistingPath.js'
export const TEMPORARY_PATH = path.join(__dirname, '..', '..', 'temp')
export const TEMPORARY_URL = new URL('../../temp', import.meta.url)
export const TEMPORARY_PATH = fileURLToPath(TEMPORARY_URL)
export const createTemporaryEmptyFolder = async (): Promise<void> => {
if (await isExistingPath(TEMPORARY_PATH)) {
await fs.promises.rm(TEMPORARY_PATH, { recursive: true, force: true })
await fs.promises.rm(TEMPORARY_URL, { recursive: true, force: true })
}
await fs.promises.mkdir(TEMPORARY_PATH)
await fs.promises.mkdir(TEMPORARY_URL)
}

View File

@ -1,14 +0,0 @@
{
"testEnvironment": "node",
"resolver": "jest-ts-webcompat-resolver",
"transform": {
"^.+\\.(t|j)sx?$": ["@swc/jest"]
},
"rootDir": "./cli",
"testPathIgnorePatterns": [
"<rootDir>/commands/run/test.ts",
"<rootDir>/services/Test.ts",
"<rootDir>/node_modules"
],
"setupFiles": ["<rootDir>/__test__/setup.ts"]
}

10854
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,9 @@
{
"name": "programming-challenges",
"version": "1.0.0",
"private": true,
"description": "programming-challenges brings together lots of programming exercises and challenges to improve your algorithmic logic.",
"private": true,
"type": "module",
"license": "MIT",
"repository": {
"type": "git",
@ -17,50 +18,50 @@
"scripts": {
"start": "node build/index.js",
"build": "rimraf ./build && swc ./cli --out-dir ./build && tsc",
"build:dev": "swc ./src --out-dir ./build --watch",
"lint:commit": "commitlint",
"lint:editorconfig": "editorconfig-checker",
"lint:markdown": "markdownlint \"**/*.md\" --dot --ignore-path \".gitignore\"",
"lint:typescript": "eslint \"**/*.{js,jsx,ts,tsx}\"",
"test": "jest"
"test": "tap"
},
"dependencies": {
"chalk": "4.1.2",
"chalk": "5.0.1",
"clipanion": "3.0.1",
"date-and-time": "2.1.2",
"execa": "5.1.1",
"ora": "5.4.1",
"date-and-time": "2.3.1",
"execa": "6.1.0",
"ora": "6.1.0",
"replace-in-file": "6.3.2",
"table": "6.8.0",
"typanion": "3.7.1",
"validate-npm-package-name": "3.0.0"
"typanion": "3.8.0",
"validate-npm-package-name": "4.0.0"
},
"devDependencies": {
"@commitlint/cli": "16.2.1",
"@commitlint/cli": "16.2.3",
"@commitlint/config-conventional": "16.2.1",
"@swc/cli": "0.1.55",
"@swc/core": "1.2.151",
"@swc/jest": "0.2.20",
"@swc/cli": "0.1.57",
"@swc/core": "1.2.171",
"@types/sinon": "10.0.11",
"@types/tap": "15.0.6",
"@types/date-and-time": "0.13.0",
"@types/jest": "27.4.1",
"@types/mock-fs": "4.13.1",
"@types/ms": "0.7.31",
"@types/node": "17.0.21",
"@types/node": "17.0.25",
"@types/validate-npm-package-name": "3.0.3",
"@typescript-eslint/eslint-plugin": "5.14.0",
"@typescript-eslint/eslint-plugin": "5.20.0",
"editorconfig-checker": "4.0.2",
"eslint": "8.10.0",
"eslint-config-conventions": "1.1.0",
"eslint-plugin-import": "2.25.4",
"eslint": "8.14.0",
"eslint-config-conventions": "2.0.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-promise": "6.0.0",
"eslint-plugin-unicorn": "41.0.0",
"eslint-plugin-unicorn": "42.0.0",
"get-stream": "6.0.1",
"jest": "27.5.1",
"jest-mock-extended": "2.0.4",
"jest-ts-webcompat-resolver": "1.0.0",
"markdownlint-cli": "0.31.1",
"mock-fs": "5.1.2",
"ms": "2.1.3",
"rimraf": "3.0.2",
"typescript": "4.6.2"
"sinon": "13.0.2",
"tap": "16.0.1",
"typescript": "4.6.3"
}
}

View File

@ -1,4 +1,7 @@
FROM gcc:11.2.0
COPY ./ ./
RUN gcc -Wall -Wextra -Werror *.c --output=solution
CMD ["./solution"]
FROM gcc:11.3.0
WORKDIR /usr/app
COPY ./ /usr/app
RUN gcc ./*.c* -o solution.exe -Wall -Wextra -Wfloat-equal -Wundef -Werror -std=c17 -pedantic -pedantic-errors
CMD ["./solution.exe"]

View File

@ -1,4 +1,7 @@
FROM gcc:11.2.0
COPY ./ ./
RUN g++ solution.cpp --output=solution
CMD ["./solution"]
FROM gcc:11.3.0
WORKDIR /usr/app
COPY ./ /usr/app
RUN g++ ./*.cpp* -o solution.exe -Wall -Wextra -Wfloat-equal -Wundef -Werror -std=c++17 -pedantic -pedantic-errors
CMD ["./solution.exe"]

View File

@ -1,5 +1,7 @@
FROM mono:6.12.0
WORKDIR /usr/src/app
COPY ./ ./
RUN mcs ./Solution.cs -out:Solution.exe
ENTRYPOINT ["mono", "./Solution.exe"]

View File

@ -1,3 +1,6 @@
FROM dart:2.16.1
COPY ./ ./
FROM dart:2.16.2
WORKDIR /usr/app
COPY ./ /usr/app
CMD ["dart", "run", "solution.dart"]

View File

@ -1,4 +1,7 @@
FROM openjdk:17
COPY ./ ./
WORKDIR /usr/app
COPY ./ /usr/app
RUN javac Solution.java
CMD ["java", "Solution"]

View File

@ -1,3 +1,6 @@
FROM node:16.14.0
COPY ./ ./
FROM node:16.14.2
WORKDIR /usr/app
COPY ./ /usr/app
CMD ["node", "solution.js"]

View File

@ -1,3 +1,6 @@
FROM python:3.10.0
COPY ./ ./
FROM pypy:3.9-7
WORKDIR /usr/app
COPY ./ /usr/app
CMD ["python", "solution.py"]

View File

@ -1,4 +1,7 @@
FROM rust:1.59.0
COPY ./ ./
FROM rust:1.60.0
WORKDIR /usr/app
COPY ./ /usr/app
RUN rustc solution.rs
CMD ["./solution"]

View File

@ -1,8 +1,7 @@
FROM node:16.14.0
FROM node:16.14.2
WORKDIR /usr/app
COPY ./ /usr/app
RUN npm install
RUN npm run build
RUN npm install && npm run build
CMD ["node", "build/solution.js"]

View File

@ -1,9 +1,10 @@
#include <cstdlib>
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << "Hello, " + line + "!" << std::endl;
}
return 0;
std::string line;
std::getline(std::cin, line);
std::cout << "Hello, " + line + "!\n";
return EXIT_SUCCESS;
}

View File

@ -1,7 +1,7 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"module": "ESNext",
"lib": ["ESNext"],
"moduleResolution": "node",
"outDir": "./build",