) {
+ await fs.writeFile(
+ ".all-contributorsrc",
+ await prettier.format(
+ JSON.stringify({
+ ...((await readFileSafeAsJson(
+ ".all-contributorsrc",
+ )) as AllContributorsData),
+ projectName: repository,
+ projectOwner: owner,
+ }),
+ { parser: "json" },
+ ),
+ );
+
+ await $`npx -y all-contributors-cli generate`;
+}
diff --git a/src/steps/updateLocalFiles.test.ts b/src/steps/updateLocalFiles.test.ts
new file mode 100644
index 00000000..20d67399
--- /dev/null
+++ b/src/steps/updateLocalFiles.test.ts
@@ -0,0 +1,445 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { Options } from "../shared/types.js";
+import { updateLocalFiles } from "./updateLocalFiles.js";
+
+const mockReplaceInFile = vi.fn();
+
+vi.mock("replace-in-file", () => ({
+ get default() {
+ return mockReplaceInFile;
+ },
+}));
+
+const mockReadFileSafeAsJson = vi.fn();
+
+vi.mock("../shared/readFileSafeAsJson.js", () => ({
+ get readFileSafeAsJson() {
+ return mockReadFileSafeAsJson;
+ },
+}));
+
+const options = {
+ access: "public",
+ author: undefined,
+ base: "everything",
+ createRepository: undefined,
+ description: "Stub description.",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: undefined,
+ excludeCompliance: undefined,
+ excludeLintJson: undefined,
+ excludeLintKnip: undefined,
+ excludeLintMd: undefined,
+ excludeLintPackageJson: undefined,
+ excludeLintPackages: undefined,
+ excludeLintPerfectionist: undefined,
+ excludeLintSpelling: undefined,
+ excludeLintYml: undefined,
+ excludeReleases: undefined,
+ excludeRenovate: undefined,
+ excludeTests: undefined,
+ funding: undefined,
+ logo: undefined,
+ mode: "create",
+ offline: true,
+ owner: "StubOwner",
+ repository: "stub-repository",
+ skipGitHubApi: false,
+ skipInstall: undefined,
+ skipRemoval: undefined,
+ skipRestore: undefined,
+ skipUninstall: undefined,
+ title: "Stub Title",
+} satisfies Options;
+
+describe("updateLocalFiles", () => {
+ it("throws a wrapping error when replaceInFiles rejects", async () => {
+ const error = new Error("Oh no!");
+
+ mockReadFileSafeAsJson.mockResolvedValue({});
+ mockReplaceInFile.mockRejectedValue(error);
+
+ await expect(async () => {
+ await updateLocalFiles({ ...options, mode: "initialize" });
+ }).rejects.toThrowErrorMatchingInlineSnapshot(
+ '"Failed to replace /Create TypeScript App/g with Stub Title in ./.github/**/*,./*.*"',
+ );
+ });
+
+ it("replaces using the common replacements when the existing package data is null", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue(null);
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /Create TypeScript App/g,
+ "to": "Stub Title",
+ },
+ ],
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /JoshuaKGoldberg\\(\\?!\\\\/console-fail-test\\)/g,
+ "to": "StubOwner",
+ },
+ ],
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /create-typescript-app/g,
+ "to": "stub-repository",
+ },
+ ],
+ [
+ {
+ "files": ".eslintrc.cjs",
+ "from": /\\\\/\\\\\\*\\\\n\\.\\+\\\\\\*\\\\/\\\\n\\\\n/gs,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"author": "\\.\\+"/g,
+ "to": "\\"author\\": \\"undefined\\"",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"bin": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:create": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:initialize": "\\.\\*/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"initialize": "\\.\\*/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:migrate": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./README.md",
+ "from": /## Getting Started\\.\\*## Development/gs,
+ "to": "## Development",
+ },
+ ],
+ [
+ {
+ "files": "./.github/DEVELOPMENT.md",
+ "from": /\\\\n## Setup Scripts\\.\\*\\$/gs,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": " \\"src/initialize/index.ts\\",
+ ",
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": " \\"src/migrate/index.ts\\",
+ ",
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": "[\\"src/index.ts!\\", \\"script/initialize*.js\\"]",
+ "to": "\\"src/index.ts!\\"",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": "[\\"src/**/*.ts!\\", \\"script/**/*.js\\"]",
+ "to": "\\"src/**/*.ts!\\"",
+ },
+ ],
+ [
+ {
+ "files": "./README.md",
+ "from": "> 💙 This package is based on [@StubOwner](https://github.com/StubOwner)'s [stub-repository](https://github.com/JoshuaKGoldberg/stub-repository).",
+ "to": "> 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).",
+ },
+ ],
+ ]
+ `);
+ });
+
+ it("replaces using the common replacements when the existing package data is an empty object", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({});
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /Create TypeScript App/g,
+ "to": "Stub Title",
+ },
+ ],
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /JoshuaKGoldberg\\(\\?!\\\\/console-fail-test\\)/g,
+ "to": "StubOwner",
+ },
+ ],
+ [
+ {
+ "files": [
+ "./.github/**/*",
+ "./*.*",
+ ],
+ "from": /create-typescript-app/g,
+ "to": "stub-repository",
+ },
+ ],
+ [
+ {
+ "files": ".eslintrc.cjs",
+ "from": /\\\\/\\\\\\*\\\\n\\.\\+\\\\\\*\\\\/\\\\n\\\\n/gs,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"author": "\\.\\+"/g,
+ "to": "\\"author\\": \\"undefined\\"",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"bin": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:create": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:initialize": "\\.\\*/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"initialize": "\\.\\*/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./package.json",
+ "from": /"test:migrate": "\\.\\+\\\\n/g,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./README.md",
+ "from": /## Getting Started\\.\\*## Development/gs,
+ "to": "## Development",
+ },
+ ],
+ [
+ {
+ "files": "./.github/DEVELOPMENT.md",
+ "from": /\\\\n## Setup Scripts\\.\\*\\$/gs,
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": " \\"src/initialize/index.ts\\",
+ ",
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": " \\"src/migrate/index.ts\\",
+ ",
+ "to": "",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": "[\\"src/index.ts!\\", \\"script/initialize*.js\\"]",
+ "to": "\\"src/index.ts!\\"",
+ },
+ ],
+ [
+ {
+ "files": "./knip.jsonc",
+ "from": "[\\"src/**/*.ts!\\", \\"script/**/*.js\\"]",
+ "to": "\\"src/**/*.ts!\\"",
+ },
+ ],
+ [
+ {
+ "files": "./README.md",
+ "from": "> 💙 This package is based on [@StubOwner](https://github.com/StubOwner)'s [stub-repository](https://github.com/JoshuaKGoldberg/stub-repository).",
+ "to": "> 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).",
+ },
+ ],
+ ]
+ `);
+ });
+
+ it("does not replace an existing description when it does not exist", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({});
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile).not.toHaveBeenCalledWith({
+ files: ["./.github/**/*", "./*.*"],
+ from: expect.anything(),
+ to: options.description,
+ });
+ });
+ it("replaces an existing description when it exists", async () => {
+ const existingDescription = "Existing description.";
+
+ mockReadFileSafeAsJson.mockResolvedValue({
+ description: existingDescription,
+ });
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile).toHaveBeenCalledWith({
+ files: ["./.github/**/*", "./*.*"],
+ from: existingDescription,
+ to: options.description,
+ });
+ });
+
+ it("removes bin when the mode is initialize", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({
+ version: "1.2.3",
+ });
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile).toHaveBeenCalledWith({
+ files: "./package.json",
+ from: /"bin": ".+\n/g,
+ to: "",
+ });
+ });
+
+ it("does not remove bin when the mode is migrate", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({
+ version: "1.2.3",
+ });
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "migrate" });
+
+ expect(mockReplaceInFile).not.toHaveBeenCalledWith({
+ files: "./package.json",
+ from: /"bin": ".+\n/g,
+ to: "",
+ });
+ });
+
+ it("resets package version to 0.0.0 when mode is initialize", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({
+ version: "1.2.3",
+ });
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "initialize" });
+
+ expect(mockReplaceInFile).toHaveBeenCalledWith({
+ files: "./package.json",
+ from: /"version": "1.2.3"/g,
+ to: '"version": "0.0.0"',
+ });
+ });
+
+ it("does not reset package version to 0.0.0 when mode is migrate", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({
+ version: "1.2.3",
+ });
+ mockReplaceInFile.mockResolvedValue([]);
+
+ await updateLocalFiles({ ...options, mode: "migrate" });
+
+ expect(mockReplaceInFile).not.toHaveBeenCalledWith({
+ files: "./package.json",
+ from: /"version": "1.2.3"/g,
+ to: '"version": "0.0.0"',
+ });
+ });
+});
diff --git a/src/steps/updateLocalFiles.ts b/src/steps/updateLocalFiles.ts
new file mode 100644
index 00000000..dc15fcc3
--- /dev/null
+++ b/src/steps/updateLocalFiles.ts
@@ -0,0 +1,71 @@
+import replaceInFile from "replace-in-file";
+
+import { readFileSafeAsJson } from "../shared/readFileSafeAsJson.js";
+import { Options } from "../shared/types.js";
+
+interface ExistingPackageData {
+ description?: string;
+ version?: string;
+}
+
+export async function updateLocalFiles(options: Options) {
+ const existingPackage = ((await readFileSafeAsJson("./package.json")) ??
+ {}) as ExistingPackageData;
+
+ const replacements = [
+ [/Create TypeScript App/g, options.title],
+ [/JoshuaKGoldberg(?!\/console-fail-test)/g, options.owner],
+ [/create-typescript-app/g, options.repository],
+ [/\/\*\n.+\*\/\n\n/gs, ``, ".eslintrc.cjs"],
+ [/"author": ".+"/g, `"author": "${options.author}"`, "./package.json"],
+ ...(options.mode === "migrate"
+ ? []
+ : [[/"bin": ".+\n/g, ``, "./package.json"]]),
+ [/"test:create": ".+\n/g, ``, "./package.json"],
+ [/"test:initialize": ".*/g, ``, "./package.json"],
+ [/"initialize": ".*/g, ``, "./package.json"],
+ [/"test:migrate": ".+\n/g, ``, "./package.json"],
+ [/## Getting Started.*## Development/gs, `## Development`, "./README.md"],
+ [/\n## Setup Scripts.*$/gs, "", "./.github/DEVELOPMENT.md"],
+ [`\t\t"src/initialize/index.ts",\n`, ``, "./knip.jsonc"],
+ [`\t\t"src/migrate/index.ts",\n`, ``, "./knip.jsonc"],
+ [
+ `["src/index.ts!", "script/initialize*.js"]`,
+ `"src/index.ts!"`,
+ "./knip.jsonc",
+ ],
+ [`["src/**/*.ts!", "script/**/*.js"]`, `"src/**/*.ts!"`, "./knip.jsonc"],
+ // Edge case: migration scripts will rewrite README.md attribution
+ [
+ `> 💙 This package is based on [@${options.owner}](https://github.com/${options.owner})'s [${options.repository}](https://github.com/JoshuaKGoldberg/${options.repository}).`,
+ `> 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).`,
+ "./README.md",
+ ],
+ ];
+
+ if (existingPackage.description) {
+ replacements.push([existingPackage.description, options.description]);
+ }
+
+ if (options.mode === "initialize" && existingPackage.version) {
+ replacements.push([
+ new RegExp(`"version": "${existingPackage.version}"`, "g"),
+ `"version": "0.0.0"`,
+ "./package.json",
+ ]);
+ }
+
+ for (const [from, to, files = ["./.github/**/*", "./*.*"]] of replacements) {
+ try {
+ // @ts-expect-error -- https://github.com/microsoft/TypeScript/issues/54342
+ await replaceInFile({ files, from, to });
+ } catch (error) {
+ throw new Error(
+ `Failed to replace ${from.toString()} with ${to} in ${files.toString()}`,
+ {
+ cause: error,
+ },
+ );
+ }
+ }
+}
diff --git a/src/steps/updateReadme.test.ts b/src/steps/updateReadme.test.ts
new file mode 100644
index 00000000..9696a569
--- /dev/null
+++ b/src/steps/updateReadme.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { updateReadme } from "./updateReadme.js";
+
+const mockAppendFile = vi.fn();
+
+vi.mock("node:fs/promises", () => ({
+ default: {
+ get appendFile() {
+ return mockAppendFile;
+ },
+ },
+}));
+
+const mockReadFileSafe = vi.fn();
+
+vi.mock("../shared/readFileSafe.js", () => ({
+ get readFileSafe() {
+ return mockReadFileSafe;
+ },
+}));
+
+describe("updateReadme", () => {
+ it("adds a notice when the file does not contain it already", async () => {
+ mockReadFileSafe.mockResolvedValue("");
+
+ await updateReadme();
+
+ expect(mockAppendFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ "./README.md",
+ "
+
+
+ > 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+ ",
+ ],
+ ]
+ `);
+ });
+
+ it("doesn't adds a notice when the file contains it already", async () => {
+ mockReadFileSafe.mockResolvedValue(
+ "",
+ );
+
+ await updateReadme();
+
+ expect(mockAppendFile.mock.calls).toMatchInlineSnapshot("[]");
+ });
+});
diff --git a/src/steps/updateReadme.ts b/src/steps/updateReadme.ts
new file mode 100644
index 00000000..a9a86889
--- /dev/null
+++ b/src/steps/updateReadme.ts
@@ -0,0 +1,22 @@
+import fs from "node:fs/promises";
+import { EOL } from "node:os";
+
+import { readFileSafe } from "../shared/readFileSafe.js";
+
+const detectionLine = ``;
+
+export const endOfReadmeNotice = [
+ ``,
+ detectionLine,
+ ``,
+ `> 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).`,
+ ``,
+].join(EOL);
+
+export async function updateReadme() {
+ const contents = await readFileSafe("./README.md", "");
+
+ if (!contents.includes(detectionLine)) {
+ await fs.appendFile("./README.md", endOfReadmeNotice);
+ }
+}
diff --git a/src/steps/writeReadme/findExistingBadges.test.ts b/src/steps/writeReadme/findExistingBadges.test.ts
new file mode 100644
index 00000000..9d98caf1
--- /dev/null
+++ b/src/steps/writeReadme/findExistingBadges.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it, test } from "vitest";
+
+import { findExistingBadges } from "./findExistingBadges.js";
+
+describe("findExistingBadges", () => {
+ describe("no result cases", () => {
+ test.each([
+ "",
+ "abc123",
+ "# Test Title",
+ "[]",
+ "[][]",
+ "[]()",
+ "[][]()()",
+ ``,
+ ])("%j", (input) => {
+ expect(findExistingBadges(input)).toEqual([]);
+ });
+ });
+
+ describe("single result cases", () => {
+ test.each([
+ `[![GitHub CI](https://github.com/JoshuaKGoldberg/console-fail-test/actions/workflows/compile.yml/badge.svg)](https://github.com/JoshuaKGoldberg/console-fail-test/actions/workflows/compile.yml)`,
+ `[![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-brightgreen.svg)](https://prettier.io)`,
+ `![TypeScript: Strict](https://img.shields.io/badge/typescript-strict-brightgreen.svg)`,
+ `[![NPM version](https://badge.fury.io/js/console-fail-test.svg)](http://badge.fury.io/js/console-fail-test)`,
+ `[![Downloads](http://img.shields.io/npm/dm/console-fail-test.svg)](https://npmjs.org/package/console-fail-test)`,
+ "badge",
+ "badge",
+ "badge",
+ "badge",
+ `
+
+
+
+
+
+ `,
+ `
+
+ `,
+ `
+
+ `,
+ `
+
+
+ `,
+ `
+
+
+ `,
+ ``,
+ ``,
+ ])("%s", (contents) => {
+ expect(findExistingBadges(contents)).toEqual([contents.trim()]);
+ });
+ });
+
+ it("doesn't collect badges after a ##", () => {
+ expect(
+ findExistingBadges(`
+
+
+ ## Usage
+
+
+ `),
+ ).toEqual([``]);
+ });
+
+ it("doesn't collect badges after an h2", () => {
+ expect(
+ findExistingBadges(`
+
+
+ Usage
+
+
+ `),
+ ).toEqual([``]);
+ });
+
+ test("real-world usage", () => {
+ expect(
+ findExistingBadges(`
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ `),
+ ).toMatchInlineSnapshot(`
+ [
+ "
+
+
+
+
+
+ ",
+ "
+
+ ",
+ "",
+ "",
+ "",
+ ]
+ `);
+ });
+});
diff --git a/src/steps/writeReadme/findExistingBadges.ts b/src/steps/writeReadme/findExistingBadges.ts
new file mode 100644
index 00000000..454a604d
--- /dev/null
+++ b/src/steps/writeReadme/findExistingBadges.ts
@@ -0,0 +1,33 @@
+export const existingBadgeMatcherCreators = [
+ () => /\[!\[.+\]\(.+\)\]\(.+\)/g,
+ () => /!\[.+\]\(.+\)/g,
+ () => /^\s*[\s\S]+?<\/a>/gm,
+ () => //g,
+];
+
+export function findExistingBadges(contents: string): string[] {
+ const badges: string[] = [];
+ let remaining = contents.split(/<\s*h2.*>|##/)[0];
+
+ for (const createMatcher of existingBadgeMatcherCreators) {
+ const matcher = createMatcher();
+
+ while (true) {
+ const matched = matcher.exec(remaining);
+
+ if (!matched) {
+ break;
+ }
+
+ const [badge] = matched;
+
+ badges.push(badge.trim());
+ remaining = [
+ remaining.slice(0, matched.index),
+ remaining.slice(matched.index + badge.length),
+ ].join("");
+ }
+ }
+
+ return badges;
+}
diff --git a/src/steps/writeReadme/findIntroSectionClose.test.ts b/src/steps/writeReadme/findIntroSectionClose.test.ts
new file mode 100644
index 00000000..60da73e6
--- /dev/null
+++ b/src/steps/writeReadme/findIntroSectionClose.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import { findIntroSectionClose } from "./findIntroSectionClose.js";
+
+describe("findIntroSectionClose", () => {
+ it.each([
+ [
+ `# First
+## Second`,
+ 6,
+ ],
+ [
+ `# First
+Second
`,
+ 6,
+ ],
+ [
+ `# First
+Second
`,
+ 6,
+ ],
+ [
+ `# First
+\`\`\`js
+...
+\`\`\``,
+ 6,
+ ],
+ [
+ `# First
+
+[![](https://img.shields.io/badge/abc-ffcc00.svg)](image.jpg)
+
+[![](https://img.shields.io/badge/abc-ffcc00.svg)](image.jpg)
+`,
+ 135,
+ ],
+ [
+ `Plain heading
+
+Next line.
+`,
+ 14,
+ ],
+ ])("%s", (contents, expected) => {
+ expect(findIntroSectionClose(contents)).toEqual(expected);
+ });
+});
diff --git a/src/steps/writeReadme/findIntroSectionClose.ts b/src/steps/writeReadme/findIntroSectionClose.ts
new file mode 100644
index 00000000..e910b5f3
--- /dev/null
+++ b/src/steps/writeReadme/findIntroSectionClose.ts
@@ -0,0 +1,22 @@
+import { existingBadgeMatcherCreators } from "./findExistingBadges.js";
+
+export function findIntroSectionClose(contents: string) {
+ // Highest priority match: an h2, presumably following badges
+ const indexOfH2OrCodeBlock = contents.search(/## |<\s*h2|```/);
+
+ if (indexOfH2OrCodeBlock !== -1) {
+ return indexOfH2OrCodeBlock - 2;
+ }
+
+ // Failing that, if any badges are found, go after the last of them
+ for (const createMatcher of existingBadgeMatcherCreators) {
+ const lastMatch = [...contents.matchAll(createMatcher())].at(-1);
+
+ if (lastMatch?.index) {
+ return lastMatch.index + lastMatch[0].length + 2;
+ }
+ }
+
+ // Lastly, go for the second line altogether
+ return contents.indexOf("\n", 1) + 1;
+}
diff --git a/src/steps/writeReadme/generateTopContent.test.ts b/src/steps/writeReadme/generateTopContent.test.ts
new file mode 100644
index 00000000..d85afee6
--- /dev/null
+++ b/src/steps/writeReadme/generateTopContent.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, it } from "vitest";
+
+import { Options } from "../../shared/types.js";
+import { generateTopContent } from "./generateTopContent.js";
+
+const optionsBase = {
+ access: "public",
+ author: undefined,
+ base: undefined,
+ createRepository: undefined,
+ description: "",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: undefined,
+ excludeCompliance: undefined,
+ excludeLintJson: undefined,
+ excludeLintKnip: undefined,
+ excludeLintMd: undefined,
+ excludeLintPackageJson: undefined,
+ excludeLintPackages: undefined,
+ excludeLintPerfectionist: undefined,
+ excludeLintSpelling: undefined,
+ excludeLintYml: undefined,
+ excludeReleases: undefined,
+ excludeRenovate: undefined,
+ excludeTests: undefined,
+ funding: undefined,
+ logo: undefined,
+ mode: "create",
+ owner: "",
+ repository: "",
+ skipGitHubApi: false,
+ skipInstall: undefined,
+ skipRemoval: undefined,
+ skipRestore: undefined,
+ skipUninstall: undefined,
+ title: "",
+} satisfies Options;
+
+describe("findExistingBadges", () => {
+ it("generates full contents when there are no existing badges", () => {
+ expect(generateTopContent(optionsBase, [])).toMatchInlineSnapshot(`
+ "
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`"
+ `);
+ });
+
+ it("replaces existing contents when there is an existing known badge", () => {
+ expect(
+ generateTopContent(optionsBase, [
+ ``,
+ ]),
+ ).toMatchInlineSnapshot(`
+ "
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`"
+ `);
+ });
+
+ it("push existing badges to the end when there is an existing unknown badge", () => {
+ expect(
+ generateTopContent(optionsBase, [
+ ``,
+ ]),
+ ).toMatchInlineSnapshot(`
+ "
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`"
+ `);
+ });
+
+ it("does not include a greet section when the mode is migrate", () => {
+ expect(generateTopContent({ ...optionsBase, mode: "migrate" }, []))
+ .toMatchInlineSnapshot(`
+ "
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
"
+ `);
+ });
+});
diff --git a/src/steps/writeReadme/generateTopContent.ts b/src/steps/writeReadme/generateTopContent.ts
new file mode 100644
index 00000000..1c7d8b59
--- /dev/null
+++ b/src/steps/writeReadme/generateTopContent.ts
@@ -0,0 +1,102 @@
+import { Options } from "../../shared/types.js";
+
+export function generateTopContent(options: Options, existingBadges: string[]) {
+ const remainingExistingBadges = new Set(existingBadges);
+ const badges: string[] = [];
+
+ function spliceBadge(
+ badgeLine: false | string | undefined,
+ existingMatcher: RegExp,
+ ) {
+ const existingMatch = existingBadges.find((existingLine) =>
+ existingMatcher.test(existingLine),
+ );
+
+ if (existingMatch) {
+ remainingExistingBadges.delete(existingMatch);
+ }
+
+ if (badgeLine) {
+ badges.push(badgeLine);
+ }
+ }
+
+ for (const [badgeLine, existingMatcher] of [
+ [
+ !options.excludeAllContributors &&
+ `
+
+
+
+
+
+`,
+ /ALL-CONTRIBUTORS-BADGE:START/,
+ ],
+ [
+ !options.excludeTests &&
+ `
+
+ `,
+ /https:\/\/codecov\.io\/gh/,
+ ],
+ [
+ `
+
+ `,
+ /CODE_OF_CONDUCT\.md/,
+ ],
+ [
+ `
+
+ `,
+ /LICENSE\.(md|txt)/,
+ ],
+ [
+ options.funding &&
+ `
+
+ `,
+ /github.+sponsors/,
+ ],
+ [
+ ``,
+ /style.*prettier/i,
+ ],
+ [
+ ``,
+ /typescript.*strict/i,
+ ],
+ [
+ ``,
+ /npm.*v/i,
+ ],
+ ] as const) {
+ spliceBadge(badgeLine, existingMatcher);
+ }
+
+ return `${options.title}
+
+${options.description}
+
+
+${[...badges, ...remainingExistingBadges]
+ .map((badge) => `\t${badge}`)
+ .join("\n")}
+
${
+ options.mode === "migrate"
+ ? ""
+ : `
+
+## Usage
+
+\`\`\`shell
+npm i ${options.repository}
+\`\`\`
+\`\`\`ts
+import { greet } from "${options.repository}";
+
+greet("Hello, world! 💖");
+\`\`\``
+ }`;
+}
diff --git a/src/steps/writeReadme/index.test.ts b/src/steps/writeReadme/index.test.ts
new file mode 100644
index 00000000..d45f249c
--- /dev/null
+++ b/src/steps/writeReadme/index.test.ts
@@ -0,0 +1,403 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { Options } from "../../shared/types.js";
+import { writeReadme } from "./index.js";
+
+const mockWriteFile = vi.fn();
+
+vi.mock("node:fs/promises", () => ({
+ get default() {
+ return {
+ get writeFile() {
+ return mockWriteFile;
+ },
+ };
+ },
+}));
+
+const mockReadFileSafe = vi.fn();
+
+vi.mock("../../shared/readFileSafe.js", () => ({
+ get readFileSafe() {
+ return mockReadFileSafe;
+ },
+}));
+
+const options = {
+ access: "public",
+ author: "Test Author",
+ base: "everything",
+ createRepository: false,
+ description: "Test description.",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: undefined,
+ excludeCompliance: undefined,
+ excludeLintJson: undefined,
+ excludeLintKnip: undefined,
+ excludeLintMd: undefined,
+ excludeLintPackageJson: undefined,
+ excludeLintPackages: undefined,
+ excludeLintPerfectionist: undefined,
+ excludeLintSpelling: undefined,
+ excludeLintYml: undefined,
+ excludeReleases: undefined,
+ excludeRenovate: undefined,
+ excludeTests: undefined,
+ funding: "TestFunding",
+ logo: undefined,
+ mode: "create",
+ owner: "TestOwner",
+ repository: "test-repository",
+ skipGitHubApi: false,
+ skipInstall: true,
+ skipRemoval: false,
+ skipRestore: false,
+ skipUninstall: false,
+ title: "Test Title",
+} satisfies Options;
+
+describe("writeReadme", () => {
+ it("writes a new file when the README.md does not yet exist", async () => {
+ mockReadFileSafe.mockResolvedValueOnce("");
+
+ await writeReadme(options);
+
+ expect(mockWriteFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ "README.md",
+ "Test Title
+
+ Test description.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i test-repository
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"test-repository\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`
+
+ ## Contributors
+
+
+
+
+
+
+
+
+
+
+
+
+
+ > 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+ ",
+ ],
+ ]
+ `);
+ });
+
+ it("adds sections when the README.md already exists and is sparse", async () => {
+ mockReadFileSafe.mockResolvedValueOnce(`# ${options.title}\n`);
+
+ await writeReadme(options);
+
+ expect(mockWriteFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ "README.md",
+ "Test Title
+
+ Test description.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i test-repository
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"test-repository\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`
+
+ ## Contributors
+
+
+
+
+
+
+
+
+
+
+
+
+
+ > 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+ ",
+ ],
+ ]
+ `);
+ });
+
+ it("adds all-contributors content when directed to and the indicator does not yet exist", async () => {
+ mockReadFileSafe.mockResolvedValueOnce(`# ${options.title}\n`);
+
+ await writeReadme({
+ ...options,
+ excludeAllContributors: false,
+ });
+
+ expect(mockWriteFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ "README.md",
+ "Test Title
+
+ Test description.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i test-repository
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"test-repository\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`
+
+ ## Contributors
+
+
+
+
+
+
+
+
+
+
+
+
+
+ > 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+ ",
+ ],
+ ]
+ `);
+ });
+
+ it("does not duplicate sections when the README.md already exists and has them", async () => {
+ mockReadFileSafe.mockResolvedValueOnce(`Test Title
+
+Test description.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Contributors
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+> 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+`);
+
+ await writeReadme(options);
+
+ expect(mockWriteFile.mock.calls).toMatchInlineSnapshot(`
+ [
+ [
+ "README.md",
+ "Test Title
+
+ Test description.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ## Usage
+
+ \`\`\`shell
+ npm i test-repository
+ \`\`\`
+ \`\`\`ts
+ import { greet } from \\"test-repository\\";
+
+ greet(\\"Hello, world! 💖\\");
+ \`\`\`
+
+ ## Contributors
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ > 💙 This package is based on [@JoshuaKGoldberg](https://github.com/JoshuaKGoldberg)'s [create-typescript-app](https://github.com/JoshuaKGoldberg/create-typescript-app).
+ ",
+ ],
+ ]
+ `);
+ });
+});
diff --git a/src/steps/writeReadme/index.ts b/src/steps/writeReadme/index.ts
new file mode 100644
index 00000000..26af70de
--- /dev/null
+++ b/src/steps/writeReadme/index.ts
@@ -0,0 +1,73 @@
+import fs from "node:fs/promises";
+
+import { readFileSafe } from "../../shared/readFileSafe.js";
+import { Options } from "../../shared/types.js";
+import { endOfReadmeNotice } from "../updateReadme.js";
+import { findExistingBadges } from "./findExistingBadges.js";
+import { findIntroSectionClose } from "./findIntroSectionClose.js";
+import { generateTopContent } from "./generateTopContent.js";
+
+const contributorsIndicator = ``;
+
+function generateAllContributorsContent(options: Options) {
+ return [
+ `## Contributors`,
+ ``,
+ ``,
+ contributorsIndicator,
+ ``,
+ !options.excludeLintMd && ``,
+ ``,
+ ``,
+ !options.excludeLintMd && ``,
+ ``,
+ ``,
+ ``,
+ ``,
+ ]
+ .filter(Boolean)
+ .join("\n");
+}
+
+export async function writeReadme(options: Options) {
+ const allContributorsContent =
+ !options.excludeAllContributors && generateAllContributorsContent(options);
+ let contents = await readFileSafe("README.md", "");
+ if (!contents) {
+ await fs.writeFile(
+ "README.md",
+ [
+ generateTopContent(options, []),
+ allContributorsContent,
+ endOfReadmeNotice,
+ ]
+ .filter(Boolean)
+ .join("\n\n"),
+ );
+ return;
+ }
+
+ const endOfIntroSection = findIntroSectionClose(contents);
+
+ contents = [
+ generateTopContent(options, findExistingBadges(contents)),
+ contents.slice(endOfIntroSection),
+ ]
+ .join("")
+ .replace(/\[!\[.+\]\(.+\)\]\(.+\)/g, "")
+ .replace(/!\[.+\]\(.+\)/g, "")
+ .replaceAll("\r", "")
+ .replaceAll("\n\n\n", "\n\n");
+
+ if (allContributorsContent && !contents.includes(contributorsIndicator)) {
+ contents = [contents, allContributorsContent].join("\n\n");
+ }
+
+ if (!contents.includes(endOfReadmeNotice)) {
+ contents = [contents, endOfReadmeNotice].join("\n\n");
+ }
+
+ await fs.writeFile("README.md", contents);
+}
diff --git a/src/steps/writing/creation/createESLintRC.test.ts b/src/steps/writing/creation/createESLintRC.test.ts
new file mode 100644
index 00000000..5eab2434
--- /dev/null
+++ b/src/steps/writing/creation/createESLintRC.test.ts
@@ -0,0 +1,274 @@
+import { describe, expect, it } from "vitest";
+
+import { Options } from "../../../shared/types.js";
+import { createESLintRC } from "./createESLintRC.js";
+
+function fakeOptions(getExcludeValue: (exclusionName: string) => boolean) {
+ return {
+ access: "public",
+ author: "TestAuthor",
+ base: "everything",
+ createRepository: true,
+ description: "Test description.",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ ...Object.fromEntries(
+ [
+ "excludeCompliance",
+ "excludeAllContributors",
+ "excludeLintDeprecation",
+ "excludeLintESLint",
+ "excludeLintJSDoc",
+ "excludeLintJson",
+ "excludeLintKnip",
+ "excludeLintMd",
+ "excludeLintPackageJson",
+ "excludeLintPackages",
+ "excludeLintPerfectionist",
+ "excludeLintRegex",
+ "excludeLintSpelling",
+ "excludeLintStrict",
+ "excludeLintStylistic",
+ "excludeLintYml",
+ "excludeReleases",
+ "excludeRenovate",
+ "excludeTests",
+ ].map((key) => [key, getExcludeValue(key)]),
+ ),
+ logo: undefined,
+ mode: "create",
+ owner: "TestOwner",
+ repository: "test-repository",
+ skipGitHubApi: true,
+ skipInstall: true,
+ skipRemoval: true,
+ title: "Test Title",
+ } satisfies Options;
+}
+
+describe("createESLintRC", () => {
+ it("creates a minimal config when all exclusions are enabled", async () => {
+ expect(await createESLintRC(fakeOptions(() => true)))
+ .toMatchInlineSnapshot(`
+ "/** @type {import(\\"@types/eslint\\").Linter.Config} */
+ module.exports = {
+ env: {
+ es2022: true,
+ node: true,
+ },
+ extends: [\\"eslint:recommended\\", \\"plugin:n/recommended\\"],
+ overrides: [
+ {
+ extends: [\\"plugin:@typescript-eslint/recommended\\"],
+ files: [\\"**/*.ts\\"],
+ parser: \\"@typescript-eslint/parser\\",
+ rules: {
+ // These off-by-default rules work well for this repo and we like them on.
+ \\"logical-assignment-operators\\": [
+ \\"error\\",
+ \\"always\\",
+ { enforceForIfStatements: true },
+ ],
+ \\"operator-assignment\\": \\"error\\",
+ },
+ },
+ {
+ files: \\"**/*.md/*.ts\\",
+ rules: {
+ \\"n/no-missing-import\\": [
+ \\"error\\",
+ { allowModules: [\\"create-typescript-app\\"] },
+ ],
+ },
+ },
+ {
+ extends: [\\"plugin:@typescript-eslint/recommended-type-checked\\"],
+ files: [\\"**/*.ts\\"],
+ parser: \\"@typescript-eslint/parser\\",
+ parserOptions: {
+ project: \\"./tsconfig.eslint.json\\",
+ },
+ },
+ ],
+ parser: \\"@typescript-eslint/parser\\",
+ plugins: [\\"@typescript-eslint\\"],
+ reportUnusedDisableDirectives: true,
+ root: true,
+ rules: {
+ // These off/less-strict-by-default rules work well for this repo and we like them on.
+ \\"@typescript-eslint/no-unused-vars\\": [\\"error\\", { caughtErrors: \\"all\\" }],
+
+ // These on-by-default rules don't work well for this repo and we like them off.
+ \\"no-case-declarations\\": \\"off\\",
+ \\"no-constant-condition\\": \\"off\\",
+ \\"no-inner-declarations\\": \\"off\\",
+ \\"no-mixed-spaces-and-tabs\\": \\"off\\",
+ },
+ };
+ "
+ `);
+ });
+
+ it("creates a full config when all exclusions are disabled", async () => {
+ expect(await createESLintRC(fakeOptions(() => false)))
+ .toMatchInlineSnapshot(`
+ "/** @type {import(\\"@types/eslint\\").Linter.Config} */
+ module.exports = {
+ env: {
+ es2022: true,
+ node: true,
+ },
+ extends: [
+ \\"eslint:recommended\\",
+ \\"plugin:eslint-comments/recommended\\",
+ \\"plugin:n/recommended\\",
+ \\"plugin:perfectionist/recommended-natural\\",
+ \\"plugin:regexp/recommended\\",
+ \\"plugin:vitest/recommended\\",
+ ],
+ overrides: [
+ {
+ extends: [\\"plugin:markdown/recommended\\"],
+ files: [\\"**/*.md\\"],
+ processor: \\"markdown/markdown\\",
+ },
+ {
+ extends: [
+ \\"plugin:jsdoc/recommended-typescript-error\\",
+ \\"plugin:@typescript-eslint/strict\\",
+ \\"plugin:@typescript-eslint/stylistic\\",
+ ],
+ files: [\\"**/*.ts\\"],
+ parser: \\"@typescript-eslint/parser\\",
+ rules: {
+ // These off-by-default rules work well for this repo and we like them on.
+ \\"jsdoc/informative-docs\\": \\"error\\",
+ \\"logical-assignment-operators\\": [
+ \\"error\\",
+ \\"always\\",
+ { enforceForIfStatements: true },
+ ],
+ \\"operator-assignment\\": \\"error\\",
+
+ // These on-by-default rules don't work well for this repo and we like them off.
+ \\"jsdoc/require-jsdoc\\": \\"off\\",
+ \\"jsdoc/require-param\\": \\"off\\",
+ \\"jsdoc/require-property\\": \\"off\\",
+ \\"jsdoc/require-returns\\": \\"off\\",
+ },
+ },
+ {
+ files: \\"**/*.md/*.ts\\",
+ rules: {
+ \\"n/no-missing-import\\": [
+ \\"error\\",
+ { allowModules: [\\"create-typescript-app\\"] },
+ ],
+ },
+ },
+ {
+ excludedFiles: [\\"**/*.md/*.ts\\"],
+ extends: [
+ \\"plugin:@typescript-eslint/strict-type-checked\\",
+ \\"plugin:@typescript-eslint/stylistic-type-checked\\",
+ ],
+ files: [\\"**/*.ts\\"],
+ parser: \\"@typescript-eslint/parser\\",
+ parserOptions: {
+ project: \\"./tsconfig.eslint.json\\",
+ },
+ rules: {
+ // These off-by-default rules work well for this repo and we like them on.
+ \\"deprecation/deprecation\\": \\"error\\",
+ },
+ },
+ {
+ excludedFiles: [\\"package.json\\"],
+ extends: [\\"plugin:jsonc/recommended-with-json\\"],
+ files: [\\"*.json\\", \\"*.jsonc\\"],
+ parser: \\"jsonc-eslint-parser\\",
+ rules: {
+ \\"jsonc/sort-keys\\": \\"error\\",
+ },
+ },
+ {
+ files: [\\"*.jsonc\\"],
+ rules: {
+ \\"jsonc/no-comments\\": \\"off\\",
+ },
+ },
+ {
+ files: \\"**/*.test.ts\\",
+ rules: {
+ // These on-by-default rules aren't useful in test files.
+ \\"@typescript-eslint/no-unsafe-assignment\\": \\"off\\",
+ \\"@typescript-eslint/no-unsafe-call\\": \\"off\\",
+ },
+ },
+ {
+ extends: [\\"plugin:yml/standard\\", \\"plugin:yml/prettier\\"],
+ files: [\\"**/*.{yml,yaml}\\"],
+ parser: \\"yaml-eslint-parser\\",
+ rules: {
+ \\"yml/file-extension\\": [\\"error\\", { extension: \\"yml\\" }],
+ \\"yml/sort-keys\\": [
+ \\"error\\",
+ {
+ order: { type: \\"asc\\" },
+ pathPattern: \\"^.*$\\",
+ },
+ ],
+ \\"yml/sort-sequence-values\\": [
+ \\"error\\",
+ {
+ order: { type: \\"asc\\" },
+ pathPattern: \\"^.*$\\",
+ },
+ ],
+ },
+ },
+ ],
+ parser: \\"@typescript-eslint/parser\\",
+ plugins: [
+ \\"@typescript-eslint\\",
+ \\"deprecation\\",
+ \\"jsdoc\\",
+ \\"no-only-tests\\",
+ \\"perfectionist\\",
+ \\"regexp\\",
+ \\"vitest\\",
+ ],
+ reportUnusedDisableDirectives: true,
+ root: true,
+ rules: {
+ // These off/less-strict-by-default rules work well for this repo and we like them on.
+ \\"@typescript-eslint/no-unused-vars\\": [\\"error\\", { caughtErrors: \\"all\\" }],
+ \\"no-only-tests/no-only-tests\\": \\"error\\",
+
+ // These on-by-default rules don't work well for this repo and we like them off.
+ \\"no-case-declarations\\": \\"off\\",
+ \\"no-constant-condition\\": \\"off\\",
+ \\"no-inner-declarations\\": \\"off\\",
+ \\"no-mixed-spaces-and-tabs\\": \\"off\\",
+
+ // Stylistic concerns that don't interfere with Prettier
+ \\"@typescript-eslint/padding-line-between-statements\\": [
+ \\"error\\",
+ { blankLine: \\"always\\", next: \\"*\\", prev: \\"block-like\\" },
+ ],
+ \\"perfectionist/sort-objects\\": [
+ \\"error\\",
+ {
+ order: \\"asc\\",
+ \\"partition-by-comment\\": true,
+ type: \\"natural\\",
+ },
+ ],
+ },
+ };
+ "
+ `);
+ });
+});
diff --git a/src/steps/writing/creation/createESLintRC.ts b/src/steps/writing/creation/createESLintRC.ts
new file mode 100644
index 00000000..d2cea501
--- /dev/null
+++ b/src/steps/writing/creation/createESLintRC.ts
@@ -0,0 +1,231 @@
+import { Options } from "../../../shared/types.js";
+import { formatTypeScript } from "./formatters/formatTypeScript.js";
+
+export async function createESLintRC(options: Options) {
+ return await formatTypeScript(`/** @type {import("@types/eslint").Linter.Config} */
+module.exports = {
+ env: {
+ es2022: true,
+ node: true,
+ },
+ extends: [
+ "eslint:recommended",
+ ${
+ options.excludeLintESLint
+ ? ""
+ : `"plugin:eslint-comments/recommended",
+ `
+ }"plugin:n/recommended",${
+ options.excludeLintPerfectionist
+ ? ""
+ : `
+ "plugin:perfectionist/recommended-natural",`
+ }${options.excludeLintRegex ? "" : `"plugin:regexp/recommended",`}${
+ options.excludeTests ? "" : `"plugin:vitest/recommended",`
+ }
+ ],
+ overrides: [${
+ options.excludeLintMd
+ ? ""
+ : `
+ {
+ extends: ["plugin:markdown/recommended"],
+ files: ["**/*.md"],
+ processor: "markdown/markdown",
+ },`
+ }
+ {
+ extends: [
+ ${
+ options.excludeLintJSDoc
+ ? ""
+ : `"plugin:jsdoc/recommended-typescript-error",
+ `
+ }"plugin:@typescript-eslint/${
+ options.excludeLintStrict ? "recommended" : "strict"
+ }",${
+ options.excludeLintStylistic
+ ? ""
+ : `
+ "plugin:@typescript-eslint/stylistic",`
+ }
+ ],
+ files: ["**/*.ts"],
+ parser: "@typescript-eslint/parser",
+ rules: {
+ // These off-by-default rules work well for this repo and we like them on.
+ ${
+ options.excludeLintJSDoc
+ ? ""
+ : `"jsdoc/informative-docs": "error",
+ `
+ }"logical-assignment-operators": [
+ "error",
+ "always",
+ { enforceForIfStatements: true },
+ ],
+ "operator-assignment": "error",${
+ options.excludeLintJSDoc
+ ? ""
+ : `
+
+ // These on-by-default rules don't work well for this repo and we like them off.
+ "jsdoc/require-jsdoc": "off",
+ "jsdoc/require-param": "off",
+ "jsdoc/require-property": "off",
+ "jsdoc/require-returns": "off",`
+ }
+ },
+ },
+ {
+ files: "**/*.md/*.ts",
+ rules: {
+ "n/no-missing-import": [
+ "error",
+ { allowModules: ["create-typescript-app"] },
+ ],
+ },
+ },
+ {
+ ${
+ options.excludeLintMd
+ ? ""
+ : `excludedFiles: ["**/*.md/*.ts"],
+ `
+ }extends: [
+ "plugin:@typescript-eslint/${
+ options.excludeLintStrict ? "recommended" : "strict"
+ }-type-checked",${
+ options.excludeLintStylistic
+ ? ""
+ : `
+ "plugin:@typescript-eslint/stylistic-type-checked",`
+ }
+ ],
+ files: ["**/*.ts"],
+ parser: "@typescript-eslint/parser",
+ parserOptions: {
+ project: "./tsconfig.eslint.json",
+ },${
+ options.excludeLintDeprecation
+ ? ""
+ : `rules: {
+ // These off-by-default rules work well for this repo and we like them on.
+ "deprecation/deprecation": "error",
+ },`
+ }
+ },
+ ${
+ options.excludeLintJson
+ ? ""
+ : `{
+ excludedFiles: ["package.json"],
+ extends: ["plugin:jsonc/recommended-with-json"],
+ files: ["*.json", "*.jsonc"],
+ parser: "jsonc-eslint-parser",
+ rules: {
+ "jsonc/sort-keys": "error",
+ },
+ },
+ {
+ files: ["*.jsonc"],
+ rules: {
+ "jsonc/no-comments": "off",
+ },
+ },`
+ }${
+ options.excludeTests
+ ? ""
+ : `\n{
+ files: "**/*.test.ts",
+ rules: {
+ // These on-by-default rules aren't useful in test files.
+ "@typescript-eslint/no-unsafe-assignment": "off",
+ "@typescript-eslint/no-unsafe-call": "off",
+ },
+ },`
+ }${
+ options.excludeLintYml
+ ? ""
+ : `\n{
+ extends: ["plugin:yml/standard", "plugin:yml/prettier"],
+ files: ["**/*.{yml,yaml}"],
+ parser: "yaml-eslint-parser",
+ rules: {
+ "yml/file-extension": ["error", { extension: "yml" }],
+ "yml/sort-keys": [
+ "error",
+ {
+ order: { type: "asc" },
+ pathPattern: "^.*$",
+ },
+ ],
+ "yml/sort-sequence-values": [
+ "error",
+ {
+ order: { type: "asc" },
+ pathPattern: "^.*$",
+ },
+ ],
+ },
+ },
+ `
+ }],
+ parser: "@typescript-eslint/parser",
+ plugins: [
+ "@typescript-eslint",
+ ${
+ options.excludeLintDeprecation
+ ? ""
+ : `"deprecation",
+ `
+ }${
+ options.excludeLintJSDoc
+ ? ""
+ : `"jsdoc",
+ `
+ }${options.excludeTests ? "" : `"no-only-tests",`}${
+ options.excludeLintPerfectionist ? "" : `"perfectionist",`
+ }${options.excludeLintRegex ? "" : `"regexp",`}${
+ options.excludeTests ? "" : `\n"vitest",`
+ }
+ ],
+ reportUnusedDisableDirectives: true,
+ root: true,
+ rules: {
+ // These off/less-strict-by-default rules work well for this repo and we like them on.
+ "@typescript-eslint/no-unused-vars": ["error", { caughtErrors: "all" }],${
+ options.excludeTests ? "" : `\n"no-only-tests/no-only-tests": "error",`
+ }
+
+ // These on-by-default rules don't work well for this repo and we like them off.
+ "no-case-declarations": "off",
+ "no-constant-condition": "off",
+ "no-inner-declarations": "off",
+ "no-mixed-spaces-and-tabs": "off",
+
+ ${
+ options.excludeLintStylistic
+ ? ""
+ : `// Stylistic concerns that don't interfere with Prettier
+ "@typescript-eslint/padding-line-between-statements": [
+ "error",
+ { blankLine: "always", next: "*", prev: "block-like" },
+ ],
+ `
+ }${
+ options.excludeLintPerfectionist
+ ? ""
+ : `"perfectionist/sort-objects": [
+ "error",
+ {
+ order: "asc",
+ "partition-by-comment": true,
+ type: "natural",
+ },
+ ],`
+ }
+ },
+};
+`);
+}
diff --git a/src/steps/writing/creation/dotGitHub/actions.test.ts b/src/steps/writing/creation/dotGitHub/actions.test.ts
new file mode 100644
index 00000000..5650f7c4
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/actions.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+
+import { createDotGitHubActions } from "./actions.js";
+
+describe("createDotGitHubActions", () => {
+ it("creates a prepare/action.yml file", () => {
+ const actual = createDotGitHubActions();
+
+ expect(actual).toEqual({
+ prepare: {
+ "action.yml": `description: Prepares the repo for a typical CI job
+
+name: Prepare
+
+runs:
+ steps:
+ - uses: pnpm/action-setup@v2
+ - uses: actions/setup-node@v3
+ with:
+ cache: pnpm
+ node-version: '18'
+ - run: pnpm install --frozen-lockfile
+ shell: bash
+ using: composite
+`,
+ },
+ });
+ });
+});
diff --git a/src/steps/writing/creation/dotGitHub/actions.ts b/src/steps/writing/creation/dotGitHub/actions.ts
new file mode 100644
index 00000000..67db8be3
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/actions.ts
@@ -0,0 +1,28 @@
+import jsYaml from "js-yaml";
+
+export function createDotGitHubActions() {
+ return {
+ prepare: {
+ "action.yml": jsYaml
+ .dump({
+ description: "Prepares the repo for a typical CI job",
+ name: "Prepare",
+ runs: {
+ steps: [
+ { uses: "pnpm/action-setup@v2" },
+ {
+ uses: "actions/setup-node@v3",
+ with: { cache: "pnpm", "node-version": "18" },
+ },
+ {
+ run: "pnpm install --frozen-lockfile",
+ shell: "bash",
+ },
+ ],
+ using: "composite",
+ },
+ })
+ .replaceAll(/\n(\S)/g, "\n\n$1"),
+ },
+ };
+}
diff --git a/src/steps/writing/creation/dotGitHub/createDevelopment.test.ts b/src/steps/writing/creation/dotGitHub/createDevelopment.test.ts
new file mode 100644
index 00000000..02a2779d
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createDevelopment.test.ts
@@ -0,0 +1,259 @@
+import { describe, expect, it } from "vitest";
+
+import { Options } from "../../../../shared/types.js";
+import { createDevelopment } from "./createDevelopment.js";
+
+const options = {
+ access: "public",
+ author: "Test Author",
+ base: "everything",
+ createRepository: false,
+ description: "Test description.",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: undefined,
+ excludeCompliance: undefined,
+ excludeLintJson: undefined,
+ excludeLintKnip: undefined,
+ excludeLintMd: undefined,
+ excludeLintPackageJson: undefined,
+ excludeLintPackages: undefined,
+ excludeLintPerfectionist: undefined,
+ excludeLintSpelling: undefined,
+ excludeLintYml: undefined,
+ excludeReleases: undefined,
+ excludeRenovate: undefined,
+ excludeTests: undefined,
+ funding: undefined,
+ logo: undefined,
+ mode: "create",
+ owner: "TestOwner",
+ repository: "test-repository",
+ skipGitHubApi: false,
+ skipInstall: true,
+ skipRemoval: false,
+ skipRestore: false,
+ skipUninstall: false,
+ title: "Test Title",
+} satisfies Options;
+
+describe("createDevelopment", () => {
+ it("creates a file with no extra linters when options exclude them", () => {
+ const actual = createDevelopment({
+ ...options,
+ excludeLintKnip: false,
+ excludeLintMd: false,
+ excludeLintPackageJson: false,
+ excludeLintPackages: false,
+ excludeLintSpelling: false,
+ });
+
+ expect(actual).toMatchInlineSnapshot(`
+ "# Development
+
+ After [forking the repo from GitHub](https://help.github.com/articles/fork-a-repo) and [installing pnpm](https://pnpm.io/installation):
+
+ \`\`\`shell
+ git clone https://github.com//test-repository
+ cd test-repository
+ pnpm install
+ \`\`\`
+
+ > This repository includes a list of suggested VS Code extensions.
+ > It's a good idea to use [VS Code](https://code.visualstudio.com) and accept its suggestion to install them, as they'll help with development.
+
+ ## Building
+
+ Run [**tsup**](https://tsup.egoist.dev) locally to build source files from \`src/\` into output files in \`lib/\`:
+
+ \`\`\`shell
+ pnpm build
+ \`\`\`
+
+ Add \`--watch\` to run the builder in a watch mode that continuously cleans and recreates \`lib/\` as you save files:
+
+ \`\`\`shell
+ pnpm build --watch
+ \`\`\`
+
+ ## Formatting
+
+ [Prettier](https://prettier.io) is used to format code.
+ It should be applied automatically when you save files in VS Code or make a Git commit.
+
+ To manually reformat all files, you can run:
+
+ \`\`\`shell
+ pnpm format --write
+ \`\`\`
+
+ ## Linting
+
+ This package includes several forms of linting to enforce consistent code quality and styling.
+ Each should be shown in VS Code, and can be run manually on the command-line:
+
+ - \`pnpm lint\` ([ESLint](https://eslint.org) with [typescript-eslint](https://typescript-eslint.io)): Lints JavaScript and TypeScript source files
+ - \`pnpm lint:knip\` ([knip](https://github.com/webpro/knip)): Detects unused files, dependencies, and code exports
+ - \`pnpm lint:md\` ([Markdownlint](https://github.com/DavidAnson/markdownlint)): Checks Markdown source files
+ - \`pnpm lint:package-json\` ([npm-package-json-lint](https://npmpackagejsonlint.org/)): Lints the \`package.json\` file
+ - \`pnpm lint:packages\` ([pnpm dedupe --check](https://pnpm.io/cli/dedupe)): Checks for unnecessarily duplicated packages in the \`pnpm-lock.yml\` file
+ - \`pnpm lint:spelling\` ([cspell](https://cspell.org)): Spell checks across all source files
+
+ Read the individual documentation for each linter to understand how it can be configured and used best.
+
+ For example, ESLint can be run with \`--fix\` to auto-fix some lint rule complaints:
+
+ \`\`\`shell
+ pnpm run lint --fix
+ \`\`\`
+
+ ## Testing
+
+ [Vitest](https://vitest.dev) is used for tests.
+ You can run it locally on the command-line:
+
+ \`\`\`shell
+ pnpm run test
+ \`\`\`
+
+ Add the \`--coverage\` flag to compute test coverage and place reports in the \`coverage/\` directory:
+
+ \`\`\`shell
+ pnpm run test --coverage
+ \`\`\`
+
+ Note that [console-fail-test](https://github.com/JoshuaKGoldberg/console-fail-test) is enabled for all test runs.
+ Calls to \`console.log\`, \`console.warn\`, and other console methods will cause a test to fail.
+
+ ### Debugging Tests
+
+ This repository includes a [VS Code launch configuration](https://code.visualstudio.com/docs/editor/debugging) for debugging unit tests.
+ To launch it, open a test file, then run _Debug Current Test File_ from the VS Code Debug panel (or press F5).
+
+ ## Type Checking
+
+ You should be able to see suggestions from [TypeScript](https://typescriptlang.org) in your editor for all open files.
+
+ However, it can be useful to run the TypeScript command-line (\`tsc\`) to type check all files in \`src/\`:
+
+ \`\`\`shell
+ pnpm tsc
+ \`\`\`
+
+ Add \`--watch\` to keep the type checker running in a watch mode that updates the display as you save files:
+
+ \`\`\`shell
+ pnpm tsc --watch
+ \`\`\`
+ "
+ `);
+ });
+
+ it("creates a file with all extra linters when options include them", () => {
+ const actual = createDevelopment({
+ ...options,
+ excludeLintKnip: true,
+ excludeLintMd: true,
+ excludeLintPackageJson: true,
+ excludeLintPackages: true,
+ excludeLintSpelling: true,
+ });
+
+ expect(actual).toMatchInlineSnapshot(`
+ "# Development
+
+ After [forking the repo from GitHub](https://help.github.com/articles/fork-a-repo) and [installing pnpm](https://pnpm.io/installation):
+
+ \`\`\`shell
+ git clone https://github.com//test-repository
+ cd test-repository
+ pnpm install
+ \`\`\`
+
+ > This repository includes a list of suggested VS Code extensions.
+ > It's a good idea to use [VS Code](https://code.visualstudio.com) and accept its suggestion to install them, as they'll help with development.
+
+ ## Building
+
+ Run [**tsup**](https://tsup.egoist.dev) locally to build source files from \`src/\` into output files in \`lib/\`:
+
+ \`\`\`shell
+ pnpm build
+ \`\`\`
+
+ Add \`--watch\` to run the builder in a watch mode that continuously cleans and recreates \`lib/\` as you save files:
+
+ \`\`\`shell
+ pnpm build --watch
+ \`\`\`
+
+ ## Formatting
+
+ [Prettier](https://prettier.io) is used to format code.
+ It should be applied automatically when you save files in VS Code or make a Git commit.
+
+ To manually reformat all files, you can run:
+
+ \`\`\`shell
+ pnpm format --write
+ \`\`\`
+
+ ## Linting
+
+ [ESLint](https://eslint.org) is used with with [typescript-eslint](https://typescript-eslint.io)) to lint JavaScript and TypeScript source files.
+ You can run it locally on the command-line:
+
+ \`\`\`shell
+ pnpm run lint
+ \`\`\`
+
+ ESLint can be run with \`--fix\` to auto-fix some lint rule complaints:
+
+ \`\`\`shell
+ pnpm run lint --fix
+ \`\`\`
+
+ ## Testing
+
+ [Vitest](https://vitest.dev) is used for tests.
+ You can run it locally on the command-line:
+
+ \`\`\`shell
+ pnpm run test
+ \`\`\`
+
+ Add the \`--coverage\` flag to compute test coverage and place reports in the \`coverage/\` directory:
+
+ \`\`\`shell
+ pnpm run test --coverage
+ \`\`\`
+
+ Note that [console-fail-test](https://github.com/JoshuaKGoldberg/console-fail-test) is enabled for all test runs.
+ Calls to \`console.log\`, \`console.warn\`, and other console methods will cause a test to fail.
+
+ ### Debugging Tests
+
+ This repository includes a [VS Code launch configuration](https://code.visualstudio.com/docs/editor/debugging) for debugging unit tests.
+ To launch it, open a test file, then run _Debug Current Test File_ from the VS Code Debug panel (or press F5).
+
+ ## Type Checking
+
+ You should be able to see suggestions from [TypeScript](https://typescriptlang.org) in your editor for all open files.
+
+ However, it can be useful to run the TypeScript command-line (\`tsc\`) to type check all files in \`src/\`:
+
+ \`\`\`shell
+ pnpm tsc
+ \`\`\`
+
+ Add \`--watch\` to keep the type checker running in a watch mode that updates the display as you save files:
+
+ \`\`\`shell
+ pnpm tsc --watch
+ \`\`\`
+ "
+ `);
+ });
+});
diff --git a/src/steps/writing/creation/dotGitHub/createDevelopment.ts b/src/steps/writing/creation/dotGitHub/createDevelopment.ts
new file mode 100644
index 00000000..4cc16000
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createDevelopment.ts
@@ -0,0 +1,126 @@
+import { Options } from "../../../../shared/types.js";
+
+export function createDevelopment(options: Options) {
+ const lintLines = [
+ !options.excludeLintKnip &&
+ `- \`pnpm lint:knip\` ([knip](https://github.com/webpro/knip)): Detects unused files, dependencies, and code exports`,
+ !options.excludeLintMd &&
+ `- \`pnpm lint:md\` ([Markdownlint](https://github.com/DavidAnson/markdownlint)): Checks Markdown source files`,
+ !options.excludeLintPackageJson &&
+ `- \`pnpm lint:package-json\` ([npm-package-json-lint](https://npmpackagejsonlint.org/)): Lints the \`package.json\` file`,
+ !options.excludeLintPackages &&
+ `- \`pnpm lint:packages\` ([pnpm dedupe --check](https://pnpm.io/cli/dedupe)): Checks for unnecessarily duplicated packages in the \`pnpm-lock.yml\` file`,
+ !options.excludeLintSpelling &&
+ `- \`pnpm lint:spelling\` ([cspell](https://cspell.org)): Spell checks across all source files`,
+ ].filter(Boolean);
+
+ return `# Development
+
+After [forking the repo from GitHub](https://help.github.com/articles/fork-a-repo) and [installing pnpm](https://pnpm.io/installation):
+
+\`\`\`shell
+git clone https://github.com//${options.repository}
+cd ${options.repository}
+pnpm install
+\`\`\`
+
+> This repository includes a list of suggested VS Code extensions.
+> It's a good idea to use [VS Code](https://code.visualstudio.com) and accept its suggestion to install them, as they'll help with development.
+
+## Building
+
+Run [**tsup**](https://tsup.egoist.dev) locally to build source files from \`src/\` into output files in \`lib/\`:
+
+\`\`\`shell
+pnpm build
+\`\`\`
+
+Add \`--watch\` to run the builder in a watch mode that continuously cleans and recreates \`lib/\` as you save files:
+
+\`\`\`shell
+pnpm build --watch
+\`\`\`
+
+## Formatting
+
+[Prettier](https://prettier.io) is used to format code.
+It should be applied automatically when you save files in VS Code or make a Git commit.
+
+To manually reformat all files, you can run:
+
+\`\`\`shell
+pnpm format --write
+\`\`\`
+
+## Linting
+
+${
+ lintLines.length
+ ? [
+ `This package includes several forms of linting to enforce consistent code quality and styling.`,
+ `Each should be shown in VS Code, and can be run manually on the command-line:`,
+ ``,
+ `- \`pnpm lint\` ([ESLint](https://eslint.org) with [typescript-eslint](https://typescript-eslint.io)): Lints JavaScript and TypeScript source files`,
+ ...lintLines,
+ ``,
+ `Read the individual documentation for each linter to understand how it can be configured and used best.`,
+ ``,
+ `For example, ESLint can be run with \`--fix\` to auto-fix some lint rule complaints:`,
+ ].join("\n")
+ : `[ESLint](https://eslint.org) is used with with [typescript-eslint](https://typescript-eslint.io)) to lint JavaScript and TypeScript source files.
+You can run it locally on the command-line:
+
+\`\`\`shell
+pnpm run lint
+\`\`\`
+
+ESLint can be run with \`--fix\` to auto-fix some lint rule complaints:`
+}
+
+\`\`\`shell
+pnpm run lint --fix
+\`\`\`
+
+${
+ !options.excludeTests &&
+ `## Testing
+
+[Vitest](https://vitest.dev) is used for tests.
+You can run it locally on the command-line:
+
+\`\`\`shell
+pnpm run test
+\`\`\`
+
+Add the \`--coverage\` flag to compute test coverage and place reports in the \`coverage/\` directory:
+
+\`\`\`shell
+pnpm run test --coverage
+\`\`\`
+
+Note that [console-fail-test](https://github.com/JoshuaKGoldberg/console-fail-test) is enabled for all test runs.
+Calls to \`console.log\`, \`console.warn\`, and other console methods will cause a test to fail.
+
+### Debugging Tests
+
+This repository includes a [VS Code launch configuration](https://code.visualstudio.com/docs/editor/debugging) for debugging unit tests.
+To launch it, open a test file, then run _Debug Current Test File_ from the VS Code Debug panel (or press F5).
+`
+}
+## Type Checking
+
+You should be able to see suggestions from [TypeScript](https://typescriptlang.org) in your editor for all open files.
+
+However, it can be useful to run the TypeScript command-line (\`tsc\`) to type check all files in \`src/\`:
+
+\`\`\`shell
+pnpm tsc
+\`\`\`
+
+Add \`--watch\` to keep the type checker running in a watch mode that updates the display as you save files:
+
+\`\`\`shell
+pnpm tsc --watch
+\`\`\`
+`;
+}
diff --git a/src/steps/writing/creation/dotGitHub/createDotGitHubFiles.ts b/src/steps/writing/creation/dotGitHub/createDotGitHubFiles.ts
new file mode 100644
index 00000000..d9a2fb99
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createDotGitHubFiles.ts
@@ -0,0 +1,290 @@
+/* spellchecker: disable */
+import { Options } from "../../../../shared/types.js";
+import { formatJson } from "../formatters/formatJson.js";
+import { formatYaml } from "../formatters/formatYaml.js";
+import { createDevelopment } from "./createDevelopment.js";
+
+export async function createDotGitHubFiles(options: Options) {
+ return {
+ "CODE_OF_CONDUCT.md": `# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+- Demonstrating empathy and kindness toward other people
+- Being respectful of differing opinions, viewpoints, and experiences
+- Giving and gracefully accepting constructive feedback
+- Accepting responsibility and apologizing to those affected by our mistakes,
+and learning from the experience
+- Focusing on what is best not just for us as individuals, but for the overall
+community
+
+Examples of unacceptable behavior include:
+
+- The use of sexualized language or imagery, and sexual attention or advances of
+any kind
+- Trolling, insulting or derogatory comments, and personal or political attacks
+- Public or private harassment
+- Publishing others' private information, such as a physical or email address,
+without their explicit permission
+- Other conduct which could reasonably be considered inappropriate in a
+professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+${options.email.github}.
+All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][mozilla coc].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][faq]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[mozilla coc]: https://github.com/mozilla/diversity
+[faq]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
+`,
+ "CONTRIBUTING.md": `# Contributing
+
+Thanks for your interest in contributing to \`${options.repository}\`! 💖
+
+> After this page, see [DEVELOPMENT.md](./DEVELOPMENT.md) for local development instructions.
+
+## Code of Conduct
+
+This project contains a [Contributor Covenant code of conduct](./CODE_OF_CONDUCT.md) all contributors are expected to follow.
+
+## Reporting Issues
+
+Please do [report an issue on the issue tracker](https://github.com/${options.owner}/${options.repository}/issues/new/choose) if there's any bugfix, documentation improvement, or general enhancement you'd like to see in the repository! Please fully fill out all required fields in the most appropriate issue form.
+
+## Sending Contributions
+
+Sending your own changes as contribution is always appreciated!
+There are two steps involved:
+
+1. [Finding an Issue](#finding-an-issue)
+2. [Sending a Pull Request](#sending-a-pull-request)
+
+### Finding an Issue
+
+With the exception of very small typos, all changes to this repository generally need to correspond to an [open issue marked as \`accepting prs\` on the issue tracker](https://github.com/${options.owner}/${options.repository}/issues?q=is%3Aopen+is%3Aissue+label%3A%22accepting+prs%22).
+If this is your first time contributing, consider searching for [unassigned issues that also have the \`good first issue\` label](https://github.com/${options.owner}/${options.repository}/issues?q=is%3Aopen+is%3Aissue+label%3A%22accepting+prs%22+label%3A%22good+first+issue%22+no%3Aassignee).
+If the issue you'd like to fix isn't found on the issue, see [Reporting Issues](#reporting-issues) for filing your own (please do!).
+
+#### Issue Claiming
+
+We don't use any kind of issue claiming system.
+We've found in the past that they result in accidental ["licked cookie"](https://devblogs.microsoft.com/oldnewthing/20091201-00/?p=15843) situations where contributors claim an issue but run out of time or energy trying before sending a PR.
+
+If an issue has been marked as \`accepting prs\` and an open PR does not exist, feel free to send a PR.
+Please don't post comments asking for permission or stating you will work on an issue.
+
+### Sending a Pull Request
+
+Once you've identified an open issue accepting PRs that doesn't yet have a PR sent, you're free to send a pull request.
+Be sure to fill out the pull request template's requested information -- otherwise your PR will likely be closed.
+
+PRs are also expected to have a title that adheres to [conventional commits](https://www.conventionalcommits.org/en/v1.0.0).
+Only PR titles need to be in that format, not individual commits.
+Don't worry if you get this wrong: you can always change the PR title after sending it.
+Check [previously merged PRs](https://github.com/${options.owner}/${options.repository}/pulls?q=is%3Apr+is%3Amerged+-label%3Adependencies+) for reference.
+
+#### Draft PRs
+
+If you don't think your PR is ready for review, [set it as a draft](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#converting-a-pull-request-to-a-draft).
+Draft PRs won't be reviewed.
+
+#### Granular PRs
+
+Please keep pull requests single-purpose: in other words, don't attempt to solve multiple unrelated problems in one pull request.
+Send one PR per area of concern.
+Multi-purpose pull requests are harder and slower to review, block all changes from being merged until the whole pull request is reviewed, and are difficult to name well with semantic PR titles.
+
+#### Pull Request Reviews
+
+When a PR is not in draft, it's considered ready for review.
+Please don't manually \`@\` tag anybody to request review.
+A maintainer will look at it when they're next able to.
+
+PRs should have passing [GitHub status checks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks) before review is requested (unless there are explicit questions asked in the PR about any failures).
+
+#### Asking Questions
+
+If you need help and/or have a question, posting a comment in the PR is a great way to do so.
+There's no need to tag anybody individually.
+One of us will drop by and help when we can.
+
+Please post comments as [line comments](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#adding-line-comments-to-a-pull-request) when possible, so that they can be threaded.
+You can [resolve conversations](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#resolving-conversations) on your own when you feel they're resolved - no need to comment explicitly and/or wait for a maintainer.
+
+#### Requested Changes
+
+After a maintainer reviews your PR, they may request changes on it.
+Once you've made those changes, [re-request review on GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/about-pull-request-reviews#re-requesting-a-review).
+
+Please try not to force-push commits to PRs that have already been reviewed.
+Doing so makes it harder to review the changes.
+We squash merge all commits so there's no need to try to preserve Git history within a PR branch.
+
+Once you've addressed all our feedback by making code changes and/or started a followup discussion, [re-request review](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/about-pull-request-reviews#re-requesting-a-review) from each maintainer whose feedback you addressed.
+
+Once all feedback is addressed and the PR is approved, we'll ensure the branch is up to date with \`main\` and merge it for you.
+
+#### Post-Merge Recognition
+
+Once your PR is merged, if you haven't yet been added to the [_Contributors_ table in the README.md](../README.md#contributors) for its [type of contribution](https://allcontributors.org/docs/en/emoji-key "Allcontributors emoji key"), you should be soon.
+Please do ping the maintainer who merged your PR if that doesn't happen within 24 hours - it was likely an oversight on our end!
+
+## Emojis & Appreciation
+
+If you made it all the way to the end, bravo dear user, we love you.
+Please include your favorite emoji in the bottom of your issues and PRs to signal to us that you did in fact read this file and are trying to conform to it as best as possible.
+💖 is a good starter if you're not sure which to use.
+`,
+ "DEVELOPMENT.md": createDevelopment(options),
+ ...(options.funding && {
+ "FUNDING.yml": formatYaml({ github: options.funding }),
+ }),
+
+ "ISSUE_TEMPLATE.md": `
+
+
+
+
+
+## Overview
+
+...
+`,
+ "PULL_REQUEST_TEMPLATE.md": `
+
+## PR Checklist
+
+- [ ] Addresses an existing open issue: fixes #000
+- [ ] That issue was marked as [\`status: accepting prs\`](https://github.com/${options.owner}/${options.repository}/issues?q=is%3Aopen+is%3Aissue+label%3A%22status%3A+accepting+prs%22)
+- [ ] Steps in [CONTRIBUTING.md](https://github.com/${options.owner}/${options.repository}/blob/main/.github/CONTRIBUTING.md) were taken
+
+## Overview
+
+
+`,
+ "SECURITY.md": `# Security Policy
+
+We take all security vulnerabilities seriously.
+If you have a vulnerability or other security issues to disclose:
+
+- Thank you very much, please do!
+- Please send them to us by emailing \`${options.email.github}\`
+
+We appreciate your efforts and responsible disclosure and will make every effort to acknowledge your contributions.
+`,
+ ...(!options.excludeRenovate && {
+ "renovate.json": await formatJson({
+ $schema: "https://docs.renovatebot.com/renovate-schema.json",
+ automerge: true,
+ internalChecksFilter: "strict",
+ labels: ["dependencies"],
+ minimumReleaseAge: "3 days",
+ postUpdateOptions: ["pnpmDedupe"],
+ }),
+ }),
+ };
+}
diff --git a/src/steps/writing/creation/dotGitHub/createWorkflowFile.test.ts b/src/steps/writing/creation/dotGitHub/createWorkflowFile.test.ts
new file mode 100644
index 00000000..396a067e
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createWorkflowFile.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+
+import { createWorkflowFile } from "./createWorkflowFile.js";
+
+describe("createWorkflowFile", () => {
+ it("creates a workflow file when runs are provided", () => {
+ const actual = createWorkflowFile({
+ name: "Test Name",
+ runs: ["pnpm build"],
+ });
+
+ expect(actual).toBe(
+ `jobs:
+ test_name:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm build
+
+name: Test Name
+
+on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+`,
+ );
+ });
+});
diff --git a/src/steps/writing/creation/dotGitHub/createWorkflowFile.ts b/src/steps/writing/creation/dotGitHub/createWorkflowFile.ts
new file mode 100644
index 00000000..da7417d0
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createWorkflowFile.ts
@@ -0,0 +1,98 @@
+import { formatYaml } from "../formatters/formatYaml.js";
+
+interface WorkflowFileConcurrency {
+ "cancel-in-progress"?: boolean;
+ group: string;
+}
+
+interface WorkflowFileOn {
+ pull_request?:
+ | {
+ branches?: string | string[];
+ types?: string[];
+ }
+ | null
+ | string;
+ pull_request_target?: {
+ types: string[];
+ };
+ push?: {
+ branches: string[];
+ };
+ release?: {
+ types: string[];
+ };
+ workflow_dispatch?: null | string;
+}
+
+interface WorkflowFilePermissions {
+ contents?: string;
+ "id-token"?: string;
+ "pull-requests"?: string;
+}
+
+interface WorkflowFileStep {
+ env?: Record;
+ if?: string;
+ name?: string;
+ run?: string;
+ uses?: string;
+ with?: Record;
+}
+
+interface WorkflowFileOptionsBase {
+ concurrency?: WorkflowFileConcurrency;
+ name: string;
+ on?: WorkflowFileOn;
+ permissions?: WorkflowFilePermissions;
+}
+
+interface WorkflowFileOptionsRuns extends WorkflowFileOptionsBase {
+ runs: (WorkflowFileStep | string)[];
+}
+
+interface WorkflowFileOptionsSteps extends WorkflowFileOptionsBase {
+ steps: WorkflowFileStep[];
+}
+
+type WorkflowFileOptions = WorkflowFileOptionsRuns | WorkflowFileOptionsSteps;
+
+export function createWorkflowFile({
+ concurrency,
+ name,
+ on = {
+ pull_request: null,
+ push: {
+ branches: ["main"],
+ },
+ },
+ permissions,
+ ...options
+}: WorkflowFileOptions) {
+ return (
+ formatYaml({
+ concurrency,
+ jobs: {
+ [name.replaceAll(" ", "_").toLowerCase()]: {
+ "runs-on": "ubuntu-latest",
+ steps:
+ "runs" in options
+ ? [
+ { uses: "actions/checkout@v4" },
+ { uses: "./.github/actions/prepare" },
+ ...options.runs.map((run) => ({ run })),
+ ]
+ : options.steps,
+ },
+ },
+ name,
+ on,
+ permissions,
+ })
+ .replaceAll(/\n(\S)/g, "\n\n$1")
+ // https://github.com/nodeca/js-yaml/pull/515
+ .replaceAll(/: "\\n(.+)"/g, ": |\n$1")
+ .replaceAll("\\n", "\n")
+ .replaceAll("\\t", " ")
+ );
+}
diff --git a/src/steps/writing/creation/dotGitHub/createWorkflows.test.ts b/src/steps/writing/creation/dotGitHub/createWorkflows.test.ts
new file mode 100644
index 00000000..3a15093d
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createWorkflows.test.ts
@@ -0,0 +1,494 @@
+import { describe, expect, it } from "vitest";
+
+import { Options } from "../../../../shared/types.js";
+import { createWorkflows } from "./createWorkflows.js";
+
+const createOptions = (exclude: boolean) =>
+ ({
+ access: "public",
+ author: undefined,
+ base: "everything",
+ description: "Stub description.",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: exclude,
+ excludeCompliance: exclude,
+ excludeLintJson: exclude,
+ excludeLintKnip: exclude,
+ excludeLintMd: exclude,
+ excludeLintPackageJson: exclude,
+ excludeLintPackages: exclude,
+ excludeLintPerfectionist: exclude,
+ excludeLintSpelling: exclude,
+ excludeLintYml: exclude,
+ excludeReleases: exclude,
+ excludeRenovate: exclude,
+ excludeTests: exclude,
+ funding: undefined,
+ logo: undefined,
+ mode: "create",
+ owner: "StubOwner",
+ repository: "stub-repository",
+ title: "Stub Title",
+ }) satisfies Options;
+
+describe("createWorkflows", () => {
+ it("creates a full set of workflows when all excludes are disabled", () => {
+ const workflows = createWorkflows(createOptions(false));
+
+ expect(workflows).toMatchInlineSnapshot(`
+ {
+ "build.yml": "jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm build
+ - run: node ./lib/index.js
+
+ name: Build
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "compliance.yml": "jobs:
+ compliance:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: mtfoley/pr-compliance-action@main
+ with:
+ body-auto-close: false
+ ignore-authors: |-
+ allcontributors
+ allcontributors[bot]
+ renovate
+ renovate[bot]
+ ignore-team-members: false
+
+ name: Compliance
+
+ on:
+ pull_request:
+ branches:
+ - main
+ types:
+ - edited
+ - opened
+ - reopened
+ - synchronize
+
+ permissions:
+ pull-requests: write
+ ",
+ "contributors.yml": "jobs:
+ contributors:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: ./.github/actions/prepare
+ - env:
+ GITHUB_TOKEN: \${{ secrets.ACCESS_TOKEN }}
+ uses: JoshuaKGoldberg/all-contributors-auto-action@v0.3.2
+
+ name: Contributors
+
+ on:
+ push:
+ branches:
+ - main
+ ",
+ "lint-knip.yml": "jobs:
+ lint_knip:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint:knip
+
+ name: Lint Knip
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint-markdown.yml": "jobs:
+ lint_markdown:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint:md
+
+ name: Lint Markdown
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint-package-json.yml": "jobs:
+ lint_package_json:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint:package-json
+
+ name: Lint Package JSON
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint-packages.yml": "jobs:
+ lint_packages:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint:packages
+
+ name: Lint Packages
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint-spelling.yml": "jobs:
+ lint_spelling:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint:spelling
+
+ name: Lint spelling
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint.yml": "jobs:
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint
+
+ name: Lint
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "post-release.yml": "jobs:
+ post_release:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - run: echo \\"npm_version=$(npm pkg get version | tr -d '\\"')\\" >> \\"$GITHUB_ENV\\"
+ - uses: apexskier/github-release-commenter@v1
+ with:
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
+ comment-template: |
+ :tada: This is included in version {release_link} :tada:
+
+ The release is available on:
+
+ * [GitHub releases](https://github.com/StubOwner/stub-repository/releases/tag/{release_tag})
+ * [npm package (@latest dist-tag)](https://www.npmjs.com/package/stub-repository/v/\${{ env.npm_version }})
+
+ Cheers! 📦🚀
+
+ name: Post Release
+
+ on:
+ release:
+ types:
+ - published
+ ",
+ "pr-review-requested.yml": "jobs:
+ pr_review_requested:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions-ecosystem/action-remove-labels@v1
+ with:
+ labels: 'status: waiting for author'
+ - if: failure()
+ run: |
+ echo \\"Don't worry if the previous step failed.\\"
+ echo \\"See https://github.com/actions-ecosystem/action-remove-labels/issues/221.\\"
+
+ name: PR Review Requested
+
+ on:
+ pull_request_target:
+ types:
+ - review_requested
+
+ permissions:
+ pull-requests: write
+ ",
+ "prettier.yml": "jobs:
+ prettier:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm format --list-different
+
+ name: Prettier
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "release.yml": "concurrency:
+ group: \${{ github.workflow }}
+
+ jobs:
+ release:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ ref: main
+ - uses: ./.github/actions/prepare
+ - run: pnpm build
+ - run: git config user.name \\"\${GITHUB_ACTOR}\\"
+ - run: git config user.email \\"\${GITHUB_ACTOR}@users.noreply.github.com\\"
+ - env:
+ NPM_TOKEN: \${{ secrets.NPM_TOKEN }}
+ run: npm config set //registry.npmjs.org/:_authToken $NPM_TOKEN
+ - name: Delete branch protection on main
+ uses: actions/github-script@v6.4.1
+ with:
+ github-token: \${{ secrets.ACCESS_TOKEN }}
+ script: |
+ try {
+ await github.request(
+ \`DELETE /repos/StubOwner/stub-repository/branches/main/protection\`,
+ );
+ } catch (error) {
+ if (!error.message?.includes?.(\\"Branch not protected\\")) {
+ throw error;
+ }
+ }
+ - env:
+ GITHUB_TOKEN: \${{ secrets.ACCESS_TOKEN }}
+ run: |
+ if pnpm run should-semantic-release ; then
+ pnpm release-it --verbose
+ fi
+ - if: always()
+ name: Recreate branch protection on main
+ uses: actions/github-script@v6.4.1
+ with:
+ github-token: \${{ secrets.ACCESS_TOKEN }}
+ script: |
+ github.request(
+ \`PUT /repos/StubOwner/stub-repository/branches/main/protection\`,
+ {
+ allow_deletions: false,
+ allow_force_pushes: true,
+ allow_fork_pushes: false,
+ allow_fork_syncing: true,
+ block_creations: false,
+ branch: \\"main\\",
+ enforce_admins: false,
+ owner: \\"StubOwner\\",
+ repo: \\"stub-repository\\",
+ required_conversation_resolution: true,
+ required_linear_history: false,
+ required_pull_request_reviews: null,
+ required_status_checks: {
+ checks: [
+ { context: \\"build\\" },
+ { context: \\"compliance\\" },
+ { context: \\"lint\\" },
+ { context: \\"lint_knip\\" },
+ { context: \\"lint_markdown\\" },
+ { context: \\"lint_package_json\\" },
+ { context: \\"lint_packages\\" },
+ { context: \\"lint_spelling\\" },
+ { context: \\"prettier\\" },
+ { context: \\"test\\" },
+ ],
+ strict: false,
+ },
+ restrictions: null,
+ }
+ );
+
+ name: Release
+
+ on:
+ push:
+ branches:
+ - main
+
+ permissions:
+ contents: write
+ id-token: write
+ ",
+ "tsc.yml": "jobs:
+ type_check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm tsc
+
+ name: Type Check
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ }
+ `);
+ });
+
+ it("creates a minimal set of workflows when all options are enabled", () => {
+ const workflows = createWorkflows(createOptions(true));
+
+ expect(workflows).toMatchInlineSnapshot(`
+ {
+ "build.yml": "jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm build
+ - run: node ./lib/index.js
+
+ name: Build
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "lint.yml": "jobs:
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm lint
+
+ name: Lint
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "pr-review-requested.yml": "jobs:
+ pr_review_requested:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions-ecosystem/action-remove-labels@v1
+ with:
+ labels: 'status: waiting for author'
+ - if: failure()
+ run: |
+ echo \\"Don't worry if the previous step failed.\\"
+ echo \\"See https://github.com/actions-ecosystem/action-remove-labels/issues/221.\\"
+
+ name: PR Review Requested
+
+ on:
+ pull_request_target:
+ types:
+ - review_requested
+
+ permissions:
+ pull-requests: write
+ ",
+ "prettier.yml": "jobs:
+ prettier:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm format --list-different
+
+ name: Prettier
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "test.yml": "jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm run test --coverage
+ - name: Codecov
+ uses: codecov/codecov-action@v3
+ with:
+ github-token: \${{ secrets.GITHUB_TOKEN }}
+
+ name: Test
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ "tsc.yml": "jobs:
+ type_check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: ./.github/actions/prepare
+ - run: pnpm tsc
+
+ name: Type Check
+
+ on:
+ pull_request: ~
+ push:
+ branches:
+ - main
+ ",
+ }
+ `);
+ });
+});
diff --git a/src/steps/writing/creation/dotGitHub/createWorkflows.ts b/src/steps/writing/creation/dotGitHub/createWorkflows.ts
new file mode 100644
index 00000000..605c4506
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/createWorkflows.ts
@@ -0,0 +1,285 @@
+/* spellchecker: disable */
+import { Options } from "../../../../shared/types.js";
+import { createWorkflowFile } from "./createWorkflowFile.js";
+
+export function createWorkflows(options: Options) {
+ return {
+ "build.yml": createWorkflowFile({
+ name: "Build",
+ runs: ["pnpm build", "node ./lib/index.js"],
+ }),
+ "pr-review-requested.yml": createWorkflowFile({
+ name: "PR Review Requested",
+ on: {
+ pull_request_target: {
+ types: ["review_requested"],
+ },
+ },
+ permissions: {
+ "pull-requests": "write",
+ },
+ steps: [
+ {
+ uses: "actions-ecosystem/action-remove-labels@v1",
+ with: {
+ labels: "status: waiting for author",
+ },
+ },
+ {
+ if: "failure()",
+ run: 'echo "Don\'t worry if the previous step failed."\necho "See https://github.com/actions-ecosystem/action-remove-labels/issues/221."\n',
+ },
+ ],
+ }),
+ "prettier.yml": createWorkflowFile({
+ name: "Prettier",
+ runs: ["pnpm format --list-different"],
+ }),
+ "tsc.yml": createWorkflowFile({
+ name: "Type Check",
+ runs: ["pnpm tsc"],
+ }),
+ ...(!options.excludeCompliance && {
+ "compliance.yml": createWorkflowFile({
+ name: "Compliance",
+ on: {
+ pull_request: {
+ branches: ["main"],
+ types: ["edited", "opened", "reopened", "synchronize"],
+ },
+ },
+ permissions: {
+ "pull-requests": "write",
+ },
+ steps: [
+ {
+ uses: "mtfoley/pr-compliance-action@main",
+ with: {
+ "body-auto-close": false,
+ "ignore-authors":
+ [
+ ...(options.excludeAllContributors
+ ? []
+ : ["allcontributors", "allcontributors[bot]"]),
+ ...(options.excludeRenovate
+ ? []
+ : ["renovate", "renovate[bot]"]),
+ ].join("\n") || undefined,
+ "ignore-team-members": false,
+ },
+ },
+ ],
+ }),
+ }),
+ ...(!options.excludeAllContributors && {
+ "contributors.yml": createWorkflowFile({
+ name: "Contributors",
+ on: {
+ push: {
+ branches: ["main"],
+ },
+ },
+ steps: [
+ { uses: "actions/checkout@v4", with: { "fetch-depth": 0 } },
+ { uses: "./.github/actions/prepare" },
+ {
+ env: { GITHUB_TOKEN: "${{ secrets.ACCESS_TOKEN }}" },
+ uses: `JoshuaKGoldberg/all-contributors-auto-action@v0.3.2`,
+ },
+ ],
+ }),
+ }),
+ "lint.yml": createWorkflowFile({
+ name: "Lint",
+ runs: ["pnpm lint"],
+ }),
+ ...(!options.excludeLintKnip && {
+ "lint-knip.yml": createWorkflowFile({
+ name: "Lint Knip",
+ runs: ["pnpm lint:knip"],
+ }),
+ }),
+ ...(!options.excludeLintMd && {
+ "lint-markdown.yml": createWorkflowFile({
+ name: "Lint Markdown",
+ runs: ["pnpm lint:md"],
+ }),
+ }),
+ ...(!options.excludeLintPackageJson && {
+ "lint-package-json.yml": createWorkflowFile({
+ name: "Lint Package JSON",
+ runs: ["pnpm lint:package-json"],
+ }),
+ }),
+ ...(!options.excludeLintPackages && {
+ "lint-packages.yml": createWorkflowFile({
+ name: "Lint Packages",
+ runs: ["pnpm lint:packages"],
+ }),
+ }),
+ ...(!options.excludeLintSpelling && {
+ "lint-spelling.yml": createWorkflowFile({
+ name: "Lint spelling",
+ runs: ["pnpm lint:spelling"],
+ }),
+ }),
+ ...(!options.excludeReleases && {
+ "post-release.yml": createWorkflowFile({
+ name: "Post Release",
+ on: {
+ release: {
+ types: ["published"],
+ },
+ },
+ steps: [
+ { uses: "actions/checkout@v4", with: { "fetch-depth": 0 } },
+ {
+ run: `echo "npm_version=$(npm pkg get version | tr -d '"')" >> "$GITHUB_ENV"`,
+ },
+ {
+ uses: "apexskier/github-release-commenter@v1",
+ with: {
+ GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}",
+ "comment-template": `
+ :tada: This is included in version {release_link} :tada:
+
+ The release is available on:
+
+ * [GitHub releases](https://github.com/${options.owner}/${options.repository}/releases/tag/{release_tag})
+ * [npm package (@latest dist-tag)](https://www.npmjs.com/package/${options.repository}/v/\${{ env.npm_version }})
+
+ Cheers! 📦🚀
+ `,
+ },
+ },
+ ],
+ }),
+ "release.yml": createWorkflowFile({
+ concurrency: {
+ group: "${{ github.workflow }}",
+ },
+ name: "Release",
+ on: {
+ push: {
+ branches: ["main"],
+ },
+ },
+ permissions: {
+ contents: "write",
+ "id-token": "write",
+ },
+ steps: [
+ {
+ uses: "actions/checkout@v4",
+ with: {
+ "fetch-depth": 0,
+ ref: "main",
+ },
+ },
+ {
+ uses: "./.github/actions/prepare",
+ },
+ {
+ run: "pnpm build",
+ },
+ {
+ run: 'git config user.name "${GITHUB_ACTOR}"',
+ },
+ {
+ run: 'git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"',
+ },
+ {
+ env: {
+ NPM_TOKEN: "${{ secrets.NPM_TOKEN }}",
+ },
+ run: "npm config set //registry.npmjs.org/:_authToken $NPM_TOKEN",
+ },
+ {
+ name: "Delete branch protection on main",
+ uses: "actions/github-script@v6.4.1",
+ with: {
+ "github-token": "${{ secrets.ACCESS_TOKEN }}",
+ script: `
+ try {
+ await github.request(
+ \`DELETE /repos/${options.owner}/${options.repository}/branches/main/protection\`,
+ );
+ } catch (error) {
+ if (!error.message?.includes?.("Branch not protected")) {
+ throw error;
+ }
+ }`,
+ },
+ },
+ {
+ env: {
+ GITHUB_TOKEN: "${{ secrets.ACCESS_TOKEN }}",
+ },
+ run: `
+ if pnpm run should-semantic-release ; then
+ pnpm release-it --verbose
+ fi`,
+ },
+ {
+ if: "always()",
+ name: "Recreate branch protection on main",
+ uses: "actions/github-script@v6.4.1",
+ with: {
+ "github-token": "${{ secrets.ACCESS_TOKEN }}",
+ script: `
+ github.request(
+ \`PUT /repos/${options.owner}/${options.repository}/branches/main/protection\`,
+ {
+ allow_deletions: false,
+ allow_force_pushes: true,
+ allow_fork_pushes: false,
+ allow_fork_syncing: true,
+ block_creations: false,
+ branch: "main",
+ enforce_admins: false,
+ owner: "${options.owner}",
+ repo: "${options.repository}",
+ required_conversation_resolution: true,
+ required_linear_history: false,
+ required_pull_request_reviews: null,
+ required_status_checks: {
+ checks: [
+ { context: "build" },
+ { context: "compliance" },
+ { context: "lint" },
+ { context: "lint_knip" },
+ { context: "lint_markdown" },
+ { context: "lint_package_json" },
+ { context: "lint_packages" },
+ { context: "lint_spelling" },
+ { context: "prettier" },
+ { context: "test" },
+ ],
+ strict: false,
+ },
+ restrictions: null,
+ }
+ );
+ `,
+ },
+ },
+ ],
+ }),
+ }),
+ ...(options.excludeTests && {
+ "test.yml": createWorkflowFile({
+ name: "Test",
+ steps: [
+ { uses: "actions/checkout@v4" },
+ { uses: "./.github/actions/prepare" },
+ { run: "pnpm run test --coverage" },
+ {
+ name: "Codecov",
+ uses: "codecov/codecov-action@v3",
+ with: { "github-token": "${{ secrets.GITHUB_TOKEN }}" },
+ },
+ ],
+ }),
+ }),
+ };
+}
diff --git a/src/steps/writing/creation/dotGitHub/index.ts b/src/steps/writing/creation/dotGitHub/index.ts
new file mode 100644
index 00000000..876e8f63
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/index.ts
@@ -0,0 +1,14 @@
+import { Options } from "../../../../shared/types.js";
+import { createDotGitHubActions } from "./actions.js";
+import { createDotGitHubFiles } from "./createDotGitHubFiles.js";
+import { createWorkflows } from "./createWorkflows.js";
+import { createDotGitHubIssueTemplate } from "./issueTemplate.js";
+
+export async function createDotGitHub(options: Options) {
+ return {
+ ISSUE_TEMPLATE: createDotGitHubIssueTemplate(options),
+ actions: createDotGitHubActions(),
+ workflows: createWorkflows(options),
+ ...(await createDotGitHubFiles(options)),
+ };
+}
diff --git a/src/steps/writing/creation/dotGitHub/issueTemplate.ts b/src/steps/writing/creation/dotGitHub/issueTemplate.ts
new file mode 100644
index 00000000..a034aec8
--- /dev/null
+++ b/src/steps/writing/creation/dotGitHub/issueTemplate.ts
@@ -0,0 +1,210 @@
+import { Options } from "../../../../shared/types.js";
+import { formatYaml } from "../formatters/formatYaml.js";
+
+export function createDotGitHubIssueTemplate({
+ owner,
+ repository,
+}: Pick) {
+ return {
+ "01-bug.yml": formatYaml({
+ body: [
+ {
+ attributes: {
+ description:
+ "If any of these required steps are not taken, we may not be able to review your issue. Help us to help you!",
+ label: "Bug Report Checklist",
+ options: [
+ {
+ label: "I have tried restarting my IDE and the issue persists.",
+ required: true,
+ },
+ {
+ label:
+ "I have pulled the latest `main` branch of the repository.",
+ required: true,
+ },
+ {
+ label: `I have [searched for related issues](https://github.com/${owner}/${repository}/issues?q=is%3Aissue) and found none that matched my issue.`,
+ required: true,
+ },
+ ],
+ },
+ type: "checkboxes",
+ },
+ {
+ attributes: {
+ description: "What did you expect to happen?",
+ label: "Expected",
+ },
+ type: "textarea",
+ validations: {
+ required: true,
+ },
+ },
+ {
+ attributes: {
+ description: "What happened instead?",
+ label: "Actual",
+ },
+ type: "textarea",
+ validations: {
+ required: true,
+ },
+ },
+ {
+ attributes: {
+ description: "Any additional info you'd like to provide.",
+ label: "Additional Info",
+ },
+ type: "textarea",
+ },
+ ],
+ description: "Report a bug trying to run the code",
+ labels: ["type: bug"],
+ name: "🐛 Bug",
+ title: "🐛 Bug: ",
+ }),
+ "02-documentation.yml": formatYaml({
+ body: [
+ {
+ attributes: {
+ description:
+ "If any of these required steps are not taken, we may not be able to review your issue. Help us to help you!",
+ label: "Bug Report Checklist",
+ options: [
+ {
+ label:
+ "I have pulled the latest `main` branch of the repository.",
+ required: true,
+ },
+ {
+ label: `I have [searched for related issues](https://github.com/${owner}/${repository}/issues?q=is%3Aissue) and found none that matched my issue.`,
+ required: true,
+ },
+ ],
+ },
+ type: "checkboxes",
+ },
+ {
+ attributes: {
+ description: "What would you like to report?",
+ label: "Overview",
+ },
+ type: "textarea",
+ validations: {
+ required: true,
+ },
+ },
+ {
+ attributes: {
+ description: "Any additional info you'd like to provide.",
+ label: "Additional Info",
+ },
+ type: "textarea",
+ },
+ ],
+ description: "Report a typo or missing area of documentation",
+ labels: ["area: documentation"],
+ name: "📝 Documentation",
+ title: "📝 Documentation: ",
+ }),
+ "03-feature.yml": formatYaml({
+ body: [
+ {
+ attributes: {
+ description:
+ "If any of these required steps are not taken, we may not be able to review your issue. Help us to help you!",
+ label: "Bug Report Checklist",
+ options: [
+ {
+ label: "I have tried restarting my IDE and the issue persists.",
+ required: true,
+ },
+ {
+ label:
+ "I have pulled the latest `main` branch of the repository.",
+ required: true,
+ },
+ {
+ label: `I have [searched for related issues](https://github.com/${owner}/${repository}/issues?q=is%3Aissue) and found none that matched my issue.`,
+ required: true,
+ },
+ ],
+ },
+ type: "checkboxes",
+ },
+ {
+ attributes: {
+ description: "What did you expect to be able to do?",
+ label: "Overview",
+ },
+ type: "textarea",
+ validations: {
+ required: true,
+ },
+ },
+ {
+ attributes: {
+ description: "Any additional info you'd like to provide.",
+ label: "Additional Info",
+ },
+ type: "textarea",
+ },
+ ],
+ description:
+ "Request that a new feature be added or an existing feature improved",
+ labels: ["type: feature"],
+ name: "🚀 Feature",
+ title: "🚀 Feature: ",
+ }),
+ "04-tooling.yml": formatYaml({
+ body: [
+ {
+ attributes: {
+ description:
+ "If any of these required steps are not taken, we may not be able to review your issue. Help us to help you!",
+ label: "Bug Report Checklist",
+ options: [
+ {
+ label: "I have tried restarting my IDE and the issue persists.",
+ required: true,
+ },
+ {
+ label:
+ "I have pulled the latest `main` branch of the repository.",
+ required: true,
+ },
+ {
+ label: `I have [searched for related issues](https://github.com/${owner}/${repository}/issues?q=is%3Aissue) and found none that matched my issue.`,
+ required: true,
+ },
+ ],
+ },
+ type: "checkboxes",
+ },
+ {
+ attributes: {
+ description: "What did you expect to be able to do?",
+ label: "Overview",
+ },
+ type: "textarea",
+ validations: {
+ required: true,
+ },
+ },
+ {
+ attributes: {
+ description: "Any additional info you'd like to provide.",
+ label: "Additional Info",
+ },
+ type: "textarea",
+ },
+ ],
+ description:
+ "Report a bug or request an enhancement in repository tooling",
+ labels: ["area: tooling"],
+ name: "🛠 Tooling",
+ title: "🛠 Tooling: ",
+ }),
+ };
+}
diff --git a/src/steps/writing/creation/dotHusky.ts b/src/steps/writing/creation/dotHusky.ts
new file mode 100644
index 00000000..b3484d7e
--- /dev/null
+++ b/src/steps/writing/creation/dotHusky.ts
@@ -0,0 +1,12 @@
+import { formatIgnoreFile } from "./formatters/formatIgnoreFile.js";
+
+export function createDotHusky() {
+ return {
+ ".gitignore": formatIgnoreFile(["_"]),
+ "pre-commit": formatIgnoreFile([
+ `#!/bin/sh`,
+ `. "$(dirname "$0")/_/husky.sh"`,
+ "npx lint-staged",
+ ]),
+ };
+}
diff --git a/src/steps/writing/creation/dotVSCode.ts b/src/steps/writing/creation/dotVSCode.ts
new file mode 100644
index 00000000..f63eb893
--- /dev/null
+++ b/src/steps/writing/creation/dotVSCode.ts
@@ -0,0 +1,54 @@
+import { Options } from "../../../shared/types.js";
+import { formatJson } from "./formatters/formatJson.js";
+
+/* spellchecker: disable */
+export async function createDotVSCode(options: Options) {
+ return {
+ "extensions.json": await formatJson({
+ recommendations: [
+ "DavidAnson.vscode-markdownlint",
+ "dbaeumer.vscode-eslint",
+ "esbenp.prettier-vscode",
+ !options.excludeLintSpelling && "streetsidesoftware.code-spell-checker",
+ ].filter(Boolean),
+ }),
+ ...(!options.excludeTests && {
+ "launch.json": await formatJson({
+ configurations: [
+ {
+ args: ["run", "${relativeFile}"],
+ autoAttachChildProcesses: true,
+ console: "integratedTerminal",
+ name: "Debug Current Test File",
+ program: "${workspaceRoot}/node_modules/vitest/vitest.mjs",
+ request: "launch",
+ skipFiles: ["/**", "**/node_modules/**"],
+ smartStep: true,
+ type: "node",
+ },
+ ],
+ version: "0.2.0",
+ }),
+ }),
+ "settings.json": await formatJson({
+ "editor.codeActionsOnSave": {
+ "source.fixAll.eslint": true,
+ },
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
+ "editor.formatOnSave": true,
+ "editor.rulers": [80],
+ "eslint.probe": [
+ "javascript",
+ "javascriptreact",
+ "json",
+ "jsonc",
+ "markdown",
+ "typescript",
+ "typescriptreact",
+ "yaml",
+ ],
+ "eslint.rules.customizations": [{ rule: "*", severity: "warn" }],
+ "typescript.tsdk": "node_modules/typescript/lib",
+ }),
+ };
+}
diff --git a/src/steps/writing/creation/formatters/formatIgnoreFile.ts b/src/steps/writing/creation/formatters/formatIgnoreFile.ts
new file mode 100644
index 00000000..f4a18355
--- /dev/null
+++ b/src/steps/writing/creation/formatters/formatIgnoreFile.ts
@@ -0,0 +1,3 @@
+export function formatIgnoreFile(lines: string[]) {
+ return [...lines, ""].join("\n");
+}
diff --git a/src/steps/writing/creation/formatters/formatJson.test.ts b/src/steps/writing/creation/formatters/formatJson.test.ts
new file mode 100644
index 00000000..0b01d8a5
--- /dev/null
+++ b/src/steps/writing/creation/formatters/formatJson.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+
+import { formatJson } from "./formatJson.js";
+
+describe("formatJson", () => {
+ it("removes undefined values", async () => {
+ const actual = await formatJson({ empty: undefined, exists: true });
+
+ expect(actual).toMatchInlineSnapshot(`
+ "{ \\"exists\\": true }
+ "
+ `);
+ });
+});
diff --git a/src/steps/writing/creation/formatters/formatJson.ts b/src/steps/writing/creation/formatters/formatJson.ts
new file mode 100644
index 00000000..d80b66ce
--- /dev/null
+++ b/src/steps/writing/creation/formatters/formatJson.ts
@@ -0,0 +1,14 @@
+import prettier from "prettier";
+
+export async function formatJson(value: object) {
+ return await prettier.format(
+ JSON.stringify(
+ Object.fromEntries(
+ Object.entries(value).filter((entry) => entry[1] !== undefined),
+ ),
+ ),
+ {
+ parser: "json",
+ },
+ );
+}
diff --git a/src/steps/writing/creation/formatters/formatTypeScript.ts b/src/steps/writing/creation/formatters/formatTypeScript.ts
new file mode 100644
index 00000000..e18daea6
--- /dev/null
+++ b/src/steps/writing/creation/formatters/formatTypeScript.ts
@@ -0,0 +1,5 @@
+import prettier from "prettier";
+
+export async function formatTypeScript(value: string) {
+ return await prettier.format(value, { parser: "typescript" });
+}
diff --git a/src/steps/writing/creation/formatters/formatYaml.ts b/src/steps/writing/creation/formatters/formatYaml.ts
new file mode 100644
index 00000000..cbfd753c
--- /dev/null
+++ b/src/steps/writing/creation/formatters/formatYaml.ts
@@ -0,0 +1,26 @@
+import jsYaml from "js-yaml";
+
+const options: jsYaml.DumpOptions = {
+ lineWidth: -1,
+ noCompatMode: true,
+ // https://github.com/nodeca/js-yaml/pull/515
+ replacer(_, value: unknown) {
+ if (typeof value !== "string" || !value.includes("\n\t\t")) {
+ return value;
+ }
+
+ return value
+ .replaceAll(": |-\n", ": |\n")
+ .replaceAll("\n\t \t\t\t", "")
+
+ .replaceAll(/\n\t\t\t\t\t\t$/g, "");
+ },
+ sortKeys: true,
+ styles: {
+ "!!null": "canonical",
+ },
+};
+
+export function formatYaml(value: unknown) {
+ return jsYaml.dump(value, options).replaceAll(`\\"`, `"`);
+}
diff --git a/src/steps/writing/creation/index.ts b/src/steps/writing/creation/index.ts
new file mode 100644
index 00000000..897e6b35
--- /dev/null
+++ b/src/steps/writing/creation/index.ts
@@ -0,0 +1,17 @@
+import { Options } from "../../../shared/types.js";
+import { Structure } from "../types.js";
+import { createDotGitHub } from "./dotGitHub/index.js";
+import { createDotHusky } from "./dotHusky.js";
+import { createDotVSCode } from "./dotVSCode.js";
+import { createRootFiles } from "./rootFiles.js";
+import { createSrc } from "./src.js";
+
+export async function createStructure(options: Options): Promise {
+ return {
+ ".github": await createDotGitHub(options),
+ ".husky": createDotHusky(),
+ ".vscode": await createDotVSCode(options),
+ ...(options.mode !== "migrate" && { src: await createSrc(options) }),
+ ...(await createRootFiles(options)),
+ };
+}
diff --git a/src/steps/writing/creation/rootFiles.ts b/src/steps/writing/creation/rootFiles.ts
new file mode 100644
index 00000000..427755f4
--- /dev/null
+++ b/src/steps/writing/creation/rootFiles.ts
@@ -0,0 +1,208 @@
+import { Options } from "../../../shared/types.js";
+import { createESLintRC } from "./createESLintRC.js";
+import { formatIgnoreFile } from "./formatters/formatIgnoreFile.js";
+import { formatJson } from "./formatters/formatJson.js";
+import { formatTypeScript } from "./formatters/formatTypeScript.js";
+import { writeAllContributorsRC } from "./writeAllContributorsRC.js";
+import { writePackageJson } from "./writePackageJson.js";
+
+export async function createRootFiles(options: Options) {
+ return {
+ ".all-contributorsrc": await writeAllContributorsRC(options),
+ ".eslintignore": formatIgnoreFile(
+ [
+ "!.*",
+ ...(options.excludeTests ? [] : ["coverage"]),
+ "lib",
+ "node_modules",
+ "pnpm-lock.yaml",
+ ].filter(Boolean),
+ ),
+ ".eslintrc.cjs": await createESLintRC(options),
+ ".gitignore": formatIgnoreFile([
+ ...(options.excludeTests ? [] : ["coverage/"]),
+ "lib/",
+ "node_modules/",
+ ]),
+ ...(!options.excludeLintMd && {
+ ".markdownlint.json": await formatJson({
+ extends: "markdownlint/style/prettier",
+ "first-line-h1": false,
+ "no-inline-html": false,
+ }),
+ ".markdownlintignore": formatIgnoreFile([
+ ".github/CODE_OF_CONDUCT.md",
+ "CHANGELOG.md",
+ "lib/",
+ "node_modules/",
+ ]),
+ }),
+ ...(!options.excludeLintPackageJson && {
+ ".npmpackagejsonlintrc.json": await formatJson({
+ extends: "npm-package-json-lint-config-default",
+ rules: {
+ "require-description": "error",
+ "require-license": "error",
+ },
+ }),
+ }),
+ ".nvmrc": `18.18.0\n`,
+ ".prettierignore": formatIgnoreFile([
+ ...(options.excludeAllContributors ? [] : [".all-contributorsrc"]),
+ ...(options.excludeTests ? [] : ["coverage/"]),
+ "lib/",
+ "pnpm-lock.yaml",
+ ]),
+ ".prettierrc": await formatJson({
+ $schema: "http://json.schemastore.org/prettierrc",
+ overrides: [
+ {
+ files: ".*rc",
+ options: { parser: "json" },
+ },
+ {
+ files: ".nvmrc",
+ options: { parser: "yaml" },
+ },
+ ],
+ plugins: ["prettier-plugin-curly", "prettier-plugin-packagejson"],
+ useTabs: true,
+ }),
+ ...(!options.excludeReleases && {
+ ".release-it.json": await formatJson({
+ git: {
+ commitMessage: "chore: release v${version}",
+ requireCommits: true,
+ },
+ github: {
+ autoGenerate: true,
+ release: true,
+ releaseName: "v${version}",
+ },
+ npm: {
+ publishArgs: [`--access ${options.access}`, "--provenance"],
+ },
+ plugins: {
+ "@release-it/conventional-changelog": {
+ infile: "CHANGELOG.md",
+ preset: "angular",
+ },
+ },
+ }),
+ }),
+ "LICENSE.md": `# MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+`,
+ ...(!options.excludeLintSpelling && {
+ "cspell.json": await formatJson({
+ dictionaries: ["typescript"],
+ ignorePaths: [
+ ".github",
+ "CHANGELOG.md",
+ ...(options.excludeTests ? [] : ["coverage"]),
+ "lib",
+ "node_modules",
+ "pnpm-lock.yaml",
+ ],
+ words: [
+ "Codecov",
+ "codespace",
+ "commitlint",
+ "contributorsrc",
+ "conventionalcommits",
+ ...(options.excludeLintKnip ? [] : ["knip"]),
+ "lcov",
+ "markdownlintignore",
+ "npmpackagejsonlintrc",
+ "outro",
+ "packagejson",
+ "tsup",
+ "quickstart",
+ "wontfix",
+ ].sort(),
+ }),
+ }),
+ ...(!options.excludeLintKnip && {
+ "knip.jsonc": await formatJson({
+ $schema: "https://unpkg.com/knip@latest/schema.json",
+ entry: ["src/index.ts!"],
+ ignoreExportsUsedInFile: {
+ interface: true,
+ type: true,
+ },
+ project: ["src/**/*.ts!"],
+ }),
+ }),
+ "package.json": await writePackageJson(options),
+ "tsconfig.eslint.json": await formatJson({
+ extends: "./tsconfig.json",
+ include: ["."],
+ }),
+ "tsconfig.json": await formatJson({
+ compilerOptions: {
+ declaration: true,
+ declarationMap: true,
+ esModuleInterop: true,
+ module: "NodeNext",
+ moduleResolution: "NodeNext",
+ noEmit: true,
+ outDir: "lib",
+ resolveJsonModule: true,
+ skipLibCheck: true,
+ sourceMap: true,
+ strict: true,
+ target: "ES2022",
+ },
+ include: ["src"],
+ }),
+ "tsup.config.ts":
+ await formatTypeScript(`import { defineConfig } from "tsup";
+
+ export default defineConfig({
+ bundle: false,
+ clean: true,
+ dts: true,
+ entry: ["src/**/*.ts"${options.excludeTests ? "" : `, "!src/**/*.test.*"`}],
+ format: "esm",
+ outDir: "lib",
+ sourcemap: true,
+ });
+ `),
+ ...(!options.excludeTests && {
+ "vitest.config.ts": `import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ clearMocks: true,
+ coverage: {
+ all: true,
+ exclude: ["lib"],
+ include: ["src"],
+ reporter: ["html", "lcov"],
+ },
+ exclude: ["lib", "node_modules"],
+ setupFiles: ["console-fail-test/setup"],
+ },
+});
+`,
+ }),
+ };
+}
diff --git a/src/steps/writing/creation/src.ts b/src/steps/writing/creation/src.ts
new file mode 100644
index 00000000..895d44df
--- /dev/null
+++ b/src/steps/writing/creation/src.ts
@@ -0,0 +1,88 @@
+import { Options } from "../../../shared/types.js";
+import { formatTypeScript } from "./formatters/formatTypeScript.js";
+
+export async function createSrc(options: Options) {
+ return {
+ ...(!options.excludeTests && {
+ "greet.test.ts": await formatTypeScript(
+ `
+ import { describe, expect, it, vi } from "vitest";
+
+ import { greet } from "./greet.js";
+
+ const message = "Yay, testing!";
+
+ describe("greet", () => {
+ it("logs to the console once when message is provided as a string", () => {
+ const logger = vi.spyOn(console, "log").mockImplementation(() => undefined);
+
+ greet(message);
+
+ expect(logger).toHaveBeenCalledWith(message);
+ expect(logger).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs to the console once when message is provided as an object", () => {
+ const logger = vi.spyOn(console, "log").mockImplementation(() => undefined);
+
+ greet({ message });
+
+ expect(logger).toHaveBeenCalledWith(message);
+ expect(logger).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs once when times is not provided in an object", () => {
+ const logger = vi.fn();
+
+ greet({ logger, message });
+
+ expect(logger).toHaveBeenCalledWith(message);
+ expect(logger).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs a specified number of times when times is provided", () => {
+ const logger = vi.fn();
+ const times = 7;
+
+ greet({ logger, message, times });
+
+ expect(logger).toHaveBeenCalledWith(message);
+ expect(logger).toHaveBeenCalledTimes(7);
+ });
+ });
+ `,
+ ),
+ }),
+ "greet.ts": await formatTypeScript(
+ `import { GreetOptions } from "./types.js";
+
+ export function greet(options: GreetOptions | string) {
+ const {
+ logger = console.log.bind(console),
+ message,
+ times = 1,
+ } = typeof options === "string" ? { message: options } : options;
+
+ for (let i = 0; i < times; i += 1) {
+ logger(message);
+ }
+ }
+ `,
+ ),
+ "index.ts": await formatTypeScript(
+ `
+ export * from "./greet.js";
+ export * from "./types.js";
+ `,
+ ),
+ "types.ts": await formatTypeScript(
+ `
+ export interface GreetOptions {
+ logger?: (message: string) => void;
+ message: string;
+ times?: number;
+ }
+ `,
+ ),
+ };
+}
diff --git a/src/steps/writing/creation/writeAllContributorsRC.ts b/src/steps/writing/creation/writeAllContributorsRC.ts
new file mode 100644
index 00000000..72ef07a5
--- /dev/null
+++ b/src/steps/writing/creation/writeAllContributorsRC.ts
@@ -0,0 +1,25 @@
+import { readFileSafeAsJson } from "../../../shared/readFileSafeAsJson.js";
+import { AllContributorsData, Options } from "../../../shared/types.js";
+import { formatJson } from "./formatters/formatJson.js";
+
+export async function writeAllContributorsRC(options: Options) {
+ const existing = (await readFileSafeAsJson(
+ ".all-contributorsrc",
+ )) as AllContributorsData | null;
+
+ return await formatJson({
+ badgeTemplate:
+ '',
+ commit: false,
+ commitConvention: "angular",
+ contributors: existing?.contributors ?? [],
+ contributorsPerLine: 7,
+ contributorsSortAlphabetically: true,
+ files: ["README.md"],
+ imageSize: 100,
+ projectName: options.repository,
+ projectOwner: options.owner,
+ repoHost: "https://github.com",
+ repoType: "github",
+ });
+}
diff --git a/src/steps/writing/creation/writePackageJson.test.ts b/src/steps/writing/creation/writePackageJson.test.ts
new file mode 100644
index 00000000..6c9ae78b
--- /dev/null
+++ b/src/steps/writing/creation/writePackageJson.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { Options } from "../../../shared/types.js";
+import { writePackageJson } from "./writePackageJson.js";
+
+const mockReadFileSafeAsJson = vi.fn();
+
+vi.mock("../../../shared/readFileSafeAsJson.js", () => ({
+ get readFileSafeAsJson() {
+ return mockReadFileSafeAsJson;
+ },
+}));
+
+const options = {
+ access: "public",
+ author: "test-author",
+ base: "everything",
+ createRepository: undefined,
+ description: "test-description",
+ email: {
+ github: "github@email.com",
+ npm: "npm@email.com",
+ },
+ excludeAllContributors: undefined,
+ excludeCompliance: undefined,
+ excludeLintJson: undefined,
+ excludeLintKnip: undefined,
+ excludeLintMd: undefined,
+ excludeLintPackageJson: undefined,
+ excludeLintPackages: undefined,
+ excludeLintPerfectionist: undefined,
+ excludeLintSpelling: undefined,
+ excludeLintYml: undefined,
+ excludeReleases: false,
+ excludeRenovate: undefined,
+ excludeTests: false,
+ funding: undefined,
+ logo: undefined,
+ mode: "create",
+ owner: "test-owner",
+ repository: "test-repository",
+ skipGitHubApi: false,
+ skipInstall: undefined,
+ skipRemoval: undefined,
+ skipRestore: undefined,
+ skipUninstall: undefined,
+ title: "",
+} satisfies Options;
+
+describe("writePackageJson", () => {
+ it("preserves existing dependencies when they exist", async () => {
+ const dependencies = { abc: "1.2.3" };
+ mockReadFileSafeAsJson.mockResolvedValue({ dependencies });
+
+ const packageJson = await writePackageJson(options);
+
+ expect(JSON.parse(packageJson)).toEqual(
+ expect.objectContaining({ dependencies }),
+ );
+ });
+
+ it("preserves existing devDependencies that aren't known to be unnecessary when they exist", async () => {
+ const devDependencies = { abc: "1.2.3", jest: "4.5.6" };
+ mockReadFileSafeAsJson.mockResolvedValue({ devDependencies });
+
+ const packageJson = await writePackageJson(options);
+
+ expect(JSON.parse(packageJson)).toEqual(
+ expect.objectContaining({ devDependencies }),
+ );
+ });
+
+ it("includes flattened keywords when they're specified", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({});
+
+ const keywords = ["abc", "def ghi", "jkl mno pqr"];
+ const packageJson = await writePackageJson({ ...options, keywords });
+
+ expect(JSON.parse(packageJson)).toEqual(
+ expect.objectContaining({
+ keywords: ["abc", "def", "ghi", "jkl", "mno", "pqr"],
+ }),
+ );
+ });
+
+ it("includes all optional portions when no exclusions are enabled", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({});
+
+ const packageJson = await writePackageJson(options);
+
+ expect(JSON.parse(packageJson)).toMatchInlineSnapshot(`
+ {
+ "author": {
+ "email": "npm@email.com",
+ "name": "test-author",
+ },
+ "description": "test-description",
+ "devDependencies": {},
+ "engines": {
+ "node": ">=18",
+ },
+ "files": [
+ "lib/",
+ "package.json",
+ "LICENSE.md",
+ "README.md",
+ ],
+ "license": "MIT",
+ "lint-staged": {
+ "*": "prettier --ignore-unknown --write",
+ },
+ "main": "./lib/index.js",
+ "name": "test-repository",
+ "packageManager": "pnpm@8.7.0",
+ "publishConfig": {
+ "provenance": true,
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/test-owner/test-repository",
+ },
+ "scripts": {
+ "build": "tsup",
+ "format": "prettier \\"**/*\\" --ignore-unknown",
+ "lint": "eslint . .*js --max-warnings 0 --report-unused-disable-directives",
+ "lint:knip": "knip",
+ "lint:md": "markdownlint \\"**/*.md\\" \\".github/**/*.md\\" --rules sentences-per-line",
+ "lint:package-json": "npmPkgJsonLint .",
+ "lint:packages": "pnpm dedupe --check",
+ "lint:spelling": "cspell \\"**\\" \\".github/**/*\\"",
+ "prepare": "husky install",
+ "should-semantic-release": "should-semantic-release --verbose",
+ "test": "vitest",
+ "tsc": "tsc",
+ },
+ "type": "module",
+ "version": "0.0.0",
+ }
+ `);
+ });
+
+ it("excludes all optional portions when all exclusions are enabled", async () => {
+ mockReadFileSafeAsJson.mockResolvedValue({});
+
+ const packageJson = await writePackageJson({
+ ...options,
+ excludeAllContributors: true,
+ excludeCompliance: true,
+ excludeLintJson: true,
+ excludeLintKnip: true,
+ excludeLintMd: true,
+ excludeLintPackageJson: true,
+ excludeLintPackages: true,
+ excludeLintPerfectionist: true,
+ excludeLintSpelling: true,
+ excludeLintYml: true,
+ excludeReleases: true,
+ excludeRenovate: true,
+ });
+
+ expect(JSON.parse(packageJson)).toMatchInlineSnapshot(`
+ {
+ "author": {
+ "email": "npm@email.com",
+ "name": "test-author",
+ },
+ "description": "test-description",
+ "devDependencies": {},
+ "engines": {
+ "node": ">=18",
+ },
+ "files": [
+ "lib/",
+ "package.json",
+ "LICENSE.md",
+ "README.md",
+ ],
+ "license": "MIT",
+ "lint-staged": {
+ "*": "prettier --ignore-unknown --write",
+ },
+ "main": "./lib/index.js",
+ "name": "test-repository",
+ "packageManager": "pnpm@8.7.0",
+ "publishConfig": {
+ "provenance": true,
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/test-owner/test-repository",
+ },
+ "scripts": {
+ "build": "tsup",
+ "format": "prettier \\"**/*\\" --ignore-unknown",
+ "lint": "eslint . .*js --max-warnings 0 --report-unused-disable-directives",
+ "prepare": "husky install",
+ "tsc": "tsc",
+ },
+ "type": "module",
+ "version": "0.0.0",
+ }
+ `);
+ });
+});
diff --git a/src/steps/writing/creation/writePackageJson.ts b/src/steps/writing/creation/writePackageJson.ts
new file mode 100644
index 00000000..69fe13f2
--- /dev/null
+++ b/src/steps/writing/creation/writePackageJson.ts
@@ -0,0 +1,118 @@
+import { readFileSafeAsJson } from "../../../shared/readFileSafeAsJson.js";
+import { Options } from "../../../shared/types.js";
+import { formatJson } from "./formatters/formatJson.js";
+
+const devDependenciesToRemove = [
+ "@babel/core",
+ "@babel/preset-env",
+ "@babel/preset-react",
+ "@babel/preset-typescript",
+ "@swc/jest",
+ "@vitest/coverage-istanbul",
+ "ava",
+ "babel-jest",
+ "commitlint",
+ "cson-parser",
+ "esbuild",
+ "eslint-plugin-jest",
+ "eslint-plugin-prettier",
+ "eslint-plugin-simple-import-sort",
+ "eslint-plugin-typescript-sort-keys",
+ "jasmine",
+ "jest",
+ "mocha",
+ "npm-run-all",
+ "pnpm-deduplicate",
+ "pretty-quick",
+ "ts-jest",
+];
+
+export async function writePackageJson(options: Options) {
+ const existingPackageJson =
+ ((await readFileSafeAsJson("./package.json")) as null | object) ?? {};
+
+ return await formatJson({
+ // If we didn't already have a version, set it to 0.0.0
+ version: "0.0.0",
+
+ // To start, copy over all existing package fields (e.g. "dependencies")
+ ...existingPackageJson,
+
+ author: { email: options.email.npm, name: options.author },
+ description: options.description,
+ keywords: options.keywords?.length
+ ? options.keywords.flatMap((keyword) => keyword.split(/ /))
+ : undefined,
+
+ // We copy all existing dev dependencies except those we know are not used anymore
+ devDependencies: copyDevDependencies(existingPackageJson),
+
+ // Remove fields we know we don't want, such as old or redundant configs
+ eslintConfig: undefined,
+ husky: undefined,
+ prettierConfig: undefined,
+ types: undefined,
+
+ // The rest of the fields are ones we know from our template
+ engines: {
+ node: ">=18",
+ },
+ files: ["lib/", "package.json", "LICENSE.md", "README.md"],
+ license: "MIT",
+ "lint-staged": {
+ "*": "prettier --ignore-unknown --write",
+ },
+ main: "./lib/index.js",
+ name: options.repository,
+ packageManager: "pnpm@8.7.0",
+ publishConfig: {
+ provenance: true,
+ },
+ repository: {
+ type: "git",
+ url: `https://github.com/${options.owner}/${options.repository}`,
+ },
+ scripts: {
+ build: "tsup",
+ format: 'prettier "**/*" --ignore-unknown',
+ lint: "eslint . .*js --max-warnings 0 --report-unused-disable-directives",
+ ...(!options.excludeLintKnip && {
+ "lint:knip": "knip",
+ }),
+ ...(!options.excludeLintMd && {
+ "lint:md":
+ 'markdownlint "**/*.md" ".github/**/*.md" --rules sentences-per-line',
+ }),
+ ...(!options.excludeLintPackageJson && {
+ "lint:package-json": "npmPkgJsonLint .",
+ }),
+ ...(!options.excludeLintPackages && {
+ "lint:packages": "pnpm dedupe --check",
+ }),
+ ...(!options.excludeLintSpelling && {
+ "lint:spelling": 'cspell "**" ".github/**/*"',
+ }),
+ prepare: "husky install",
+ ...(!options.excludeReleases && {
+ "should-semantic-release": "should-semantic-release --verbose",
+ }),
+ ...(!options.excludeReleases && { test: "vitest" }),
+ tsc: "tsc",
+ },
+ type: "module",
+ });
+}
+
+function copyDevDependencies(existingPackageJson: object) {
+ const devDependencies =
+ "devDependencies" in existingPackageJson
+ ? (existingPackageJson.devDependencies as Record)
+ : {};
+
+ for (const devDependencyToRemove of devDependenciesToRemove) {
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
+ delete devDependencies[devDependencyToRemove];
+ }
+
+ return devDependencies;
+}
diff --git a/src/steps/writing/types.ts b/src/steps/writing/types.ts
new file mode 100644
index 00000000..6b5449c3
--- /dev/null
+++ b/src/steps/writing/types.ts
@@ -0,0 +1,3 @@
+export interface Structure {
+ [i: string]: Structure | string;
+}
diff --git a/src/steps/writing/writeStructure.ts b/src/steps/writing/writeStructure.ts
new file mode 100644
index 00000000..6ac11046
--- /dev/null
+++ b/src/steps/writing/writeStructure.ts
@@ -0,0 +1,12 @@
+import { $ } from "execa";
+
+import { Options } from "../../shared/types.js";
+import { createStructure } from "./creation/index.js";
+import { writeStructureWorker } from "./writeStructureWorker.js";
+
+export async function writeStructure(options: Options) {
+ await writeStructureWorker(await createStructure(options), ".");
+
+ // https://github.com/JoshuaKGoldberg/create-typescript-app/issues/718
+ await $`chmod ug+x .husky/pre-commit`;
+}
diff --git a/src/steps/writing/writeStructureWorker.test.ts b/src/steps/writing/writeStructureWorker.test.ts
new file mode 100644
index 00000000..92c03b1c
--- /dev/null
+++ b/src/steps/writing/writeStructureWorker.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { writeStructureWorker } from "./writeStructureWorker.js";
+
+const mockMkdir = vi.fn();
+const mockWriteFile = vi.fn();
+
+vi.mock("node:fs/promises", () => ({
+ get mkdir() {
+ return mockMkdir;
+ },
+ get writeFile() {
+ return mockWriteFile;
+ },
+}));
+
+describe("writeStructureWorker", () => {
+ it("writes an unformatted file when structure has a file", async () => {
+ await writeStructureWorker(
+ {
+ file: "content",
+ },
+ ".",
+ );
+
+ expect(mockMkdir).toHaveBeenCalledWith(".", { recursive: true });
+ expect(mockWriteFile).toHaveBeenCalledWith("file", "content");
+ });
+
+ it.each([
+ ["implicit json", ".rc", '{ "value": true }', '{ "value": true }\n'],
+ ["cjs", "file.cjs", " module.exports = { };", "module.exports = {};\n"],
+ ["js", "file.js", " export default { }", "export default {};\n"],
+ ["explicit json", "file.json", "{ }", "{}\n"],
+ ["md", "file.md", " # h1 ", "# h1\n"],
+ ["yml", "file.yml", " on: true ", "on: true\n"],
+ ])("writes a formatted %s file", async (_, file, input, output) => {
+ await writeStructureWorker({ [file]: input }, ".");
+ expect(mockWriteFile).toHaveBeenCalledWith(file, output);
+ });
+
+ it("writes a nested file when structure has a file inside a directory", async () => {
+ await writeStructureWorker(
+ {
+ directory: {
+ file: "content",
+ },
+ },
+ ".",
+ );
+
+ expect(mockMkdir).toHaveBeenCalledWith(".", { recursive: true });
+ expect(mockMkdir).toHaveBeenCalledWith("directory", { recursive: true });
+ });
+});
diff --git a/src/steps/writing/writeStructureWorker.ts b/src/steps/writing/writeStructureWorker.ts
new file mode 100644
index 00000000..9a02547d
--- /dev/null
+++ b/src/steps/writing/writeStructureWorker.ts
@@ -0,0 +1,55 @@
+import * as fs from "node:fs/promises";
+import * as path from "path";
+import prettier from "prettier";
+
+import { Structure } from "./types.js";
+
+export async function writeStructureWorker(
+ structure: Structure,
+ basePath: string,
+) {
+ await fs.mkdir(basePath, { recursive: true });
+
+ for (const [fileName, contents] of Object.entries(structure)) {
+ if (typeof contents === "string") {
+ await fs.writeFile(
+ path.join(basePath, fileName),
+ await format(fileName, contents),
+ );
+ } else {
+ await writeStructureWorker(contents, path.join(basePath, fileName));
+ }
+ }
+}
+
+async function format(fileName: string, text: string) {
+ const parser = inferParser(fileName, text);
+ if (!parser) {
+ return text;
+ }
+
+ return await prettier.format(text, {
+ parser,
+ useTabs: true,
+ });
+}
+
+function inferParser(fileName: string, text: string) {
+ if (text.startsWith("{")) {
+ return "json";
+ }
+
+ switch (fileName.split(".").at(-1)) {
+ case "cjs":
+ case "js":
+ return "babel";
+ case "json":
+ return "json";
+ case "md":
+ return "markdown";
+ case "yml":
+ return "yaml";
+ }
+
+ return undefined;
+}
diff --git a/src/types.ts b/src/types.ts
new file mode 100644
index 00000000..4f16ae39
--- /dev/null
+++ b/src/types.ts
@@ -0,0 +1,5 @@
+export interface GreetOptions {
+ logger?: (message: string) => void;
+ message: string;
+ times?: number;
+}
diff --git a/tsconfig.eslint.json b/tsconfig.eslint.json
new file mode 100644
index 00000000..3e219c8f
--- /dev/null
+++ b/tsconfig.eslint.json
@@ -0,0 +1 @@
+{ "extends": "./tsconfig.json", "include": ["."] }
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 00000000..f0eaf1a8
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "declaration": true,
+ "declarationMap": true,
+ "esModuleInterop": true,
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "noEmit": true,
+ "outDir": "lib",
+ "resolveJsonModule": true,
+ "skipLibCheck": true,
+ "sourceMap": true,
+ "strict": true,
+ "target": "ES2022"
+ },
+ "include": ["src"]
+}
diff --git a/tsup.config.ts b/tsup.config.ts
new file mode 100644
index 00000000..43c6f24e
--- /dev/null
+++ b/tsup.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from "tsup";
+
+export default defineConfig({
+ bundle: false,
+ clean: true,
+ dts: true,
+ entry: ["src/**/*.ts", "!src/**/*.test.*"],
+ format: "esm",
+ outDir: "lib",
+ sourcemap: true,
+});
diff --git a/vitest.config.ts b/vitest.config.ts
new file mode 100644
index 00000000..36fbb032
--- /dev/null
+++ b/vitest.config.ts
@@ -0,0 +1,15 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ clearMocks: true,
+ coverage: {
+ all: true,
+ exclude: ["lib"],
+ include: ["src"],
+ reporter: ["html", "lcov"],
+ },
+ exclude: ["lib", "node_modules"],
+ setupFiles: ["console-fail-test/setup"],
+ },
+});