Skip to content

Commit

Permalink
feat(create-cloudflare): allow users to change some answers
Browse files Browse the repository at this point in the history
  • Loading branch information
edmundhung committed Aug 8, 2024
1 parent a504725 commit eef5faa
Show file tree
Hide file tree
Showing 6 changed files with 245 additions and 179 deletions.
30 changes: 11 additions & 19 deletions packages/cli/args.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
import { getRenderers, inputPrompt } from "./interactive";
import { crash, logRaw } from ".";
import { inputPrompt } from "./interactive";
import type { Arg, PromptConfig } from "./interactive";

export const processArgument = async <T>(
args: Record<string, Arg>,
name: string,
promptConfig: PromptConfig
) => {
let value = args[name];
const renderSubmitted = getRenderers(promptConfig).submit;
const value = args[name];
const result = await inputPrompt<T>({
...promptConfig,
// Accept the default value if the arg is already set
acceptDefault: promptConfig.acceptDefault ?? value !== undefined,
defaultValue: value ?? promptConfig.defaultValue,
});

// If the value has already been set via args, use that
if (value !== undefined) {
const error = promptConfig.validate?.(value);
if (error) {
crash(error);
}
// Update value in args before returning the result
args[name] = result as Arg;

const lines = renderSubmitted({ value });
logRaw(lines.join("\n"));

return value as T;
}

value = await inputPrompt(promptConfig);

return value as T;
return result;
};
3 changes: 3 additions & 0 deletions packages/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export const shapes = {
radioInactive: "○",
radioActive: "●",

backActive: "◀",
backInactive: "◁",

bar: "│",
leftT: "├",
rigthT: "┤",
Expand Down
6 changes: 4 additions & 2 deletions packages/cli/interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export type Option = {
sublabel?: string; // user-visible string
value: string; // underlying key
hidden?: boolean;
activeIcon?: string;
inactiveIcon?: string;
};

export type BasePromptConfig = {
Expand Down Expand Up @@ -316,8 +318,8 @@ const getSelectRenderers = (

const indicator =
isInListOfValues || (active && !Array.isArray(value))
? color(shapes.radioActive)
: color(shapes.radioInactive);
? color(opt.activeIcon ?? shapes.radioActive)
: color(opt.inactiveIcon ?? shapes.radioInactive);

return `${space(2)}${indicator} ${text} ${sublabel}`;
};
Expand Down
54 changes: 13 additions & 41 deletions packages/create-cloudflare/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
#!/usr/bin/env node
import { mkdirSync } from "fs";
import { basename, dirname, resolve } from "path";
import { dirname } from "path";
import { chdir } from "process";
import { crash, endSection, logRaw, startSection } from "@cloudflare/cli";
import { processArgument } from "@cloudflare/cli/args";
import { dim } from "@cloudflare/cli/colors";
import { isInteractive } from "@cloudflare/cli/interactive";
import { parseArgs } from "helpers/args";
import { C3_DEFAULTS, isUpdateAvailable } from "helpers/cli";
import { isUpdateAvailable } from "helpers/cli";
import { runCommand } from "helpers/command";
import {
detectPackageManager,
Expand All @@ -16,13 +15,14 @@ import {
import { installWrangler, npmInstall } from "helpers/packages";
import { version } from "../package.json";
import { offerToDeploy, runDeploy } from "./deploy";
import { gitCommit, isInsideGitRepo, offerGit } from "./git";
import { gitCommit, offerGit } from "./git";
import { createProject } from "./pages";
import { printSummary } from "./summary";
import {
addWranglerToGitIgnore,
copyTemplateFiles,
selectTemplate,
createContext,
inferRelatedArgs,
updatePackageName,
updatePackageScripts,
} from "./templates";
Expand Down Expand Up @@ -69,58 +69,28 @@ export const runLatest = async () => {
export const runCli = async (args: Partial<C3Args>) => {
printBanner();

const defaultName = args.existingScript || C3_DEFAULTS.projectName;

const projectName = await processArgument<string>(args, "projectName", {
type: "text",
question: `In which directory do you want to create your application?`,
helpText: "also used as application name",
defaultValue: defaultName,
label: "dir",
validate: (value) =>
validateProjectDirectory(String(value) || C3_DEFAULTS.projectName, args),
format: (val) => `./${val}`,
});

const validatedArgs: C3Args = {
...args,
projectName,
};

const originalCWD = process.cwd();
const { name, path } = setupProjectDirectory(validatedArgs);

const template = await selectTemplate(validatedArgs);
const ctx: C3Context = {
project: { name, path },
args: validatedArgs,
template,
originalCWD,
gitRepoAlreadyExisted: await isInsideGitRepo(dirname(path)),
deployment: {},
};
inferRelatedArgs(args);

const ctx = await createContext(args);

await runTemplate(ctx);
};

export const setupProjectDirectory = (args: C3Args) => {
export const setupProjectDirectory = (ctx: C3Context) => {
// Crash if the directory already exists
const path = resolve(args.projectName);
const err = validateProjectDirectory(path, args);
const path = ctx.project.path;
const err = validateProjectDirectory(path, ctx.args);
if (err) {
crash(err);
}

const directory = dirname(path);
const pathBasename = basename(path);

// If the target is a nested directory, create the parent
mkdirSync(directory, { recursive: true });

// Change to the parent directory
chdir(directory);

return { name: pathBasename, path };
};

const runTemplate = async (ctx: C3Context) => {
Expand All @@ -134,6 +104,8 @@ const runTemplate = async (ctx: C3Context) => {
const create = async (ctx: C3Context) => {
const { template } = ctx;

setupProjectDirectory(ctx);

if (template.generate) {
await template.generate(ctx);
}
Expand Down
6 changes: 5 additions & 1 deletion packages/create-cloudflare/src/helpers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ export const probePaths = (paths: string[]) => {
};

export const usesTypescript = (ctx: C3Context) => {
return existsSync(join(`${ctx.project.path}`, `tsconfig.json`));
return hasTsConfig(ctx.project.path);
};

export const hasTsConfig = (path: string) => {
return existsSync(join(`${path}`, `tsconfig.json`));
};

const eslintRcExts = ["js", "cjs", "yaml", "yml", "json"] as const;
Expand Down
Loading

0 comments on commit eef5faa

Please sign in to comment.