Skip to content

Commit

Permalink
feat: add import order sorting via prettier (#1392)
Browse files Browse the repository at this point in the history
* added import order sorting

* cli format

* format www

* .

* done?

* lint

* we do a little reverse

* fixed format:check writing

* smoll changes

* split out installers

* removed eslint from base project

* added eslint back

* formatting

* fixed linting

* fixed base project

* rip ci time

* Update cli/template/extras/config/_prettier.config.cjs

* need to test this but.

* removed uneeded resolve

* docs update

* Moved over to a seperate prompt

* yuh

* spelling

* this?

---------

Co-authored-by: Julius Marminge <[email protected]>
  • Loading branch information
FinnDore and juliusmarminge committed May 17, 2023
1 parent 5d6108e commit e1a5245
Show file tree
Hide file tree
Showing 16 changed files with 226 additions and 50 deletions.
7 changes: 4 additions & 3 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ jobs:
tailwind: ["true", "false"]
nextAuth: ["true", "false"]
prisma: ["true", "false"]
prettierAndExtendedEslint: ["true", "false"]

name: "Build and Start T3 App ${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }}"
name: "Build and Start T3 App ${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }}-${{ matrix.prettierAndExtendedEslint }}"
steps:
- uses: actions/checkout@v3
with:
Expand Down Expand Up @@ -65,7 +66,7 @@ jobs:
# has to be scaffolded outside the CLI project so that no lint/tsconfig are leaking
# through. this way it ensures that it is the app's configs that are being used
# FIXME: this is a bit hacky, would rather have --packages=trpc,tailwind,... but not sure how to setup the matrix for that
- run: cd cli && pnpm start ../../ci-${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }} --noGit --CI --trpc=${{ matrix.trpc }} --tailwind=${{ matrix.tailwind }} --nextAuth=${{ matrix.nextAuth }} --prisma=${{ matrix.prisma }}
- run: cd ../ci-${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }} && pnpm build
- run: cd cli && pnpm start ../../ci-${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }}-${{ matrix.prettierAndExtendedEslint }} --noGit --CI --trpc=${{ matrix.trpc }} --tailwind=${{ matrix.tailwind }} --nextAuth=${{ matrix.nextAuth }} --prisma=${{ matrix.prisma }} --prettier-and-extended-eslint=${{ matrix.prettierAndExtendedEslint }}
- run: cd ../ci-${{ matrix.trpc }}-${{ matrix.tailwind }}-${{ matrix.nextAuth }}-${{ matrix.prisma }}-${{ matrix.prettierAndExtendedEslint }} && pnpm build
env:
NEXTAUTH_SECRET: foo
33 changes: 31 additions & 2 deletions cli/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import chalk from "chalk";
import { Command } from "commander";
import inquirer from "inquirer";
import { CREATE_T3_APP, DEFAULT_APP_NAME } from "~/consts.js";
import { type AvailablePackages } from "~/installers/index.js";
import { availablePackages } from "~/installers/index.js";
import {
availablePackages,
type AvailablePackages,
} from "~/installers/index.js";
import { getVersion } from "~/utils/getT3Version.js";
import { getUserPkgManager } from "~/utils/getUserPkgManager.js";
import { logger } from "~/utils/logger.js";
Expand All @@ -15,6 +17,7 @@ interface CliFlags {
noInstall: boolean;
default: boolean;
importAlias: string;
prettierAndExtendedEslint: boolean;

/** @internal Used in CI. */
CI: boolean;
Expand Down Expand Up @@ -47,6 +50,7 @@ const defaultOptions: CliResults = {
prisma: false,
nextAuth: false,
importAlias: "~/",
prettierAndExtendedEslint: false,
},
};

