Skip to content

Commit

Permalink
prettier format instance with cli itself (#55)
Browse files Browse the repository at this point in the history
Co-authored-by: Rinat <rinat@hey.com>
  • Loading branch information
technophile-04 and rin-st authored Jun 28, 2024
1 parent 1f3c740 commit 4db51ac
Show file tree
Hide file tree
Showing 11 changed files with 567 additions and 244 deletions.
5 changes: 5 additions & 0 deletions .changeset/angry-zoos-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-eth": patch
---

cli: format instance with prettier from cli
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -48,14 +47,17 @@
},
"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",
"inquirer": "9.2.0",
"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.3.2",
"prettier-plugin-solidity": "^1.3.1"
},
"packageManager": "yarn@3.5.0"
}
14 changes: 4 additions & 10 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ export async function createProject(options: Options) {
)}${options.externalExtension ? ` with the ${chalk.green.bold(options.dev ? options.externalExtension : 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),
Expand All @@ -45,16 +49,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(SOLIDITY_FRAMEWORKS.FOUNDRY) ? " and submodules" : ""}`,
task: () => createFirstGitCommit(targetDirectory, options),
Expand Down
51 changes: 45 additions & 6 deletions src/tasks/prettier-format.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,54 @@
import { execa } from "execa";
import path from "path";
import { Options } from "../types";
import { SOLIDITY_FRAMEWORKS } from "../utils/consts";

// TODO: Instead of using execa, use prettier package from cli to format targetDir
export async function prettierFormat(targetDir: 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,
"--config",
prettierConfigPath,
...prettierPlugins,
"--no-editorconfig",
]);
if (result.failed) {
throw new Error(`There was a problem running prettier in ${targetPath.join(" ")}`);
}
}

export async function prettierFormat(targetDir: string, options: Options) {
try {
const result = await execa("yarn", ["format"], { cwd: targetDir });
const nextJsPath = path.join(targetDir, "packages", "nextjs");
const nextPrettierConfig = path.join(nextJsPath, ".prettierrc.json");

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 hardhatPaths = [
`${hardhatPackagePath}/*.ts`,
`${hardhatPackagePath}/deploy/**/*.ts`,
`${hardhatPackagePath}/scripts/**/*.ts`,
`${hardhatPackagePath}/test/**/*.ts`,
`${hardhatPackagePath}/contracts/**/*.sol`,
];

await runPrettier(hardhatPaths, hardhatPrettierConfig, ["--plugin=prettier-plugin-solidity"]);
}

if (result.failed) {
throw new Error("There was a problem running the format command");
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 forge fmt in the foundry package");
}
}
} catch (error) {
throw new Error("Failed to create directory", { cause: error });
throw new Error("Failed to run prettier", { cause: error });
}

return true;
Expand Down
3 changes: 2 additions & 1 deletion templates/base/packages/nextjs/.prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"tabWidth": 2,
"trailingComma": "all",
"importOrder": ["^react$", "^next/(.*)$", "<THIRD_PARTY_MODULES>", "^@heroicons/(.*)$", "^~~/(.*)$"],
"importOrderSortSpecifiers": true
"importOrderSortSpecifiers": true,
"plugins": ["@trivago/prettier-plugin-sort-imports"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 { }
}
6 changes: 5 additions & 1 deletion templates/extensions/foundry/packages/foundry/foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading

0 comments on commit 4db51ac

Please sign in to comment.