Skip to content

Commit d83e013

Browse files
committed
Releases: auto-re-pin tag-pinned links on every version bump
The AGENTS.md link policy (tag-pinned absolute links instead of blob/main) would rot without automation: at each release, every link meant to track a package's latest docs needs moving to the new tag, and forgetting one is silent. The new repo-wide scripts/update-pinned-links.mjs closes that gap and runs from each publishable package's version lifecycle, before the library's README regeneration. The mechanism leans on an invariant instead of configuration: links that should track a package's latest release are, by construction, pinned to its newest existing tag — this script rewrites exactly those, repo-wide, to the tag the running release is about to create, while links pinned to older tags (changelogs, migration guides) are deliberately historical and never touched. The previous tag is derived from git (newest semver among the package's namespaced tags plus the legacy v* history for tailwind-merge, mirroring the release-commenter's fallback); the new tag comes from the already-bumped manifest, since npm creates the git tag only after the version scripts run. That ordering also dictates the validation target: each rewritten link's path is checked against the working tree, which is what the new tag will contain. Pre-monorepo root paths remap into the package directory automatically, so the 3.7.0 release will carry the six v3.6.0-pinned links (JSDoc plus the vite package docs) onto [email protected] with packages/tailwind-merge/ paths on its own, retiring the manual reminder the release guide briefly held. Unresolvable paths fail the version step loudly and atomically — replacements are computed in a first pass and written only when the whole run is clean, so an aborted release leaves the tree untouched. The script is dependency-free Node rather than zx so the vite package's new version script doesn't pull zx in; it lives at the repo root because it serves every package, which also brings the root scripts/ directory back and with it a root-scope no-console override. GitHub resolving slashed scoped tags in blob URLs unencoded was verified against a real-world case beforehand, so @tailwind-merge/vite@<version> links need no escaping. Verified in a scratch git repo across the matrix: v3.6.0 → [email protected] with path remapping and fragments preserved, raw.githubusercontent form, namespaced → namespaced bumps, historical and other-package tags untouched, idempotent reruns (including the git grep no-match exit), graceful first-release no-op, and the atomic failure path leaving a half-fixable file fully unmodified. Docs synced: AGENTS.md link policy names the automation, the release guide replaces the manual vite-docs reminder with the automated behavior, and the internals guide documents the script in the build-and-packaging section.
1 parent b71fd41 commit d83e013

7 files changed

Lines changed: 194 additions & 6 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ This repository is a pnpm monorepo hosting `tailwind-merge` — a TypeScript lib
1212

1313
- The library package: `packages/tailwind-merge/` — source in `src/`, tests in `tests/`, human docs in `docs/`, build/release scripts in `scripts/`, published overview `README.md` (autogenerated from `docs/README.md`).
1414
- Sibling workspace packages (not yet published): `packages/configurator/` — research and prototype for generating tailwind-merge configs from Tailwind v4 CSS — and `packages/vite/`, the `@tailwind-merge/vite` plugin wrapping it.
15-
- Repo root: workspace orchestration only — `pnpm-workspace.yaml` (workspace list + shared tool-version catalog), `eslint.config.base.mjs` (shared lint base every scope spreads), root `eslint.config.mjs` (lints root files and `.github/`), root `vitest.config.mts` (aggregates the packages' Vitest projects plus the local GitHub actions' tests), and the repo-level `README.md`.
15+
- Repo root: workspace orchestration only — `pnpm-workspace.yaml` (workspace list + shared tool-version catalog), `eslint.config.base.mjs` (shared lint base every scope spreads), root `eslint.config.mjs` (lints root files and `.github/`), root `vitest.config.mts` (aggregates the packages' Vitest projects plus the local GitHub actions' tests), repo-wide release tooling in `scripts/` (currently `update-pinned-links.mjs`), and the repo-level `README.md`.
1616
- CI workflows: `.github/workflows/`
1717
- Local GitHub actions: `.github/actions/`
1818

