From 29d47a8edb3fec6d94588579ed41915fbc7ecc5c Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Sat, 15 Jun 2024 21:00:19 +0530 Subject: [PATCH 01/13] move prettier as main dependency --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 5963fa70a..1942b846a 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,6 @@ "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.1.3", "lefthook": "^1.6.16", - "prettier": "3.2.5", "rollup": "3.21.0", "rollup-plugin-auto-external": "2.0.0", "tslib": "2.5.0", @@ -55,7 +54,8 @@ "listr2": "^8.2.1", "merge-packages": "^0.1.6", "ncp": "2.0.0", - "pkg-install": "1.0.0" + "pkg-install": "1.0.0", + "prettier": "3.2.5" }, "packageManager": "yarn@3.5.0" } From d2208f5efd7e7cc0c34057b4a81520572be5e7ee Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Mon, 17 Jun 2024 14:07:08 +0530 Subject: [PATCH 02/13] format files with prettier --- package.json | 4 +- src/main.ts | 18 +- src/tasks/copy-template-files.ts | 31 +++- src/tasks/index.ts | 1 - src/tasks/prettier-format.ts | 16 -- src/utils/format-with-prettier.ts | 47 +++++ yarn.lock | 292 +++++++++++++++++++++++++++++- 7 files changed, 372 insertions(+), 37 deletions(-) delete mode 100644 src/tasks/prettier-format.ts create mode 100644 src/utils/format-with-prettier.ts diff --git a/package.json b/package.json index 1942b846a..1fd526ac5 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ }, "dependencies": { "@changesets/cli": "^2.26.2", + "@trivago/prettier-plugin-sort-imports": "^4.3.0", "arg": "5.0.2", "chalk": "5.2.0", "execa": "7.1.1", @@ -55,7 +56,8 @@ "merge-packages": "^0.1.6", "ncp": "2.0.0", "pkg-install": "1.0.0", - "prettier": "3.2.5" + "prettier": "3.2.5", + "prettier-plugin-solidity": "^1.3.1" }, "packageManager": "yarn@3.5.0" } diff --git a/src/main.ts b/src/main.ts index 9f3f78f68..c5b70e2bc 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,10 +1,4 @@ -import { - copyTemplateFiles, - createProjectDirectory, - installPackages, - createFirstGitCommit, - prettierFormat, -} from "./tasks"; +import { copyTemplateFiles, createProjectDirectory, installPackages, createFirstGitCommit } from "./tasks"; import type { Options } from "./types"; import { renderOutroMessage } from "./utils/render-outro-message"; import chalk from "chalk"; @@ -44,16 +38,6 @@ export async function createProject(options: Options) { return false; }, }, - { - title: "🪄 Formatting files with prettier", - task: () => prettierFormat(targetDirectory), - skip: () => { - if (!options.install) { - return "Skipping because prettier install was skipped"; - } - return false; - }, - }, { title: `📡 Initializing Git repository ${options.extensions.includes("foundry") ? "and submodules" : ""}`, task: () => createFirstGitCommit(targetDirectory, options), diff --git a/src/tasks/copy-template-files.ts b/src/tasks/copy-template-files.ts index 1ab981b94..4775dc32a 100644 --- a/src/tasks/copy-template-files.ts +++ b/src/tasks/copy-template-files.ts @@ -11,6 +11,10 @@ import path from "path"; import { promisify } from "util"; import link from "../utils/link"; import { getArgumentFromExternalExtensionOption } from "../utils/external-extensions"; +// @ts-expect-error - no types available +import solidityPlugin from "prettier-plugin-solidity"; +import pluginSorter from "@trivago/prettier-plugin-sort-imports"; +import { formatWithPrettier, hardhatPrettierConfig, nextJsPrettierConfig } from "../utils/format-with-prettier"; const EXTERNAL_EXTENSION_TMP_FOLDER = "tmp-external-extension"; const copy = promisify(ncp); @@ -213,7 +217,32 @@ const processTemplatedFiles = async ( templateFileDescriptor.relativePath.split(templateTargetName)[0], templateTargetName, ); - fs.writeFileSync(targetPath, output); + + let finalOutput = output; + + const containsNextjs = targetPath.includes("nextjs"); + const containsDotfile = /\/\.[^/]+/.test(targetPath); + const hardhatOrFoundry = targetPath.split("packages")[1]?.split("/")[1]; + const isHardhatOrFoundry = + hardhatOrFoundry && (hardhatOrFoundry.includes("hardhat") || hardhatOrFoundry.includes("foundry")); + + if (containsNextjs && !containsDotfile) { + finalOutput = await formatWithPrettier(output, { + ...nextJsPrettierConfig, + parser: "typescript", + plugins: [pluginSorter], + fallbackConfig: { parser: "typescript", plugins: undefined }, + }); + } else if (isHardhatOrFoundry && !containsDotfile) { + finalOutput = await formatWithPrettier(output, { + ...hardhatPrettierConfig, + parser: "solidity-parse", + plugins: [solidityPlugin], + fallbackConfig: { parser: "typescript", plugins: undefined }, + }); + } + + fs.writeFileSync(targetPath, finalOutput); if (isDev) { const hasCombinedArgs = Object.keys(combinedArgs).length > 0; diff --git a/src/tasks/index.ts b/src/tasks/index.ts index 75a12fecb..e3b7c4ed3 100644 --- a/src/tasks/index.ts +++ b/src/tasks/index.ts @@ -2,4 +2,3 @@ export * from "./copy-template-files"; export * from "./create-project-directory"; export * from "./install-packages"; export * from "./create-first-git-commit"; -export * from "./prettier-format"; diff --git a/src/tasks/prettier-format.ts b/src/tasks/prettier-format.ts deleted file mode 100644 index b126ce2e6..000000000 --- a/src/tasks/prettier-format.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { execa } from "execa"; - -// TODO: Instead of using execa, use prettier package from cli to format targetDir -export async function prettierFormat(targetDir: string) { - try { - const result = await execa("yarn", ["format"], { cwd: targetDir }); - - if (result.failed) { - throw new Error("There was a problem running the format command"); - } - } catch (error) { - throw new Error("Failed to create directory", { cause: error }); - } - - return true; -} diff --git a/src/utils/format-with-prettier.ts b/src/utils/format-with-prettier.ts new file mode 100644 index 000000000..ae78b51a8 --- /dev/null +++ b/src/utils/format-with-prettier.ts @@ -0,0 +1,47 @@ +import { Options, format } from "prettier"; + +export const formatWithPrettier = async ( + output: string, + { fallbackConfig, parser, plugins, ...config }: Options & { fallbackConfig?: Options }, +) => { + try { + return await format(output, { ...config, parser, plugins }); + } catch (e) { + try { + if (!fallbackConfig) return output; + + return await format(output, { parser, plugins, ...config, ...fallbackConfig }); + } catch (e) { + return output; + } + } +}; + +export const nextJsPrettierConfig = { + arrowParens: "avoid", + printWidth: 120, + tabWidth: 2, + trailingComma: "all", + importOrder: ["^react$", "^next/(.*)$", "", "^@heroicons/(.*)$", "^~~/(.*)$"], + importOrderSortSpecifiers: true, +} as const; + +export const hardhatPrettierConfig = { + arrowParens: "avoid", + printWidth: 120, + tabWidth: 2, + trailingComma: "all", + overrides: [ + { + files: "*.sol", + options: { + printWidth: 80, + tabWidth: 4, + useTabs: true, + singleQuote: false, + bracketSpacing: true, + explicitTypes: "always", + }, + }, + ], +} as const; diff --git a/yarn.lock b/yarn.lock index b2681772e..8b420a0a2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15,6 +15,90 @@ __metadata: languageName: node linkType: hard +"@babel/code-frame@npm:^7.22.13, @babel/code-frame@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/code-frame@npm:7.24.7" + dependencies: + "@babel/highlight": ^7.24.7 + picocolors: ^1.0.0 + checksum: 830e62cd38775fdf84d612544251ce773d544a8e63df667728cc9e0126eeef14c6ebda79be0f0bc307e8318316b7f58c27ce86702e0a1f5c321d842eb38ffda4 + languageName: node + linkType: hard + +"@babel/generator@npm:7.17.7": + version: 7.17.7 + resolution: "@babel/generator@npm:7.17.7" + dependencies: + "@babel/types": ^7.17.0 + jsesc: ^2.5.1 + source-map: ^0.5.0 + checksum: e7344b9b4559115f2754ecc2ae9508412ea6a8f617544cd3d3f17cabc727bd30630765f96c8a4ebc8901ded1492a3a6c23d695a4f1e8f3042f860b30c891985c + languageName: node + linkType: hard + +"@babel/generator@npm:^7.23.0": + version: 7.24.7 + resolution: "@babel/generator@npm:7.24.7" + dependencies: + "@babel/types": ^7.24.7 + "@jridgewell/gen-mapping": ^0.3.5 + "@jridgewell/trace-mapping": ^0.3.25 + jsesc: ^2.5.1 + checksum: 0ff31a73b15429f1287e4d57b439bba4a266f8c673bb445fe313b82f6d110f586776997eb723a777cd7adad9d340edd162aea4973a90112c5d0cfcaf6686844b + languageName: node + linkType: hard + +"@babel/helper-environment-visitor@npm:^7.22.20": + version: 7.24.7 + resolution: "@babel/helper-environment-visitor@npm:7.24.7" + dependencies: + "@babel/types": ^7.24.7 + checksum: 079d86e65701b29ebc10baf6ed548d17c19b808a07aa6885cc141b690a78581b180ee92b580d755361dc3b16adf975b2d2058b8ce6c86675fcaf43cf22f2f7c6 + languageName: node + linkType: hard + +"@babel/helper-function-name@npm:^7.23.0": + version: 7.24.7 + resolution: "@babel/helper-function-name@npm:7.24.7" + dependencies: + "@babel/template": ^7.24.7 + "@babel/types": ^7.24.7 + checksum: 142ee08922074dfdc0ff358e09ef9f07adf3671ab6eef4fca74dcf7a551f1a43717e7efa358c9e28d7eea84c28d7f177b7a58c70452fc312ae3b1893c5dab2a4 + languageName: node + linkType: hard + +"@babel/helper-hoist-variables@npm:^7.22.5": + version: 7.24.7 + resolution: "@babel/helper-hoist-variables@npm:7.24.7" + dependencies: + "@babel/types": ^7.24.7 + checksum: 6cfdcf2289cd12185dcdbdf2435fa8d3447b797ac75851166de9fc8503e2fd0021db6baf8dfbecad3753e582c08e6a3f805c8d00cbed756060a877d705bd8d8d + languageName: node + linkType: hard + +"@babel/helper-split-export-declaration@npm:^7.22.6": + version: 7.24.7 + resolution: "@babel/helper-split-export-declaration@npm:7.24.7" + dependencies: + "@babel/types": ^7.24.7 + checksum: e3ddc91273e5da67c6953f4aa34154d005a00791dc7afa6f41894e768748540f6ebcac5d16e72541aea0c89bee4b89b4da6a3d65972a0ea8bfd2352eda5b7e22 + languageName: node + linkType: hard + +"@babel/helper-string-parser@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/helper-string-parser@npm:7.24.7" + checksum: 09568193044a578743dd44bf7397940c27ea693f9812d24acb700890636b376847a611cdd0393a928544e79d7ad5b8b916bd8e6e772bc8a10c48a647a96e7b1a + languageName: node + linkType: hard + +"@babel/helper-validator-identifier@npm:^7.16.7, @babel/helper-validator-identifier@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/helper-validator-identifier@npm:7.24.7" + checksum: 6799ab117cefc0ecd35cd0b40ead320c621a298ecac88686a14cffceaac89d80cdb3c178f969861bf5fa5e4f766648f9161ea0752ecfe080d8e89e3147270257 + languageName: node + linkType: hard + "@babel/helper-validator-identifier@npm:^7.22.5": version: 7.22.5 resolution: "@babel/helper-validator-identifier@npm:7.22.5" @@ -33,6 +117,27 @@ __metadata: languageName: node linkType: hard +"@babel/highlight@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/highlight@npm:7.24.7" + dependencies: + "@babel/helper-validator-identifier": ^7.24.7 + chalk: ^2.4.2 + js-tokens: ^4.0.0 + picocolors: ^1.0.0 + checksum: 5cd3a89f143671c4ac129960024ba678b669e6fc673ce078030f5175002d1d3d52bc10b22c5b916a6faf644b5028e9a4bd2bb264d053d9b05b6a98690f1d46f1 + languageName: node + linkType: hard + +"@babel/parser@npm:^7.20.5, @babel/parser@npm:^7.23.0, @babel/parser@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/parser@npm:7.24.7" + bin: + parser: ./bin/babel-parser.js + checksum: fc9d2c4c8712f89672edc55c0dc5cf640dcec715b56480f111f85c2bc1d507e251596e4110d65796690a96ac37a4b60432af90b3e97bb47e69d4ef83872dbbd6 + languageName: node + linkType: hard + "@babel/runtime@npm:^7.20.1, @babel/runtime@npm:^7.5.5": version: 7.22.10 resolution: "@babel/runtime@npm:7.22.10" @@ -42,6 +147,56 @@ __metadata: languageName: node linkType: hard +"@babel/template@npm:^7.24.7": + version: 7.24.7 + resolution: "@babel/template@npm:7.24.7" + dependencies: + "@babel/code-frame": ^7.24.7 + "@babel/parser": ^7.24.7 + "@babel/types": ^7.24.7 + checksum: ea90792fae708ddf1632e54c25fe1a86643d8c0132311f81265d2bdbdd42f9f4fac65457056c1b6ca87f7aa0d6a795b549566774bba064bdcea2034ab3960ee9 + languageName: node + linkType: hard + +"@babel/traverse@npm:7.23.2": + version: 7.23.2 + resolution: "@babel/traverse@npm:7.23.2" + dependencies: + "@babel/code-frame": ^7.22.13 + "@babel/generator": ^7.23.0 + "@babel/helper-environment-visitor": ^7.22.20 + "@babel/helper-function-name": ^7.23.0 + "@babel/helper-hoist-variables": ^7.22.5 + "@babel/helper-split-export-declaration": ^7.22.6 + "@babel/parser": ^7.23.0 + "@babel/types": ^7.23.0 + debug: ^4.1.0 + globals: ^11.1.0 + checksum: 26a1eea0dde41ab99dde8b9773a013a0dc50324e5110a049f5d634e721ff08afffd54940b3974a20308d7952085ac769689369e9127dea655f868c0f6e1ab35d + languageName: node + linkType: hard + +"@babel/types@npm:7.17.0": + version: 7.17.0 + resolution: "@babel/types@npm:7.17.0" + dependencies: + "@babel/helper-validator-identifier": ^7.16.7 + to-fast-properties: ^2.0.0 + checksum: 12e5a287986fe557188e87b2c5202223f1dc83d9239a196ab936fdb9f8c1eb0be717ff19f934b5fad4e29a75586d5798f74bed209bccea1c20376b9952056f0e + languageName: node + linkType: hard + +"@babel/types@npm:^7.17.0, @babel/types@npm:^7.23.0, @babel/types@npm:^7.24.7, @babel/types@npm:^7.8.3": + version: 7.24.7 + resolution: "@babel/types@npm:7.24.7" + dependencies: + "@babel/helper-string-parser": ^7.24.7 + "@babel/helper-validator-identifier": ^7.24.7 + to-fast-properties: ^2.0.0 + checksum: 3e4437fced97e02982972ce5bebd318c47d42c9be2152c0fd28c6f786cc74086cc0a8fb83b602b846e41df37f22c36254338eada1a47ef9d8a1ec92332ca3ea8 + languageName: node + linkType: hard + "@changesets/apply-release-plan@npm:^6.1.4": version: 6.1.4 resolution: "@changesets/apply-release-plan@npm:6.1.4" @@ -359,6 +514,48 @@ __metadata: languageName: node linkType: hard +"@jridgewell/gen-mapping@npm:^0.3.5": + version: 0.3.5 + resolution: "@jridgewell/gen-mapping@npm:0.3.5" + dependencies: + "@jridgewell/set-array": ^1.2.1 + "@jridgewell/sourcemap-codec": ^1.4.10 + "@jridgewell/trace-mapping": ^0.3.24 + checksum: ff7a1764ebd76a5e129c8890aa3e2f46045109dabde62b0b6c6a250152227647178ff2069ea234753a690d8f3c4ac8b5e7b267bbee272bffb7f3b0a370ab6e52 + languageName: node + linkType: hard + +"@jridgewell/resolve-uri@npm:^3.1.0": + version: 3.1.2 + resolution: "@jridgewell/resolve-uri@npm:3.1.2" + checksum: 83b85f72c59d1c080b4cbec0fef84528963a1b5db34e4370fa4bd1e3ff64a0d80e0cee7369d11d73c704e0286fb2865b530acac7a871088fbe92b5edf1000870 + languageName: node + linkType: hard + +"@jridgewell/set-array@npm:^1.2.1": + version: 1.2.1 + resolution: "@jridgewell/set-array@npm:1.2.1" + checksum: 832e513a85a588f8ed4f27d1279420d8547743cc37fcad5a5a76fc74bb895b013dfe614d0eed9cb860048e6546b798f8f2652020b4b2ba0561b05caa8c654b10 + languageName: node + linkType: hard + +"@jridgewell/sourcemap-codec@npm:^1.4.10, @jridgewell/sourcemap-codec@npm:^1.4.14": + version: 1.4.15 + resolution: "@jridgewell/sourcemap-codec@npm:1.4.15" + checksum: b881c7e503db3fc7f3c1f35a1dd2655a188cc51a3612d76efc8a6eb74728bef5606e6758ee77423e564092b4a518aba569bbb21c9bac5ab7a35b0c6ae7e344c8 + languageName: node + linkType: hard + +"@jridgewell/trace-mapping@npm:^0.3.24, @jridgewell/trace-mapping@npm:^0.3.25": + version: 0.3.25 + resolution: "@jridgewell/trace-mapping@npm:0.3.25" + dependencies: + "@jridgewell/resolve-uri": ^3.1.0 + "@jridgewell/sourcemap-codec": ^1.4.14 + checksum: 9d3c40d225e139987b50c48988f8717a54a8c994d8a948ee42e1412e08988761d0754d7d10b803061cc3aebf35f92a5dbbab493bd0e1a9ef9e89a2130e83ba34 + languageName: node + linkType: hard + "@manypkg/find-root@npm:^1.1.0": version: 1.1.0 resolution: "@manypkg/find-root@npm:1.1.0" @@ -474,6 +671,13 @@ __metadata: languageName: node linkType: hard +"@solidity-parser/parser@npm:^0.17.0": + version: 0.17.0 + resolution: "@solidity-parser/parser@npm:0.17.0" + checksum: 2f47732c9a4f6b264ce6c8a0544bd5a0805f824d3c40a8a253e59d5dbe9a98163f55c06460232f57a6b389bb5235c18d0563f94425202ec2f859d88f2378e0ac + languageName: node + linkType: hard + "@tootallnate/once@npm:2": version: 2.0.0 resolution: "@tootallnate/once@npm:2.0.0" @@ -481,6 +685,26 @@ __metadata: languageName: node linkType: hard +"@trivago/prettier-plugin-sort-imports@npm:^4.3.0": + version: 4.3.0 + resolution: "@trivago/prettier-plugin-sort-imports@npm:4.3.0" + dependencies: + "@babel/generator": 7.17.7 + "@babel/parser": ^7.20.5 + "@babel/traverse": 7.23.2 + "@babel/types": 7.17.0 + javascript-natural-sort: 0.7.1 + lodash: ^4.17.21 + peerDependencies: + "@vue/compiler-sfc": 3.x + prettier: 2.x - 3.x + peerDependenciesMeta: + "@vue/compiler-sfc": + optional: true + checksum: 22bb311ca24f09eef25915a66727e7be113b703f196f6ea0589dc9730b11a6f1e5e4bcc468213101d138b570d310792c83abb8d9487c53f9e597942fea052b6e + languageName: node + linkType: hard + "@types/estree@npm:^1.0.0": version: 1.0.1 resolution: "@types/estree@npm:1.0.1" @@ -1298,6 +1522,7 @@ __metadata: "@changesets/cli": ^2.26.2 "@eslint/js": ^9.3.0 "@rollup/plugin-typescript": 11.1.0 + "@trivago/prettier-plugin-sort-imports": ^4.3.0 "@types/inquirer": 9.0.3 "@types/ncp": 2.0.5 "@types/node": 18.16.0 @@ -1314,6 +1539,7 @@ __metadata: ncp: 2.0.0 pkg-install: 1.0.0 prettier: 3.2.5 + prettier-plugin-solidity: ^1.3.1 rollup: 3.21.0 rollup-plugin-auto-external: 2.0.0 tslib: 2.5.0 @@ -2247,6 +2473,13 @@ __metadata: languageName: node linkType: hard +"globals@npm:^11.1.0": + version: 11.12.0 + resolution: "globals@npm:11.12.0" + checksum: 67051a45eca3db904aee189dfc7cd53c20c7d881679c93f6146ddd4c9f4ab2268e68a919df740d39c71f4445d2b38ee360fc234428baea1dbdfe68bbcb46979e + languageName: node + linkType: hard + "globals@npm:^14.0.0": version: 14.0.0 resolution: "globals@npm:14.0.0" @@ -2861,6 +3094,13 @@ __metadata: languageName: node linkType: hard +"javascript-natural-sort@npm:0.7.1": + version: 0.7.1 + resolution: "javascript-natural-sort@npm:0.7.1" + checksum: 161e2c512cc7884bc055a582c6645d9032cab88497a76123d73cb23bfb03d97a04cf7772ecdb8bd3366fc07192c2f996366f479f725c23ef073fffe03d6a586a + languageName: node + linkType: hard + "jju@npm:^1.4.0": version: 1.4.0 resolution: "jju@npm:1.4.0" @@ -2898,6 +3138,15 @@ __metadata: languageName: node linkType: hard +"jsesc@npm:^2.5.1": + version: 2.5.2 + resolution: "jsesc@npm:2.5.2" + bin: + jsesc: bin/jsesc + checksum: 4dc190771129e12023f729ce20e1e0bfceac84d73a85bc3119f7f938843fe25a4aeccb54b6494dce26fcf263d815f5f31acdefac7cc9329efb8422a4f4d9fa9d + languageName: node + linkType: hard + "json-buffer@npm:3.0.1": version: 3.0.1 resolution: "json-buffer@npm:3.0.1" @@ -3852,6 +4101,13 @@ __metadata: languageName: node linkType: hard +"picocolors@npm:^1.0.0": + version: 1.0.1 + resolution: "picocolors@npm:1.0.1" + checksum: fa68166d1f56009fc02a34cdfd112b0dd3cf1ef57667ac57281f714065558c01828cdf4f18600ad6851cbe0093952ed0660b1e0156bddf2184b6aaf5817553a5 + languageName: node + linkType: hard + "picomatch@npm:^2.3.1": version: 2.3.1 resolution: "picomatch@npm:2.3.1" @@ -3921,6 +4177,19 @@ __metadata: languageName: node linkType: hard +"prettier-plugin-solidity@npm:^1.3.1": + version: 1.3.1 + resolution: "prettier-plugin-solidity@npm:1.3.1" + dependencies: + "@solidity-parser/parser": ^0.17.0 + semver: ^7.5.4 + solidity-comments-extractor: ^0.0.8 + peerDependencies: + prettier: ">=2.3.0" + checksum: 286bf3b5899d7fad66e49c78ebac164bacfbf419f874a932ed99e491d97d77e91fa03ca068197939d3696ba7991db9e5258390dd42dee8d2184fa8c2e11921e4 + languageName: node + linkType: hard + "prettier@npm:3.2.5": version: 3.2.5 resolution: "prettier@npm:3.2.5" @@ -4308,7 +4577,7 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.6.0": +"semver@npm:^7.5.4, semver@npm:^7.6.0": version: 7.6.2 resolution: "semver@npm:7.6.2" bin: @@ -4445,6 +4714,13 @@ __metadata: languageName: node linkType: hard +"solidity-comments-extractor@npm:^0.0.8": + version: 0.0.8 + resolution: "solidity-comments-extractor@npm:0.0.8" + checksum: ad025fc968e2d744b4270710c2f7f55b43d8046ab3f155fd880a7768d6fd163a93ea98f62be3b1115a29ba815bd8b5736bb5ffd1feff79083eca1bf273108d07 + languageName: node + linkType: hard + "sort-object-keys@npm:^1.1.3": version: 1.1.3 resolution: "sort-object-keys@npm:1.1.3" @@ -4468,6 +4744,13 @@ __metadata: languageName: node linkType: hard +"source-map@npm:^0.5.0": + version: 0.5.7 + resolution: "source-map@npm:0.5.7" + checksum: 5dc2043b93d2f194142c7f38f74a24670cd7a0063acdaf4bf01d2964b402257ae843c2a8fa822ad5b71013b5fcafa55af7421383da919752f22ff488bc553f4d + languageName: node + linkType: hard + "spawndamnit@npm:^2.0.0": version: 2.0.0 resolution: "spawndamnit@npm:2.0.0" @@ -4764,6 +5047,13 @@ __metadata: languageName: node linkType: hard +"to-fast-properties@npm:^2.0.0": + version: 2.0.0 + resolution: "to-fast-properties@npm:2.0.0" + checksum: be2de62fe58ead94e3e592680052683b1ec986c72d589e7b21e5697f8744cdbf48c266fa72f6c15932894c10187b5f54573a3bcf7da0bfd964d5caf23d436168 + languageName: node + linkType: hard + "to-regex-range@npm:^5.0.1": version: 5.0.1 resolution: "to-regex-range@npm:5.0.1" From ec4193c2be92eebc3e39a3a485778e3df7c9938b Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Mon, 17 Jun 2024 14:31:00 +0530 Subject: [PATCH 03/13] format foundry inline with hadhat prettier config --- .../foundry/contracts/YourContract.sol | 116 +++++----- .../foundry/packages/foundry/foundry.toml | 6 +- .../foundry/script/DeployHelpers.s.sol | 113 +++++----- .../packages/foundry/script/VerifyAll.s.sol | 209 ++++++++---------- .../packages/foundry/test/YourContract.t.sol | 34 +-- 5 files changed, 233 insertions(+), 245 deletions(-) diff --git a/templates/extensions/foundry/packages/foundry/contracts/YourContract.sol b/templates/extensions/foundry/packages/foundry/contracts/YourContract.sol index 631b8b100..314277455 100644 --- a/templates/extensions/foundry/packages/foundry/contracts/YourContract.sol +++ b/templates/extensions/foundry/packages/foundry/contracts/YourContract.sol @@ -13,72 +13,72 @@ import "forge-std/console.sol"; * @author BuidlGuidl */ contract YourContract { - // State Variables - address public immutable owner; - string public greeting = "Building Unstoppable Apps!!!"; - bool public premium = false; - uint256 public totalCounter = 0; - mapping(address => uint256) public userGreetingCounter; + // State Variables + address public immutable owner; + string public greeting = "Building Unstoppable Apps!!!"; + bool public premium = false; + uint256 public totalCounter = 0; + mapping(address => uint256) public userGreetingCounter; - // Events: a way to emit log statements from smart contract that can be listened to by external parties - event GreetingChange( - address indexed greetingSetter, - string newGreeting, - bool premium, - uint256 value - ); + // Events: a way to emit log statements from smart contract that can be listened to by external parties + event GreetingChange( + address indexed greetingSetter, + string newGreeting, + bool premium, + uint256 value + ); - // Constructor: Called once on contract deployment - // Check packages/foundry/deploy/Deploy.s.sol - constructor(address _owner) { - owner = _owner; - } - - // Modifier: used to define a set of rules that must be met before or after a function is executed - // Check the withdraw() function - modifier isOwner() { - // msg.sender: predefined variable that represents address of the account that called the current function - require(msg.sender == owner, "Not the Owner"); - _; - } + // Constructor: Called once on contract deployment + // Check packages/foundry/deploy/Deploy.s.sol + constructor(address _owner) { + owner = _owner; + } - /** - * Function that allows anyone to change the state variable "greeting" of the contract and increase the counters - * - * @param _newGreeting (string memory) - new greeting to save on the contract - */ - function setGreeting(string memory _newGreeting) public payable { - // Print data to the anvil chain console. Remove when deploying to a live network. + // Modifier: used to define a set of rules that must be met before or after a function is executed + // Check the withdraw() function + modifier isOwner() { + // msg.sender: predefined variable that represents address of the account that called the current function + require(msg.sender == owner, "Not the Owner"); + _; + } - console.logString("Setting new greeting"); - console.logString(_newGreeting); + /** + * Function that allows anyone to change the state variable "greeting" of the contract and increase the counters + * + * @param _newGreeting (string memory) - new greeting to save on the contract + */ + function setGreeting(string memory _newGreeting) public payable { + // Print data to the anvil chain console. Remove when deploying to a live network. - greeting = _newGreeting; - totalCounter += 1; - userGreetingCounter[msg.sender] += 1; + console.logString("Setting new greeting"); + console.logString(_newGreeting); - // msg.value: built-in global variable that represents the amount of ether sent with the transaction - if (msg.value > 0) { - premium = true; - } else { - premium = false; - } + greeting = _newGreeting; + totalCounter += 1; + userGreetingCounter[msg.sender] += 1; - // emit: keyword used to trigger an event - emit GreetingChange(msg.sender, _newGreeting, msg.value > 0, msg.value); + // msg.value: built-in global variable that represents the amount of ether sent with the transaction + if (msg.value > 0) { + premium = true; + } else { + premium = false; } - /** - * Function that allows the owner to withdraw all the Ether in the contract - * The function can only be called by the owner of the contract as defined by the isOwner modifier - */ - function withdraw() public isOwner { - (bool success,) = owner.call{value: address(this).balance}(""); - require(success, "Failed to send Ether"); - } + // emit: keyword used to trigger an event + emit GreetingChange(msg.sender, _newGreeting, msg.value > 0, msg.value); + } + + /** + * Function that allows the owner to withdraw all the Ether in the contract + * The function can only be called by the owner of the contract as defined by the isOwner modifier + */ + function withdraw() public isOwner { + (bool success,) = owner.call{ value: address(this).balance }(""); + require(success, "Failed to send Ether"); + } - /** - * Function that allows the contract to receive ETH - */ - receive() external payable {} + /** + * Function that allows the contract to receive ETH + */ + receive() external payable { } } diff --git a/templates/extensions/foundry/packages/foundry/foundry.toml b/templates/extensions/foundry/packages/foundry/foundry.toml index c15273b23..feee8aa32 100644 --- a/templates/extensions/foundry/packages/foundry/foundry.toml +++ b/templates/extensions/foundry/packages/foundry/foundry.toml @@ -34,7 +34,11 @@ sepolia = { key = "${ETHERSCAN_API_KEY}" } [fmt] -line_length = 80 multiline_func_header = "params_first" +line_length = 80 +tab_width = 2 +quote_style = "double" +bracket_spacing = true +int_types = "long" # See more config options https://github.com/foundry-rs/foundry/tree/master/config diff --git a/templates/extensions/foundry/packages/foundry/script/DeployHelpers.s.sol b/templates/extensions/foundry/packages/foundry/script/DeployHelpers.s.sol index b7d6620d2..7338ac1af 100644 --- a/templates/extensions/foundry/packages/foundry/script/DeployHelpers.s.sol +++ b/templates/extensions/foundry/packages/foundry/script/DeployHelpers.s.sol @@ -5,77 +5,74 @@ import "forge-std/Script.sol"; import "forge-std/Vm.sol"; contract ScaffoldETHDeploy is Script { - error InvalidChain(); + error InvalidChain(); - struct Deployment { - string name; - address addr; - } + struct Deployment { + string name; + address addr; + } - string root; - string path; - Deployment[] public deployments; + string root; + string path; + Deployment[] public deployments; - function setupLocalhostEnv() - internal - returns (uint256 localhostPrivateKey) - { - if (block.chainid == 31337) { - root = vm.projectRoot(); - path = string.concat(root, "/localhost.json"); - string memory json = vm.readFile(path); - bytes memory mnemonicBytes = vm.parseJson(json, ".wallet.mnemonic"); - string memory mnemonic = abi.decode(mnemonicBytes, (string)); - return vm.deriveKey(mnemonic, 0); - } else { - return vm.envUint("DEPLOYER_PRIVATE_KEY"); - } + function setupLocalhostEnv() internal returns (uint256 localhostPrivateKey) { + if (block.chainid == 31337) { + root = vm.projectRoot(); + path = string.concat(root, "/localhost.json"); + string memory json = vm.readFile(path); + bytes memory mnemonicBytes = vm.parseJson(json, ".wallet.mnemonic"); + string memory mnemonic = abi.decode(mnemonicBytes, (string)); + return vm.deriveKey(mnemonic, 0); + } else { + return vm.envUint("DEPLOYER_PRIVATE_KEY"); } + } - function exportDeployments() internal { - // fetch already existing contracts - root = vm.projectRoot(); - path = string.concat(root, "/deployments/"); - string memory chainIdStr = vm.toString(block.chainid); - path = string.concat(path, string.concat(chainIdStr, ".json")); + function exportDeployments() internal { + // fetch already existing contracts + root = vm.projectRoot(); + path = string.concat(root, "/deployments/"); + string memory chainIdStr = vm.toString(block.chainid); + path = string.concat(path, string.concat(chainIdStr, ".json")); - string memory jsonWrite; + string memory jsonWrite; - uint256 len = deployments.length; + uint256 len = deployments.length; - for (uint256 i = 0; i < len; i++) { - vm.serializeString( - jsonWrite, vm.toString(deployments[i].addr), deployments[i].name - ); - } + for (uint256 i = 0; i < len; i++) { + vm.serializeString( + jsonWrite, vm.toString(deployments[i].addr), deployments[i].name + ); + } - string memory chainName; + string memory chainName; - try this.getChain() returns (Chain memory chain) { - chainName = chain.name; - } catch { - chainName = findChainName(); - } - jsonWrite = vm.serializeString(jsonWrite, "networkName", chainName); - vm.writeJson(jsonWrite, path); + try this.getChain() returns (Chain memory chain) { + chainName = chain.name; + } catch { + chainName = findChainName(); } + jsonWrite = vm.serializeString(jsonWrite, "networkName", chainName); + vm.writeJson(jsonWrite, path); + } - function getChain() public returns (Chain memory) { - return getChain(block.chainid); - } + function getChain() public returns (Chain memory) { + return getChain(block.chainid); + } - function findChainName() public returns (string memory) { - uint256 thisChainId = block.chainid; - string[2][] memory allRpcUrls = vm.rpcUrls(); - for (uint256 i = 0; i < allRpcUrls.length; i++) { - try vm.createSelectFork(allRpcUrls[i][1]) { - if (block.chainid == thisChainId) { - return allRpcUrls[i][0]; - } - } catch { - continue; - } + function findChainName() public returns (string memory) { + uint256 thisChainId = block.chainid; + string[2][] memory allRpcUrls = vm.rpcUrls(); + for (uint256 i = 0; i < allRpcUrls.length; i++) { + try vm.createSelectFork(allRpcUrls[i][1]) { + if (block.chainid == thisChainId) { + return allRpcUrls[i][0]; } - revert InvalidChain(); + } catch { + continue; + } } + revert InvalidChain(); + } } diff --git a/templates/extensions/foundry/packages/foundry/script/VerifyAll.s.sol b/templates/extensions/foundry/packages/foundry/script/VerifyAll.s.sol index 9990f9c6b..23b0b2a04 100644 --- a/templates/extensions/foundry/packages/foundry/script/VerifyAll.s.sol +++ b/templates/extensions/foundry/packages/foundry/script/VerifyAll.s.sol @@ -11,136 +11,123 @@ import "solidity-bytes-utils/BytesLib.sol"; * @notice will be deleted once the forge/std is updated */ struct FfiResult { - int32 exit_code; - bytes stdout; - bytes stderr; + int32 exit_code; + bytes stdout; + bytes stderr; } interface tempVm { - function tryFfi(string[] calldata) external returns (FfiResult memory); + function tryFfi(string[] calldata) external returns (FfiResult memory); } contract VerifyAll is Script { - uint96 currTransactionIdx; + uint96 currTransactionIdx; - function run() external { - string memory root = vm.projectRoot(); - string memory path = string.concat( - root, - "/broadcast/Deploy.s.sol/", - vm.toString(block.chainid), - "/run-latest.json" - ); - string memory content = vm.readFile(path); + function run() external { + string memory root = vm.projectRoot(); + string memory path = string.concat( + root, + "/broadcast/Deploy.s.sol/", + vm.toString(block.chainid), + "/run-latest.json" + ); + string memory content = vm.readFile(path); - while (this.nextTransaction(content)) { - _verifyIfContractDeployment(content); - currTransactionIdx++; - } + while (this.nextTransaction(content)) { + _verifyIfContractDeployment(content); + currTransactionIdx++; } + } - function _verifyIfContractDeployment(string memory content) internal { - string memory txType = abi.decode( - vm.parseJson( - content, searchStr(currTransactionIdx, "transactionType") - ), - (string) - ); - if (keccak256(bytes(txType)) == keccak256(bytes("CREATE"))) { - _verifyContract(content); - } + function _verifyIfContractDeployment(string memory content) internal { + string memory txType = abi.decode( + vm.parseJson(content, searchStr(currTransactionIdx, "transactionType")), + (string) + ); + if (keccak256(bytes(txType)) == keccak256(bytes("CREATE"))) { + _verifyContract(content); } + } - function _verifyContract(string memory content) internal { - string memory contractName = abi.decode( - vm.parseJson(content, searchStr(currTransactionIdx, "contractName")), - (string) - ); - address contractAddr = abi.decode( - vm.parseJson( - content, searchStr(currTransactionIdx, "contractAddress") - ), - (address) - ); - bytes memory deployedBytecode = abi.decode( - vm.parseJson( - content, searchStr(currTransactionIdx, "transaction.data") - ), - (bytes) - ); - bytes memory compiledBytecode = abi.decode( - vm.parseJson(_getCompiledBytecode(contractName), ".bytecode.object"), - (bytes) - ); - bytes memory constructorArgs = BytesLib.slice( - deployedBytecode, - compiledBytecode.length, - deployedBytecode.length - compiledBytecode.length - ); + function _verifyContract(string memory content) internal { + string memory contractName = abi.decode( + vm.parseJson(content, searchStr(currTransactionIdx, "contractName")), + (string) + ); + address contractAddr = abi.decode( + vm.parseJson(content, searchStr(currTransactionIdx, "contractAddress")), + (address) + ); + bytes memory deployedBytecode = abi.decode( + vm.parseJson(content, searchStr(currTransactionIdx, "transaction.data")), + (bytes) + ); + bytes memory compiledBytecode = abi.decode( + vm.parseJson(_getCompiledBytecode(contractName), ".bytecode.object"), + (bytes) + ); + bytes memory constructorArgs = BytesLib.slice( + deployedBytecode, + compiledBytecode.length, + deployedBytecode.length - compiledBytecode.length + ); - string[] memory inputs = new string[](9); - inputs[0] = "forge"; - inputs[1] = "verify-contract"; - inputs[2] = vm.toString(contractAddr); - inputs[3] = contractName; - inputs[4] = "--chain"; - inputs[5] = vm.toString(block.chainid); - inputs[6] = "--constructor-args"; - inputs[7] = vm.toString(constructorArgs); - inputs[8] = "--watch"; + string[] memory inputs = new string[](9); + inputs[0] = "forge"; + inputs[1] = "verify-contract"; + inputs[2] = vm.toString(contractAddr); + inputs[3] = contractName; + inputs[4] = "--chain"; + inputs[5] = vm.toString(block.chainid); + inputs[6] = "--constructor-args"; + inputs[7] = vm.toString(constructorArgs); + inputs[8] = "--watch"; - FfiResult memory f = tempVm(address(vm)).tryFfi(inputs); + FfiResult memory f = tempVm(address(vm)).tryFfi(inputs); - if (f.stderr.length != 0) { - console.logString( - string.concat( - "Submitting verification for contract: ", - vm.toString(contractAddr) - ) - ); - console.logString(string(f.stderr)); - } else { - console.logString(string(f.stdout)); - } - return; + if (f.stderr.length != 0) { + console.logString( + string.concat( + "Submitting verification for contract: ", vm.toString(contractAddr) + ) + ); + console.logString(string(f.stderr)); + } else { + console.logString(string(f.stdout)); } + return; + } - function nextTransaction(string memory content) - external - view - returns (bool) - { - try this.getTransactionFromRaw(content, currTransactionIdx) { - return true; - } catch { - return false; - } + function nextTransaction(string memory content) external view returns (bool) { + try this.getTransactionFromRaw(content, currTransactionIdx) { + return true; + } catch { + return false; } + } - function _getCompiledBytecode(string memory contractName) - internal - view - returns (string memory compiledBytecode) - { - string memory root = vm.projectRoot(); - string memory path = string.concat( - root, "/out/", contractName, ".sol/", contractName, ".json" - ); - compiledBytecode = vm.readFile(path); - } + function _getCompiledBytecode(string memory contractName) + internal + view + returns (string memory compiledBytecode) + { + string memory root = vm.projectRoot(); + string memory path = + string.concat(root, "/out/", contractName, ".sol/", contractName, ".json"); + compiledBytecode = vm.readFile(path); + } - function getTransactionFromRaw( - string memory content, - uint96 idx - ) external pure { - abi.decode(vm.parseJson(content, searchStr(idx, "hash")), (bytes32)); - } + function getTransactionFromRaw( + string memory content, + uint96 idx + ) external pure { + abi.decode(vm.parseJson(content, searchStr(idx, "hash")), (bytes32)); + } - function searchStr( - uint96 idx, - string memory searchKey - ) internal pure returns (string memory) { - return - string.concat(".transactions[", vm.toString(idx), "].", searchKey); - } + function searchStr( + uint96 idx, + string memory searchKey + ) internal pure returns (string memory) { + return string.concat(".transactions[", vm.toString(idx), "].", searchKey); + } } diff --git a/templates/extensions/foundry/packages/foundry/test/YourContract.t.sol b/templates/extensions/foundry/packages/foundry/test/YourContract.t.sol index 2bb348efd..a6a2c10d0 100644 --- a/templates/extensions/foundry/packages/foundry/test/YourContract.t.sol +++ b/templates/extensions/foundry/packages/foundry/test/YourContract.t.sol @@ -5,24 +5,24 @@ import "forge-std/Test.sol"; import "../contracts/YourContract.sol"; contract YourContractTest is Test { - YourContract public yourContract; + YourContract public yourContract; - function setUp() public { - yourContract = new YourContract(vm.addr(1)); - } + function setUp() public { + yourContract = new YourContract(vm.addr(1)); + } - function testMessageOnDeployment() public view { - require( - keccak256(bytes(yourContract.greeting())) - == keccak256("Building Unstoppable Apps!!!") - ); - } + function testMessageOnDeployment() public view { + require( + keccak256(bytes(yourContract.greeting())) + == keccak256("Building Unstoppable Apps!!!") + ); + } - function testSetNewMessage() public { - yourContract.setGreeting("Learn Scaffold-ETH 2! :)"); - require( - keccak256(bytes(yourContract.greeting())) - == keccak256("Learn Scaffold-ETH 2! :)") - ); - } + function testSetNewMessage() public { + yourContract.setGreeting("Learn Scaffold-ETH 2! :)"); + require( + keccak256(bytes(yourContract.greeting())) + == keccak256("Learn Scaffold-ETH 2! :)") + ); + } } From 9712cc3b8ab4ff978c88284618ab3bb3e69dac44 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Tue, 18 Jun 2024 14:27:01 +0530 Subject: [PATCH 04/13] use tripe equal check instead of include + update name --- src/tasks/copy-template-files.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/tasks/copy-template-files.ts b/src/tasks/copy-template-files.ts index 4775dc32a..fe128b021 100644 --- a/src/tasks/copy-template-files.ts +++ b/src/tasks/copy-template-files.ts @@ -222,9 +222,8 @@ const processTemplatedFiles = async ( const containsNextjs = targetPath.includes("nextjs"); const containsDotfile = /\/\.[^/]+/.test(targetPath); - const hardhatOrFoundry = targetPath.split("packages")[1]?.split("/")[1]; - const isHardhatOrFoundry = - hardhatOrFoundry && (hardhatOrFoundry.includes("hardhat") || hardhatOrFoundry.includes("foundry")); + const packageName = targetPath.split("packages")[1]?.split("/")[1]; + const isHardhatOrFoundry = packageName && (packageName === "hardhat" || packageName === "foundry"); if (containsNextjs && !containsDotfile) { finalOutput = await formatWithPrettier(output, { From c2cd9d12a25bbb71e0542cadecd23a408ae4297e Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 22:07:12 +0530 Subject: [PATCH 05/13] format file using execa command --- src/main.ts | 5 +++ src/tasks/copy-template-files.ts | 29 +---------------- src/tasks/prettier-format.ts | 53 ++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 28 deletions(-) create mode 100644 src/tasks/prettier-format.ts diff --git a/src/main.ts b/src/main.ts index c5b70e2bc..01ceb98cf 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,6 +6,7 @@ import { Listr } from "listr2"; import path from "path"; import { fileURLToPath } from "url"; import { getArgumentFromExternalExtensionOption } from "./utils/external-extensions"; +import { prettierFormat } from "./tasks/prettier-format"; export async function createProject(options: Options) { console.log(`\n`); @@ -28,6 +29,10 @@ export async function createProject(options: Options) { )}${options.externalExtension ? ` with the ${chalk.green.bold(getArgumentFromExternalExtensionOption(options.externalExtension))} extension` : ""}`, task: () => copyTemplateFiles(options, templateDirectory, targetDirectory), }, + { + title: "🪄 Formatting files", + task: () => prettierFormat(targetDirectory, options), + }, { title: `📦 Installing dependencies with yarn, this could take a while`, task: () => installPackages(targetDirectory), diff --git a/src/tasks/copy-template-files.ts b/src/tasks/copy-template-files.ts index fe128b021..e17419b66 100644 --- a/src/tasks/copy-template-files.ts +++ b/src/tasks/copy-template-files.ts @@ -11,10 +11,6 @@ import path from "path"; import { promisify } from "util"; import link from "../utils/link"; import { getArgumentFromExternalExtensionOption } from "../utils/external-extensions"; -// @ts-expect-error - no types available -import solidityPlugin from "prettier-plugin-solidity"; -import pluginSorter from "@trivago/prettier-plugin-sort-imports"; -import { formatWithPrettier, hardhatPrettierConfig, nextJsPrettierConfig } from "../utils/format-with-prettier"; const EXTERNAL_EXTENSION_TMP_FOLDER = "tmp-external-extension"; const copy = promisify(ncp); @@ -218,30 +214,7 @@ const processTemplatedFiles = async ( templateTargetName, ); - let finalOutput = output; - - const containsNextjs = targetPath.includes("nextjs"); - const containsDotfile = /\/\.[^/]+/.test(targetPath); - const packageName = targetPath.split("packages")[1]?.split("/")[1]; - const isHardhatOrFoundry = packageName && (packageName === "hardhat" || packageName === "foundry"); - - if (containsNextjs && !containsDotfile) { - finalOutput = await formatWithPrettier(output, { - ...nextJsPrettierConfig, - parser: "typescript", - plugins: [pluginSorter], - fallbackConfig: { parser: "typescript", plugins: undefined }, - }); - } else if (isHardhatOrFoundry && !containsDotfile) { - finalOutput = await formatWithPrettier(output, { - ...hardhatPrettierConfig, - parser: "solidity-parse", - plugins: [solidityPlugin], - fallbackConfig: { parser: "typescript", plugins: undefined }, - }); - } - - fs.writeFileSync(targetPath, finalOutput); + fs.writeFileSync(targetPath, output); if (isDev) { const hasCombinedArgs = Object.keys(combinedArgs).length > 0; diff --git a/src/tasks/prettier-format.ts b/src/tasks/prettier-format.ts new file mode 100644 index 000000000..4fd02aa2e --- /dev/null +++ b/src/tasks/prettier-format.ts @@ -0,0 +1,53 @@ +import { execa } from "execa"; +import path from "path"; +import { Options } from "../types"; + +export async function prettierFormat(targetDir: string, options: Options) { + try { + const nextJsPath = path.join(targetDir, "/packages/nextjs"); + const nextPrettierConfig = path.join(nextJsPath, ".prettierrc.json"); + const result = await execa("yarn", [ + "prettier", + "--write", + nextJsPath, + "--config", + nextPrettierConfig, + "--plugin=@trivago/prettier-plugin-sort-imports", + ]); + if (result.failed) { + throw new Error("There was a problem running the prettier in nextjs package"); + } + + if (options.extensions.includes("hardhat")) { + const hardhatPackagePath = path.join(targetDir, "/packages/hardhat"); + const hardhatPrettierConfig = path.join(hardhatPackagePath, ".prettierrc.json"); + const hardhatResult = await execa("yarn", [ + "prettier", + "--write", + `${hardhatPackagePath}/*.ts`, + `${hardhatPackagePath}/deploy/**/*.ts`, + `${hardhatPackagePath}/scripts/**/*.ts`, + `${hardhatPackagePath}/test/**/*.ts`, + `${hardhatPackagePath}/contracts/**/*.sol`, + "--config", + hardhatPrettierConfig, + "--plugin=prettier-plugin-solidity", + ]); + if (hardhatResult.failed) { + throw new Error("There was a problem running prettier in the hardhat package"); + } + } + + if (options.extensions.includes("foundry")) { + const foundryPackagePath = path.resolve(targetDir, "packages", "foundry"); + const foundryResult = await execa("forge", ["fmt"], { cwd: foundryPackagePath }); + if (foundryResult.failed) { + throw new Error("There was a problem running the forge fmt in the foundry package"); + } + } + } catch (error) { + throw new Error("Failed to run prettier", { cause: error }); + } + + return true; +} From 09fa8c0a2b0a7011af7a01d49899c8679ebfc775 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 22:48:39 +0530 Subject: [PATCH 06/13] update main.ts --- src/main.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.ts b/src/main.ts index 6c55fc982..5ae5e8d60 100644 --- a/src/main.ts +++ b/src/main.ts @@ -43,7 +43,7 @@ export async function createProject(options: Options) { } return false; }, - }, + }, { title: `📡 Initializing Git repository${options.extensions.includes(SOLIDITY_FRAMEWORKS.FOUNDRY) ? " and submodules" : ""}`, task: () => createFirstGitCommit(targetDirectory, options), From 277e55c27838858eaffda3723e7a73c48326ef7f Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 22:51:25 +0530 Subject: [PATCH 07/13] use SOLIDITY_FRAMEWORKS variable instead of hardcoding --- src/tasks/prettier-format.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/tasks/prettier-format.ts b/src/tasks/prettier-format.ts index 4fd02aa2e..2e190691a 100644 --- a/src/tasks/prettier-format.ts +++ b/src/tasks/prettier-format.ts @@ -1,10 +1,11 @@ import { execa } from "execa"; import path from "path"; import { Options } from "../types"; +import { SOLIDITY_FRAMEWORKS } from "../utils/consts"; export async function prettierFormat(targetDir: string, options: Options) { try { - const nextJsPath = path.join(targetDir, "/packages/nextjs"); + const nextJsPath = path.join(targetDir, "packages", "nextjs"); const nextPrettierConfig = path.join(nextJsPath, ".prettierrc.json"); const result = await execa("yarn", [ "prettier", @@ -18,8 +19,8 @@ export async function prettierFormat(targetDir: string, options: Options) { throw new Error("There was a problem running the prettier in nextjs package"); } - if (options.extensions.includes("hardhat")) { - const hardhatPackagePath = path.join(targetDir, "/packages/hardhat"); + if (options.extensions.includes(SOLIDITY_FRAMEWORKS.HARDHAT)) { + const hardhatPackagePath = path.join(targetDir, "packages", SOLIDITY_FRAMEWORKS.HARDHAT); const hardhatPrettierConfig = path.join(hardhatPackagePath, ".prettierrc.json"); const hardhatResult = await execa("yarn", [ "prettier", @@ -38,8 +39,8 @@ export async function prettierFormat(targetDir: string, options: Options) { } } - if (options.extensions.includes("foundry")) { - const foundryPackagePath = path.resolve(targetDir, "packages", "foundry"); + if (options.extensions.includes(SOLIDITY_FRAMEWORKS.FOUNDRY)) { + const foundryPackagePath = path.resolve(targetDir, "packages", SOLIDITY_FRAMEWORKS.FOUNDRY); const foundryResult = await execa("forge", ["fmt"], { cwd: foundryPackagePath }); if (foundryResult.failed) { throw new Error("There was a problem running the forge fmt in the foundry package"); From fd3b4be6b27976ada59c5ad68dcf47e556b017b8 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 23:05:43 +0530 Subject: [PATCH 08/13] clean prettier-format logic --- src/tasks/prettier-format.ts | 43 ++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/src/tasks/prettier-format.ts b/src/tasks/prettier-format.ts index 2e190691a..e45fee071 100644 --- a/src/tasks/prettier-format.ts +++ b/src/tasks/prettier-format.ts @@ -3,47 +3,46 @@ import path from "path"; import { Options } from "../types"; import { SOLIDITY_FRAMEWORKS } from "../utils/consts"; +async function runPrettier(targetPath: string, prettierConfigPath: string, prettierPlugins: string[]) { + const result = await execa("yarn", [ + "prettier", + "--write", + targetPath, + "--config", + prettierConfigPath, + ...prettierPlugins, + ]); + if (result.failed) { + throw new Error(`There was a problem running prettier in ${targetPath}`); + } +} + export async function prettierFormat(targetDir: string, options: Options) { try { const nextJsPath = path.join(targetDir, "packages", "nextjs"); const nextPrettierConfig = path.join(nextJsPath, ".prettierrc.json"); - const result = await execa("yarn", [ - "prettier", - "--write", - nextJsPath, - "--config", - nextPrettierConfig, - "--plugin=@trivago/prettier-plugin-sort-imports", - ]); - if (result.failed) { - throw new Error("There was a problem running the prettier in nextjs package"); - } + + await runPrettier(nextJsPath, nextPrettierConfig, ["--plugin=@trivago/prettier-plugin-sort-imports"]); if (options.extensions.includes(SOLIDITY_FRAMEWORKS.HARDHAT)) { const hardhatPackagePath = path.join(targetDir, "packages", SOLIDITY_FRAMEWORKS.HARDHAT); const hardhatPrettierConfig = path.join(hardhatPackagePath, ".prettierrc.json"); - const hardhatResult = await execa("yarn", [ - "prettier", - "--write", + const hardhatPaths = [ `${hardhatPackagePath}/*.ts`, `${hardhatPackagePath}/deploy/**/*.ts`, `${hardhatPackagePath}/scripts/**/*.ts`, `${hardhatPackagePath}/test/**/*.ts`, `${hardhatPackagePath}/contracts/**/*.sol`, - "--config", - hardhatPrettierConfig, - "--plugin=prettier-plugin-solidity", - ]); - if (hardhatResult.failed) { - throw new Error("There was a problem running prettier in the hardhat package"); - } + ]; + + await runPrettier(hardhatPaths.join(" "), hardhatPrettierConfig, ["--plugin=prettier-plugin-solidity"]); } if (options.extensions.includes(SOLIDITY_FRAMEWORKS.FOUNDRY)) { const foundryPackagePath = path.resolve(targetDir, "packages", SOLIDITY_FRAMEWORKS.FOUNDRY); const foundryResult = await execa("forge", ["fmt"], { cwd: foundryPackagePath }); if (foundryResult.failed) { - throw new Error("There was a problem running the forge fmt in the foundry package"); + throw new Error("There was a problem running forge fmt in the foundry package"); } } } catch (error) { From 25cee7269b808986ba7381365a0e0e4325e39507 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 23:06:33 +0530 Subject: [PATCH 09/13] remove extra line from copy-template-files --- src/tasks/copy-template-files.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/tasks/copy-template-files.ts b/src/tasks/copy-template-files.ts index cdd1b11b8..f13fa1fd7 100644 --- a/src/tasks/copy-template-files.ts +++ b/src/tasks/copy-template-files.ts @@ -225,7 +225,6 @@ const processTemplatedFiles = async ( templateFileDescriptor.relativePath.split(templateTargetName)[0], templateTargetName, ); - fs.writeFileSync(targetPath, output); if (isDev) { From 839200e7e0ba8172c1c5d362ca1d8970e69b3247 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Wed, 26 Jun 2024 23:08:45 +0530 Subject: [PATCH 10/13] cleanup --- src/main.ts | 9 ++++-- src/tasks/index.ts | 1 + src/utils/format-with-prettier.ts | 47 ------------------------------- 3 files changed, 8 insertions(+), 49 deletions(-) delete mode 100644 src/utils/format-with-prettier.ts diff --git a/src/main.ts b/src/main.ts index 5ae5e8d60..7dfdb0fae 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,10 @@ -import { copyTemplateFiles, createProjectDirectory, installPackages, createFirstGitCommit } from "./tasks"; +import { + copyTemplateFiles, + createProjectDirectory, + installPackages, + createFirstGitCommit, + prettierFormat, +} from "./tasks"; import type { Options } from "./types"; import { renderOutroMessage } from "./utils/render-outro-message"; import chalk from "chalk"; @@ -6,7 +12,6 @@ import { Listr } from "listr2"; import path from "path"; import { fileURLToPath } from "url"; import { getArgumentFromExternalExtensionOption } from "./utils/external-extensions"; -import { prettierFormat } from "./tasks/prettier-format"; import { SOLIDITY_FRAMEWORKS } from "./utils/consts"; export async function createProject(options: Options) { diff --git a/src/tasks/index.ts b/src/tasks/index.ts index e3b7c4ed3..75a12fecb 100644 --- a/src/tasks/index.ts +++ b/src/tasks/index.ts @@ -2,3 +2,4 @@ export * from "./copy-template-files"; export * from "./create-project-directory"; export * from "./install-packages"; export * from "./create-first-git-commit"; +export * from "./prettier-format"; diff --git a/src/utils/format-with-prettier.ts b/src/utils/format-with-prettier.ts deleted file mode 100644 index ae78b51a8..000000000 --- a/src/utils/format-with-prettier.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Options, format } from "prettier"; - -export const formatWithPrettier = async ( - output: string, - { fallbackConfig, parser, plugins, ...config }: Options & { fallbackConfig?: Options }, -) => { - try { - return await format(output, { ...config, parser, plugins }); - } catch (e) { - try { - if (!fallbackConfig) return output; - - return await format(output, { parser, plugins, ...config, ...fallbackConfig }); - } catch (e) { - return output; - } - } -}; - -export const nextJsPrettierConfig = { - arrowParens: "avoid", - printWidth: 120, - tabWidth: 2, - trailingComma: "all", - importOrder: ["^react$", "^next/(.*)$", "", "^@heroicons/(.*)$", "^~~/(.*)$"], - importOrderSortSpecifiers: true, -} as const; - -export const hardhatPrettierConfig = { - arrowParens: "avoid", - printWidth: 120, - tabWidth: 2, - trailingComma: "all", - overrides: [ - { - files: "*.sol", - options: { - printWidth: 80, - tabWidth: 4, - useTabs: true, - singleQuote: false, - bracketSpacing: true, - explicitTypes: "always", - }, - }, - ], -} as const; From 4e982aea38cea0af2e349aefeb76be28ec26e7d7 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Thu, 27 Jun 2024 14:35:07 +0530 Subject: [PATCH 11/13] spread use array for runPrettier targetPath --- src/tasks/prettier-format.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/tasks/prettier-format.ts b/src/tasks/prettier-format.ts index e45fee071..2bf6cb3da 100644 --- a/src/tasks/prettier-format.ts +++ b/src/tasks/prettier-format.ts @@ -3,17 +3,19 @@ import path from "path"; import { Options } from "../types"; import { SOLIDITY_FRAMEWORKS } from "../utils/consts"; -async function runPrettier(targetPath: string, prettierConfigPath: string, prettierPlugins: string[]) { +async function runPrettier(targetPath: string[], prettierConfigPath: string, prettierPlugins: string[]) { + console.log("the prettier config path is", prettierConfigPath); const result = await execa("yarn", [ "prettier", "--write", - targetPath, + ...targetPath, "--config", prettierConfigPath, ...prettierPlugins, + "--no-editorconfig", ]); if (result.failed) { - throw new Error(`There was a problem running prettier in ${targetPath}`); + throw new Error(`There was a problem running prettier in ${targetPath.join(" ")}`); } } @@ -22,7 +24,7 @@ export async function prettierFormat(targetDir: string, options: Options) { const nextJsPath = path.join(targetDir, "packages", "nextjs"); const nextPrettierConfig = path.join(nextJsPath, ".prettierrc.json"); - await runPrettier(nextJsPath, nextPrettierConfig, ["--plugin=@trivago/prettier-plugin-sort-imports"]); + await runPrettier([nextJsPath], nextPrettierConfig, ["--plugin=@trivago/prettier-plugin-sort-imports"]); if (options.extensions.includes(SOLIDITY_FRAMEWORKS.HARDHAT)) { const hardhatPackagePath = path.join(targetDir, "packages", SOLIDITY_FRAMEWORKS.HARDHAT); @@ -35,7 +37,7 @@ export async function prettierFormat(targetDir: string, options: Options) { `${hardhatPackagePath}/contracts/**/*.sol`, ]; - await runPrettier(hardhatPaths.join(" "), hardhatPrettierConfig, ["--plugin=prettier-plugin-solidity"]); + await runPrettier(hardhatPaths, hardhatPrettierConfig, ["--plugin=prettier-plugin-solidity"]); } if (options.extensions.includes(SOLIDITY_FRAMEWORKS.FOUNDRY)) { From 61f35b4ac03f5e15206d53d197a99ba3d97af7e1 Mon Sep 17 00:00:00 2001 From: Rinat Date: Thu, 27 Jun 2024 21:01:16 +0200 Subject: [PATCH 12/13] fix: spaces bug --- package.json | 2 +- templates/base/packages/nextjs/.prettierrc.json | 3 ++- templates/base/packages/nextjs/package.json | 2 +- yarn.lock | 10 +++++----- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 3306b6095..527bf98c3 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,7 @@ "merge-packages": "^0.1.6", "ncp": "2.0.0", "pkg-install": "1.0.0", - "prettier": "3.2.5", + "prettier": "3.3.2", "prettier-plugin-solidity": "^1.3.1" }, "packageManager": "yarn@3.5.0" diff --git a/templates/base/packages/nextjs/.prettierrc.json b/templates/base/packages/nextjs/.prettierrc.json index 36fa5f31e..a417fdf1f 100644 --- a/templates/base/packages/nextjs/.prettierrc.json +++ b/templates/base/packages/nextjs/.prettierrc.json @@ -4,5 +4,6 @@ "tabWidth": 2, "trailingComma": "all", "importOrder": ["^react$", "^next/(.*)$", "", "^@heroicons/(.*)$", "^~~/(.*)$"], - "importOrderSortSpecifiers": true + "importOrderSortSpecifiers": true, + "plugins": ["@trivago/prettier-plugin-sort-imports"] } diff --git a/templates/base/packages/nextjs/package.json b/templates/base/packages/nextjs/package.json index b23d940b0..a5710bc7c 100644 --- a/templates/base/packages/nextjs/package.json +++ b/templates/base/packages/nextjs/package.json @@ -50,7 +50,7 @@ "eslint-config-prettier": "~8.5.0", "eslint-plugin-prettier": "~4.2.1", "postcss": "~8.4.16", - "prettier": "~2.8.4", + "prettier": "3.3.2", "tailwindcss": "~3.4.3", "type-fest": "~4.6.0", "typescript": "5.1.6", diff --git a/yarn.lock b/yarn.lock index 8b420a0a2..28c2393a4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1538,7 +1538,7 @@ __metadata: merge-packages: ^0.1.6 ncp: 2.0.0 pkg-install: 1.0.0 - prettier: 3.2.5 + prettier: 3.3.2 prettier-plugin-solidity: ^1.3.1 rollup: 3.21.0 rollup-plugin-auto-external: 2.0.0 @@ -4190,12 +4190,12 @@ __metadata: languageName: node linkType: hard -"prettier@npm:3.2.5": - version: 3.2.5 - resolution: "prettier@npm:3.2.5" +"prettier@npm:3.3.2": + version: 3.3.2 + resolution: "prettier@npm:3.3.2" bin: prettier: bin/prettier.cjs - checksum: 2ee4e1417572372afb7a13bb446b34f20f1bf1747db77cf6ccaf57a9be005f2f15c40f903d41a6b79eec3f57fff14d32a20fb6dee1f126da48908926fe43c311 + checksum: 5557d8caed0b182f68123c2e1e370ef105251d1dd75800fadaece3d061daf96b1389141634febf776050f9d732c7ae8fd444ff0b4a61b20535e7610552f32c69 languageName: node linkType: hard From 79ecf572ca6e2d80a8eb02225bcd0c8f67142d65 Mon Sep 17 00:00:00 2001 From: Shiv Bhonde Date: Fri, 28 Jun 2024 20:48:02 +0530 Subject: [PATCH 13/13] add changeset --- .changeset/angry-zoos-kneel.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/angry-zoos-kneel.md diff --git a/.changeset/angry-zoos-kneel.md b/.changeset/angry-zoos-kneel.md new file mode 100644 index 000000000..1dafff23a --- /dev/null +++ b/.changeset/angry-zoos-kneel.md @@ -0,0 +1,5 @@ +--- +"create-eth": patch +--- + +cli: format instance with prettier from cli