CLI: safe-ts migrate, codemods for throw, null and enum #20
Loading…
Reference in a new issue
No description provided.
Delete branch "codemods"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
What
safe-ts migrate <codemod> <files or dirs...>adds codemods for the three rewrites that repeat across an existing codebase. By default it prints a unified diff to stdout, and a report to stderr: what changed, what was left as written and why, and uses that need a decision. Files change only with--write. The report on stderr means> changes.patchgives a clean patch forgit apply.Built on oxc's AST. The edits are byte-offset
TextEdits (the quick-fix type fromfixes.rs; imports go through itsImportContext). Only the rewritten ranges change, so comments and formatting elsewhere stay. Every rewritten file is re-parsed; if edits overlap or the result doesn't parse, the file is left unchanged and the report says so.throw-to-result: a top-level function whose throws theno-throwrule reports getsResult<T, E>, and eachthrow xbecomesreturn err(x). Callers that return aResult, or are converted too, getq(...), includingawait, namespace imports and nested arrows that declare aResult.q.new Error("text")andthrow "text"become astringerror, as the errors guide recommends; anew Error(...)built from anything else stays anError.Result. Every other use is listed as needing a decision, and the function is left alone so the code keeps compiling: a caller that doesn't return one, a call inside a larger expression or atry, the function passed as a value, a re-export, or a caller whose declared error type doesn't include the new errors.unknown/any, throws inside the function's owntry, throws in callbacks or methods, throws of a value whose class it can't tell (throw wrap(e)), overloads, default exports, generators, and files that define their ownq/err/Result.null-to-undefined:nullbecomesundefined,T | nullbecomesOption<T>(the std import is added, orT | undefinedif the file has its ownOption),=== nullbecomes=== undefined, andx ?? nullbecomesx. Nested unions are handled, and parentheses that are no longer needed are dropped.nullfrom or to outside code stays and is reported: JSON (JSON.parse,.json()), DOM and Web APIs, packages, values typed with types not declared in the given files, your types that describe such data (followed across files), arguments to outside code (Object.create(null), values passed toJSON.stringify), callbacks it calls,on*/DOM property assignments, and conditional types.ts-enum: a string enum whose uses are all plain becomes a string union, andStatus.Draftbecomes"draft"as a value, as a type, and inside template literals. Imports in other files becometypeimports, or are removed when nothing is left.constobject + type, with the same values: when it's used as an object, when a bare string would widen tostring, or for numeric enums.E.Aas a type becomestypeof E.A, and an unannotatedlet x = E.Agets: E.declare enum, merged declarations, re-exported, default-exported or namespace-imported enums, and numeric enums used as objects (reverse mapping).Docs: a "Migrating with codemods" section in
docs/guide/adoption.md, with a before/after for each codemod and what each refuses; a CLI line in the README.Tests
crates/safe_ts_core/tests/migrate.rscovers 7 cases undertests/migrate/<codemod>/<case>/:input/,expected/, andreport.txtfor the notes. Each codemod has a refusal case; refusals are marked// left: <rule>in the input. The test checks:expected/and the report matchesreport.txt;left:lines;noUncheckedIndexedAccess,exactOptionalPropertyTypes) compiles the input, the output, and the output after the build-time transform, so aqpassing up an undeclared error type fails;I checked that a wrong expected file and a drifted docs example both make it fail.
Rebased onto main at
1fe2d1dRebased onto
mainat1fe2d1d(after #2, #3, #4, #5, #6, #8, #9, #10, #11, #12, #13, #16, #23). What had to change:no-throw:throw eof the unchangedcatch (e)binding is no longer reported. The refuses case'sthrow error; // left: no-throwstopped being one, and that exposed a bug: refusals that don't depend on a throw (returningunknown/any, overloads, default export, generator) were reported for every function, including ones with nothing to convert, sorethrowsshowed up as "skipped: it returnsunknown". A function is now converted or reported only if it has a throwno-throwreports (new commit). The refuses case now rethrows a new value (throw wrap(error), still ano-throw), and a newpassesOnrethrows the caught binding and returnsunknown: no note, no change. That case fails on the previous code. The adoption guide's "not converted" list says the same (a rethrow of the caught error stays as written).safe-ts checkon every case's input and output and compared all rules other than each codemod's own. No new diagnostics in any output: none of no-accumulating-copy (#3), stable-shape (#8), fetch-signal (#6), floating-rejection (#11), or the others fire. Every other rule's count is the same before and after, except theunhandled-failures that throw-to-result resolves (callers nowq(...)aResult). No expected file or report changed, apart from the refuses case above. The adoption-guide examples test passes unchanged.Results after the rebase:
cargo nextest run --workspace: 108 passed, 0 failed (thefeaturesfixture failure is fixed on main by #23).crates/safe_ts_core/tests/migrate.rs: 4/4, including tsc on input, output and emitted output (TypeScript 7.0.2; I checked it still reports a deliberate type error in the same setup).npm run test:std: 130 passed, 0 failed.npm run test:vite: passed.npm run typecheck: passed.npm run test:docs: passed (docs typecheck, wasm, VitePress build).examples/demo/src: exit 0, no diff, the same kind of reasoned refusals.npm run bench:checknot run: no benches or transform code changed.Before the rebase (on
0e01fb3):cargo nextest run --workspace98 passed, 1 failed (thefeaturesfixture, also failing on0e01fb3);npm run test:std115 passed, 1 failed (feature-node inventory drift, since fixed by #23); test:vite and test:docs passed; clippy clean for the new code.Left out / uncertain
.vuefiles are skipped, with a warning.functiondeclarations only, not arrow functions assigned to consts or methods.nullreaching a value through a path it doesn't follow (an unusual library method, several hops through functions) can be converted wrongly. tsc catches most of these, since the converted types rejectnull; a runtime-only case wouldn't be caught. The docs say this.number; after conversion, tsc flags code that relied on that. That's intended, but it means "keeps compiling" holds only for code that didn't pass non-members.| null, are lost; they're within the edited range.max_width=120,use_small_heuristics=Max, the width the existing core files match) and left existing code alone.🤖 Generated with Claude Code
ff5a4c3725to7103943a6e