@@ -74,7 +74,7 @@ Required when relevant:
7474
2. Update `AGENTS.md` whenever repository-wide agent workflow, repo conventions, required commands, or high-level guardrails change.
7575
3. Update the relevant file in `agents/` whenever specialized architecture, workflow, CI, release, or testing guidance changes.
7676
4. Do not regenerate the READMEs during normal development. The library `README.md` and the marked section of the repo-level `README.md` are intentionally generated as part of the version/release flow so visitors are routed to docs for the latest release.
77-
5. Never reference repo files through `blob/main`/`raw/main`/`tree/main` URLs — they break whenever a file moves. Within the repo use relative links; where a link must be absolute (published docs, JSDoc, release notes), pin it to the latest release tag whose tree contains the file (e.g. `blob/v3.6.0/docs/...`, `blob/[email protected]/packages/tailwind-merge/docs/...`).
77+
5. Never reference repo files through `blob/main`/`raw/main`/`tree/main` URLs — they break whenever a file moves. Within the repo use relative links; where a link must be absolute (published docs, JSDoc, release notes), pin it to the latest release tag whose tree contains the file (e.g. `blob/v3.6.0/docs/...`, `blob/[email protected]/packages/tailwind-merge/docs/...`). Links pinned to a package's latest tag are re-pinned automatically at that package's next release by `scripts/update-pinned-links.mjs` (run in each publishable package's `version` lifecycle); links pinned to older tags are treated as deliberately historical and never touched.
7878

7979
Definition of done for every PR/change:
8080

‎agents/release-workflow.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ The tag and version-commit format comes from each package's `.npmrc` (`tag-versi
3030
- A PR touching both packages appears in both drafts — correct, since both releases ship it.
3131
- A PR touching neither package directory (repo infrastructure, CI, root docs) appears in no draft; mention it by hand in a changelog if it matters to users.
3232
- First namespaced release per package: `tag-prefix` matches no existing release, so the draft's proposed version is wrong. Set the tag name and title by hand when publishing (for example `[email protected]` following `v3.6.0`), and write the Full Changelog compare line manually (`[email protected]`).
33-
- Before the first `@tailwind-merge/vite` release: its docs pin tailwind-merge doc links to the newest tag containing them (currently `v3.6.0` with pre-monorepo paths); bump them to the freshly released `tailwind-merge@<version>` tag with `packages/tailwind-merge/` paths so the published plugin docs reference the tailwind-merge version they actually require.
33+
- Tag-pinned file links repo-wide (the AGENTS.md link policy) are maintained automatically: each publishable package's `version` lifecycle runs `scripts/update-pinned-links.mjs`, which rewrites every link pinned to that package's newest existing tag to the tag being released, verifies each target path against the working tree (failing the version step loudly on unresolvable paths, touching nothing), remaps pre-monorepo root paths into the package directory, and leaves links pinned to older tags alone as deliberately historical. First release of a package is a no-op for it. Concretely: the tailwind-merge 3.7.0 release will re-pin the vite docs' `v3.6.0` links to `tailwind-merge@3.7.0` with `packages/tailwind-merge/` paths on its own.
3434
- The autolabeler section lives only in the tailwind-merge config; labels are repo-wide.
3535

3636
## Publishing
@@ -81,7 +81,7 @@ gh workflow run comment-released-prs-and-issues.yml \
8181

8282
## Commands
8383

84-
Bump a package's version with `pnpm version <version|patch|minor|major>` run inside the package directory (for the library: `packages/tailwind-merge/`). pnpm runs the existing `preversion`, `version`, and `postversion` lifecycle scripts and creates the version commit and namespaced tag from the package's `.npmrc`. For the library, the `version` step regenerates both the package README and the generated section of the repo-level README via `scripts/update-readme.mjs`, with links pinned to the new release tag.
84+
Bump a package's version with `pnpm version <version|patch|minor|major>` run inside the package directory (for the library: `packages/tailwind-merge/`). pnpm runs the existing `preversion`, `version`, and `postversion` lifecycle scripts and creates the version commit and namespaced tag from the package's `.npmrc`. The `version` step first re-pins tag-pinned links repo-wide via the shared `scripts/update-pinned-links.mjs` (see Release drafting notes above); for the library it then regenerates both the package README and the generated section of the repo-level README via its own `scripts/update-readme.mjs`, with links pinned to the new release tag.
8585

8686
Fetch draft release:
8787

‎agents/tailwind-merge-internals.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Recommended local sequence for non-trivial changes:
107107
- Both scripts execute the default and ES5 bundles so build-tool upgrades cannot break only the legacy entry point unnoticed.
108108
- `pnpm test:types` type-checks both the source and the test suite with the development compiler. `scripts/typescript-compatibility/consumer.ts` separately compiles the built declaration bundle with the `typescript-compat` compiler alias pinned to TypeScript 3.8.3. `pnpm test:exports` includes the compatibility check because TypeScript 3.8 is the documented minimum consumer version; keep the alias excluded from Renovate updates and treat any increase to this floor as a major-version change.
109109
- `scripts/update-readme.mjs` (run in the `version` script via `zx`) generates two targets from `docs/README.md`: the package `README.md` shipped to npm, and the section between the `tailwind-merge-docs` markers in the repo-level `README.md`; it fails the version step loudly when the repo README's markers are missing.
110+
- The `version` script also runs the repo-wide `scripts/update-pinned-links.mjs` (repo root, dependency-free Node), which re-pins every link pinned to the package's newest existing tag onto the tag being released, verifying targets against the working tree and failing loudly — without touching anything — when a linked path no longer resolves. Older-tag links are deliberately historical and stay untouched.
110111

111112
## CI Behavior And Security
112113

‎eslint.config.mjs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,10 @@ export default [
1212
],
1313
},
1414
...baseConfig,
15+
{
16+
files: ['scripts/**/*.?(m|c)@(t|j)s'],
17+
rules: {
18+
'no-console': 'off',
19+
},
20+
},
1521
]

