Skip to content

feat: run framework detection and run plugins on netlify build #5029

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/commands/build/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ const { error, exit, generateNetlifyGraphJWT, getEnvelopeEnv, getToken, normaliz
/**
* @param {import('../../lib/build').BuildConfig} options
*/
const checkOptions = ({ cachedConfig: { siteInfo = {} }, token }) => {
if (!siteInfo.id) {
error('Could not find the site ID. Please run netlify link.')
}

const checkOptions = ({ token }) => {
if (!token) {
error('Could not find the access token. Please run netlify login.')
}
Expand Down Expand Up @@ -72,7 +68,7 @@ const build = async (options, command) => {
await injectEnv(command, { api, buildOptions, context, site, siteInfo })
}

const { exitCode } = await runBuild(buildOptions)
const { exitCode } = await runBuild(buildOptions, command, options)
exit(exitCode)
}

Expand Down
6 changes: 4 additions & 2 deletions src/commands/deploy/deploy.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,11 @@ const runDeploy = async ({
*
* @param {object} config
* @param {*} config.cachedConfig
* @param {*} config.command
* @param {import('commander').OptionValues} config.options The options of the command
* @returns
*/
const handleBuild = async ({ cachedConfig, options }) => {
const handleBuild = async ({ cachedConfig, command, options }) => {
if (!options.build) {
return {}
}
Expand All @@ -388,7 +389,7 @@ const handleBuild = async ({ cachedConfig, options }) => {
token,
options,
})
const { configMutations, exitCode, newConfig } = await runBuild(resolvedOptions)
const { configMutations, exitCode, newConfig } = await runBuild(resolvedOptions, command, options)
if (exitCode !== 0) {
exit(exitCode)
}
Expand Down Expand Up @@ -573,6 +574,7 @@ const deploy = async (options, command) => {

const { newConfig, configMutations = [] } = await handleBuild({
cachedConfig: command.netlify.cachedConfig,
command,
options,
})
const config = newConfig || command.netlify.config
Expand Down
61 changes: 57 additions & 4 deletions src/lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const process = require('process')

const netlifyBuildPromise = import('@netlify/build')

const { NETLIFYDEVERR, detectServerSettings, error, log } = require('../utils')

/**
* The buildConfig + a missing cachedConfig
* @typedef BuildConfig
Expand Down Expand Up @@ -41,11 +43,20 @@ const getBuildOptions = ({ cachedConfig, options: { context, cwd, debug, dry, js

/**
* run the build command
* @param {BuildConfig} options
* @param {BuildConfig} buildOptions
* @param {import('../commands/base-command').BaseCommand} command
* @param {import('commander').OptionValues} commandOptions
* @returns
*/
const runBuild = async (options) => {
const runBuild = async (buildOptions, command, commandOptions) => {
const { default: build } = await netlifyBuildPromise
const { cachedConfig, config, site } = command.netlify
const devConfig = {
framework: '#auto',
...(config.functionsDirectory && { functions: config.functionsDirectory }),
...config.dev,
...commandOptions,
}

// If netlify NETLIFY_API_URL is set we need to pass this information to @netlify/build
// TODO don't use testOpts, but add real properties to do this.
Expand All @@ -55,10 +66,52 @@ const runBuild = async (options) => {
scheme: apiUrl.protocol.slice(0, -1),
host: apiUrl.host,
}
options = { ...options, testOpts }
buildOptions = { ...buildOptions, testOpts }
}

/** @type {Partial<import('../../utils/types').ServerSettings>} */
let settings = {}
try {
settings = await detectServerSettings(devConfig, commandOptions, site.root)

const defaultConfig = { build: {} }

if (settings.buildCommand && settings.dist) {
buildOptions.cachedConfig.config.build.command = settings.buildCommand
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the sort of question that is tricky to answer without types in place, but is there a chance that some of these intermediate properties will be undefined, leaving to a reference error?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eduardoboucas

Did some chasing here, and found that cachedConfig is created by @netlify/config - and cachedconfig.config.build is always added. https://github.com/netlify/build/blob/d2c74c02280bd2324cb9b933df4be9ba8c399789/packages/config/src/base.js#L32

I'm not sure what I should do to safeguard against that situation popping up if there's a breaking change in @netlify/config though. The node version doesn't support optional chaining, and I don't want to do 4 different hasOwnPropertys :/

But wow, wouldn't this all be so much nicer with Typescript πŸ˜…

defaultConfig.build.command = settings.buildCommand
buildOptions.cachedConfig.config.build.publish = settings.buildCommand
defaultConfig.build.publish = settings.dist
}

if (defaultConfig.build.command && defaultConfig.build.publish) {
buildOptions.defaultConfig = defaultConfig
}

// If there are plugins that we should be running for this site, add them
// to the config as if they were declared in netlify.toml. We must check
// whether the plugin has already been added by another source (like the
// TOML file or the UI), as we don't want to run the same plugin twice.
if (settings.plugins) {
const { plugins: existingPlugins = [] } = cachedConfig.config
const existingPluginNames = new Set(existingPlugins.map((plugin) => plugin.package))
const newPlugins = settings.plugins
.map((pluginName) => {
if (existingPluginNames.has(pluginName)) {
return
}

return { package: pluginName, origin: 'config', inputs: {} }
})
.filter(Boolean)

buildOptions.cachedConfig.config.plugins = [...newPlugins, ...cachedConfig.config.plugins]
}
} catch (detectServerSettingsError) {
log(NETLIFYDEVERR, detectServerSettingsError.message)
error(detectServerSettingsError)
}

const { configMutations, netlifyConfig: newConfig, severityCode: exitCode } = await build(options)
const { configMutations, netlifyConfig: newConfig, severityCode: exitCode } = await build(buildOptions)
return { exitCode, newConfig, configMutations }
}

Expand Down
8 changes: 7 additions & 1 deletion src/utils/detect-server-settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ const handleStaticServer = async ({ devConfig, options, projectDir }) => {
*/
const getSettingsFromFramework = (framework) => {
const {
build: { directory: dist },
build: {
directory: dist,
commands: [buildCommand],
},
dev: {
commands: [command],
port: frameworkPort,
Expand All @@ -172,6 +175,7 @@ const getSettingsFromFramework = (framework) => {

return {
command,
buildCommand,
frameworkPort,
dist: staticDir || dist,
framework: frameworkName,
Expand Down Expand Up @@ -250,6 +254,7 @@ const handleCustomFramework = ({ devConfig }) => {
const mergeSettings = async ({ devConfig, frameworkSettings = {} }) => {
const {
command: frameworkCommand,
buildCommand,
frameworkPort: frameworkDetectedPort,
dist,
framework,
Expand All @@ -263,6 +268,7 @@ const mergeSettings = async ({ devConfig, frameworkSettings = {} }) => {
const useStaticServer = !(command && frameworkPort)
return {
command,
buildCommand,
frameworkPort: useStaticServer ? await getStaticServerPort({ devConfig }) : frameworkPort,
dist: devConfig.publish || dist || getDefaultDist(),
framework,
Expand Down
3 changes: 3 additions & 0 deletions src/utils/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export type FrameworkNames = '#static' | '#auto' | '#custom' | string
export type FrameworkInfo = {
build: {
directory: string
commands: string[]
}
dev: {
commands: string[]
Expand Down Expand Up @@ -32,6 +33,8 @@ export type BaseServerSettings = {
env?: NodeJS.ProcessEnv
pollingStrategies?: string[]
plugins?: string[]
/** The command that was provided for the dev config */
buildCommand?: string
}

export type ServerSettings = BaseServerSettings & {
Expand Down
41 changes: 24 additions & 17 deletions tests/integration/110.command.build.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,23 +241,6 @@ test('should error when using invalid netlify.toml', async (t) => {
})
})

test('should error when a site id is missing', async (t) => {
await withSiteBuilder('no-site-id-site', async (builder) => {
builder.withNetlifyToml({ config: { build: { command: 'echo testCommand' } } })

await builder.buildAsync()

await withMockApi(routes, async ({ apiUrl }) => {
await runBuildCommand(t, builder.directory, {
apiUrl,
exitCode: 1,
output: 'Could not find the site ID',
env: { ...defaultEnvs, NETLIFY_SITE_ID: '' },
})
})
})
})

test('should not require a linked site when offline flag is set', async (t) => {
await withSiteBuilder('success-site', async (builder) => {
await builder.withNetlifyToml({ config: { build: { command: 'echo testCommand' } } }).buildAsync()
Expand Down Expand Up @@ -285,3 +268,27 @@ test('should not send network requests when offline flag is set', async (t) => {
})
})
})

test('should run without site id', async (t) => {
await withSiteBuilder('success-site', async (builder) => {
builder.withNetlifyToml({ config: { build: { command: 'echo testCommand' } } })

await builder.buildAsync()
await withMockApi(routesWithCommand, async ({ apiUrl }) => {
await runBuildCommand(t, builder.directory, { apiUrl, output: 'testCommand' })
})
})
})

test('should add plugin if framework is detected', async (t) => {
await withSiteBuilder('success-site', async (builder) => {
builder.withPackageJson({ packageJson: { dependencies: { next: '^12.2.0' }, scripts: { build: 'next build' } } })

await builder.buildAsync()

await withMockApi(routes, async ({ apiUrl }) => {
// Error expected as this isn't a real next app
await runBuildCommand(t, builder.directory, { apiUrl, output: '@netlify/plugin-nextjs', exitCode: 2 })
})
})
})