chore: resolve srcDir relative to cwd when initializing

pull/4571/head
Divyansh Singh 7 months ago
parent 518c0945f1
commit 4f3f5eac15

@ -1,16 +1,30 @@
┌ Welcome to VitePress! ┌ Welcome to VitePress!
│ │
◇ Where should VitePress initialize the config? ◇ Where should VitePress initialize the config?
│ ./docs │ ./docs
│ │
◇ Site title: ◇ Where should VitePress look for your markdown files?
│ My Awesome Project │ ./docs
│ │
◇ Site description: ◇ Site title:
│ A VitePress Site │ My Awesome Project
│ │
◆ Theme: ◇ Site description:
│ ● Default Theme (Out of the box, good-looking docs) │ A VitePress Site
│ ○ Default Theme + Customization │
│ ○ Custom Theme ◇ Theme:
└ │ Default Theme
│
◇ Use TypeScript for config and theme files?
│ Yes
│
◇ Add VitePress npm scripts to package.json?
│ Yes
│
◇ Add a prefix for VitePress npm scripts?
│ Yes
│
◇ Prefix for VitePress npm scripts:
│ docs
│
└ Done! Now run pnpm run docs:dev and start writing.

@ -12,6 +12,7 @@ import template from 'lodash.template'
import path from 'node:path' import path from 'node:path'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import { bold, cyan, yellow } from 'picocolors' import { bold, cyan, yellow } from 'picocolors'
import { slash } from '../shared'
export enum ScaffoldThemeType { export enum ScaffoldThemeType {
Default = 'default theme', Default = 'default theme',
@ -20,13 +21,13 @@ export enum ScaffoldThemeType {
} }
export interface ScaffoldOptions { export interface ScaffoldOptions {
root: string root?: string
srcDir: string srcDir?: string
title?: string title?: string
description?: string description?: string
theme: ScaffoldThemeType theme?: ScaffoldThemeType
useTs: boolean useTs?: boolean
injectNpmScripts: boolean injectNpmScripts?: boolean
addNpmScriptsPrefix?: boolean addNpmScriptsPrefix?: boolean
npmScriptsPrefix?: string npmScriptsPrefix?: string
} }
@ -36,10 +37,10 @@ const getPackageManger = () => {
return name.split('/')[0] return name.split('/')[0]
} }
export async function init(root: string | undefined) { export async function init(root?: string) {
intro(bold(cyan('Welcome to VitePress!'))) intro(bold(cyan('Welcome to VitePress!')))
const options: ScaffoldOptions = (await group( const options = await group(
{ {
root: async () => { root: async () => {
if (root) return root if (root) return root
@ -47,6 +48,7 @@ export async function init(root: string | undefined) {
return text({ return text({
message: 'Where should VitePress initialize the config?', message: 'Where should VitePress initialize the config?',
initialValue: './', initialValue: './',
defaultValue: './',
validate(value) { validate(value) {
// TODO make sure directory is inside // TODO make sure directory is inside
return undefined return undefined
@ -54,73 +56,80 @@ export async function init(root: string | undefined) {
}) })
}, },
srcDir: async () => { srcDir: async ({ results }: any) => {
return text({ return text({
message: 'Where should VitePress look for your markdown files?', message: 'Where should VitePress look for your markdown files?',
initialValue: './' initialValue: results.root,
defaultValue: results.root
}) })
}, },
title: () => title: async () => {
text({ return text({
message: 'Site title:', message: 'Site title:',
placeholder: 'My Awesome Project' placeholder: 'My Awesome Project',
}), defaultValue: 'My Awesome Project'
})
},
description: () => description: async () => {
text({ return text({
message: 'Site description:', message: 'Site description:',
placeholder: 'A VitePress Site' placeholder: 'A VitePress Site',
}), defaultValue: 'A VitePress Site'
})
},
theme: () => theme: async () => {
select({ return select({
message: 'Theme:', message: 'Theme:',
options: [ options: [
{ {
// @ts-ignore
value: ScaffoldThemeType.Default, value: ScaffoldThemeType.Default,
label: 'Default Theme', label: 'Default Theme',
hint: 'Out of the box, good-looking docs' hint: 'Out of the box, good-looking docs'
}, },
{ {
// @ts-ignore
value: ScaffoldThemeType.DefaultCustom, value: ScaffoldThemeType.DefaultCustom,
label: 'Default Theme + Customization', label: 'Default Theme + Customization',
hint: 'Add custom CSS and layout slots' hint: 'Add custom CSS and layout slots'
}, },
{ {
// @ts-ignore
value: ScaffoldThemeType.Custom, value: ScaffoldThemeType.Custom,
label: 'Custom Theme', label: 'Custom Theme',
hint: 'Build your own or use external' hint: 'Build your own or use external'
} }
] ]
}), })
},
useTs: () => useTs: async () => {
confirm({ message: 'Use TypeScript for config and theme files?' }), return confirm({
message: 'Use TypeScript for config and theme files?'
})
},
injectNpmScripts: () => injectNpmScripts: async () => {
confirm({ return confirm({
message: 'Add VitePress npm scripts to package.json?' message: 'Add VitePress npm scripts to package.json?'
}), })
},
addNpmScriptsPrefix: ({ results }) => { addNpmScriptsPrefix: async ({ results }: any) => {
if (!results.injectNpmScripts) return Promise.resolve(false) if (!results.injectNpmScripts) return false
return confirm({ return confirm({
message: 'Add a prefix for VitePress npm scripts?', message: 'Add a prefix for VitePress npm scripts?'
initialValue: true
}) })
}, },
npmScriptsPrefix: ({ results }) => { npmScriptsPrefix: async ({ results }: any) => {
if (!results.addNpmScriptsPrefix) return Promise.resolve('docs') if (!results.addNpmScriptsPrefix) return 'docs'
return text({ return text({
message: 'Prefix for VitePress npm scripts:', message: 'Prefix for VitePress npm scripts:',
placeholder: 'docs' placeholder: 'docs',
defaultValue: 'docs'
}) })
} }
}, },
@ -130,31 +139,35 @@ export async function init(root: string | undefined) {
process.exit(0) process.exit(0)
} }
} }
)) as ScaffoldOptions )
outro(scaffold(options)) outro(scaffold(options))
} }
export function scaffold({ export function scaffold({
root = './', root: root_ = './',
srcDir = './', srcDir: srcDir_ = root_,
title = 'My Awesome Project', title = 'My Awesome Project',
description = 'A VitePress Site', description = 'A VitePress Site',
theme, theme = ScaffoldThemeType.Default,
useTs, useTs = true,
injectNpmScripts, injectNpmScripts = true,
addNpmScriptsPrefix = true, addNpmScriptsPrefix = true,
npmScriptsPrefix = 'docs' npmScriptsPrefix = 'docs'
}: ScaffoldOptions): string { }: ScaffoldOptions) {
const resolvedRoot = path.resolve(root) const resolvedRoot = path.resolve(root_)
const resolvedSrcDir = path.resolve(root, srcDir) const root = path.relative(process.cwd(), resolvedRoot)
const resolvedSrcDir = path.resolve(srcDir_)
const srcDir = path.relative(resolvedRoot, resolvedSrcDir)
const templateDir = path.resolve( const templateDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)), path.dirname(fileURLToPath(import.meta.url)),
'../../template' '../../template'
) )
const data = { const data = {
srcDir: srcDir === './' ? undefined : JSON.stringify(srcDir), // omit if default srcDir: srcDir ? JSON.stringify(srcDir) : undefined, // omit if default
title: JSON.stringify(title), title: JSON.stringify(title),
description: JSON.stringify(description), description: JSON.stringify(description),
useTs, useTs,
@ -214,34 +227,31 @@ export function scaffold({
renderFile(file) renderFile(file)
} }
const dir =
root === './' ? '' : ` ${root.replace(/^\.\//, '').replace(/[/\\]$/, '')}`
const gitignorePrefix = dir ? `${dir}/.vitepress` : '.vitepress'
const tips = [] const tips = []
const gitignorePrefix = root ? `${slash(root)}/.vitepress` : '.vitepress'
if (fs.existsSync('.git')) { if (fs.existsSync('.git')) {
tips.push( tips.push(
`Make sure to add ${cyan(`${gitignorePrefix}/dist`)} and ` + `Make sure to add ${cyan(`${gitignorePrefix}/dist`)} and ${cyan(`${gitignorePrefix}/cache`)} to your ${cyan(`.gitignore`)} file.`
`${cyan(`${gitignorePrefix}/cache`)} to your ` +
`${cyan(`.gitignore`)} file.`
) )
} }
if ( if (
theme !== ScaffoldThemeType.Default && theme !== ScaffoldThemeType.Default &&
!userPkg.dependencies?.['vue'] && !userPkg.dependencies?.['vue'] &&
!userPkg.devDependencies?.['vue'] !userPkg.devDependencies?.['vue']
) { ) {
tips.push( tips.push(
`Since you've chosen to customize the theme, ` + `Since you've chosen to customize the theme, you should also explicitly install ${cyan(`vue`)} as a dev dependency.`
`you should also explicitly install ${cyan(`vue`)} as a dev dependency.`
) )
} }
const tip = tips.length ? yellow([`\n\nTips:`, ...tips].join('\n- ')) : `` const tip = tips.length ? yellow([`\n\nTips:`, ...tips].join('\n- ')) : ``
const dir = root ? ' ' + root : ''
const pm = getPackageManger()
if (injectNpmScripts) { if (injectNpmScripts) {
const scripts: Record<string, string> = {} const scripts: Record<string, string> = {}
const prefix = addNpmScriptsPrefix ? `${npmScriptsPrefix}:` : '' const prefix = addNpmScriptsPrefix ? `${npmScriptsPrefix}:` : ''
scripts[`${prefix}dev`] = `vitepress dev${dir}` scripts[`${prefix}dev`] = `vitepress dev${dir}`
@ -250,13 +260,9 @@ export function scaffold({
Object.assign(userPkg.scripts || (userPkg.scripts = {}), scripts) Object.assign(userPkg.scripts || (userPkg.scripts = {}), scripts)
fs.writeFileSync(pkgPath, JSON.stringify(userPkg, null, 2)) fs.writeFileSync(pkgPath, JSON.stringify(userPkg, null, 2))
return `Done! Now run ${cyan(
`${getPackageManger()} run ${prefix}dev` return `Done! Now run ${cyan(`${pm} run ${prefix}dev`)} and start writing.${tip}`
)} and start writing.${tip}`
} else { } else {
const pm = getPackageManger() return `You're all set! Now run ${cyan(`${pm === 'npm' ? 'npx' : pm} vitepress dev${dir}`)} and start writing.${tip}`
return `You're all set! Now run ${cyan(
`${pm === 'npm' ? 'npx' : pm} vitepress dev${dir}`
)} and start writing.${tip}`
} }
} }

Loading…
Cancel
Save