Skip to content

Commit

Permalink
refactor: cleanup code and fix eleventy tests
Browse files Browse the repository at this point in the history
  • Loading branch information
erezrokah committed Apr 22, 2021
1 parent 3d34143 commit b3e3b4e
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 68 deletions.
3 changes: 1 addition & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@
"update-notifier": "^4.0.0",
"uuid": "^8.0.0",
"wait-port": "^0.2.2",
"which": "^2.0.2",
"winston": "^3.2.1",
"wrap-ansi": "^7.0.0",
"write-file-atomic": "^3.0.0"
Expand Down
71 changes: 10 additions & 61 deletions src/commands/dev/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
const childProcess = require('child_process')
const path = require('path')
const process = require('process')

const { flags: flagsLib } = require('@oclif/command')
const boxen = require('boxen')
const chalk = require('chalk')
const fetch = require('node-fetch')
const waitFor = require('p-wait-for')
const execa = require('execa')
const StaticServer = require('static-server')
const stripAnsiCc = require('strip-ansi-control-characters')
const waitPort = require('wait-port')
const which = require('which')
const wrapAnsi = require('wrap-ansi')

const Command = require('../../utils/command')
Expand All @@ -23,11 +20,6 @@ const { startProxy } = require('../../utils/proxy')
const { startFunctionsServer } = require('../../utils/serve-functions')
const { startForwardProxy } = require('../../utils/traffic-mesh')

// 1 second
const SERVER_POLL_INTERVAL = 1e3
// 20 seconds
const SERVER_POLL_TIMEOUT = 2e4