‎packages/tailwind-merge/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
"test:types:compat": "node node_modules/typescript-compat/bin/tsc --project scripts/typescript-compatibility/tsconfig.json",
6767
"lint": "eslint --max-warnings 0 .",
6868
"preversion": "if [ -n \"$DANYS_MACHINE\" ]; then git checkout main && git pull; fi",
69-
"version": "zx scripts/update-readme.mjs",
69+
"version": "node ../../scripts/update-pinned-links.mjs && zx scripts/update-readme.mjs",
7070
"postversion": "if [ -n \"$DANYS_MACHINE\" ]; then git push --follow-tags && open https://github.com/dcastil/tailwind-merge/releases; fi"
7171
},
7272
"dependencies": {},

‎packages/vite/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
"lint": "eslint --max-warnings 0 .",
1616
"test": "vitest --no-watch",
1717
"test:watch": "vitest",
18-
"test:types": "tsc --noEmit"
18+
"test:types": "tsc --noEmit",
19+
"version": "node ../../scripts/update-pinned-links.mjs"
1920
},
2021
"peerDependencies": {
2122
"@tailwindcss/vite": "~4.3.3",

‎scripts/update-pinned-links.mjs‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Re-pins tag-pinned GitHub file links when a package releases. Runs from a package directory as
2+
// part of its `version` lifecycle (cwd = the package, manifest already carries the new version).
3+
//
4+
// Model: absolute links into this repo are pinned to release tags per the AGENTS.md link policy.
5+
// Links that should track the latest release of a package are, by construction, pinned to that
6+
// package's newest existing tag — this script rewrites exactly those, repo-wide, to the tag the
7+
// running release is about to create. Links pinned to older tags are deliberately historical
8+
// (changelogs, migration guides, old threads) and are never touched.
9+
//
10+
// Every rewritten link is verified against the working tree, which is what the new tag will
11+
// contain. A path that no longer exists fails the version step loudly so a release can never
12+
// re-pin links onto targets that do not resolve; re-pin such links to an old tag by hand (making
13+
// them historical) or fix their paths, then rerun. Paths that lived at the repo root before the
14+
// monorepo migration are remapped into the package directory automatically.
15+
16+
import { execFileSync } from 'node:child_process'
17+
import fs from 'node:fs'
18+
import path from 'node:path'
19+
import { fileURLToPath } from 'node:url'
20+
21+
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
22+
const packageDir = process.cwd()
23+
24+
// Tags without a package prefix (v3.6.0 and earlier) are the pre-monorepo history and belong to tailwind-merge, mirroring the fallback in the release-commenter action.
25+
const LEGACY_TAG_OWNER = 'tailwind-merge'
26+
27+
const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'))
28+
const newTag = `${manifest.name}@${manifest.version}`
29+
30+
const previousTag = findPreviousTag(manifest.name)
31+
if (!previousTag) {
32+
console.log(`[update-pinned-links] No previous release tag for ${manifest.name} — nothing to re-pin.`)
33+
process.exit(0)
34+
}
35+
36+
console.log(`[update-pinned-links] Re-pinning links from ${previousTag} to ${newTag}`)
37+
38+
// Matches the pinned-link forms the repo uses: github.com blob/raw/tree URLs and raw.githubusercontent.com URLs. The path capture stops at characters that end a URL in Markdown or code; fragments and queries stay in place untouched.
39+
const linkRegex = new RegExp(
40+
`(https?://(?:www\\.)?(?:github\\.com/dcastil/tailwind-merge/(?:blob|raw|tree)|raw\\.githubusercontent\\.com/dcastil/tailwind-merge))/${escapeRegex(previousTag)}/([^\\s)\\]"'\`<>*\\\\#?]*)`,
41+
'g',
42+
)
43+
44+
const trackedFiles = findFilesMentioning(previousTag)
45+
46+
// Two passes so a failure leaves the working tree untouched: first compute every replacement and collect unresolvable links, then write only when the whole run is clean.
47+
const unresolvedLinks = []
48+
const pendingWrites = []
49+
50+
for (const file of trackedFiles) {
51+
const filePath = path.join(repoRoot, file)
52+
const content = fs.readFileSync(filePath, 'utf8')
53+
54+
const nextContent = content.replace(linkRegex, (match, base, linkedPath) => {
55+
const resolvedPath = resolveLinkedPath(linkedPath)
56+
if (resolvedPath === null) {
57+
unresolvedLinks.push(`${file}: ${match}`)
58+
return match
59+
}
60+
return `${base}/${newTag}/${resolvedPath}`
61+
})
62+
63+
if (nextContent !== content) {
64+
pendingWrites.push({ file, filePath, nextContent })
65+
}
66+
}
67+
68+
if (unresolvedLinks.length > 0) {
69+
console.error(
70+
`[update-pinned-links] ${unresolvedLinks.length} link(s) point at paths that do not exist in the tree the new tag will contain. Fix the paths or re-pin them to an old tag by hand, then rerun:\n${unresolvedLinks.join('\n')}`,
71+
)
72+
process.exit(1)
73+
}
74+
75+
for (const { file, filePath, nextContent } of pendingWrites) {
76+
fs.writeFileSync(filePath, nextContent)
77+
execFileSync('git', ['add', file], { cwd: repoRoot })
78+
console.log(`[update-pinned-links] Updated ${file}`)
79+
}
80+
81+
console.log(
82+
pendingWrites.length > 0
83+
? `[update-pinned-links] Re-pinned links in ${pendingWrites.length} file(s).`
84+
: '[update-pinned-links] No links needed re-pinning.',
85+
)
86+
87+
/**
88+
* Lists tracked text files mentioning the previous tag, as a cheap pre-filter for the link rewrite. git grep exits 1 when nothing matches, which is a normal outcome here.
89+
*
90+
* @param {string} tag
91+
* @returns {string[]}
92+
*/
93+
function findFilesMentioning(tag) {
94+
try {
95+
return execFileSync('git', ['grep', '-lI', '--fixed-strings', `/${tag}/`], {
96+
cwd: repoRoot,
97+
encoding: 'utf8',
98+
})
99+
.split('\n')
100+
.filter(Boolean)
101+
} catch (error) {
102+
if (error && typeof error === 'object' && error.status === 1) return []
103+
throw error
104+
}
105+
}
106+
107+
/**
108+
* Finds the newest existing release tag of the given package by semver, including the un-prefixed legacy tags for the package that owns the pre-monorepo history. The tag for the running release does not exist yet (npm creates it after the version scripts), so the newest existing tag is the previous release.
109+
*
110+
* @param {string} packageName
111+
* @returns {string | null}
112+
*/
113+
function findPreviousTag(packageName) {
114+
const allTags = execFileSync('git', ['tag', '--list'], { cwd: repoRoot, encoding: 'utf8' })
115+
.split('\n')
116+
.filter(Boolean)
117+
118+
const versionByTag = new Map()
119+
for (const tag of allTags) {
120+
let versionText = null
121+
if (tag.startsWith(`${packageName}@`)) {
122+
versionText = tag.slice(packageName.length + 1)
123+
} else if (packageName === LEGACY_TAG_OWNER && /^v\d/.test(tag)) {
124+
versionText = tag.slice(1)
125+
}
126+
if (!versionText) continue
127+
128+
const match = versionText.match(/^(\d+)\.(\d+)\.(\d+)$/)
129+
if (!match) continue
130+
131+
versionByTag.set(tag, match.slice(1, 4).map(Number))
132+
}
133+
134+
let best = null
135+
for (const [tag, version] of versionByTag) {
136+
if (!best || compareVersions(version, best.version) > 0) {
137+
best = { tag, version }
138+
}
139+
}
140+
141+
return best?.tag ?? null
142+
}
143+
144+
/**
145+
* @param {number[]} a
146+
* @param {number[]} b
147+
* @returns {number}
148+
*/
149+
function compareVersions(a, b) {
150+
for (let index = 0; index < 3; index += 1) {
151+
if (a[index] !== b[index]) return a[index] - b[index]
152+
}
153+
return 0
154+
}
155+
156+
/**
157+
* Validates a linked path against the working tree, remapping pre-monorepo root paths into the package directory when the file moved there. Returns null when the path resolves nowhere.
158+
*
159+
* @param {string} linkedPath
160+
* @returns {string | null}
161+
*/
162+
function resolveLinkedPath(linkedPath) {
163+
const normalizedPath = linkedPath.replace(/\/+$/, '')
164+
if (normalizedPath === '') return ''
165+
if (fs.existsSync(path.join(repoRoot, normalizedPath))) return normalizedPath
166+
167+
const packageDirRelative = path.relative(repoRoot, packageDir)
168+
const remappedPath = `${packageDirRelative}/${normalizedPath}`
169+
if (fs.existsSync(path.join(repoRoot, remappedPath))) return remappedPath
170+
171+
return null
172+
}
173+
174+
/**
175+
* @param {string} value
176+
* @returns {string}
177+
*/
178+
function escapeRegex(value) {
179+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
180+
}

0 commit comments

Comments
 (0)