-
Notifications
You must be signed in to change notification settings - Fork 3
feat(init): support sanity-template.json with postInitMessage
#771
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
Open
hermanwikner
wants to merge
1
commit into
main
Choose a base branch
from
crx-2061
base: main
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.
Open
Changes from all commits
Commits
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
46 changes: 46 additions & 0 deletions
46
packages/@sanity/cli/src/actions/init/__tests__/getPostInitMessageDisplay.test.ts
This file contains hidden or 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,46 @@ | ||
| import {describe, expect, test} from 'vitest' | ||
|
|
||
| import {getPostInitMessageDisplay} from '../getPostInitMessageDisplay.js' | ||
|
|
||
| describe('getPostInitMessageDisplay', () => { | ||
| test('returns null for undefined', () => { | ||
| expect(getPostInitMessageDisplay(undefined)).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null for empty string', () => { | ||
| expect(getPostInitMessageDisplay('')).toBeNull() | ||
| expect(getPostInitMessageDisplay(' ')).toBeNull() | ||
| }) | ||
|
|
||
| test('returns single line for non-empty string', () => { | ||
| expect(getPostInitMessageDisplay('Hello')).toEqual(['Hello']) | ||
| }) | ||
|
|
||
| test('splits string on newlines like separate array entries', () => { | ||
| expect(getPostInitMessageDisplay('a\n\nb')).toEqual(['a', 'b']) | ||
| }) | ||
|
|
||
| test('strips ANSI sequences from string', () => { | ||
| const withAnsi = '\u001B[31mred\u001B[0m text' | ||
| expect(getPostInitMessageDisplay(withAnsi)).toEqual(['red text']) | ||
| }) | ||
|
|
||
| test('returns null for empty array', () => { | ||
| expect(getPostInitMessageDisplay([])).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null when array is only whitespace', () => { | ||
| expect(getPostInitMessageDisplay(['', ' ', '\t'])).toBeNull() | ||
| }) | ||
|
|
||
| test('filters empty entries and preserves order', () => { | ||
| expect(getPostInitMessageDisplay(['a', '', ' ', 'b'])).toEqual(['a', 'b']) | ||
| }) | ||
|
|
||
| test('strips ANSI from each array line', () => { | ||
| expect(getPostInitMessageDisplay(['\u001B[1mbold\u001B[0m', 'plain'])).toEqual([ | ||
| 'bold', | ||
| 'plain', | ||
| ]) | ||
| }) | ||
| }) |
136 changes: 136 additions & 0 deletions
136
packages/@sanity/cli/src/actions/init/__tests__/readTemplateManifest.test.ts
This file contains hidden or 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,136 @@ | ||
| import path from 'node:path' | ||
|
|
||
| import {afterEach, describe, expect, test, vi} from 'vitest' | ||
|
|
||
| import {readTemplateManifest, removeTemplateManifestFromOutput} from '../readTemplateManifest.js' | ||
|
|
||
| const MANIFEST_PATH = path.join('/tmp/project', 'sanity-template.json') | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| noop: () => {}, | ||
| readFile: vi.fn(), | ||
| unlink: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('node:fs/promises', () => ({ | ||
| readFile: mocks.readFile, | ||
| unlink: mocks.unlink, | ||
| })) | ||
|
|
||
| vi.mock('@sanity/cli-core', () => ({ | ||
| subdebug: () => mocks.noop, | ||
| })) | ||
|
|
||
| describe('readTemplateManifest', () => { | ||
| afterEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| test('returns manifest when sanity-template.json exists with postInitMessage', async () => { | ||
| mocks.readFile.mockResolvedValue( | ||
| JSON.stringify({postInitMessage: 'Run npx skills add sanity-io/agent-context --all'}), | ||
| ) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toEqual({ | ||
| postInitMessage: 'Run npx skills add sanity-io/agent-context --all', | ||
| }) | ||
| expect(mocks.readFile).toHaveBeenCalledWith(MANIFEST_PATH, 'utf8') | ||
| }) | ||
|
|
||
| test('returns manifest when postInitMessage is a string array', async () => { | ||
| mocks.readFile.mockResolvedValue(JSON.stringify({postInitMessage: ['Line one', 'Line two']})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toEqual({postInitMessage: ['Line one', 'Line two']}) | ||
| }) | ||
|
|
||
| test('strips unknown keys from manifest', async () => { | ||
| mocks.readFile.mockResolvedValue( | ||
| JSON.stringify({ | ||
| postInitMessage: 'ok', | ||
| unknownField: 'ignored', | ||
| }), | ||
| ) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toEqual({postInitMessage: 'ok'}) | ||
| }) | ||
|
|
||
| test('returns manifest when file has no postInitMessage field', async () => { | ||
| mocks.readFile.mockResolvedValue(JSON.stringify({})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toEqual({}) | ||
| }) | ||
|
|
||
| test('returns null when sanity-template.json does not exist', async () => { | ||
| mocks.readFile.mockRejectedValue(Object.assign(new Error('ENOENT'), {code: 'ENOENT'})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null when sanity-template.json contains invalid JSON', async () => { | ||
| mocks.readFile.mockResolvedValue('not valid json {{{') | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null when postInitMessage has invalid type', async () => { | ||
| mocks.readFile.mockResolvedValue(JSON.stringify({postInitMessage: 42})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null when postInitMessage array contains non-strings', async () => { | ||
| mocks.readFile.mockResolvedValue(JSON.stringify({postInitMessage: ['ok', 1]})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toBeNull() | ||
| }) | ||
|
|
||
| test('returns null when postInitMessage exceeds schema size limits', async () => { | ||
| mocks.readFile.mockResolvedValue(JSON.stringify({postInitMessage: 'x'.repeat(2001)})) | ||
|
|
||
| const manifest = await readTemplateManifest('/tmp/project') | ||
|
|
||
| expect(manifest).toBeNull() | ||
| }) | ||
| }) | ||
|
|
||
| describe('removeTemplateManifestFromOutput', () => { | ||
| afterEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| test('unlinks sanity-template.json under output path', async () => { | ||
| mocks.unlink.mockResolvedValue(undefined) | ||
|
|
||
| await removeTemplateManifestFromOutput('/tmp/project') | ||
|
|
||
| expect(mocks.unlink).toHaveBeenCalledWith(MANIFEST_PATH) | ||
| }) | ||
|
|
||
| test('does not throw when file is already missing', async () => { | ||
| mocks.unlink.mockRejectedValue(Object.assign(new Error('ENOENT'), {code: 'ENOENT'})) | ||
|
|
||
| await expect(removeTemplateManifestFromOutput('/tmp/project')).resolves.toBeUndefined() | ||
| }) | ||
|
|
||
| test('does not throw when unlink fails for another reason', async () => { | ||
| mocks.unlink.mockRejectedValue(Object.assign(new Error('EACCES'), {code: 'EACCES'})) | ||
|
|
||
| await expect(removeTemplateManifestFromOutput('/tmp/project')).resolves.toBeUndefined() | ||
| }) | ||
| }) |
This file contains hidden or 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 |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| export const INIT_API_VERSION = 'v2025-06-01' | ||
|
|
||
| export const TEMPLATE_MANIFEST_FILENAME = 'sanity-template.json' as const |
28 changes: 28 additions & 0 deletions
28
packages/@sanity/cli/src/actions/init/getPostInitMessageDisplay.ts
This file contains hidden or 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,28 @@ | ||
| import {stripVTControlCharacters} from 'node:util' | ||
|
|
||
| import {type TemplateManifest} from './types.js' | ||
|
|
||
| function normalizeLines(rawLines: string[]): string[] | null { | ||
| const lines = rawLines | ||
| .map((line) => stripVTControlCharacters(line)) | ||
| .filter((line) => line.trim() !== '') | ||
|
|
||
| return lines.length > 0 ? lines : null | ||
| } | ||
|
|
||
| /** | ||
| * Normalizes the template manifest `postInitMessage` field into lines for the CLI to print. | ||
| * Strips VT/ANSI-style escapes and removes blank-only entries; returns `null` when there is nothing to show. | ||
| * String values are split on newlines so spacing matches an equivalent array of lines. | ||
| */ | ||
| export function getPostInitMessageDisplay( | ||
| postInitMessage: TemplateManifest['postInitMessage'], | ||
| ): string[] | null { | ||
| if (!postInitMessage) return null | ||
|
|
||
| if (Array.isArray(postInitMessage)) { | ||
| return normalizeLines(postInitMessage) | ||
| } | ||
|
|
||
| return normalizeLines(postInitMessage.split(/\r?\n/)) | ||
| } |
47 changes: 47 additions & 0 deletions
47
packages/@sanity/cli/src/actions/init/readTemplateManifest.ts
This file contains hidden or 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,47 @@ | ||
| import {readFile, unlink} from 'node:fs/promises' | ||
| import {join} from 'node:path' | ||
|
|
||
| import {subdebug} from '@sanity/cli-core' | ||
|
|
||
| import {TEMPLATE_MANIFEST_FILENAME} from './constants.js' | ||
| import {type TemplateManifest, templateManifestSchema} from './types.js' | ||
|
|
||
| const debug = subdebug('init:readTemplateManifest') | ||
|
|
||
| /** | ||
| * Reads `sanity-template.json` from the bootstrapped project directory (`outputPath`) when present. | ||
| * Returns `null` if the file is missing, cannot be parsed as JSON, or does not match the manifest schema. | ||
| * Never throws. | ||
| */ | ||
| export async function readTemplateManifest(outputPath: string): Promise<TemplateManifest | null> { | ||
| const manifestPath = join(outputPath, TEMPLATE_MANIFEST_FILENAME) | ||
| try { | ||
| const content = await readFile(manifestPath, 'utf8') | ||
| const json: unknown = JSON.parse(content) | ||
| const parsed = templateManifestSchema.safeParse(json) | ||
|
|
||
| if (!parsed.success) { | ||
| debug('Invalid template manifest at %s', manifestPath) | ||
| return null | ||
| } | ||
|
|
||
| return parsed.data | ||
| } catch (err) { | ||
| debug('Template manifest not used at %s: %s', manifestPath, err) | ||
|
|
||
| return null | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Removes `sanity-template.json` from the project directory after init has read it. | ||
| */ | ||
| export async function removeTemplateManifestFromOutput(outputPath: string): Promise<void> { | ||
| const manifestPath = join(outputPath, TEMPLATE_MANIFEST_FILENAME) | ||
|
|
||
| try { | ||
| await unlink(manifestPath) | ||
| } catch (err) { | ||
| debug('Could not remove template manifest at %s: %s', manifestPath, err) | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -29,7 +29,12 @@ import {countNestedFolders} from '../actions/init/countNestedFolders.js' | |
| import {determineAppTemplate} from '../actions/init/determineAppTemplate.js' | ||
| import {createOrAppendEnvVars} from '../actions/init/env/createOrAppendEnvVars.js' | ||
| import {fetchPostInitPrompt} from '../actions/init/fetchPostInitPrompt.js' | ||
| import {getPostInitMessageDisplay} from '../actions/init/getPostInitMessageDisplay.js' | ||
| import {tryGitInit} from '../actions/init/git.js' | ||
| import { | ||
| readTemplateManifest, | ||
| removeTemplateManifestFromOutput, | ||
| } from '../actions/init/readTemplateManifest.js' | ||
| import { | ||
| checkIsRemoteTemplate, | ||
| getGitHubRepoInfo, | ||
|
|
@@ -717,6 +722,22 @@ export class InitCommand extends SanityCommand<typeof InitCommand> { | |
| this.log('We look forward to seeing you there!\n') | ||
| } | ||
|
|
||
| const templateManifest = await readTemplateManifest(outputPath) | ||
| const postInitLines = getPostInitMessageDisplay(templateManifest?.postInitMessage) | ||
|
|
||
| if (postInitLines) { | ||
| this.log('') | ||
| this.log(styleText('dim', 'Message from the template author:')) | ||
| for (const line of postInitLines) { | ||
| this.log('') | ||
| this.log(line) | ||
| } | ||
| } | ||
|
|
||
| if (templateManifest) { | ||
| await removeTemplateManifestFromOutput(outputPath) | ||
|
Contributor
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. Saw claude mentioned that if a bad template manifest or the read fails we do not clean it up? Is it worth cleaning up here regardless or even in |
||
| } | ||
|
|
||
| this._trace.complete() | ||
| } | ||
|
|
||
|
|
||
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.
Will need an update to
zod/miniper #847