Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prettier auto formatting #233

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .git-hooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env node

const { execSync } = require("child_process");
const { existsSync, promises: fsPromises } = require("fs");
const { join, resolve } = require("path");

const excludedDirs = ["node_modules"];
Copy link
Owner

Choose a reason for hiding this comment

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

Do you guys think it's a good idea to make this code read and exclude whatever is in the .gitignore file, instead of hard coding node_modules, in case we have something else in the future that we don't want to format (since we don't need to format anything that is not going to be pushed)

Copy link
Collaborator

Choose a reason for hiding this comment

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

That is a good point, it should exclude anything in the .gitignore file.

Copy link
Author

Choose a reason for hiding this comment

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

Yes guys, you are right. I was considering the same approach, as it offers more flexibility.
However, considering that:

  1. We are formatting .js files only
  2. Among the directories/files listed in .gitignore, only the node_modules directory contains .js files.
  3. After checking a list of most frequently "gitignored" files/directories, it seems unlikely that we will encounter other .js files within .gitignore.
  4. The .gitignore file is typically not very dynamic once the project architecture is established.
  5. The execution time using the hardcoded approach is significantly faster.

Taking all these factors into account, I hdecided to go for the hardcoded approach, as it strikes a suitable balance between speed and efficiency. However, if you still prefer to pursue the .gitignore approach, I would be glad to refactor the code accordingly


const getAllJsFiles = async (dir) => {
const getFilesRecursively = async (currentDir) => {
const files = await fsPromises.readdir(currentDir);
let jsFiles = [];

for (const file of files) {
const filePath = join(currentDir, file);
const fileStat = await fsPromises.stat(filePath);

if (fileStat.isDirectory() && !excludedDirs.includes(file)) {
jsFiles.push(...(await getFilesRecursively(filePath)));
} else if (file.endsWith(".js")) {
jsFiles.push(filePath);
}
}

return jsFiles;
};

try {
return await getFilesRecursively(dir);
} catch (error) {
console.error("Error occurred while getting JS files:", error.message);
throw error;
}
};

const runPrettierOnAllJsFiles = async () => {
try {
const projectDir = resolve(process.cwd());
const allJsFiles = await getAllJsFiles(projectDir);

console.log("Code formatting...");

if (allJsFiles.length > 0) {
let prettierCmd = "npx prettier";
const localPrettierPath = resolve(projectDir, "node_modules/.bin/prettier");
if (existsSync(localPrettierPath)) {
prettierCmd = localPrettierPath;
}

prettierCmd += ` --config ${resolve(projectDir, ".prettierrc.json")} --write ${allJsFiles.join(" ")}`;

execSync(prettierCmd, { stdio: "inherit" });

console.log("Prettier formatting applied to all JS files.");

const gitAddCmd = `git add ${allJsFiles.join(" ")}`;
Copy link
Owner

Choose a reason for hiding this comment

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

Is this going to add (stage) everything even if I try to add one file?

Copy link
Author

Choose a reason for hiding this comment

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

@lugenx you can add just one file. However, during git commit execution, all .js files will be formatted with prettier, to maintain consistent styling even if local formatting tools/settings are used by some devs.
Then formatted files are staged, ensuring accurate tracking by Git version control, which might not always catch formatting changes as effectively as content changes.
If your added file is the only one with style or content differences, only that one gets pushed

Copy link
Collaborator

Choose a reason for hiding this comment

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

@lugenx seeing that this PR itself formatted all files to fit the prettier configuration settings, any updated forks making commits after this merge will be formatted the same. So any files that are updated in future PRs should be the only files pushed.

Copy link
Author

Choose a reason for hiding this comment

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

yes, you are right @tsimian

execSync(gitAddCmd);

console.log("Staged all JS files.");
} else {
console.log("No JS files found in the repository.");
}
} catch (error) {
console.error("An error occurred during Prettier execution:", error.message);
process.exit(1);
}
};

runPrettierOnAllJsFiles();

2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ If you prefer the command line way of downloading and installing things, then fe
##### `git clone https://github.com/lugenx/ecohabit.git`
- Open the cloned folder in VS Code. Open the terminal and make sure its pointing to the root of the cloned project.

- Set custom path for git hooks using terminal command `git config core.hooksPath .git-hooks` in the root directory of the cloned repository;

- Running Backend Node JS Application:

- Change the directory to server folder using terminal command: `cd server`
Expand Down
24 changes: 24 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,8 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"prettier": "^3.0.1"
}
}
17 changes: 7 additions & 10 deletions client/src/components/Main.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ const Main = () => {
flexDirection="column"
minHeight="550px"
justifyContent="space-between"
marginTop="auto">
marginTop="auto"
>
<Box>
<Typography
variant="h2"
Expand All @@ -45,19 +46,15 @@ const Main = () => {
</Box>
.
</Typography>
<Typography
fontSize = "1.3rem"
mt={2}
variant="subtitle2"
>
Join a community of like-minded individuals and make a positive impact
on the planet &rarr;
<Typography fontSize="1.3rem" mt={2} variant="subtitle2">
Join a community of like-minded individuals and make a positive
impact on the planet &rarr;
</Typography>
</Box>
<Box
sx={{
display:"flex",
width:"100%",
display: "flex",
width: "100%",
justifyContent: "space-between",
}}
>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Recycle.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const Recycle = () => {
sx={{
display: "flex",
flexFlow: "row wrap",
justifyContent: "center",
justifyContent: "center",
gap: 2,
m: "0 0 20px 0",
}}
Expand Down
24 changes: 24 additions & 0 deletions mockapi-earth911/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion mockapi-earth911/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@
"author": "",
"license": "ISC",
"description": "",
"type": "module"
"type": "module",
"devDependencies": {
"prettier": "^3.0.1"
}
}
24 changes: 24 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@
"node-fetch": "^3.3.0",
"validator": "^13.9.0"
},
"type": "module"
"type": "module",
"devDependencies": {
"prettier": "^3.0.1"
}
}
12 changes: 3 additions & 9 deletions server/src/controller/habitController.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ const getHabit = async (req, res) => {
try {
//check if string format is correct
if (!mongoose.Types.ObjectId.isValid(id)) {
return res
.status(400)
.json({ error: "Bad Request" });
return res.status(400).json({ error: "Bad Request" });
}

const habit = await Habit.findById(id);
Expand All @@ -57,9 +55,7 @@ const updateHabit = async (req, res) => {

try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res
.status(400)
.json({ error: "Bad Request" });
return res.status(400).json({ error: "Bad Request" });
}

const habit = await Habit.findOneAndUpdate({ _id: id }, { ...req.body });
Expand All @@ -78,9 +74,7 @@ const deleteHabit = async (req, res) => {

try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res
.status(400)
.json({ error: "Bad Request" });
return res.status(400).json({ error: "Bad Request" });
}

const habit = await Habit.findOneAndDelete({ _id: id });
Expand Down
1 change: 0 additions & 1 deletion server/src/middleware/errorHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ const errorHandler = (err, req, res, next) => {
};

export { notFound, errorHandler };

Loading