-
-
Notifications
You must be signed in to change notification settings - Fork 56
feat(DEP0162): add codemod for 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
base: main
Are you sure you want to change the base?
Changes from all commits
a7618bf
ed6d502
50f5d38
24bb316
34c6008
d7a13db
d2df6a7
b548b41
7f6002b
0a51024
d29aa90
a3733bb
457afb4
a3270ac
0d364ff
46faab6
62bf995
b533228
399afae
898e000
File filter
Filter by extension
Conversations
Jump to
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.
| 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)); | ||
| ``` |
| 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 |
| 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": "*" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| 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, Kinds } 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(node: SgNode<Js, Kinds<Js>>): boolean { | ||
| const text = node.text().trim(); | ||
|
|
||
| // String literals and template literals (', ", `) | ||
| if (/^['"`]/.test(text)) return true; | ||
|
|
||
| // Already has .toString() | ||
| if (text.endsWith('.toString()')) return true; | ||
|
|
||
| // Already wrapped in String() — exact match to avoid false positives like Stringify() | ||
| if (/^String\(/.test(text) && text.endsWith(')')) return true; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ditto |
||
|
|
||
| // Buffer.from(), Buffer.alloc(), etc. | ||
| if (/^Buffer\.\w+\(/.test(text)) return true; | ||
|
|
||
| // new Uint8Array, new Int8Array, etc. | ||
| if ( | ||
| /^new\s+(Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|DataView)\b/.test( | ||
| text, | ||
| ) | ||
| ) | ||
| return true; | ||
|
|
||
| // Numeric literal (integers and floats) | ||
| if (/^\d+(\.\d+)?$/.test(text)) return true; | ||
|
|
||
|
Comment on lines
+37
to
+50
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. All these aren't very robust |
||
| // null or undefined | ||
| if (text === 'null' || text === 'undefined') return true; | ||
|
|
||
| return false; | ||
| } | ||
|
syhstanley marked this conversation as resolved.
|
||
|
|
||
|
|
||
| /** | ||
| * 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 = [ | ||
|
syhstanley marked this conversation as resolved.
|
||
| ...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<'call_expression'>({ | ||
| rule: { | ||
| kind: 'call_expression', | ||
| has: { | ||
| field: 'function', | ||
| any: [ | ||
| { kind: 'identifier', pattern: 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.field('arguments'); | ||
| if (!argsNode) continue; | ||
|
|
||
| // Get all direct child nodes that are arguments (skip commas, parens) | ||
| const args = argsNode | ||
| .children() | ||
| .filter((child) => child.isNamed() && !child.is('comment')); | ||
|
|
||
| // 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(dataArg)) 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, '\\$&'); | ||
| } | ||
| 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()); |
| 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()); |
| 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; | ||
| }); |
| 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; | ||
| }); |
| 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)); |
| 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); |
| 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)); |
| 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); |
| 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)); |
| 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); |
| 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); | ||
| }); |
| 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); | ||
| }); |
| 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; | ||
| }); |
| 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; | ||
| }); |
| 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)); |
| 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); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about odd variations of this, e.g.:
.toString?.()["toString"]()