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

feat(generators): support starting from a template #4951

Merged
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
6 changes: 5 additions & 1 deletion docs/turbo/generators/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ interface Answers extends Object {
turboYearsSaved: string;
}

const MINUTES_IN_YEAR = 60 * 24 * 365;
Copy link
Member Author

Choose a reason for hiding this comment

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

cc @chris-olszewski added here from your prev comment!


const PUBLIC_TB_TOKEN =
"p.eyJ1IjogIjAzYzA0Y2MyLTM1YTAtNDhhNC05ZTZjLThhMWE0NGNhNjhkZiIsICJpZCI6ICJmOWIzMTU5Yi0wOTVjLTQyM2UtOWIwNS04ZDZlNzIyNjEwNzIifQ.A3TOPdm3Lhmn-1x5m6jNvulCQbbgUeQfAIO3IaaAt5k";

Expand Down Expand Up @@ -37,7 +39,9 @@ export async function releasePostStats(answers: Answers): Promise<string> {
const totalMinutesSaved: number =
timeSavedData.data[0].remote_cache_minutes_saved +
timeSavedData.data[0].local_cache_minutes_saved;
const totalYearsSaved: number = Math.floor(totalMinutesSaved / 60 / 24 / 365);
const totalYearsSaved: number = Math.floor(
totalMinutesSaved / MINUTES_IN_YEAR
);
const weeklyDownloads: number = Object.keys(downloadsData.downloads).reduce(
(sum, version) => sum + downloadsData.downloads[version],
0
Expand Down
27 changes: 27 additions & 0 deletions packages/turbo-gen/src/commands/generate/prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,30 @@ export async function customGenerators({

return generatorAnswer;
}

export async function chooseGeneratorTemplate() {
return await inquirer.prompt<{ answer: "ts" | "js" }>({
type: "list",
name: "answer",
message: "Should the generator config be created with TS or JS?",
default: "ts",
choices: [
{
name: "js",
value: "js",
},
{
name: "ts",
value: "ts",
},
],
});
}

export async function confirm({ message }: { message: string }) {
return await inquirer.prompt<{ answer: boolean }>({
type: "confirm",
name: "answer",
message,
});
}
26 changes: 24 additions & 2 deletions packages/turbo-gen/src/generators/custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,39 @@ import { getCustomGenerators, runCustomGenerator } from "../utils/plop";
import * as prompts from "../commands/generate/prompts";
import type { CustomGeneratorArguments } from "./types";
import { GeneratorError } from "../utils/error";
import { setupFromTemplate } from "../utils/setupFromTemplate";

export async function generate({
generator,
project,
opts,
}: CustomGeneratorArguments) {
const generators = getCustomGenerators({ project, configPath: opts.config });
let generators = getCustomGenerators({ project, configPath: opts.config });
if (!generators.length) {
logger.error(`No custom generators found.`);
console.log();
return;

const { answer } = await prompts.confirm({
message: `Would you like to add generators to ${project.name}?`,
});

if (answer) {
const { answer: template } = await prompts.chooseGeneratorTemplate();
try {
await setupFromTemplate({ project, template });
} catch (err) {
if (err instanceof GeneratorError) {
throw err;
}
logger.error(`Failed to create generator config`);
throw err;
}

// fetch generators again, and continue to selection prompt
generators = getCustomGenerators({ project, configPath: opts.config });
} else {
return;
}
}
const { selectedGenerator } = await prompts.customGenerators({
generators,
Expand Down
31 changes: 31 additions & 0 deletions packages/turbo-gen/src/templates/simple-js/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module.exports = function generator(plop) {
plop.setGenerator("example", {
description:
"An example Turborepo generator - creates a new file at the root of the project",
prompts: [
{
type: "input",
name: "file",
message: "What is the name of the file to create?",
},
{
type: "input",
name: "author",
message: "What is your name? (Will be added as the file author)",
},
{
type: "list",
name: "type",
message: "What type of file should be created?",
choices: [".md", ".txt"],
},
],
actions: [
{
type: "add",
path: "{{ turbo.paths.root }}/{{ dashCase file }}{{ type }}",
templateFile: "templates/turborepo-generators.hbs",
},
],
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Turborepo Generators

Read the docs at [turbo.build](https://turbo.build/repo/docs).

Created by {{ author }}.
33 changes: 33 additions & 0 deletions packages/turbo-gen/src/templates/simple-ts/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { PlopTypes } from "@turbo/gen";

export default function generator(plop: PlopTypes.NodePlopAPI): void {
plop.setGenerator("example", {
description:
"An example Turborepo generator - creates a new file at the root of the project",
prompts: [
{
type: "input",
name: "file",
message: "What is the name of the file to create?",
},
{
type: "input",
name: "author",
message: "What is your name? (Will be added as the file author)",
},
{
type: "list",
name: "type",
message: "What type of file should be created?",
choices: [".md", ".txt"],
},
],
actions: [
{
type: "add",
path: "{{ turbo.paths.root }}/{{ dashCase file }}{{ type }}",
templateFile: "templates/turborepo-generators.hbs",
},
],
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Turborepo Generators

Read the docs at [turbo.build](https://turbo.build/repo/docs).

Created by {{ author }}.
1 change: 1 addition & 0 deletions packages/turbo-gen/src/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export type GenerateErrorType =
| "plop_error_running_generator"
| "plop_unable_to_load_config"
| "plop_generator_not_found"
| "config_directory_already_exists"
// default
| "unknown";

Expand Down
30 changes: 30 additions & 0 deletions packages/turbo-gen/src/utils/setupFromTemplate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { Project } from "@turbo/workspaces";
import path from "path";
import fs from "fs-extra";
import { GeneratorError } from "./error";

export async function setupFromTemplate({
project,
template,
}: {
project: Project;
template: "ts" | "js";
}) {
const configDirectory = path.join(project.paths.root, "turbo", "generators");

// TODO: could create some more complex starters in the future
const toCopy = `simple-${template}`;

// required to ensure we don't overwrite any existing files at this location
if (await fs.pathExists(configDirectory)) {
throw new GeneratorError(
`Generator config directory already exists at ${configDirectory}`,
{ type: "config_directory_already_exists" }
);
}

// copy templates to project
await fs.copy(path.join(__dirname, "templates", toCopy), configDirectory, {
recursive: true,
});
}
13 changes: 13 additions & 0 deletions packages/turbo-gen/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import { defineConfig, Options } from "tsup";
import fs from "fs-extra";
import chalk from "chalk";

export default defineConfig((options: Options) => ({
entry: ["src/cli.ts", "src/types.ts"],
format: ["cjs"],
dts: true,
clean: true,
minify: true,
onSuccess: async () => {
// start time
const start = Date.now();
await fs.copy("src/templates", "dist/templates");
// make the output match
console.log(
chalk.hex("#7c5cad")("TEMPLATES"),
"copied in",
chalk.green(`${Date.now() - start}ms`)
);
},
...options,
}));
36 changes: 36 additions & 0 deletions turbo/generators/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { PlopTypes } from "@turbo/gen";

export default function generator(plop: PlopTypes.NodePlopAPI): void {
plop.setGenerator("example", {
description:
"An example Turborepo generator - creates a new file at the root of the project",
prompts: [
{
type: "input",
name: "file",
placeholder: "generator-docs",
message: "What is the name of the file to create?",
},
{
type: "input",
name: "author",
default: "turbobot",
message: "What is your name? (Will be added as the file author)",
},
{
type: "list",
name: "type",
message: "What type of file should be created?",
choices: [".md", ".txt"],
default: ".md",
},
],
actions: [
{
type: "add",
path: "{{ turbo.paths.root }}/{{ dashCase file }}{{ type }}",
templateFile: "templates/turborepo-generators.hbs",
},
],
});
}
5 changes: 5 additions & 0 deletions turbo/generators/templates/turborepo-generators.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Turborepo Generators

Read the docs at [turbo.build](https://turbo.build/repo/docs).

Created by {{ author }}.