const startFrameworkServer = async function ({ settings, log, exit }) {
if (settings.useStaticServer) {
const server = new StaticServer({
Expand All @@ -49,24 +41,10 @@ const startFrameworkServer = async function ({ settings, log, exit }) {
}

log(`${NETLIFYDEVLOG} Starting Netlify Dev with ${settings.framework || 'custom config'}`)
const [command, ...commandArgs] = settings.command.split(/\s+/)
const commandBin = await which(command).catch((error) => {
if (error.code === 'ENOENT') {
throw new Error(
`"${command}" could not be found in your PATH. Please make sure that "${command}" is installed and available in your PATH`,
)
}
throw error
})
const ps = childProcess.spawn(commandBin, commandArgs, {
env: { ...process.env, ...settings.env, FORCE_COLOR: 'true' },
stdio: 'pipe',
})

ps.stdout.pipe(stripAnsiCc.stream()).pipe(process.stdout)
ps.stderr.pipe(stripAnsiCc.stream()).pipe(process.stderr)

process.stdin.pipe(process.stdin)
const frameworkProcess = execa.command(settings.command, { preferLocal: true })
frameworkProcess.stdout.pipe(stripAnsiCc.stream()).pipe(process.stdout)
frameworkProcess.stderr.pipe(stripAnsiCc.stream()).pipe(process.stderr)
process.stdin.pipe(frameworkProcess.stdin)

const handleProcessExit = function (code) {
log(
Expand All @@ -75,16 +53,12 @@ const startFrameworkServer = async function ({ settings, log, exit }) {
)
process.exit(code)
}
ps.on('close', handleProcessExit)
ps.on('SIGINT', handleProcessExit)
ps.on('SIGTERM', handleProcessExit)
frameworkProcess.on('close', handleProcessExit)
frameworkProcess.on('SIGINT', handleProcessExit)
frameworkProcess.on('SIGTERM', handleProcessExit)
;['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGHUP', 'exit'].forEach((signal) => {
process.on(signal, () => {
try {
process.kill(-ps.pid)
} catch (error) {
// Ignore
}
frameworkProcess.kill('SIGTERM', { forceKillAfterTimeout: 500 })
process.exit()
})
})
Expand All @@ -94,42 +68,17 @@ const startFrameworkServer = async function ({ settings, log, exit }) {
port: settings.frameworkPort,
output: 'silent',
timeout: FRAMEWORK_PORT_TIMEOUT,
...(settings.pollingStrategies.includes('HTTP') && { protocol: 'http' }),
})

if (!open) {
throw new Error(`Timed out waiting for port '${settings.frameworkPort}' to be open`)
}

if (!settings.disableLocalServerPolling) {
const waitForServerToRespond = async () => {
try {
await fetch(`http://localhost:${settings.frameworkPort}`, {
method: 'HEAD',
timeout: SERVER_POLL_INTERVAL,
})
} catch (_) {
return false
}

return true
}

try {
await waitFor(waitForServerToRespond, {
interval: SERVER_POLL_INTERVAL,
timeout: SERVER_POLL_TIMEOUT,
})
} catch (_) {
log(NETLIFYDEVWARN, 'Netlify Dev could not verify that your framework server is responding to requests.')
}
}
} catch (error) {
log(NETLIFYDEVERR, `Netlify Dev could not connect to localhost:${settings.frameworkPort}.`)
log(NETLIFYDEVERR, `Please make sure your framework server is running on port ${settings.frameworkPort}`)
exit(1)
}

return ps
}

// 10 minutes
Expand Down
17 changes: 14 additions & 3 deletions src/utils/detect-server-settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,21 @@ const getSettingsFromFramework = (framework) => {
dev: {
commands: [command],
port: frameworkPort,
pollingStrategies,
},
name: frameworkName,
staticAssetsDirectory: staticDir,
env,
} = framework

return { command, frameworkPort, dist: staticDir || dist, framework: frameworkName, env }
return {
command,
frameworkPort,
dist: staticDir || dist,
framework: frameworkName,
env,
pollingStrategies: pollingStrategies.map(({ name }) => name),
}
}

const detectFrameworkSettings = async ({ projectDir, log }) => {
Expand Down Expand Up @@ -203,7 +211,7 @@ const handleForcedFramework = async ({ devConfig, projectDir }) => {
`Unsupported "framework" "${devConfig.framework}". Please consult the documentation for more details: https://cli.netlify.com/netlify-dev/#project-detection`,
)
}
const { command, frameworkPort, dist, framework, env } = getSettingsFromFramework(
const { command, frameworkPort, dist, framework, env, pollingStrategies } = getSettingsFromFramework(
await getFramework(devConfig.framework, { projectDir }),
)
return {
Expand All @@ -212,6 +220,7 @@ const handleForcedFramework = async ({ devConfig, projectDir }) => {
dist: devConfig.publish || dist,
framework,
env,
pollingStrategies,
}
}

Expand All @@ -233,13 +242,14 @@ const detectServerSettings = async (devConfig, flags, projectDir, log) => {
settings = await handleStaticServer({ flags, log, devConfig, projectDir })
} else {
validateFrameworkConfig({ devConfig })
const { command, frameworkPort, dist, framework, env } = frameworkSettings || {}
const { command, frameworkPort, dist, framework, env, pollingStrategies } = frameworkSettings || {}
settings = {
command: devConfig.command || command,
frameworkPort: devConfig.targetPort || frameworkPort,
dist: devConfig.publish || dist || getDefaultDist({ log }),
framework,
env,
pollingStrategies,
}
}
} else if (devConfig.framework === '#custom') {
Expand All @@ -261,6 +271,7 @@ const detectServerSettings = async (devConfig, flags, projectDir, log) => {
})
const functionsDir = devConfig.functions || settings.functions

console.log(settings)
return {
...settings,
port: acquiredPort,
Expand Down
6 changes: 5 additions & 1 deletion tests/eleventy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ const { startDevServer } = require('./utils/dev-server')
const got = require('./utils/got')

test.before(async (t) => {
const server = await startDevServer({ cwd: path.join(__dirname, 'eleventy-site') })
const server = await startDevServer({
cwd: path.join(__dirname, 'eleventy-site'),
// required so configuration won't be resolved from the current CLI repo linked site
args: ['--offline'],
})

t.context.server = server
})
Expand Down

0 comments on commit b3e3b4e

Please sign in to comment.