-
-
Notifications
You must be signed in to change notification settings - Fork 35
feat: add codemod for DEP0162 fs write coercion #416
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
Open
syhstanley
wants to merge
5
commits into
nodejs:main
Choose a base branch
from
syhstanley:feat/fs-write-coercion-codemod
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a7618bf
feat(fs-write-coercion): add codemod for DEP0162 fs write coercion
stanleyshen2003 ed6d502
fix(fs-write-coercion): improve codebase alignment and fix edge cases
stanleyshen2003 50f5d38
fix(fs-write-coercion): address reviewer feedback
stanleyshen2003 24bb316
Merge branch 'main' into feat/fs-write-coercion-codemod
syhstanley 34c6008
fix(fs-write-coercion): fix test script path in package.json
stanleyshen2003 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # DEP0162: Implicit coercion of objects to strings in `fs` write functions | ||
|
|
||
| This recipe adds explicit `String()` conversion for objects passed as the data parameter to `fs` write functions. | ||
|
|
||
| See [DEP0162](https://nodejs.org/api/deprecations.html#DEP0162). | ||
|
|
||
| ## Example | ||
|
|
||
| ```diff | ||
| const fs = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "file content" }; | ||
| - fs.writeFileSync("file.txt", data); | ||
| + fs.writeFileSync("file.txt", String(data)); | ||
| ``` | ||
|
|
||
| ## Supported APIs | ||
|
|
||
| - `fs.writeFile` / `fs.writeFileSync` | ||
| - `fs.appendFile` / `fs.appendFileSync` | ||
| - `fs.write` | ||
| - `fsPromises.writeFile` / `fsPromises.appendFile` | ||
|
|
||
| Also handles destructured imports: | ||
|
|
||
| ```diff | ||
| const { writeFileSync } = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "content" }; | ||
| - writeFileSync("file.txt", data); | ||
| + writeFileSync("file.txt", String(data)); | ||
| ``` |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| schema_version: "1.0" | ||
| name: "@nodejs/fs-write-coercion" | ||
| version: "1.0.0" | ||
| description: Handle DEP0162 by adding explicit String() conversion for objects passed to fs write functions. | ||
| author: Stanley Shen | ||
| license: MIT | ||
| workflow: workflow.yaml | ||
| category: migration | ||
|
|
||
| targets: | ||
| languages: | ||
| - javascript | ||
| - typescript | ||
|
|
||
| keywords: | ||
| - transformation | ||
| - migration | ||
| - fs | ||
| - DEP0162 | ||
|
|
||
| registry: | ||
| access: public | ||
| visibility: public |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| { | ||
| "name": "@nodejs/fs-write-coercion", | ||
| "version": "1.0.0", | ||
| "description": "Handle DEP0162 by adding explicit String() conversion for objects passed to fs write functions.", | ||
| "type": "module", | ||
| "scripts": { | ||
| "test": "npx codemod jssg test -l typescript ./src/workflow.ts ./tests" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/nodejs/userland-migrations.git", | ||
| "directory": "recipes/fs-write-coercion", | ||
| "bugs": "https://github.com/nodejs/userland-migrations/issues" | ||
| }, | ||
| "author": "Stanley Shen", | ||
| "license": "MIT", | ||
| "homepage": "https://github.com/nodejs/userland-migrations/blob/main/recipes/fs-write-coercion/README.md", | ||
| "devDependencies": { | ||
| "@codemod.com/jssg-types": "^1.5.0" | ||
| }, | ||
| "dependencies": { | ||
| "@nodejs/codemod-utils": "*" | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| import { getModuleDependencies } from '@nodejs/codemod-utils/ast-grep/module-dependencies'; | ||
| import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path'; | ||
| import type { SgRoot, Edit, SgNode } from '@codemod.com/jssg-types/main'; | ||
| import type Js from '@codemod.com/jssg-types/langs/javascript'; | ||
|
|
||
| /** | ||
| * fs write functions where the data parameter is the 2nd argument. | ||
| */ | ||
| const TARGET_FUNCTIONS = [ | ||
| { path: '$.writeFile', prop: 'writeFile' }, | ||
| { path: '$.writeFileSync', prop: 'writeFileSync' }, | ||
| { path: '$.appendFile', prop: 'appendFile' }, | ||
| { path: '$.appendFileSync', prop: 'appendFileSync' }, | ||
| { path: '$.write', prop: 'write' }, | ||
| // promises API | ||
| { path: '$.promises.writeFile', prop: 'writeFile' }, | ||
| { path: '$.promises.appendFile', prop: 'appendFile' }, | ||
| ]; | ||
|
|
||
| /** | ||
| * Check if a text expression is already a safe type that doesn't need String() wrapping. | ||
| * Safe types: string literals, template literals, Buffer/TypedArray expressions, | ||
| * already-wrapped String() or .toString() calls. | ||
| */ | ||
| function isSafeType(text: string): boolean { | ||
| const trimmed = text.trim(); | ||
|
|
||
| // String literals and template literals (', ", `) | ||
| if (/^['"`]/.test(trimmed)) return true; | ||
|
|
||
| // Already has .toString() | ||
| if (trimmed.endsWith('.toString()')) return true; | ||
|
|
||
| // Already wrapped in String() — exact match to avoid false positives like Stringify() | ||
| if (/^String\(/.test(trimmed) && trimmed.endsWith(')')) return true; | ||
|
|
||
| // Buffer.from(), Buffer.alloc(), etc. | ||
| if (/^Buffer\.\w+\(/.test(trimmed)) return true; | ||
|
|
||
| // new Uint8Array, new Int8Array, etc. | ||
| if ( | ||
| /^new\s+(Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|DataView)\b/.test( | ||
| trimmed, | ||
| ) | ||
| ) | ||
| return true; | ||
|
|
||
| // Numeric literal (integers and floats) | ||
| if (/^\d+(\.\d+)?$/.test(trimmed)) return true; | ||
|
|
||
| // null or undefined | ||
| if (trimmed === 'null' || trimmed === 'undefined') return true; | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * fs.write() has two overloaded signatures: | ||
| * 1. fs.write(fd, buffer, offset, length, position, callback) — buffer overload (>=4 args typically) | ||
| * 2. fs.write(fd, string, position, encoding, callback) — string overload | ||
| * | ||
| * When called with >= 4 args where the 3rd arg looks like a numeric offset, | ||
| * it's likely the buffer overload — skip wrapping to avoid corrupting Buffer data. | ||
| */ | ||
| function isLikelyBufferOverload(args: readonly { text: () => string }[]): boolean { | ||
| if (args.length < 4) return false; | ||
| const thirdArg = args[2]!.text().trim(); | ||
| // If the 3rd argument is a numeric literal (offset), it's likely the buffer overload | ||
| return /^\d+$/.test(thirdArg); | ||
| } | ||
|
|
||
| /** | ||
| * Transform function that adds explicit String() conversion for objects | ||
| * passed as the data parameter to fs write functions. | ||
| * | ||
| * See DEP0162: https://nodejs.org/api/deprecations.html#DEP0162 | ||
| * | ||
| * Handles: | ||
| * - fs.writeFile(file, data, ...) → fs.writeFile(file, String(data), ...) | ||
| * - fs.writeFileSync(file, data, ...) → fs.writeFileSync(file, String(data), ...) | ||
| * - fs.appendFile(path, data, ...) → fs.appendFile(path, String(data), ...) | ||
| * - fs.appendFileSync(path, data, ...) → fs.appendFileSync(path, String(data), ...) | ||
| * - fs.write(fd, data, ...) → fs.write(fd, String(data), ...) | ||
| * - fsPromises.writeFile/appendFile | ||
| * - Destructured imports: writeFile(path, data) → writeFile(path, String(data)) | ||
| */ | ||
| export default function transform(root: SgRoot<Js>): string | null { | ||
| const rootNode = root.root(); | ||
| const edits: Edit[] = []; | ||
|
|
||
| // Gather fs import/require statements (both 'fs' and 'fs/promises') | ||
| const stmtNodes = [ | ||
| ...getModuleDependencies(root, 'fs'), | ||
| ...getModuleDependencies(root, 'fs/promises'), | ||
| ]; | ||
|
|
||
| if (!stmtNodes.length) return null; | ||
|
|
||
| for (const stmt of stmtNodes) { | ||
| for (const target of TARGET_FUNCTIONS) { | ||
| const local = resolveBindingPath(stmt, target.path); | ||
| if (!local) continue; | ||
|
|
||
| // Find all call expressions for this binding | ||
| const calls = rootNode.findAll({ | ||
| rule: { | ||
| kind: 'call_expression', | ||
| has: { | ||
| field: 'function', | ||
| any: [ | ||
| { kind: 'identifier', regex: `^${local}$` }, | ||
| { | ||
| kind: 'member_expression', | ||
| has: { | ||
| field: 'property', | ||
| kind: 'property_identifier', | ||
| regex: `^${escapeRegex(target.prop)}$`, | ||
| }, | ||
| }, | ||
| ], | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| for (const call of calls) { | ||
| // Get the arguments node | ||
| const argsNode = call.find({ rule: { kind: 'arguments' } }); | ||
| if (!argsNode) continue; | ||
|
|
||
| // Get all direct child nodes that are arguments (skip commas, parens) | ||
| const args = argsNode | ||
| .children() | ||
| .filter( | ||
| (child) => | ||
| child.kind() !== ',' && | ||
| child.kind() !== '(' && | ||
| child.kind() !== ')', | ||
| ); | ||
|
|
||
| // Data is the 2nd argument (index 1) | ||
| if (args.length < 2) continue; | ||
|
|
||
| // For fs.write(), skip the buffer overload: | ||
| // fs.write(fd, buffer, offset, length, ...) — wrapping buffer with String() is wrong | ||
| if (target.prop === 'write' && isLikelyBufferOverload(args)) continue; | ||
|
|
||
| const dataArg = args[1]!; | ||
| const dataText = dataArg.text(); | ||
|
|
||
| // Skip if already a safe type | ||
| if (isSafeType(dataText)) continue; | ||
|
|
||
| // Wrap with String() | ||
| edits.push(dataArg.replace(`String(${dataText})`)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (!edits.length) return null; | ||
|
|
||
| return rootNode.commitEdits(edits); | ||
| } | ||
|
|
||
| function escapeRegex(str: string): string { | ||
| return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | ||
| } | ||
8 changes: 8 additions & 0 deletions
8
recipes/fs-write-coercion/tests/already-valid-calls/expected.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| // These are all valid and don't need changes | ||
| fs.writeFileSync("file1.txt", "string"); | ||
| fs.writeFileSync("file2.txt", Buffer.from("buffer")); | ||
| fs.writeFileSync("file3.txt", new Uint8Array([1, 2, 3])); | ||
| fs.writeFileSync("file4.txt", String(someObj)); | ||
| fs.writeFileSync("file5.txt", someObj.toString()); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| // These are all valid and don't need changes | ||
| fs.writeFileSync("file1.txt", "string"); | ||
| fs.writeFileSync("file2.txt", Buffer.from("buffer")); | ||
| fs.writeFileSync("file3.txt", new Uint8Array([1, 2, 3])); | ||
| fs.writeFileSync("file4.txt", String(someObj)); | ||
| fs.writeFileSync("file5.txt", someObj.toString()); |
6 changes: 6 additions & 0 deletions
6
recipes/fs-write-coercion/tests/append-file-callback/expected.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const content = { toString: () => "more content" }; | ||
| fs.appendFile("file.txt", String(content), (err) => { | ||
| if (err) throw err; | ||
| }); |
6 changes: 6 additions & 0 deletions
6
recipes/fs-write-coercion/tests/append-file-callback/input.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const content = { toString: () => "more content" }; | ||
| fs.appendFile("file.txt", content, (err) => { | ||
| if (err) throw err; | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "appended data" }; | ||
| fs.appendFileSync("file.txt", String(data)); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "appended data" }; | ||
| fs.appendFileSync("file.txt", data); |
5 changes: 5 additions & 0 deletions
5
recipes/fs-write-coercion/tests/destructured-imports/expected.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| const { writeFileSync, appendFileSync } = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "file content" }; | ||
| writeFileSync("file.txt", String(data)); | ||
| appendFileSync("log.txt", String(data)); |
5 changes: 5 additions & 0 deletions
5
recipes/fs-write-coercion/tests/destructured-imports/input.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| const { writeFileSync, appendFileSync } = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "file content" }; | ||
| writeFileSync("file.txt", data); | ||
| appendFileSync("log.txt", data); |
4 changes: 4 additions & 0 deletions
4
recipes/fs-write-coercion/tests/esm-write-file-promises/expected.mjs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| import { writeFile } from "node:fs/promises"; | ||
|
|
||
| const data = { toString: () => "async content" }; | ||
| await writeFile("file.txt", String(data)); |
4 changes: 4 additions & 0 deletions
4
recipes/fs-write-coercion/tests/esm-write-file-promises/input.mjs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| import { writeFile } from "node:fs/promises"; | ||
|
|
||
| const data = { toString: () => "async content" }; | ||
| await writeFile("file.txt", data); |
8 changes: 8 additions & 0 deletions
8
recipes/fs-write-coercion/tests/fs-write-callback/expected.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const fd = fs.openSync("file.txt", "w"); | ||
| const data = { toString: () => "buffer content" }; | ||
| fs.write(fd, String(data), (err) => { | ||
| if (err) throw err; | ||
| fs.closeSync(fd); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const fd = fs.openSync("file.txt", "w"); | ||
| const data = { toString: () => "buffer content" }; | ||
| fs.write(fd, data, (err) => { | ||
| if (err) throw err; | ||
| fs.closeSync(fd); | ||
| }); |
6 changes: 6 additions & 0 deletions
6
recipes/fs-write-coercion/tests/write-file-callback/expected.js
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const obj = { toString: () => "content" }; | ||
| fs.writeFile("file.txt", String(obj), (err) => { | ||
| if (err) throw err; | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const obj = { toString: () => "content" }; | ||
| fs.writeFile("file.txt", obj, (err) => { | ||
| if (err) throw err; | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "file content" }; | ||
| fs.writeFileSync("file.txt", String(data)); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| const fs = require("node:fs"); | ||
|
|
||
| const data = { toString: () => "file content" }; | ||
| fs.writeFileSync("file.txt", data); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.