Repository navigation
Do not migrate a variant literal behind a conditional - #20436
HuzaifaChaudary wants to merge 6 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThe codemod now matches one-level object literals inside conditional Merge Risk:
|
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Linked Issues check | The changes address the conditional-expression cases in issue #20435 and preserve neighboring class migrations. The issue also requires comment candidates to remain unchanged, but comment extraction i… |
Also prevent migration of matching text inside comments, or split the comment requirement into a separate issue and do not claim that issue #20435 is fully closed by this pull request. |
✅ Passed checks (3 passed)
-
Check name Status Explanation Out of Scope Changes check ✅ Passed The implementation and tests stay within the scope of protecting variant prop values during template migration. No unrelated code changes are evident. Title check ✅ Passed The title clearly and concisely describes the main change: preventing migration of variant literals behind conditional expressions. Description check ✅ Passed The description directly explains the reported problem, implementation, test coverage, and scope limits for the variant migration guard.
Full details: Linked Issues check
-
Explanation
The changes address the conditional-expression cases in issue
#20435and preserve neighboring class migrations. The issue also requires comment candidates to remain unchanged, but comment extraction is not modified.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2de9ab43-138d-47a0-b13e-f979998d0475
📒 Files selected for processing (2)
packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.tspackages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
Pull request overview
This PR updates the @tailwindcss/upgrade template migration safety heuristics to avoid rewriting shadcn/ui-style variant="outline" literals when they appear inside simple conditional expressions, preventing accidental breakage of React prop values during upgrades.
Changes:
- Expanded the
variantlook-behind guard inisSafeMigrationto allow one ternary/nullish operator between thevariantprop and the string literal. - Added regression tests covering the reported conditional
variantcases and ensuring conditional class strings still migrate as expected.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts | Broadens the variant guard regex used to decide when migrations are unsafe. |
| packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.ts | Adds negative cases for conditional variant literals and positive cases to ensure conditional class migration still works. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| // shadcn/ui variants, including a ternary or nullish branch between the prop | ||
| // and the literal. Braces and commas are excluded so the match cannot reach | ||
| // out of its own value into a neighbouring prop such as `className`. |
| // shadcn/ui variants, including a ternary or nullish branch between the prop | ||
| // and the literal. Braces and commas are excluded so the match cannot reach | ||
| // out of its own value into a neighbouring prop such as `className`. | ||
| /variant\s*[:=]\s*\{?(?:[^{},]*?(?:\?\?|\?|:)\s*)?['"`]$/, |
[Medium impact] The PR appears safe to merge with two non-blocking cases that skip genuine class changes. Reviews (8) · Last reviewed commit: "scan the variant value instead of matchi..." · Reviewed by Greptile |
|
thanks, two of the three were real and are now fixed in a call in the condition. a parenthesised branch. the guard is now /variant\s*[:=]\s*\{?(?:(?:[^{},()]|\([^()]*\))*?(?:\?\?|\?|:)\s*)?\(*\s*['"`]$/a bare comma or brace still ends the match, which is what keeps a neighbouring on the brace comment. i think that one is a misread. on multiline values. correct, and it is not something this change introduces. tests are now 78 in |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4414dc19-0856-45eb-ab38-21ef4aac62f7
📒 Files selected for processing (2)
packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.tspackages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
|
both of these were right, fixed in the vue one is the important one, and it was a regression i introduced. the rule i had wrong is when a quote may be crossed. inside a brace a quoted ternary branch is ordinary, so nested parens. i pulled the pattern out into named parts above the array rather than growing the inline literal. three reviewers have now had to reason about this regex and the one liner was getting hard to read, so the parts are named and commented. two new tests, one in each direction, and both fail on the previous commit:
thanks for the catch, the vue case is one i should have tested for myself given the whole point of the guard is not to suppress real classes. |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9036e261-589b-43a9-a864-bf4a836e59d5
📒 Files selected for processing (2)
packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.tspackages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
|
all three were right. fixed in three rounds of review have now found holes in this guard, and looking at why, they were all the same underlying mistake: one regex trying to know where a value ends in three different syntaxes at once. every time i widened it for one syntax it either missed another or reached into a neighbouring attribute. so it is now one rule per form, each stopping at what actually ends that form. the array already tests each rule independently so nothing else had to change. that covers the three you found:
three more negative tests, all failing on the previous commit. happy to keep going if there is another hole, but if the maintainers would rather this whole heuristic move off regexes and onto a real parse of the surrounding expression, that is a bigger change than i should make unasked and i would open a separate issue for it instead. |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9fc6a8b9-d9c1-40e4-807e-2531ee803f25
📒 Files selected for processing (2)
packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.tspackages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
|
both fixed in
both are covered by tests and both fail on the previous commit. where i think this actually standsthis is the fifth round, and i want to be straight about the trend rather than keep quietly widening things. @coderabbitai is right that the real answer is scanning the expression with balanced brace, paren and quote state instead of matching it. a regex can only ever handle a bounded nesting depth. what i am less sure about is whether that scanner belongs in this pull request. every entry in so my suggestion, and it is only a suggestion since this is your file:
either is fine by me. i would rather ask than keep adding nesting levels until someone finds level four. |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 94bee8a8-3ea5-4017-ba50-d7f61fc37806
📒 Files selected for processing (2)
packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.tspackages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
implementation=$(fd -a '^is-safe-migration\.ts$' packages)
tests=$(fd -a '^is-safe-migration\.test\.ts$' packages)
printf '%s\n' '=== Implementation outline ==='
ast-grep outline "$implementation" --items all --type variable,constant,function
printf '%s\n' '=== Conditional guard implementation ==='
rg -n -C 12 'OBJECT_GROUP|PAREN_GROUP|CONDITIONAL_TEMPLATE_SYNTAX|variant' "$implementation"
printf '%s\n' '=== Related tests ==='
rg -n -C 6 'isActive\(\{ x: 1 \}\)|tone: "dark"|variant=.*\?' "$tests"
printf '%s\n' '=== Commit availability and changed files ==='
git show --no-ext-diff --format=fuller --stat 75e4e2f6 --
git diff --no-ext-diff 75e4e2f6^ 75e4e2f6 -- \
"$implementation" "$tests"Length of output: 13586
The three syntax-specific rules use the correct value boundaries. The two new tests cover the reported object-literal cases. The existing valid-position test confirms that a neighboring Vue A stateful scanner would remove the bounded-nesting limit. That is a separate refactor. It should replace the broader conditional-syntax mechanism in a dedicated change, not extend this targeted fix. No additional blocking concern from my review. ✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! You are interacting with an AI system. |
|
both of these are real, and both are the ceiling i described in the last comment rather than new defects. a brace inside a string and an object nested past one level are the same structural limit: a regex cannot track balanced state, so there is always a next case. i said i would not keep adding levels and i am going to hold to that. what i did do is measure which direction the remaining gaps fail in, because that is the part that decides whether this is mergeable as it stands. they only fail by under guarding. for both of your cases the guard does not fire, so the prop is rewritten as a class, which is exactly what nothing over guards. the failure i actually care about is a real class silently no longer migrating, since that is worse than the bug this fixes. i checked that direction explicitly, including with your new shapes: so the state of this pr is: fixes the four forms from #20435 plus eleven more the reviews surfaced, cannot suppress a class that migrates today, and leaves a shrinking tail of exotic shapes behaving exactly as they already do on that seems like a reasonable place to stop to me, but it is your call and i am happy either way:
i would rather do that once, deliberately, than keep going a level at a time. |
|
pushed what i verified first@coderabbitai on a brace inside a string and @greptile-apps on an object nested past one level. i reproduced both against both real and both are the depth ceiling i described last time. so i did the scan rather than add a third nesting level. something neither review foundwhile writing probes i found the previous commit over guarding which is the direction i claimed was safe.
what it does nowwalk the value from the prop until whatever ends its own syntax. the candidate is the last thing on the line so the value it sits in is the one that has not ended yet.
strings and balanced groups are skipped while walking so nesting has no limit. two things are deliberately not part of the value. an argument passed to a call because it is passed to that call and not to the prop. and a
evidenceeach fix reverted on its own and watched to fail. source reverted to source reverted to only the in a string check removed with the fix against 68 and 415 on on ci
happy to keep iterating if anything here reads wrong. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
implementation=$(fd -a '^is-safe-migration\.ts$' packages)
tests=$(fd -a '^is-safe-migration\.test\.ts$' packages)
printf '%s\n' '=== Commit and changed files ==='
git show --no-ext-diff --format=fuller --stat 518310c2 --
git diff --no-ext-diff --name-status 518310c2^ 518310c2 --
printf '%s\n' '=== Implementation outline ==='
ast-grep outline "$implementation" --items all --type variable,constant,function
printf '%s\n' '=== Focused implementation ==='
rg -n -C 16 'CONDITIONAL_TEMPLATE_SYNTAX|variant|currentLineBeforeCandidate|safe|conditional|quote|brace|paren|scan' "$implementation"
printf '%s\n' '=== Focused tests ==='
rg -n -C 5 'tone: "\}"|a: \{ b: \{ c: 1 \}|cn\("ghost"|title="variant: outline"|variant=.*\?' "$tests"
printf '%s\n' '=== Exact source diff ==='
git diff --no-ext-diff 518310c2^ 518310c2 -- "$implementation" "$tests"Length of output: 24159
I reviewed commit
The added tests cover both prior under-guarding cases and the new over-guarding regressions. I found no additional blocking concern. The GitHub workflows still need maintainer approval before CI can provide independent verification. 🧠 Learnings usedYou are interacting with an AI system. |
|
The scan-based fix addresses the two depth/string cases and the For this positive case: <Button variant={{ a: 1 }} className={b ? "shadow" : "none"} />
The braced branch should include the outer brace in the scan—conceptually, call So unless Tip: You can customize Greptile's behavior for this repo with |
|
@greptile-apps i ran this one rather than argue it, because the claim is specific enough to settle. that exact line is already a test. it went in with it passes. 92 passed, 0 failed. then i applied the change you asked for, case #11 is the line you gave. so the change is the thing that breaks it, which is the opposite way round from the report. the reason is the so including the outer brace is what causes the walk past the prop, not what prevents it. worth saying the underlying point was fair. that boundary is where this thing would break if it broke, i just had it covered already. |
|
You're right. Case #11 already covers the exact nested-object-plus-conditional shape, and the experiment shows that changing |
518310c to
36917ce
Compare
|
ran both p1s against
first branch bypasses guard, does not reproduce. the reasoning was that a later outer quote makes the calls expose conditional variant literals, reproduces. confirmed, but look at the last two rows together. they are the same shape, a string literal inside a call inside <Button variant={getVariant(cond ? "outline" : "ghost")} /> must NOT migrate
<Button variant={cn("ghost", active ? "shadow" : "none")} /> must migratenothing in the syntax separates them. it depends on what the callee does with the argument, which the codemod cannot know. the current rule picks the so this is a trade off rather than a fix, and it is a maintainer call:
i have not guessed at it. happy to push either once you say which, and if you want the second, the existing positive case needs to move to the negative list in the same commit. 92 passed on |
the shadcn variant guard only looked at the text right before the literal so any ternary or nullish branch between variant and the string defeated it and the upgrade rewrote a react prop value as if it were a class braces and commas stay excluded from the new part so the match cannot run past its own value into a neighbouring prop like className
review pointed out two holes. a comma inside a call like isActive(foo, bar) ended the match early, and a branch wrapped in parens put a ( between the operator and the literal a parenthesised group is now consumed as a unit so its commas stay inside it, and parens are allowed right before the literal. a bare comma or brace still ends the match so a neighbouring prop is still out of reach
review caught an over match i introduced. vue writes attributes without braces so the gap happily crossed variant="ghost" and carried on into :class, which suppressed a class that should have migrated quotes may now only be crossed inside a brace, where a quoted ternary branch is ordinary. outside one a quote closes the attribute value so the match stops there. nested parens in a condition are handled while i was in here
three rounds of review kept finding holes in a single pattern because one regex was trying to know where the value ends in three different syntaxes at once each form now stops at what actually ends it. a brace for a jsx expression, the opening quote for an attribute so it cannot run into a neighbouring one, a comma or brace for an object literal where quotes are normal the array already tests each rule on its own so this needs no other change
review found two more, both an object literal inside the condition. a vue
binding calling isActive({ x: 1 }) and a jsx expression starting with an
inline object
an object group is now allowed as a unit the same way a parenthesised group
already was, so the braces inside it do not read as the end of the value
the four regex rules could only reach a fixed nesting depth so an object inside a condition or a brace inside a string still got through. this walks the value from the prop until whatever ends its own syntax so there is no depth limit any more. it also drops two over guards the regexes had. a class inside a call in a variant prop migrates again and so does a class next to an attribute that only mentions variant in its text.
36917ce to
cdcaa7e
Compare
|
I rebased this PR on the latest Sent by an AI assistant on behalf of @RobinMalfait. |
| } else if (char === '"' || char === "'" || char === '`') { | ||
| quote = char | ||
| } else if (char === '(' || char === '[' || char === '{') { | ||
| groups.push(char === '(' && CALLEE.test(line[i - 1] ?? '')) |
There was a problem hiding this comment.
Call spacing blocks class changes
In <Button variant={cn (active ? "shadow" : "none")} />, the space before ( makes isOpenValue treat the call as a grouped value. The upgrade then leaves shadow unchanged instead of migrating it to shadow-sm. A comment before ( causes the same problem.
Check the preceding call expression rather than only the adjacent character.
| } else if (char === '"' || char === "'" || char === '`') { | ||
| quote = char | ||
| } else if (char === '(' || char === '[' || char === '{') { | ||
| groups.push(char === '(' && CALLEE.test(line[i - 1] ?? '')) | ||
| } else if (char === ')' || char === ']' || char === '}') { | ||
| if (groups.length === 0) return false | ||
| groups.pop() |
There was a problem hiding this comment.
Regex braces block nearby classes
In <Button variant={/\{/.test(value) ? "default" : "ghost"} className="shadow" />, isOpenValue counts the escaped { inside the regular expression as an open group. The real closing brace then closes that group instead of ending the value. This makes the guard cross into className, leaving shadow unchanged instead of migrating it to shadow-sm.
Skip regular expression contents before counting groups.
Knowledge Base Used: Upgrade tool transformations
Closes #20435
problem
@tailwindcss/upgraderewritesvariant="outline"tovariant="outline-solid"when a conditional sits betweenvariantand the string. these are react prop values and not class names so the rewrite breaks them.#18922 added a guard for the direct forms and those still work. the guard is a look behind that only inspects the text immediately before the literal
/variant\s*[:=]\s*\{?['"`]$/so as soon as a ternary or a nullish branch comes between the two it no longer matches. the four cases from the issue
fix
find where the
variantvalue starts and follow it until whatever ends its own syntax. the candidate is the last thing on the line so the value it sits in is the one that has not ended yet.variant={…}ends at its matching bracevariant="…"ends at its own quote which is what keeps the match inside a single attribute and away from a neighbouring:class{ variant: … }ends at a comma or at the brace around itthe walk skips strings and balanced groups as it goes so there is no nesting limit. two things are deliberately not part of the value
<Button variant={cn("ghost", a ? "shadow" : "x")} />still migratesshadowvariant:that only appears inside some other attribute text so<div title="variant: outline" className={b ? "shadow" : "x"}>still migratesshadowCONDITIONAL_TEMPLATE_SYNTAXis byte identical tomain. the diff only adds one more heuristic below it plus the two helpers it needs.tests
21 negatives in
is-safe-migration.test.tsand 14 positives.is-safe-migrationonmainis-safe-migrationhere@tailwindcss/upgradeonmain@tailwindcss/upgradeherewith the source reverted to
mainand the tests kept 17 of the 21 shadcn negatives fail. prettier is clean on both files.not covered
the guard is line scoped like every other entry in
CONDITIONAL_TEMPLATE_SYNTAXso a value wrapped across lines is still not seenthat limit is shared by the whole array and by
isMiddleOfStringso lifting it is a separate change rather than something to fold in here.the issue also notes that a comment mentioning
outline: nonegets rewritten. that one is candidate extraction rather than this safety guard so it is a different fix and i have left it alone.disclaimer: this contribution was prepared with the help of an ai agent. i reviewed the change, reproduced the failing cases against
mainfirst, and ran the package test suite locally before opening it.