Skip to content

feat(prettier-plugin-pkg): Sort pre/post scripts around the base script - #500

Merged
JounQin merged 8 commits into
un-ts:masterfrom
porada:feature/sort-pre-post-scripts
Mar 19, 2026
Merged

JounQin merged 8 commits into
un-ts:masterfrom
porada:feature/sort-pre-post-scripts

Conversation

@porada

@porada porada commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #403.

Before:

{
  "scripts": {
    "build": "tsc -p tsconfig.build.json",
    "posttest": "rm -rf coverage",
    "prebuild": "rm -rf dist",
    "test": "vitest run --coverage"
  }
}

After:

{
  "scripts": {
    "prebuild": "rm -rf dist",
    "build": "tsc -p tsconfig.build.json",
    "test": "vitest run --coverage",
    "posttest": "rm -rf coverage"
  }
}

Summary by CodeRabbit

  • New Features
    • Improved npm script sorting: lifecycle hooks (pre/post) are ordered around their base scripts with lifecycle-aware rules while preserving special-case names.
  • Tests
    • Added unit tests covering lifecycle ordering and edge cases.
  • Chores
    • Added a changeset entry to document the minor release and updated test fixture to include a prebuild script.

@changeset-bot

changeset-bot Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4a6da73

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
prettier-plugin-pkg Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds npm lifecycle-aware script sorting: new utilities classify and order pre*/post* hooks relative to base scripts, integrate sorting into the object rule for scripts, add tests and a fixture update, and include a Changeset for a minor release.

Changes

Cohort / File(s) Summary
Script Sorting Utilities
packages/pkg/src/utils.ts
Adds lifecycle-aware functions: getScriptSortProps, sortScriptNames, and sortScripts to compute and apply ordering for npm pre/post hooks; exports sortScriptNames and sortScripts.
Rule Integration
packages/pkg/src/rules/object.ts
Integrates sortScripts() when object key is scripts; keeps existing sortObject/sortStringArray behavior and guards against missing target items.
Tests
packages/pkg/test/utils.spec.ts
New Jest suite validating ordering of pre*/post* hooks around base scripts, unmatched prefix/post handling, and lifecycle cases.
Fixture
packages/pkg/test/fixtures/fixture2.json
Adds a prebuild script and minor JSON punctuation change to exercise new sorting.
Changeset
.changeset/cold-moles-vanish.md
Adds a changeset documenting a minor release and describing the new script sorting behavior.

Sequence Diagram(s)

(omitted — changes are internal sorting utilities and rule integration without multi-component sequential interactions)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

enhancement, feature

Poem

🐇 I hop through package trees at night,
Pre, post, and base now fall in line,
I nudge the scripts with a tiny bite,
Smooth order found — the output's fine! 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR successfully implements the core requirement from #403 to position pre/post scripts adjacent to their base scripts. However, parameterization/configurability mentioned in the issue is not addressed in the code changes. The PR fulfills the primary sorting behavior requirement but does not implement the parameterization/configurability aspect requested in issue #403. Consider adding configuration options for users to control this behavior.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: implementing sorting of pre/post scripts around their base scripts.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the pre/post script sorting feature described in #403. Changes include sorting utilities, object processing logic, test fixtures, tests, and changelog entry—all focused on the feature scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/pkg/src/utils.ts`:
- Around line 52-53: The code uses ES2023 array methods ranks.toReversed() and
scriptNames.toSorted(...) which break Node 14/16 compatibility; replace those
calls with compatibility-safe equivalents by cloning then using legacy methods:
change ranks.toReversed() to an immutable reverse via spreading and .reverse()
(e.g., create [...ranks].reverse()) and change scriptNames.toSorted(comparator)
to a stable sort via [...scriptNames].sort(comparator), ensuring you preserve
the original arrays and comparator logic in the functions that reference ranks
and scriptNames.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eb97d786-ac7e-4098-bf45-3ee86e849ae7

📥 Commits

Reviewing files that changed from the base of the PR and between 7a4346d and 5c7096b.

⛔ Files ignored due to path filters (3)
  • packages/pkg/test/__snapshots__/sort-order-preset.spec.ts.snap is excluded by !**/*.snap
  • packages/pkg/test/__snapshots__/sort-order.spec.ts.snap is excluded by !**/*.snap
  • packages/pkg/test/__snapshots__/test.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (4)
  • packages/pkg/src/rules/object.ts
  • packages/pkg/src/utils.ts
  • packages/pkg/test/fixtures/fixture2.json
  • packages/pkg/test/utils.spec.ts

Comment thread packages/pkg/src/utils.ts Resolved
@porada

porada commented Mar 16, 2026

Copy link
Copy Markdown
Contributor Author

Note: I tried fixing the SonarQube issues by configuring it not to analyze test files, but that didn’t work.

@pkg-pr-new

pkg-pr-new Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

prettier-plugin-autocorrect

npm i https://pkg.pr.new/prettier-plugin-autocorrect@500

prettier-plugin-pkg

npm i https://pkg.pr.new/prettier-plugin-pkg@500

prettier-plugin-sh