Expand Down Expand Up @@ -114,6 +118,12 @@ export const runCli = async () => {
"Explicitly tell the CLI to use a custom import alias",
defaultOptions.flags.importAlias,
)
/** @experimental - Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"-p, --prettier-and-extended-eslint",
"Explicitly tell the CLI to use a custom import alias",
defaultOptions.flags.prettierAndExtendedEslint,
)
/** END CI-FLAGS */
.version(getVersion(), "-v, --version", "Display the version number")
.addHelpText(
Expand Down Expand Up @@ -153,6 +163,9 @@ export const runCli = async () => {
if (cliResults.flags.tailwind) cliResults.packages.push("tailwind");
if (cliResults.flags.prisma) cliResults.packages.push("prisma");
if (cliResults.flags.nextAuth) cliResults.packages.push("nextAuth");
if (cliResults.flags.prettierAndExtendedEslint) {
cliResults.flags.prettierAndExtendedEslint = true;
}
}

// Explained below why this is in a try/catch block
Expand Down Expand Up @@ -186,6 +199,9 @@ export const runCli = async () => {
}

cliResults.flags.importAlias = await promptImportAlias();

cliResults.flags.prettierAndExtendedEslint =
await promtPrettierAndExtendedEslint();
}
} catch (err) {
// If the user is not calling create-t3-app from an interactive terminal, inquirer will throw an error with isTTYError = true
Expand Down Expand Up @@ -329,3 +345,16 @@ const promptImportAlias = async (): Promise<string> => {

return importAlias;
};

const promtPrettierAndExtendedEslint = async (): Promise<boolean> => {
const { prettierAndExtendedEslint } = await inquirer.prompt<
Pick<CliFlags, "prettierAndExtendedEslint">
>({
name: "prettierAndExtendedEslint",
type: "confirm",
message: "Would you like to use prettier and extended eslint conifg?",
default: defaultOptions.flags.prettierAndExtendedEslint,
});

return prettierAndExtendedEslint;
};
14 changes: 14 additions & 0 deletions cli/src/helpers/createProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@ import path from "path";
import { installPackages } from "~/helpers/installPackages.js";
import { scaffoldProject } from "~/helpers/scaffoldProject.js";
import { selectAppFile, selectIndexFile } from "~/helpers/selectBoilerplate.js";
import { installExtendedEslint } from "~/installers/eslint.js";
import { type PkgInstallerMap } from "~/installers/index.js";
import { installPrettier } from "~/installers/prettier.js";
import { getUserPkgManager } from "~/utils/getUserPkgManager.js";

interface CreateProjectOptions {
projectName: string;
packages: PkgInstallerMap;
noInstall: boolean;
importAlias: string;
prettierAndExtendedEslint: boolean;
}

export const createProject = async ({
projectName,
packages,
noInstall,
prettierAndExtendedEslint,
}: CreateProjectOptions) => {
const pkgManager = getUserPkgManager();
const projectDir = path.resolve(process.cwd(), projectName);
Expand All @@ -36,6 +40,16 @@ export const createProject = async ({
noInstall,
});

if (prettierAndExtendedEslint) {
const installArgs = {
projectDir,
pkgManager,
noInstall,
};
installPrettier(installArgs);
installExtendedEslint(installArgs);
}

// TODO: Look into using handlebars or other templating engine to scaffold without needing to maintain multiple copies of the same file
selectAppFile({ projectDir, packages });
selectIndexFile({ projectDir, packages });
Expand Down
13 changes: 8 additions & 5 deletions cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const main = async () => {
const {
appName,
packages,
flags: { noGit, noInstall, importAlias },
flags: { noGit, noInstall, importAlias, prettierAndExtendedEslint },
} = await runCli();

const usePackages = buildPkgInstallerMap(packages);
Expand All @@ -45,6 +45,7 @@ const main = async () => {
packages: usePackages,
importAlias: importAlias,
noInstall,
prettierAndExtendedEslint,
});

// Write name to package.json
Expand All @@ -67,10 +68,12 @@ const main = async () => {
}

// Rename _eslintrc.json to .eslintrc.json - we use _eslintrc.json to avoid conflicts with the monorepos linter
fs.renameSync(
path.join(projectDir, "_eslintrc.cjs"),
path.join(projectDir, ".eslintrc.cjs"),
);
if (fs.existsSync(path.join(projectDir, "_eslintrc.cjs"))) {
fs.renameSync(
path.join(projectDir, "_eslintrc.cjs"),
path.join(projectDir, ".eslintrc.cjs"),
);
}

if (!noGit) {
await initializeGit(projectDir);
Expand Down
12 changes: 9 additions & 3 deletions cli/src/installers/dependencyVersionMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ export const dependencyVersionMap = {
tailwindcss: "^3.3.0",
autoprefixer: "^10.4.14",
postcss: "^8.4.21",
prettier: "^2.8.6",
"prettier-plugin-tailwindcss": "^0.2.6",
"@types/prettier": "^2.7.2",

// tRPC
"@trpc/client": "^10.18.0",
Expand All @@ -26,5 +23,14 @@ export const dependencyVersionMap = {
"@trpc/next": "^10.18.0",
"@tanstack/react-query": "^4.28.0",
superjson: "1.12.2",

// Prettier
prettier: "^2.8.6",
"prettier-plugin-tailwindcss": "^0.2.6",
"@types/prettier": "^2.7.2",
"@ianvs/prettier-plugin-sort-imports": "^3.7.2",

// Eslint
"eslint-config-next": "^13.4.1",
} as const;
export type AvailableDependencies = keyof typeof dependencyVersionMap;
23 changes: 23 additions & 0 deletions cli/src/installers/eslint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type Installer } from "./index.js";
import fs from "fs-extra";
import path from "path";
import { PKG_ROOT } from "~/consts.js";
import { addPackageDependency } from "~/utils/addPackageDependency.js";

export const installExtendedEslint: Installer = ({ projectDir }) => {
addPackageDependency({
dependencies: ["eslint-config-next"],
devMode: true,
projectDir,
});

const configDir = path.join(PKG_ROOT, "template/extras/config");

// Remove the default config
fs.rmSync(path.join(projectDir, "_eslintrc.cjs"));

fs.copySync(
path.join(configDir, "_eslintrc.cjs"),
path.join(projectDir, ".eslintrc.cjs"),
);
};
55 changes: 55 additions & 0 deletions cli/src/installers/prettier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { type Installer } from "../installers/index.js";
import { type AvailableDependencies } from "./dependencyVersionMap.js";
import fs from "fs-extra";
import path from "path";
import { PKG_ROOT } from "~/consts.js";
import { addPackageDependency } from "~/utils/addPackageDependency.js";
import { addPackageScript } from "~/utils/addPackageScript.js";

export const installPrettier: Installer = ({ projectDir, packages }) => {
const packeagesToInstall: AvailableDependencies[] = [
"prettier",
"@types/prettier",
"@ianvs/prettier-plugin-sort-imports",
];

if (packages?.tailwind.inUse) {
packeagesToInstall.push("prettier-plugin-tailwindcss");
}

addPackageDependency({
projectDir,
dependencies: packeagesToInstall,
devMode: true,
});

addPackageScript({
projectDir,
scripts: [
{
name: "format",
value: "pnpm format:check --write",
},
{
name: "format:check",
value:
"pnpm prettier --check --plugin-search-dir=. **/*.{cjs,mjs,ts,tsx,md,json} --ignore-path ../.gitignore --ignore-unknown --no-error-on-unmatched-pattern",
},
],
});

if (packages?.tailwind.inUse) {
fs.copySync(
path.join(
PKG_ROOT,
"template/extras/config/prettier-with-tailwind.config.cjs",
),
path.join(projectDir, "prettier.config.cjs"),
);
} else {
fs.copySync(
path.join(PKG_ROOT, "template/extras/config/_prettier.config.cjs"),
path.join(projectDir, "prettier.config.cjs"),
);
}
};
13 changes: 1 addition & 12 deletions cli/src/installers/tailwind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,7 @@ import { addPackageDependency } from "~/utils/addPackageDependency.js";
export const tailwindInstaller: Installer = ({ projectDir }) => {
addPackageDependency({
projectDir,
dependencies: [
"tailwindcss",
"postcss",
"autoprefixer",
"prettier",
"prettier-plugin-tailwindcss",
"@types/prettier",
],
dependencies: ["tailwindcss", "postcss", "autoprefixer"],
devMode: true,
});

Expand All @@ -26,16 +19,12 @@ export const tailwindInstaller: Installer = ({ projectDir }) => {
const postcssCfgSrc = path.join(extrasDir, "config/postcss.config.cjs");
const postcssCfgDest = path.join(projectDir, "postcss.config.cjs");

const prettierSrc = path.join(extrasDir, "config/prettier.config.cjs");
const prettierDest = path.join(projectDir, "prettier.config.cjs");

const cssSrc = path.join(extrasDir, "src/styles/globals.css");
const cssDest = path.join(projectDir, "src/styles/globals.css");

fs.copySync(twCfgSrc, twCfgDest);
fs.copySync(postcssCfgSrc, postcssCfgDest);
fs.copySync(cssSrc, cssDest);
fs.copySync(prettierSrc, prettierDest);

// Remove vanilla css file
const indexModuleCss = path.join(projectDir, "src/pages/index.module.css");
Expand Down
26 changes: 26 additions & 0 deletions cli/src/utils/addPackageScript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import fs from "fs-extra";
import path from "path";
import sortPackageJson from "sort-package-json";
import { type PackageJson } from "type-fest";

export const addPackageScript = (opts: {
scripts: { name: string; value: string }[];
projectDir: string;
}) => {
const pkgJson = fs.readJSONSync(
path.join(opts.projectDir, "package.json"),
) as PackageJson;

if (!pkgJson.scripts) {
pkgJson.scripts = {};
}

for (const script of opts.scripts) {
pkgJson.scripts[script.name] = script.value;
}
const sortedPkgJson = sortPackageJson(pkgJson);

fs.writeJSONSync(path.join(opts.projectDir, "package.json"), sortedPkgJson, {
spaces: 2,
});
};
22 changes: 0 additions & 22 deletions cli/template/base/_eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,11 @@ const path = require("path");

/** @type {import("eslint").Linter.Config} */
const config = {
overrides: [
{
extends: [
"plugin:@typescript-eslint/recommended-requiring-type-checking",
],
files: ["*.ts", "*.tsx"],
parserOptions: {
project: path.join(__dirname, "tsconfig.json"),
},
},
],
parser: "@typescript-eslint/parser",
parserOptions: {
project: path.join(__dirname, "tsconfig.json"),
},
plugins: ["@typescript-eslint"],
extends: ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
rules: {
"@typescript-eslint/consistent-type-imports": [
"warn",
{
prefer: "type-imports",
fixStyle: "inline-type-imports",
},
],
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }],
},
};

module.exports = config;
1 change: 0 additions & 1 deletion cli/template/base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"@typescript-eslint/eslint-plugin": "^5.56.0",
"@typescript-eslint/parser": "^5.56.0",
"eslint": "^8.36.0",
"eslint-config-next": "^13.4.1",
"typescript": "^5.0.2"
}
}

0 comments on commit e1a5245

Please sign in to comment.