-
Notifications
You must be signed in to change notification settings - Fork 429
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
feat(cli): add support for remote templates with --template
#7867
Open
RostiMelk
wants to merge
34
commits into
next
Choose a base branch
from
feat/cli/remote-templates
base: next
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+11,244
−13,726
Open
Changes from 5 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
f7c47a3
fix: remove trailing commas when sanitizing
RostiMelk da20886
feat: add support for React Compiler beta (#7702)
stipsan 48035a1
feat: initial branch commit
RostiMelk b4fe4ad
feat: bad rebase
RostiMelk 2b1c1cb
feat: wip tests
RostiMelk 5bac6af
feat: token, package name, git init
RostiMelk 3e420e2
feat: more debugs
RostiMelk df17185
feat: reorder intro msg
RostiMelk e544df3
feat: remove unused var
RostiMelk 610e3a9
feat: lints
RostiMelk 29aa52d
feat: remove console log
RostiMelk a8dec47
feat: framework name on error
RostiMelk 7734959
feat: allow slug sanity
RostiMelk 6dd40b9
feat: allow slug sanity
RostiMelk fede57b
feat: pass bearer to fetcher
RostiMelk 6cd69c7
feat: cleanup env func
RostiMelk bd69dff
feat: update tests to match template
RostiMelk 05da0d6
feat: update throw
RostiMelk acd2846
feat: check repo info earlier
RostiMelk a8526e3
feat: lint
RostiMelk c8b88d1
feat: check for .env.local.template
RostiMelk 735850f
feat: support for applying to env.local.example
RostiMelk f422fd9
feat: remove console logs
RostiMelk cc9ff7c
feat: official template
RostiMelk 611a268
feat: patch metadata
RostiMelk ccb02a3
feat: pass context + clean up a bit
RostiMelk 42a1614
feat: add suport for monorepos
RostiMelk 578e50b
fix: return
RostiMelk ce43f61
feat: handle envs
RostiMelk 7b065c4
feat: support for studio alt
RostiMelk 21493b9
feat: generate token
RostiMelk c36e5df
feat: cleanup
RostiMelk 511a6b5
feat: cleanup
RostiMelk a5f2dde
feat: filter empty filepaths and update type path
RostiMelk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
packages/@sanity/cli/src/actions/init-project/bootstrapRemoteTemplate.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import fs from 'node:fs/promises' | ||
|
||
import {debug} from '../../debug' | ||
import { | ||
applyEnvVariables, | ||
downloadAndExtractRepo, | ||
getGihubRepoInfo, | ||
isNextJsTemplate, | ||
validateRemoteTemplate, | ||
} from '../../util/remoteTemplate' | ||
import {type GenerateConfigOptions} from './createStudioConfig' | ||
|
||
export interface BootstrapOptions { | ||
packageName: string | ||
templateName: string | ||
outputPath: string | ||
variables: GenerateConfigOptions['variables'] | ||
} | ||
|
||
export async function bootstrapRemoteTemplate(opts: BootstrapOptions): Promise<void> { | ||
const {outputPath, templateName, variables} = opts | ||
|
||
debug('Getting Github repo info for "%s"', templateName) | ||
const repoInfo = await getGihubRepoInfo(templateName) | ||
|
||
await validateRemoteTemplate(repoInfo) | ||
|
||
debug('Create new directory "%s"', outputPath) | ||
await fs.mkdir(outputPath, {recursive: true}) | ||
|
||
await downloadAndExtractRepo(outputPath, repoInfo) | ||
|
||
const isNext = await isNextJsTemplate(outputPath) | ||
const envName = isNext ? '.env.local' : '.env' | ||
await applyEnvVariables(outputPath, variables, envName) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,17 +35,21 @@ import { | |
type CliCommandDefinition, | ||
type SanityCore, | ||
type SanityModuleInternal, | ||
type SanityUser, | ||
} from '../../types' | ||
import {getClientWrapper} from '../../util/clientWrapper' | ||
import {dynamicRequire} from '../../util/dynamicRequire' | ||
import {getProjectDefaults, type ProjectDefaults} from '../../util/getProjectDefaults' | ||
import {getProviderName} from '../../util/getProviderName' | ||
import {getUserConfig} from '../../util/getUserConfig' | ||
import {isCommandGroup} from '../../util/isCommandGroup' | ||
import {isInteractive} from '../../util/isInteractive' | ||
import {fetchJourneyConfig} from '../../util/journeyConfig' | ||
import {checkIsRemoteTemplate} from '../../util/remoteTemplate' | ||
import {login, type LoginFlags} from '../login/login' | ||
import {createProject} from '../project/createProject' | ||
import {type BootstrapOptions, bootstrapTemplate} from './bootstrapTemplate' | ||
import {bootstrapLocalTemplate, type BootstrapOptions} from './bootstrapLocalTemplate' | ||
import {bootstrapRemoteTemplate} from './bootstrapRemoteTemplate' | ||
import {type GenerateConfigOptions} from './createStudioConfig' | ||
import {absolutify, validateEmptyPath} from './fsUtils' | ||
import {tryGitInit} from './git' | ||
|
@@ -143,6 +147,7 @@ export default async function initSanity( | |
const bareOutput = cliFlags.bare | ||
const env = cliFlags.env | ||
const packageManager = cliFlags['package-manager'] | ||
const isRemoteTemplate = checkIsRemoteTemplate(cliFlags.template) | ||
|
||
let defaultConfig = cliFlags['dataset-default'] | ||
let showDefaultConfigPrompt = !defaultConfig | ||
|
@@ -167,6 +172,10 @@ export default async function initSanity( | |
return | ||
} | ||
|
||
if (detectedFramework && isRemoteTemplate) { | ||
throw new Error('A remote template cannot be used with a detected framework.') | ||
} | ||
|
||
// Only allow either --project-plan or --coupon | ||
if (intendedCoupon && intendedPlan) { | ||
throw new Error( | ||
|
@@ -253,24 +262,20 @@ export default async function initSanity( | |
} | ||
const envFilename = typeof env === 'string' ? env : envFilenameDefault | ||
if (!envFilename.startsWith('.env')) { | ||
throw new Error(`Env filename must start with .env`) | ||
throw new Error('Env filename must start with .env') | ||
} | ||
|
||
const usingBareOrEnv = cliFlags.bare || cliFlags.env | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Vastly simplified the intro message |
||
print( | ||
cliFlags.quickstart | ||
? "You're ejecting a remote Sanity project!" | ||
: `You're setting up a new project!`, | ||
) | ||
print(`We'll make sure you have an account with Sanity.io. ${usingBareOrEnv ? '' : `Then we'll`}`) | ||
if (!usingBareOrEnv) { | ||
print('install an open-source JS content editor that connects to') | ||
print('the real-time hosted API on Sanity.io. Hang on.\n') | ||
|
||
let introMessage = "Let's get you started with a new project" | ||
if (cliFlags.quickstart) { | ||
introMessage = "Let's get you started with remote Sanity project" | ||
} else if (isRemoteTemplate) { | ||
introMessage = "Let's get you started with a remote Sanity template" | ||
} | ||
print('Press ctrl + C at any time to quit.\n') | ||
print('Prefer web interfaces to terminals?') | ||
print('You can also set up best practice Sanity projects with') | ||
print('your favorite frontends on https://www.sanity.io/templates\n') | ||
print('') | ||
print(` ➡️ ${chalk.gray(introMessage)}`) | ||
print('') | ||
|
||
// If the user isn't already authenticated, make it so | ||
const userConfig = getUserConfig() | ||
|
@@ -279,7 +284,13 @@ export default async function initSanity( | |
debug(hasToken ? 'User already has a token' : 'User has no token') | ||
if (hasToken) { | ||
trace.log({step: 'login', alreadyLoggedIn: true}) | ||
print('Looks like you already have a Sanity-account. Sweet!\n') | ||
const user = await getUserData(apiClient) | ||
print( | ||
`${chalk.gray(" 👤 You're logged in as %s using %s")}`, | ||
user.name, | ||
getProviderName(user.provider), | ||
) | ||
print('') | ||
} else if (!unattended) { | ||
trace.log({step: 'login'}) | ||
await getOrCreateUser() | ||
|
@@ -581,18 +592,20 @@ export default async function initSanity( | |
const templateName = await selectProjectTemplate() | ||
trace.log({step: 'selectProjectTemplate', selectedOption: templateName}) | ||
const template = templates[templateName] | ||
if (!template) { | ||
if (isRemoteTemplate === false && !template) { | ||
throw new Error(`Template "${templateName}" not found`) | ||
} | ||
|
||
// Use typescript? | ||
const typescriptOnly = template.typescriptOnly === true | ||
let useTypeScript = true | ||
if (!typescriptOnly && typeof cliFlags.typescript === 'boolean') { | ||
useTypeScript = cliFlags.typescript | ||
} else if (!typescriptOnly && !unattended) { | ||
useTypeScript = await promptForTypeScript(prompt) | ||
trace.log({step: 'useTypeScript', selectedOption: useTypeScript ? 'yes' : 'no'}) | ||
if (isRemoteTemplate === false && template) { | ||
const typescriptOnly = template.typescriptOnly === true | ||
if (!typescriptOnly && typeof cliFlags.typescript === 'boolean') { | ||
useTypeScript = cliFlags.typescript | ||
} else if (!typescriptOnly && !unattended) { | ||
useTypeScript = await promptForTypeScript(prompt) | ||
trace.log({step: 'useTypeScript', selectedOption: useTypeScript ? 'yes' : 'no'}) | ||
} | ||
} | ||
|
||
// we enable auto-updates by default, but allow users to specify otherwise | ||
|
@@ -618,7 +631,7 @@ export default async function initSanity( | |
|
||
// If the template has a sample dataset, prompt the user whether or not we should import it | ||
const shouldImport = | ||
!unattended && template.datasetUrl && (await promptForDatasetImport(template.importPrompt)) | ||
!unattended && template?.datasetUrl && (await promptForDatasetImport(template.importPrompt)) | ||
|
||
trace.log({step: 'importTemplateDataset', selectedOption: shouldImport ? 'yes' : 'no'}) | ||
|
||
|
@@ -641,7 +654,9 @@ export default async function initSanity( | |
debug('Failed to update cliInitializedAt metadata') | ||
}), | ||
// Bootstrap Sanity, creating required project files, manifests etc | ||
bootstrapTemplate(templateOptions, context), | ||
isRemoteTemplate | ||
? bootstrapRemoteTemplate(templateOptions, context) | ||
: bootstrapLocalTemplate(templateOptions, context), | ||
]) | ||
|
||
if (bootstrapPromise.status === 'rejected' && bootstrapPromise.reason instanceof Error) { | ||
|
@@ -823,29 +838,26 @@ export default async function initSanity( | |
isFirstProject: boolean | ||
userAction: 'create' | 'select' | ||
}> { | ||
const spinner = context.output.spinner('Fetching existing projects').start() | ||
const client = apiClient({requireUser: true, requireProject: false}) | ||
let projects | ||
let organizations: ProjectOrganization[] | ||
|
||
try { | ||
const client = apiClient({requireUser: true, requireProject: false}) | ||
const [allProjects, allOrgs] = await Promise.all([ | ||
client.projects.list({includeMembers: false}), | ||
client.request({uri: '/organizations'}), | ||
]) | ||
projects = allProjects.sort((a, b) => b.createdAt.localeCompare(a.createdAt)) | ||
organizations = allOrgs | ||
spinner.succeed() | ||
} catch (err) { | ||
if (unattended && flags.project) { | ||
spinner.succeed() | ||
return { | ||
projectId: flags.project, | ||
displayName: 'Unknown project', | ||
isFirstProject: false, | ||
userAction: 'select', | ||
} | ||
} | ||
spinner.fail() | ||
throw new Error(`Failed to communicate with the Sanity API:\n${err.message}`) | ||
} | ||
|
||
|
@@ -1479,6 +1491,16 @@ async function getPlanFromCoupon(apiClient: CliApiClient, couponCode: string): P | |
return planId | ||
} | ||
|
||
async function getUserData(apiClient: CliApiClient): Promise<SanityUser> { | ||
return await apiClient({ | ||
requireUser: true, | ||
requireProject: false, | ||
}).request({ | ||
method: 'GET', | ||
uri: 'users/me', | ||
}) | ||
} | ||
|
||
async function getPlanFromId(apiClient: CliApiClient, planId: string): Promise<string> { | ||
const response = await apiClient({ | ||
requireUser: false, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import {type SanityUser} from '../types' | ||
|
||
export function getProviderName(provider: SanityUser['provider']) { | ||
if (provider === 'google') return 'Google' | ||
if (provider === 'github') return 'GitHub' | ||
if (provider === 'sanity') return 'Email' | ||
if (provider.startsWith('saml-')) return 'SAML' | ||
return provider | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Renamed file from bootstrapTemplate to bootstrapLocalTemplate to better distinguish between flows