Skip to content
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
11 changes: 3 additions & 8 deletions packages/void/src/cli/init-git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { cancel, confirm, isCancel, log } from '@voidzero-dev/vite-plus-prompts';
import { dirname, join, resolve } from 'pathslash';
import { quoteShellPath, shellDirectory } from './init-shell.ts';

export async function setupGit(root: string, git?: boolean): Promise<boolean> {
if (git === false) {
Expand Down Expand Up @@ -58,14 +59,8 @@ export async function setupGit(root: string, git?: boolean): Promise<boolean> {
}

export function initialCommitCommand(root: string): string {
// Quote paths for the user's shell, including names containing quotes, $ or
// backticks. Use the absolute path because init can create a subfolder.
// Use the absolute path because init can create a subfolder.
const directory = resolve(root);
const argument = /^[A-Za-z0-9_@./:-]+$/.test(directory)
? directory
: process.platform === 'win32'
? `"${directory}"`
: `'${directory.replaceAll("'", "'\\''")}'`;
const git = directory === resolve(process.cwd()) ? 'git' : `git -C ${argument}`;
const git = directory === shellDirectory() ? 'git' : `git -C ${quoteShellPath(directory)}`;
return `${git} add -A && ${git} commit -m "chore: initial commit"`;
}
29 changes: 29 additions & 0 deletions packages/void/src/cli/init-shell.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { relative, resolve } from 'pathslash';

/**
* The directory of the user's shell. Printed commands start there, which is
* not the project root when init creates a subfolder.
*/
export function shellDirectory(): string {
return resolve(process.cwd());
}

/** Quote a path for the user's shell, including names containing quotes, $ or backticks. */
export function quoteShellPath(path: string): string {
if (/^[A-Za-z0-9_@./:-]+$/.test(path)) {
return path;
}
return process.platform === 'win32' ? `"${path}"` : `'${path.replaceAll("'", "'\\''")}'`;
}

/** Prefix `command` with a `cd` from the user's shell into `root` when they differ. */
export function commandInProject(root: string, command: string): string {
const shell = shellDirectory();
const directory = resolve(root);
if (directory === shell) {
return command;
}
const path = relative(shell, directory);
// `cd` would read a leading dash as an option, and `cd -` as the previous directory.
return `cd ${quoteShellPath(path.startsWith('-') ? `./${path}` : path)} && ${command}`;
}
63 changes: 44 additions & 19 deletions packages/void/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { maybeSetupDeployProject } from './deploy-setup.ts';
import { maybeScaffoldEnvTs } from './env-scaffold.ts';
import { migrateFrameworkAdapterPaths } from './framework-config-migrate.ts';
import { initialCommitCommand, setupGit } from './init-git.ts';
import { commandInProject } from './init-shell.ts';
import { configureVitePlusScaffold } from './init-vite-plus.ts';
import { migrateLegacyVoidConfig } from './migrate.ts';
import { formatUrl, note, printSuccess } from './output.ts';
Expand Down Expand Up @@ -1423,19 +1424,27 @@ function writeDatabaseDialect(root: string, config: VoidConfig, dialect: Databas
writeVoidProjectConfig(root, next);
}

/** `quiet` is for a new starter, whose prompt already showed the database. */
type DatabaseDialectOptions = { quiet?: boolean };

function clearConfiguredDatabase(
root: string,
messages: { unchanged: string; updated: string },
options: DatabaseDialectOptions,
): void {
const config = readConfig(root);

if (getDatabaseDialect(config) === 'sqlite') {
log.info(messages.unchanged);
if (!options.quiet) {
log.info(messages.unchanged);
}
return;
}

writeDatabaseDialect(root, config, 'sqlite');
log.step(messages.updated);
if (!options.quiet) {
log.step(messages.updated);
}
}

/** Remove `database` entirely: its casing alone still makes Void serve `void/db`. */
Expand All @@ -1451,35 +1460,51 @@ function removeDatabaseConfig(root: string): void {
log.step('Removed database config from void.config.ts');
}

function applyDatabaseDialect(root: string, dialect: DatabaseDialect): void {
function applyDatabaseDialect(
root: string,
dialect: DatabaseDialect,
options: DatabaseDialectOptions = {},
): void {
const config = readConfig(root);

if (dialect === 'postgresql') {
if (getDatabaseDialect(config) === 'postgresql') {
log.info('PostgreSQL already configured in void.config.ts');
if (!options.quiet) {
log.info('PostgreSQL already configured in void.config.ts');
}
return;
}

writeDatabaseDialect(root, config, 'postgresql');
log.step('Configured PostgreSQL in void.config.ts');
if (!options.quiet) {
log.step('Configured PostgreSQL in void.config.ts');
}
return;
}

if (dialect === 'mysql') {
if (getDatabaseDialect(config) === 'mysql') {
log.info('MySQL already configured in void.config.ts');
if (!options.quiet) {
log.info('MySQL already configured in void.config.ts');
}
return;
}

writeDatabaseDialect(root, config, 'mysql');
log.step('Configured MySQL in void.config.ts');
if (!options.quiet) {
log.step('Configured MySQL in void.config.ts');
}
return;
}

clearConfiguredDatabase(root, {
unchanged: 'Using default D1 (SQLite) configuration',
updated: 'Updated void.config.ts to use the default D1 (SQLite) configuration',
});
clearConfiguredDatabase(
root,
{
unchanged: 'Using default D1 (SQLite) configuration',
updated: 'Updated void.config.ts to use the default D1 (SQLite) configuration',
},
options,
);
}

function detectDatabaseSetup(root: string): DatabaseSetupChoice {
Expand Down Expand Up @@ -2330,7 +2355,7 @@ function scaffoldPagesApp(

ensureGitignore(root);
if (starterMode !== 'static') {
applyDatabaseDialect(root, starterMode);
applyDatabaseDialect(root, starterMode, { quiet: true });
}

if (starterMode === 'postgresql') {
Expand Down Expand Up @@ -2768,7 +2793,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
}

if (!targeted && !framework && isScaffoldableEmptyProject(root)) {
log.info('Empty project detected. Scaffolding a Pages starter...');
log.info('Empty project detected. Creating a Pages starter.');
const scaffoldToolchain = await promptScaffoldToolchain(initArgs?.toolchain);
if (detectedPagesFramework) {
scaffoldedPagesFramework = detectedPagesFramework;
Expand Down Expand Up @@ -2891,10 +2916,11 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
log.info('Bundled Void docs: node_modules/void/docs/');
}

// Demo code only in the full flow, and not for meta-frameworks.
if (!targeted && !framework) {
// Demo code only in the full flow, and not for meta-frameworks or a new
// starter, which already has its own pages.
if (!targeted && !framework && !didScaffoldStarter) {
const existingDemoFiles = Object.values(demoFiles(root)).filter((file) => existsSync(file));
if (didScaffoldStarter || state.hasRoutes || state.hasMigrations || state.hasPages) {
if (state.hasRoutes || state.hasMigrations || state.hasPages) {
log.info('Project already has pages, routes, or migrations, skipping demo');
} else if (hasDrizzleSchema(root)) {
log.info('Project already has a database schema, skipping demo');
Expand Down Expand Up @@ -3038,8 +3064,7 @@ export async function runInitCommand(root: string, initArgs?: InitArgs): Promise
printSuccess('Project initialized. Run your workspace install to finish setup.');
}
} else {
printSuccess(
`Project initialized. Run \`${getDevCommand(root, framework)}\` to start developing.`,
);
const devCommand = commandInProject(root, getDevCommand(root, framework));
printSuccess(`Project initialized. Run \`${devCommand}\` to start developing.`);
}
}
26 changes: 26 additions & 0 deletions packages/void/test/unit/init-shell.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { join } from 'node:path';
import { describe, expect, it } from 'vite-plus/test';
import { commandInProject } from '../../src/cli/init-shell.ts';

describe('commandInProject', () => {
it('keeps the command when the shell is in the project', () => {
expect(commandInProject(process.cwd(), 'vp dev')).toBe('vp dev');
});

it('changes into a project folder relative to the shell', () => {
expect(commandInProject(join(process.cwd(), 'my-app'), 'vp dev')).toBe('cd my-app && vp dev');
});

it('quotes the folder for the shell', () => {
const quoted = process.platform === 'win32' ? '"my app"' : "'my app'";
expect(commandInProject(join(process.cwd(), 'my app'), 'vp dev')).toBe(
`cd ${quoted} && vp dev`,
);
});

it.each(['-', '-app'])('keeps cd from reading %s as an option', (folder) => {
expect(commandInProject(join(process.cwd(), folder), 'vp dev')).toBe(
`cd ./${folder} && vp dev`,
);
});
});
16 changes: 15 additions & 1 deletion packages/void/test/unit/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const mockNote = vi.fn();
const mockOutro = vi.fn();
const mockLogWarn = vi.fn();
const mockLogInfo = vi.fn();
const mockLogStep = vi.fn();
const mockGetToken = vi.fn();
const mockGetApiUrl = vi.fn();
const mockRunLogin = vi.fn();
Expand Down Expand Up @@ -334,7 +335,7 @@ vi.mock('@voidzero-dev/vite-plus-prompts', () => ({
warn: (...args: Array<unknown>) => mockLogWarn(...args),
error: vi.fn(),
info: (...args: Array<unknown>) => mockLogInfo(...args),
step: vi.fn(),
step: (...args: Array<unknown>) => mockLogStep(...args),
},
confirm: (...args: Array<unknown>) => mockConfirm(...args),
select: (...args: Array<unknown>) => mockSelect(...args),
Expand Down Expand Up @@ -622,6 +623,7 @@ afterEach(() => {
mockOutro.mockReset();
mockLogWarn.mockReset();
mockLogInfo.mockReset();
mockLogStep.mockReset();
mockGetToken.mockReset();
mockGetApiUrl.mockReset();
mockRunLogin.mockReset();
Expand Down Expand Up @@ -1448,6 +1450,11 @@ describe('isScaffoldableEmptyProject', () => {
expect(tsconfig.compilerOptions.jsx).toBe('react-jsx');
expect(tsconfig.include).toContain('pages');
expect(tsconfig.include).toContain('db');

expect(mockLogInfo).toHaveBeenCalledWith('Empty project detected. Creating a Pages starter.');
// The starter prompt already showed the database, and the starter has its own pages.
expect(mockLogInfo).not.toHaveBeenCalledWith('Using default D1 (SQLite) configuration');
expect(mockLogInfo).not.toHaveBeenCalledWith(expect.stringContaining('skipping demo'));
} finally {
rmSync(root, { recursive: true, force: true });
}
Expand Down Expand Up @@ -1494,6 +1501,7 @@ describe('isScaffoldableEmptyProject', () => {
expect(readFileSync(join(root, 'db', 'migrations', '0000_generated.sql'), 'utf-8')).toContain(
'CREATE TABLE "messages"',
);
expect(mockLogStep).not.toHaveBeenCalledWith('Configured PostgreSQL in void.config.ts');

const toolchainPrompt = mockSelect.mock.calls[0]?.[0];
expect(toolchainPrompt.message).toBe('Choose a Pages scaffold toolchain:');
Expand Down Expand Up @@ -1743,6 +1751,8 @@ describe('isScaffoldableEmptyProject', () => {

it('offers to scaffold in a subfolder from a non-project parent directory', async () => {
const root = mkdtempSync(join(tmpdir(), 'void-init-'));
// The user's shell stays in the parent directory.
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root);
try {
mkdirSync(join(root, 'existing-project'));
mockSelect
Expand Down Expand Up @@ -1794,7 +1804,11 @@ describe('isScaffoldableEmptyProject', () => {
shell: process.platform === 'win32',
}),
);
expect(String(mockOutro.mock.calls.at(-1)?.[0])).toContain(
'Run `cd my-new-app && vp dev` to start developing.',
);
} finally {
cwd.mockRestore();
rmSync(root, { recursive: true, force: true });
}
});
Expand Down
Loading