2021-06-09 20:31:45 +02:00
|
|
|
import execa from 'execa'
|
|
|
|
import ora from 'ora'
|
|
|
|
|
|
|
|
class Docker {
|
2021-11-30 21:42:43 +01:00
|
|
|
static CONTAINER_TAG = 'programming-challenges'
|
2021-12-06 19:04:16 +01:00
|
|
|
static SIGSEGV_EXIT_CODE = 139
|
2021-11-30 21:42:43 +01:00
|
|
|
|
2021-06-09 20:31:45 +02:00
|
|
|
public async build (): Promise<void> {
|
|
|
|
const loader = ora('Building the Docker image').start()
|
|
|
|
try {
|
2021-11-30 21:42:43 +01:00
|
|
|
await execa.command(`docker build --tag=${Docker.CONTAINER_TAG} ./`)
|
2021-06-09 20:31:45 +02:00
|
|
|
loader.stop()
|
|
|
|
} catch (error) {
|
|
|
|
loader.fail()
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async run (input: string): Promise<string> {
|
|
|
|
const subprocess = execa.command(
|
2021-11-30 21:42:43 +01:00
|
|
|
`docker run --interactive --rm ${Docker.CONTAINER_TAG}`,
|
2021-06-09 20:31:45 +02:00
|
|
|
{
|
|
|
|
input
|
|
|
|
}
|
|
|
|
)
|
2021-12-06 19:04:16 +01:00
|
|
|
try {
|
|
|
|
const { stdout, stderr } = await subprocess
|
|
|
|
if (stderr.length !== 0) {
|
|
|
|
throw new Error(stderr)
|
|
|
|
}
|
|
|
|
return stdout
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.exitCode === Docker.SIGSEGV_EXIT_CODE) {
|
|
|
|
throw new Error('Docker run failed: SIGSEGV indicates a segmentation fault (attempts to access a memory location that it\'s not allowed to access).')
|
|
|
|
}
|
|
|
|
throw new Error(`Docker run failed: ${error.message as string}`)
|
2021-06-09 20:31:45 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const docker = new Docker()
|