Skip to content
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

Refactor recipes + add nextjs recipe #815

Merged
merged 7 commits into from
Jan 3, 2024
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
66 changes: 11 additions & 55 deletions packages/create/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,22 @@
#!/usr/bin/env node

import * as p from "@clack/prompts";
import process from "node:process";
import path from "node:path";
import debug from "debug";

import * as utils from "./utils.js";
import { recipes, type Framework } from "./recipes/index.js";

const logger = debug("@edgedb/create:main");
import { baseRecipe, recipes as _recipes } from "./recipes/index.js";

async function main() {
const packageManager = utils.getPackageManager();
logger({ packageManager });
const baseOptions = await baseRecipe.getOptions();
const recipeOptions: any[] = [];

const setup = await p.group(
{
projectName: () =>
p.text({
message: "What is the name of your project or application?",
}),
framework: () =>
p.select<{ value: Framework; label: string }[], Framework>({
message: "What web framework should be used?",
options: [
{ value: "next", label: "Next.js" },
{ value: "remix", label: "Remix" },
{ value: "express", label: "Express" },
{ value: "node-http", label: "Node HTTP Server" },
{ value: "none", label: "None" },
],
}),
useEdgeDBAuth: () =>
p.confirm({
message: "Use the EdgeDB Auth extension?",
initialValue: true,
}),
shouldGitInit: () =>
p.confirm({
message: "Initialize a git repository and stage changes?",
initialValue: true,
}),
shouldInstall: () =>
p.confirm({
message: `Install dependencies with ${packageManager}?`,
initialValue: true,
}),
},
{
onCancel: () => {
process.exit(1);
},
}
const recipes = _recipes.filter(
(recipe) => !(recipe.skip?.(baseOptions) ?? false)
);

logger(setup);

for (const recipe of recipes) {
await recipe({
...setup,
projectDir: path.resolve(process.cwd(), setup.projectName),
});
recipeOptions.push(await recipe.getOptions?.(baseOptions));
}

await baseRecipe.apply(baseOptions);
for (let i = 0; i < recipes.length; i++) {
await recipes[i].apply(baseOptions, recipeOptions[i]);
Comment on lines +14 to +19
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about unwinding these changes and requiring that recipes are encapsulated again given that they can create their own prompts and can encode their own "skipping" logic in the function itself?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was the aim to keep the recipes encapsulated, but I did split the prompts part into a separate step of each recipe, as I think it's preferable to do all the prompts before we start actually copying any files. I don't mind if we drop the skipping bit, that was just so we didn't have to duplicate that logic for the prompts and apply step for every recipe, but I think it's fine either way.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was the aim to keep the recipes encapsulated, but I did split the prompts part into a separate step of each recipe, as I think it's preferable to do all the prompts before we start actually copying any files.

In general, I think I prefer the recipe to be completely opaque to the caller: pass the base options and let the recipe know how to do everything else. I'm not sure having the prompts happen upfront is objectively better: Imagine there was an issue in one recipe, but you answered the questions for all of the recipes. It seems just as valid to answer some questions then do the related work, answer more questions, do more work. The one possible advantage is being able to cancel before you do any changes, but I also see that as a possible disadvantage when trying to debug or troubleshoot an issue (e.g. you run through the changes until just before the issue and you can inspect the state of the filesystem or running recipe while the prompt is waiting for input).

It's also possible that there are prompts that are only relevant after some other side-effects have run, which is fine: even with the proposed changes you can continue to prompt the user, but then I think the whole case for hoisting the prompts up becomes weaker still.

To summarize, my case for keeping recipes fully opaque is:

  • The mechanism for running the recipes is trivial (for recipe of recipes { await recipe(opts); })
  • Reading a recipe is a complete description of the runtime behavior (rather than having to know about what each method does)
  • Failing faster might mean troubleshooting issues is easier/quicker as we add more recipes
  • More flexible: prompts are not special—they're just side effects

}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"name": "replace-me",
"version": "0.1.0",
"type": "module",
"private": true,
"dependencies": {
"edgedb": "1.x"
Expand Down
106 changes: 106 additions & 0 deletions packages/create/src/recipes/_base/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import process from "node:process";
import fs from "node:fs/promises";
import path from "node:path";

import debug from "debug";
import * as p from "@clack/prompts";

import { updatePackage } from "write-package";

import * as utils from "../../utils.js";
import type { Framework, BaseRecipe, BaseOptions } from "../types.js";

const logger = debug("@edgedb/create:recipe:base");

const recipe: BaseRecipe = {
async getOptions() {
const packageManager = utils.getPackageManager();
logger({ packageManager });

const opts = await p.group(
{
projectName: () =>
p.text({
message: "What is the name of your project or application?",
}),
framework: () =>
p.select<{ value: Framework; label: string }[], Framework>({
message: "What web framework should be used?",
options: [
{ value: "next", label: "Next.js" },
{ value: "remix", label: "Remix" },
{ value: "express", label: "Express" },
{ value: "node-http", label: "Node HTTP Server" },
{ value: "none", label: "None" },
],
}),
useEdgeDBAuth: () =>
p.confirm({
message: "Use the EdgeDB Auth extension?",
initialValue: true,
}),
},
{
onCancel: () => {
process.exit(1);
},
}
);

return {
...opts,
packageManager,
projectDir: path.resolve(process.cwd(), opts.projectName),
};
},
async apply({ projectDir, projectName }: BaseOptions) {
logger("Running base recipe");
try {
const projectDirStat = await fs.stat(projectDir);
logger({ projectDirStat });

if (!projectDirStat.isDirectory()) {
throw new Error(
`Target project directory ${projectDir} is not a directory`
);
}
const files = await fs.readdir(projectDir);
if (files.length > 0) {
throw new Error(`Target project directory ${projectDir} is not empty`);
}
} catch (err) {
if (
typeof err === "object" &&
err !== null &&
"code" in err &&
err.code === "ENOENT"
) {
await fs.mkdir(projectDir, { recursive: true });
logger(`Created project directory: ${projectDir}`);
} else {
throw err;
}
}

const dirname = path.dirname(new URL(import.meta.url).pathname);

logger("Copying files");
await fs.copyFile(
path.resolve(dirname, "./_eslint.config.js"),
path.resolve(projectDir, "eslint.config.js")
);
await fs.copyFile(
path.resolve(dirname, "./_package.json"),
path.resolve(projectDir, "package.json")
);
await fs.copyFile(
path.resolve(dirname, "./_tsconfig.json"),
path.resolve(projectDir, "tsconfig.json")
);

logger("Writing package.json");
await updatePackage(projectDir, { name: projectName });
},
};

export default recipe;
50 changes: 50 additions & 0 deletions packages/create/src/recipes/_edgedb/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as p from "@clack/prompts";
import fs from "node:fs/promises";
import path from "node:path";
import debug from "debug";
import util from "node:util";
import childProcess from "node:child_process";

import { BaseOptions, Recipe } from "../types.js";

const logger = debug("@edgedb/create:recipe:edgedb");
const exec = util.promisify(childProcess.exec);

const recipe: Recipe = {
async apply({ projectDir, useEdgeDBAuth }: BaseOptions) {
logger("Running edgedb recipe");

const spinner = p.spinner();

spinner.start("Initializing EdgeDB project");
await exec("edgedb project init --non-interactive", { cwd: projectDir });
const { stdout, stderr } = await exec(
"edgedb query 'select sys::get_version_as_str()'",
{ cwd: projectDir }
);
const serverVersion = JSON.parse(stdout.trim());
logger(`EdgeDB version: ${serverVersion}`);
if (serverVersion === "") {
const err = new Error(
"There was a problem initializing the EdgeDB project"
);
spinner.stop(err.message);
logger({ stdout, stderr });

throw err;
}
spinner.stop(`EdgeDB v${serverVersion} project initialized`);

if (useEdgeDBAuth) {
logger("Adding auth extension to project");

spinner.start("Enabling auth extension in EdgeDB schema");
const filePath = path.resolve(projectDir, "./dbschema/default.esdl");
const data = await fs.readFile(filePath, "utf8");
await fs.writeFile(filePath, `using extension auth;\n\n${data}`);
spinner.stop("Auth extension enabled in EdgeDB schema");
}
},
};

export default recipe;
34 changes: 34 additions & 0 deletions packages/create/src/recipes/_install/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import debug from "debug";
import * as p from "@clack/prompts";

import * as utils from "../../utils.js";
import { BaseOptions, Recipe } from "../types.js";

const logger = debug("@edgedb/create:recipe:install");

interface InstallOptions {
shouldGitInit: boolean;
shouldInstall: boolean;
}

const recipe: Recipe<InstallOptions> = {
getOptions({ packageManager }: BaseOptions) {
return p.group({
shouldGitInit: () =>
p.confirm({
message: "Initialize a git repository and stage changes?",
initialValue: true,
}),
shouldInstall: () =>
p.confirm({
message: `Install dependencies with ${packageManager}?`,
initialValue: true,
}),
});
},
async apply(baseOptions: BaseOptions, recipeOptions: InstallOptions) {
logger("Running install recipe");
},
};

export default recipe;
63 changes: 0 additions & 63 deletions packages/create/src/recipes/base/index.ts

This file was deleted.

49 changes: 0 additions & 49 deletions packages/create/src/recipes/edgedb/index.ts

This file was deleted.

Loading