npm i https://pkg.pr.new/prettier-plugin-sh@500

prettier-plugin-sql

npm i https://pkg.pr.new/prettier-plugin-sql@500

prettier-plugin-toml

npm i https://pkg.pr.new/prettier-plugin-toml@500

commit: 4a6da73

@codecov

codecov Bot commented Mar 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.13%. Comparing base (7a4346d) to head (4a6da73).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
packages/pkg/src/utils.ts 96.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #500      +/-   ##
==========================================
+ Coverage   86.69%   88.13%   +1.43%     
==========================================
  Files          10       10              
  Lines         203      236      +33     
  Branches       57       68      +11     
==========================================
+ Hits          176      208      +32     
- Misses         26       27       +1     
  Partials        1        1              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread packages/pkg/test/utils.spec.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates prettier-plugin-pkg’s package.json sorting behavior so that npm hook scripts (pre* / post*) are ordered around their base script (including nested hook prefixes), rather than purely alphabetically.

Changes:

  • Added a script-aware sorting algorithm that groups pre*/post* scripts around their resolved base script name (with support for nested prefixes).
  • Applied this specialized ordering when sorting the scripts object.
  • Added unit tests and updated fixtures/snapshots to validate the new ordering.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
packages/pkg/src/utils.ts Implements sortScriptNames + sortScripts to group pre/post hooks around base scripts (including nested prefixes).
packages/pkg/src/rules/object.ts Uses sortScripts when processing the scripts key instead of generic object key sorting.
packages/pkg/test/utils.spec.ts Adds focused unit tests for the new script sorting behavior.
packages/pkg/test/fixtures/fixture2.json Updates fixture scripts to include prebuild for integration coverage.
packages/pkg/test/snapshots/test.spec.ts.snap Updates snapshot to reflect new scripts ordering.
packages/pkg/test/snapshots/sort-order.spec.ts.snap Updates snapshot to reflect new scripts ordering under custom sort order.
packages/pkg/test/snapshots/sort-order-preset.spec.ts.snap Updates snapshot to reflect new scripts ordering under presets.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment thread packages/pkg/src/utils.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds npm-aware sorting for scripts so that matching pre* hooks appear immediately before their base script and matching post* hooks immediately after, improving readability and aligning with npm semantics.

Changes:

  • Introduced sortScriptNames / sortScripts utilities to group pre/base/post scripts together per base name.
  • Updated object-sorting rule to apply the specialized script sorter for the scripts field.
  • Added unit tests and updated fixtures/snapshots to cover the new ordering behavior.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/pkg/src/utils.ts Implements pre/base/post-aware script name sorting and applies it to script object properties.
packages/pkg/src/rules/object.ts Switches scripts object sorting to the new script-aware sorter.
packages/pkg/test/utils.spec.ts Adds focused unit coverage for script name sorting behavior (matched and unmatched hooks).
packages/pkg/test/fixtures/fixture2.json Extends fixture scripts to exercise prebuild ordering.
packages/pkg/test/snapshots/test.spec.ts.snap Updates expected formatted output to include the new script ordering.
packages/pkg/test/snapshots/sort-order.spec.ts.snap Updates snapshot to reflect prebuild placement.
packages/pkg/test/snapshots/sort-order-preset.spec.ts.snap Updates preset snapshots to reflect prebuild placement.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

@porada

porada commented Mar 17, 2026

Copy link
Copy Markdown
Contributor Author

@JounQin — Let me know if this needs any other tweaks.

@porada
porada requested a review from JounQin March 19, 2026 09:43
Comment thread packages/pkg/test/utils.spec.ts Resolved
Comment thread packages/pkg/src/utils.ts Resolved
Comment thread packages/pkg/src/utils.ts Resolved
Comment thread packages/pkg/test/utils.spec.ts Resolved
Update the version of prettier-plugin-pkg to minor and clarify sorting behavior for scripts.
@sonarqubecloud

Copy link
Copy Markdown

@JounQin

JounQin commented Mar 19, 2026

Copy link
Copy Markdown
Member

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Mar 19, 2026

Copy link
Copy Markdown
✅ Actions performed

Reviews resumed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.changeset/cold-moles-vanish.md:
- Line 7: The fenced code block that contains the lines "pare postpare
preprepare prepare postprepare" is missing a language tag; update the opening
fence (the triple backticks for that fenced block) to include a language
identifier (e.g., ```text) so the block becomes ```text ... ``` to satisfy the
markdown/remark linter.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 679fcc51-5466-4bf3-882d-d114b02fad81

📥 Commits

Reviewing files that changed from the base of the PR and between fc328b7 and 4a6da73.

📒 Files selected for processing (3)
  • .changeset/cold-moles-vanish.md
  • packages/pkg/src/utils.ts
  • packages/pkg/test/utils.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/pkg/src/utils.ts
  • packages/pkg/test/utils.spec.ts

Comment thread .changeset/cold-moles-vanish.md Resolved
@JounQin
JounQin merged commit 041b9e5 into un-ts:master Mar 19, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[prettier-plugin-pkg] "pre" and "post" scripts

3 participants