Last active
January 15, 2026 20:29
-
-
Save stephenlf/387f802d1bd1ef7ddbe0b04623bb5efe to your computer and use it in GitHub Desktop.
Simple node script to remove trailing newlines and carriage returns from files. Addresses issues associated with prettier, Salesforce source tracking, and git diff.
This file contains hidden or 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
| #!/usr/bin/env node | |
| /** | |
| * This script removes trailing newlines and carriage returns from files. | |
| * | |
| * Read related issue | |
| * https://github.com/prettier/prettier/issues/6360#issuecomment-3380097220 | |
| * | |
| * By default, SFDX installs a prettier pre-commit git hook. Prettier always adds | |
| * newlines to the end of files. Salesforce strips those newlines away. This leads | |
| * to an endless `git diff` loop, where the difference is just a newline disappearing | |
| * and reappearing. This script addresses that. | |
| * | |
| * ## How to use | |
| * | |
| * Save this to "ci/strip-trailing-newlines.js". Then you can run this directly. | |
| * | |
| * ``` | |
| * node ./ci/strip-trailing-newlines.js -- path/to/file.js | |
| * ``` | |
| * | |
| * You can pipe `git diff` into the script. | |
| * | |
| * ``` | |
| * git diff --name-only | xargs -d '\n' node ./ci/strip-trailing-newlines.js -- | |
| * ``` | |
| * | |
| * You can even configure it to run immediately after prettier in the pre-commit | |
| * hook, by adding this line to "package.json". | |
| ```json | |
| // package.json | |
| "scripts": { | |
| // ... | |
| "precommit": "lint-staged" | |
| }, | |
| "lint-staged": { | |
| "** /*.{cls,cmp,component,css,html,js,json,md,page,trigger,xml,yaml,yml}": [ | |
| "prettier --write", | |
| "node ./ci/strip-trailing-newline.js" | |
| ], | |
| }, | |
| ``` | |
| */ | |
| const fs = require("fs"); | |
| // Get files from command-line args (after `--`) | |
| const files = process.argv.slice(process.argv.indexOf("--") + 1); | |
| if (files.length === 0) { | |
| console.error( | |
| "Usage: node ./scripts/utilities/strip-newlines.js -- file1.cls file2.js" | |
| ); | |
| process.exit(1); | |
| } | |
| files.forEach((file) => { | |
| try { | |
| let content = fs.readFileSync(file, "utf8"); | |
| // Remove carriage returns | |
| content = content.replace(/\r/g, ""); | |
| // Remove a single trailing newline at the end | |
| content = content.replace(/\n$/, ""); | |
| // Write back to the same file | |
| fs.writeFileSync(file, content, "utf8"); | |
| console.log(`Processed: ${file}`); | |
| } catch (err) { | |
| console.error(`Error processing ${file}:`, err.message); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment