Skip to content
Open
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
1 change: 1 addition & 0 deletions src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ For more information about getting started with Netlify CLI, see ${terminalLink(
.action(async (options: OptionValues, command: BaseCommand) => {
const { init } = await import('./init.js')
await init(options, command, {
skipPromptsWithoutTerminal: true,
setupAgentSkills: !options.skipAgentSetup,
setupAgentMcp: !options.skipAgentSetup && !options.skipMcpSetup,
resetMcpSetup: Boolean(options.resetMcpSetup),
Expand Down
64 changes: 59 additions & 5 deletions src/commands/init/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { confirm, select } from '@inquirer/prompts'
import { isEmpty } from '../../utils/object-utilities.js'

import { type APIError, chalk, exit, log, logAndThrowError, netlifyCommand, warn } from '../../utils/command-helpers.js'
import getRepoData, { type RepoDataError } from '../../utils/get-repo-data.js'
import getRepoData, { type RepoData, type RepoDataError } from '../../utils/get-repo-data.js'
import { ensureNetlifyIgnore } from '../../utils/gitignore.js'
import { configureRepo } from '../../utils/init/config.js'
import { isInteractive } from '../../utils/scripted-commands.js'
import { track } from '../../utils/telemetry/index.js'
import type BaseCommand from '../base-command.js'
import { link } from '../link/link.js'
Expand Down Expand Up @@ -65,6 +66,53 @@ const logLinkedWithoutGitAndExit = ({
return exit()
}

const canAnswerPrompts = (): boolean => isInteractive() || process.env.TESTING_PROMPTS === 'true'

const logNextStepsAndExit = ({
command,
linkedSiteInfo,
repoData,
}: {
command: BaseCommand
linkedSiteInfo: SiteInfo | undefined
repoData: RepoData | RepoDataError
}): never => {
const run = (args: string): string => chalk.cyanBright.bold(`${netlifyCommand()} ${args}`)
const teams = command.netlify.accounts
const teamSlug = teams.length === 1 ? teams[0].slug : '<team-slug>'

log()
log('Project setup asks questions and there is no terminal to answer them in, so it was skipped.')
log()
if (linkedSiteInfo) {
log(`This folder is linked to the Netlify project ${chalk.cyan(linkedSiteInfo.name)}.`)
log()
log(`To deploy to it, run ${run('deploy')}.`)
} else {
if (command.netlify.state.get('siteId') === undefined) {
log('This folder is not linked to a Netlify project yet. To continue without a terminal, run one of:')
} else {
log('The Netlify project saved as the link for this folder could not be used. See the warning above.')
log(`If you are logged in to the right account, run ${run('unlink')} to remove the saved link. Then run one of:`)
}
log()
if (!('error' in repoData)) {
log(` ${run(`link --git-remote-url ${repoData.httpsUrl}`)} links the project connected to this repository`)
}
log(` ${run('link --id <project-id>')} links an existing project`)
log(` ${run(`sites:create --name <name> --account-slug ${teamSlug}`)} creates a project and links it`)
if (teams.length > 1) {
log()
log(`Teams: ${teams.map(({ slug }) => slug).join(', ')}`)
log('Ask the user which team a new project belongs in.')
}
log()
log(`Then run ${run('deploy')} to deploy.`)
}
log(`To deploy on every push, run ${run('init')} in a terminal. It asks for access to the Git provider.`)
return exit()
}

const ignoreLinkedSiteForThisRun = (command: BaseCommand): void => {
const { site } = command.netlify
command.siteId = undefined
Expand Down Expand Up @@ -294,6 +342,7 @@ type InitExitMessageCustomizer = (code: InitExitCode, defaultMessage: string) =>
type InitExtraOptions = {
customizeExitMessage?: InitExitMessageCustomizer | undefined
exitAfterConfiguringRepo?: boolean | undefined
skipPromptsWithoutTerminal?: boolean | undefined
setupAgentSkills?: boolean | undefined
setupAgentMcp?: boolean | undefined
resetContext?: boolean | undefined
Expand Down Expand Up @@ -369,6 +418,7 @@ export const init = async (
{
customizeExitMessage,
exitAfterConfiguringRepo = false,
skipPromptsWithoutTerminal = false,
setupAgentSkills: shouldSetupAgentSkills = false,
setupAgentMcp: shouldSetupAgentMcp = false,
resetContext = false,
Expand Down Expand Up @@ -402,17 +452,21 @@ export const init = async (
mcpScope,
})

const promptsSkipped = skipPromptsWithoutTerminal && !canAnswerPrompts()
const linkedSiteInfo = await getLinkedSiteInfo(command)
if (linkedSiteInfo && getRepoUrl(linkedSiteInfo) && !options.force) {
if (linkedSiteInfo && getRepoUrl(linkedSiteInfo) && (!options.force || promptsSkipped)) {
logExistingAndExit({ siteInfo: linkedSiteInfo })
}

// Look for local repo
const repoData = await getRepoData({ workingDir: command.workingDir, remoteName: options.gitRemoteName })
if ('error' in repoData && linkedSiteInfo) {
return logLinkedWithoutGitAndExit({ siteInfo: linkedSiteInfo, repoError: repoData })
}
if (promptsSkipped) {
return logNextStepsAndExit({ command, linkedSiteInfo, repoData })
}
if ('error' in repoData) {
if (linkedSiteInfo) {
return logLinkedWithoutGitAndExit({ siteInfo: linkedSiteInfo, repoError: repoData })
}
// TODO(ndhoule): Custom error messaage here
return await handleNoGitRemoteAndExit({
command,
Expand Down
86 changes: 77 additions & 9 deletions tests/integration/commands/init/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import { withSiteBuilder } from '../../utils/site-builder.js'

const defaultFunctionsDirectory = 'netlify/functions'

const answersPrompts = { TESTING_PROMPTS: 'true' }
const noTerminal = { TESTING_PROMPTS: 'false' }

const SKILL_CONTENT = '# netlify-functions\n'

const sha256 = (content: string) => `sha256:${createHash('sha256').update(content).digest('hex')}`
Expand Down Expand Up @@ -187,7 +190,12 @@ describe.concurrent('commands/init', () => {
const childProcess = execa(cliPath, ['init', '--force', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
// NETLIFY_SITE_ID and NETLIFY_AUTH_TOKEN are required for @netlify/config to retrieve site info
env: { NETLIFY_API_URL: apiUrl, NETLIFY_SITE_ID: 'site_id', NETLIFY_AUTH_TOKEN: 'fake-token' },
env: {
...answersPrompts,
NETLIFY_API_URL: apiUrl,
NETLIFY_SITE_ID: 'site_id',
NETLIFY_AUTH_TOKEN: 'fake-token',
},
})

handleQuestions(childProcess, initQuestions)
Expand Down Expand Up @@ -282,7 +290,7 @@ describe.concurrent('commands/init', () => {
// --manual is used to avoid the config-github flow that uses GitHub API
const childProcess = execa(cliPath, ['init', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...answersPrompts, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
encoding: 'utf8',
})

Expand Down Expand Up @@ -361,7 +369,7 @@ describe.concurrent('commands/init', () => {
await withMockApi(routes, async ({ apiUrl }) => {
const childProcess = execa(cliPath, ['init', '--skip-agent-setup'], {
cwd: builder.directory,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...answersPrompts, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
encoding: 'utf8',
})

Expand Down Expand Up @@ -469,7 +477,7 @@ describe.concurrent('commands/init', () => {
// --manual is used to avoid the config-github flow that uses GitHub API
const childProcess = execa(cliPath, ['init', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...answersPrompts, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
})

handleQuestions(childProcess, initQuestions)
Expand Down Expand Up @@ -574,7 +582,7 @@ describe.concurrent('commands/init', () => {
// --manual is used to avoid the config-github flow that uses GitHub API
const childProcess = execa(cliPath, ['init', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...answersPrompts, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
})

handleQuestions(childProcess, initQuestions)
Expand Down Expand Up @@ -666,7 +674,12 @@ describe.concurrent('commands/init', () => {
const childProcess = execa(cliPath, ['init', '--force', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
// NETLIFY_SITE_ID and NETLIFY_AUTH_TOKEN are required for @netlify/config to retrieve site info
env: { NETLIFY_API_URL: apiUrl, NETLIFY_SITE_ID: 'site_id', NETLIFY_AUTH_TOKEN: 'fake-token' },
env: {
...answersPrompts,
NETLIFY_API_URL: apiUrl,
NETLIFY_SITE_ID: 'site_id',
NETLIFY_AUTH_TOKEN: 'fake-token',
},
})

handleQuestions(childProcess, initQuestions)
Expand Down Expand Up @@ -771,7 +784,7 @@ describe.concurrent('commands/init', () => {
// --manual is used to avoid the config-github flow that uses GitHub API
const childProcess = execa(cliPath, ['init', '--manual', '--skip-agent-setup'], {
cwd: builder.directory,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...answersPrompts, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
})

handleQuestions(childProcess, initQuestions)
Expand Down Expand Up @@ -843,6 +856,7 @@ describe.concurrent('commands/init', () => {
}) =>
async (...flags: string[]) => {
const env = {
...answersPrompts,
NETLIFY_API_URL: apiUrl,
NETLIFY_SITE_ID: 'site_id',
NETLIFY_AUTH_TOKEN: 'fake-token',
Expand All @@ -854,7 +868,7 @@ describe.concurrent('commands/init', () => {
...(home ? { HOME: home, USERPROFILE: home } : {}),
}
const mcpFlags = claudeBin || agent ? [] : ['--skip-mcp-setup']
const childProcess = execa(cliPath, ['init', '--manual', ...mcpFlags, ...flags], { cwd, env })
const childProcess = execa(cliPath, ['init', '--force', '--manual', ...mcpFlags, ...flags], { cwd, env })
if (process.env.DEBUG_TESTS) {
childProcess.stdout?.on('data', (data: Buffer) => {
process.stderr.write(data)
Expand Down Expand Up @@ -1111,10 +1125,11 @@ describe.concurrent('commands/init', () => {
apiUrl: string,
questions: { question: string; answer: string | string[] }[],
flags: string[] = [],
promptEnv: Record<string, string> = answersPrompts,
) => {
const childProcess = execa(cliPath, ['init', '--manual', '--skip-agent-setup', ...flags], {
cwd,
env: { NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
env: { ...promptEnv, NETLIFY_API_URL: apiUrl, NETLIFY_AUTH_TOKEN: 'fake-token' },
encoding: 'utf8',
})
handleQuestions(childProcess, questions)
Expand Down Expand Up @@ -1314,6 +1329,59 @@ describe.concurrent('commands/init', () => {
})
})

test('netlify init without a terminal skips the project prompts, prints the next commands and exits cleanly', async (t) => {
await withSiteBuilder(t, async (builder) => {
await builder.withGit().build()

await withMockApi(noGitRoutes, async ({ apiUrl, requests }) => {
const { exitCode, stdout } = await runInitIn(builder.directory, apiUrl, [], [], noTerminal)

t.expect(exitCode).toBe(0)
t.expect(stdout).not.toContain('What would you like to do?')
t.expect(stdout).toContain('This folder is not linked to a Netlify project yet')
t.expect(stdout).toMatch(/netlify link --git-remote-url https:\/\/github\.com\/owner\/repo/)
t.expect(stdout).toMatch(/netlify sites:create --name <name> --account-slug test-account/)
t.expect(stdout).toMatch(/Then run (npx )?netlify deploy to deploy\./)
t.expect(countSiteCreations(requests)).toBe(0)
})
})
})

test('netlify init without a terminal says to unlink first when the linked project no longer exists', async (t) => {
await withSiteBuilder(t, async (builder) => {
await builder.withGit().withStateFile({ siteId: 'deleted_site_id' }).build()

await withMockApi(
[deletedSiteRoute, ...noGitRoutes],
async ({ apiUrl, requests }) => {
const { exitCode, stdout } = await runInitIn(builder.directory, apiUrl, [], [], noTerminal)

t.expect(exitCode).toBe(0)
t.expect(stdout).toMatch(/run (npx )?netlify unlink to remove the saved link/)
t.expect(stdout).not.toContain('This folder is not linked to a Netlify project yet')
t.expect(countSiteCreations(requests)).toBe(0)
await t.expect(readStateSiteId(builder.directory)).resolves.toBe('deleted_site_id')
},
true,
)
})
})

test('netlify init without a terminal reports a linked project instead of configuring its repo', async (t) => {
await withSiteBuilder(t, async (builder) => {
await builder.withGit().withStateFile({ siteId: 'site_id' }).build()

await withMockApi(noGitRoutes, async ({ apiUrl, requests }) => {
const { exitCode, stdout } = await runInitIn(builder.directory, apiUrl, [], [], noTerminal)

t.expect(exitCode).toBe(0)
t.expect(stdout).toContain('This folder is linked to the Netlify project test-site-name')
t.expect(stdout).toMatch(/To deploy to it, run (npx )?netlify deploy\./)
t.expect(requests.some(({ method }) => method === 'PATCH' || method === 'POST')).toBe(false)
})
})
})

test('netlify init stops without creating a project when the linked project cannot be loaded', async (t) => {
const routes = [
{ path: 'sites/unavailable_site_id', status: 500, response: { message: 'Internal Server Error' } },
Expand Down
Loading