Created
April 6, 2023 08:09
-
-
Save shreesharma07/64569a622103d1544dbf7fd07b4ac0cc to your computer and use it in GitHub Desktop.
Prettifying Code through Command Line Using Prettier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ! // Importing Modules // | |
import path from "path"; | |
import prettier from "prettier"; | |
import glob from "glob"; | |
import minimist from "minimist"; | |
import shell from "shelljs"; | |
import fs from "fs"; | |
import chalk from "chalk"; | |
try { | |
// * // Get Working Directory Path // | |
const __dirname = shell.pwd().toString(); | |
// * // Default Ignore // | |
const defaultIgnore = ["node_modules", "Temp", ".git", ".husky", ".env", ".eslintignore", ".eslintrc", ".gitignore", ".prettierignore", ".prettierrc", "package-lock.json", "package.json", "tsconfig.json"]; | |
// * // Extenstions to Include // | |
const extensions = ["js", "jsx", "ts", "tsx", "json"]; | |
// * // Ignore files // | |
const ignoreInfo = | |
fs | |
.readFileSync(path.join(__dirname, ".prettierignore"), "utf8") | |
.split("/\r") | |
.join("") | |
.split("\n") | |
.filter((a) => a !== "") || defaultIgnore; | |
// * // Custom Prettier Configs // | |
const config = prettier.resolveConfig.sync(__dirname) || { | |
singleQuote: false, | |
printWidth: 1000, | |
proseWrap: "always", | |
tabWidth: 2, | |
useTabs: true, | |
semi: true, | |
trailingComma: "none", | |
bracketSpacing: true | |
}; | |
// % // Function to Fetch All Folder // | |
const getValidFolderAndFiles = (rootPath) => { | |
if (!(typeof rootPath === "string" && rootPath !== "")) { | |
return []; | |
} else { | |
let allDirs = fs.readdirSync(rootPath); | |
allDirs = allDirs.filter((file) => { | |
const isDir = fs.statSync(path.join(rootPath, file)).isDirectory(); | |
const isIgnored = defaultIgnore.includes(file); | |
const hasValidExtension = extensions.includes(path.extname(path.join(rootPath, file)).substring(1)); | |
// ! // Check for Valid Directory to be included // | |
if (isDir && !isIgnored) { | |
return true; | |
} | |
// ! // Ignorable Directories // | |
if (!isDir && isIgnored) { | |
return false; | |
} | |
// ! // Check for Valid Extension Files // | |
if (!isDir && hasValidExtension) { | |
return true; | |
} | |
// * // Default Return // | |
return false; | |
}); | |
// ! // Return Directory Data // | |
return allDirs || []; | |
} | |
}; | |
// % // Function to Prettify Code // | |
const prettify = (dirs = []) => { | |
// @ // Iterate loop on directories // | |
for (let directory of dirs) { | |
console.time(`\n${chalk.gray.bold(`Formatted ${chalk.cyan.bold(directory)} in `)}`); | |
// ! // Check for Ignore Folders // | |
if (ignoreInfo.includes(directory)) { | |
console.log(`[ ⚠️ ] Ignoring "${directory}" folder as per .prettierignore file contents.`); | |
} else { | |
// * // Get Complete Directory Path // | |
let completePath = path.join(__dirname, directory); | |
let isDirectory = fs.statSync(completePath).isDirectory(); | |
let patterns = isDirectory ? extensions.map((ext) => `${directory}/**/*.${ext}`) : directory; | |
// ! // Check for Folder Exists // | |
if (fs.existsSync(completePath)) { | |
// * // Get all files // | |
let files = patterns.map((pattern) => glob.sync(pattern, { ignore: ignoreInfo })).flat(Infinity); | |
// @ // Iterate over the array and format each file individually // | |
files.forEach((file) => { | |
const startTime = performance.now(); | |
const code = fs.readFileSync(file, "utf8"); | |
let formattedCode = prettier.format(code, { ...config, filepath: file, ignore: ignoreInfo }); | |
// ! // Check for Changes // | |
if (code === formattedCode) { | |
console.log(chalk.black.bold.strikethrough.dim(file)); | |
} else { | |
fs.writeFileSync(file, formattedCode, "utf-8"); | |
let str = `${chalk.white.bold(file)} ${chalk.white.bold(":")} ${chalk.yellowBright.bold(`${(performance.now() - startTime).toFixed(2).toString()} ms`)}`; | |
console.log(str); | |
} | |
}); | |
} else { | |
console.error(chalk.red.bold(`"${directory}" does not exists.`)); | |
} | |
} | |
console.timeEnd(`\n${chalk.gray.bold(`Formatted ${chalk.cyan.bold(directory)} in `)}`); | |
} | |
}; | |
// * // Parse the directory from the command arguments // | |
const args = minimist(process.argv.slice(2)); | |
const dirs = args["_"]; | |
const allDirs = getValidFolderAndFiles(__dirname); | |
// ! // Check for Config Error // | |
if (!config) { | |
console.error("[ ❌ ] Error: No Prettier Configurations Found."); | |
process.exit(0); | |
} | |
// ! // Check for Folders // | |
if (dirs.length === 0) { | |
// * // Prettify All Files in the Root Directory // | |
prettify(allDirs || []); | |
process.exit(0); | |
} else { | |
// * // Prettify Files // | |
prettify(dirs); | |
} | |
} catch (error) { | |
console.log(chalk.bold.red("Error"), chalk.bold.white(":"), chalk.gray.bold(`${error.message}`)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🐼
Install prettier and nodemon to the execute the above script.
npm i prettier@latest #
To Execute the above file, run the below command :
Example :
Author : @shreesharma07