-
Notifications
You must be signed in to change notification settings - Fork 6
feat: pnpm codemod for patch convert #12
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
e3d95ad
feat: pnpm codemod for patch convert
btea 85b4bba
feat: update
btea 665797e
fix: remove test file
btea c21a096
fix: update readme
btea c7f9c0e
feat: update
btea c44a3b5
Update patch/codemod.yaml
btea fbb7606
fix: update
btea 034c0a3
Apply suggestion from @Copilot
btea 3330cc2
Update patch/src/utils/errors.ts
btea 59d73f0
Update patch/src/transforms/patch-file.ts
btea 3c57f64
Update patch/src/utils/path.ts
btea 615ba44
Update patch/src/transforms/package-json.ts
btea bb8bafb
Update patch/package.json
btea dbbd06f
fix: update
btea 9f321d9
fix: update
btea c2c9307
fix: update
btea File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,5 +4,8 @@ | |
| "packageManager": "[email protected]", | ||
| "devDependencies": { | ||
| "@biomejs/biome": "^1.8.3" | ||
| }, | ||
| "scripts": { | ||
| "startRun": "pnpm -C patch startRun" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| node_modules | ||
| dist |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| The MIT License (MIT) | ||
|
|
||
| Copyright (c) 2024 | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| This codemod help migrate patch files generated by `patch-package` to a format that complies with pnpm. | ||
|
|
||
|
|
||
| ```shell | ||
| pnpx codemod pnpm/patch-convert | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| schema_version: "1.0" | ||
|
|
||
| name: "patch-package-to-pnpm" | ||
| version: "0.1.0" | ||
| description: "onverts patch-package patches to pnpm format by removing node_modules/ prefixes from patch file content and updating package.json/pnpm-workspace.yaml configuration." | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| author: "Alex Bit <[email protected]>, btea" | ||
| license: "MIT" | ||
| workflow: "workflow.yaml" | ||
|
|
||
|
|
||
| targets: | ||
| languages: ["json", "yaml"] | ||
|
|
||
| keywords: ["pnpm", "migration"] | ||
|
|
||
| registry: | ||
| access: "public" | ||
| visibility: "public" | ||
|
|
||
| capabilities: | ||
| - fs | ||
| - path | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| { | ||
| "name": "patch-package-to-pnpm", | ||
| "version": "0.1.0", | ||
| "description": "Transform legacy code patterns", | ||
| "type": "module", | ||
| "devDependencies": { | ||
| "@codemod.com/jssg-types": "^1.0.9", | ||
| "@types/node": "20.9.0", | ||
| "typescript": "^5.8.3" | ||
| }, | ||
| "scripts": { | ||
| "validate": "pnpx codemod workflow validate -w workflow.yaml", | ||
| "startRun": "pnpx codemod workflow run -w workflow.yaml --dry-run", | ||
| "test": "pnpx codemod@latest jssg test -l typescript ./src/codemod.ts", | ||
| "check-types": "tsc --noEmit" | ||
| } | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import type { Transform, SgRoot } from "codemod:ast-grep"; | ||
| import type JSON from "codemod:ast-grep/langs/json"; | ||
| import { access } from "fs/promises"; | ||
| import { dirname, join } from "path"; | ||
| import { | ||
| PATCH_EXTENSION, | ||
| PACKAGE_JSON_FILE, | ||
| WORKSPACE_YAML_FILE, | ||
| } from "./constants.ts"; | ||
| import { normalizePath, findWorkspaceRoot } from "./utils/path.ts"; | ||
| import { transformPatchFile } from "./transforms/patch-file.ts"; | ||
| import { transformPackageJson } from "./transforms/package-json.ts"; | ||
| import { transformWorkspaceYaml } from "./transforms/workspace-yaml.ts"; | ||
|
|
||
| const transform: Transform<JSON> = async (root: SgRoot<JSON>): Promise<string | null> => { | ||
| const fileName = normalizePath(root.filename()); | ||
| console.log(`Processing file: ${fileName}`); | ||
|
|
||
| if (fileName.endsWith(PATCH_EXTENSION)) { | ||
| return await transformPatchFile(root); | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| if (fileName.endsWith(PACKAGE_JSON_FILE)) { | ||
| const workspaceRoot = await findWorkspaceRoot(fileName); | ||
|
|
||
| try { | ||
| const workspaceYamlPath = normalizePath(join(workspaceRoot, WORKSPACE_YAML_FILE)); | ||
| await access(workspaceYamlPath); | ||
| return null; | ||
| } catch { | ||
| } | ||
|
|
||
| const packageJsonDir = normalizePath(dirname(fileName)); | ||
| const isRoot = packageJsonDir === workspaceRoot; | ||
| if (!isRoot) { | ||
| return null; | ||
| } | ||
|
|
||
| return await transformPackageJson(root.root(), root); | ||
| } | ||
|
|
||
| if (fileName.endsWith(WORKSPACE_YAML_FILE)) { | ||
| return await transformWorkspaceYaml(root); | ||
| } | ||
|
|
||
| return null; | ||
| }; | ||
|
|
||
| export default transform; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| export const PATCH_EXTENSION = '.patch'; | ||
| export const PACKAGE_JSON_FILE = 'package.json'; | ||
| export const WORKSPACE_YAML_FILE = 'pnpm-workspace.yaml'; | ||
| export const PATCHES_DIR_NAME = 'patches'; | ||
| export const PATCH_PACKAGE_SEPARATOR = '+'; | ||
| export const PNPM_NAME_SEPARATOR = '__'; | ||
| export const PNPM_VERSION_SEPARATOR = '@'; | ||
|
|
||
| // YAML parsing patterns | ||
| export const YAML_PATTERNS = { | ||
| PATCHED_DEPS_SECTION: /patchedDependencies:\s*\n((?:\s+['"][^'"]+['"]:\s*['"][^'"]+['"]\n?)*)/, | ||
|
|
||
| PATCHED_DEPS_ENTRY: /['"]([^'"]+)['"]:\s*['"]([^'"]+)['"]/g, | ||
| } as const; | ||
|
|
||
| // Patch filename validation | ||
| export const PATCH_FILENAME_PATTERNS = { | ||
| isPnpmFormat: (filename: string): boolean => { | ||
| return filename.includes(PNPM_VERSION_SEPARATOR) && !filename.includes(PATCH_PACKAGE_SEPARATOR); | ||
| }, | ||
|
|
||
| isPatchPackageFormat: (filename: string): boolean => { | ||
| return filename.includes(PATCH_PACKAGE_SEPARATOR); | ||
| }, | ||
| } as const; | ||
|
|
||
| export const ERROR_CODE_ENOENT = 'ENOENT'; | ||
| export const ERROR_MESSAGE_NOT_FOUND = 'No such file or directory'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { readdir, stat } from "fs/promises"; | ||
| import { dirname, join } from "path"; | ||
| import { PATCH_EXTENSION, PATCHES_DIR_NAME, PATCH_FILENAME_PATTERNS } from "../constants.ts"; | ||
| import type { PatchesMap } from "../types.ts"; | ||
| import { normalizePath } from "../utils/path.ts"; | ||
| import { findWorkspaceRoot } from "../utils/path.ts"; | ||
| import { convertPatchFilename, getPatchedDependencyKey } from "../utils/patch-filename.ts"; | ||
| import { isNotFoundError } from "../utils/errors.ts"; | ||
|
|
||
| export async function scanForConvertedPatches(patchesDir: string): Promise<PatchesMap> { | ||
| const patches = new Map<string, string>(); | ||
|
|
||
| try { | ||
| const stats = await stat(patchesDir); | ||
| if (!stats.isDirectory()) { | ||
| return patches; | ||
| } | ||
|
|
||
| const files = await readdir(patchesDir); | ||
| const dirName = normalizePath(patchesDir.split(/[/\\]/).pop() || PATCHES_DIR_NAME); | ||
|
|
||
| for (const file of files) { | ||
| const normalizedFile = normalizePath(file); | ||
|
|
||
| if (!normalizedFile.endsWith(PATCH_EXTENSION)) { | ||
| continue; | ||
| } | ||
|
|
||
| let pnpmFormatFileName: string; | ||
| let key: string; | ||
|
|
||
| // Check if it's already in pnpm format (contains '@' and doesn't contain '+') | ||
| if (PATCH_FILENAME_PATTERNS.isPnpmFormat(normalizedFile)) { | ||
| // Already converted to pnpm format | ||
| pnpmFormatFileName = normalizedFile; | ||
| key = getPatchedDependencyKey(normalizedFile); | ||
| } | ||
| // Check if it's in patch-package format (contains '+') | ||
| else if (PATCH_FILENAME_PATTERNS.isPatchPackageFormat(normalizedFile)) { | ||
| // Convert patch-package format to pnpm format on-the-fly | ||
| try { | ||
| pnpmFormatFileName = convertPatchFilename(normalizedFile); | ||
| key = getPatchedDependencyKey(pnpmFormatFileName); | ||
| } catch (error) { | ||
| // Skip invalid patch filenames | ||
| console.warn(`Skipping invalid patch filename: ${normalizedFile}`, error); | ||
| continue; | ||
| } | ||
| } else { | ||
| // Skip files that don't match either format | ||
| continue; | ||
| } | ||
|
|
||
| // Get relative path: directory name + filename (e.g., "patches/@[email protected]") | ||
| const relativePath = normalizePath(join(dirName, pnpmFormatFileName)); | ||
| patches.set(key, relativePath); | ||
| } | ||
| } catch (error: unknown) { | ||
| // If directory doesn't exist or can't be read, return empty map | ||
| // This is expected when packages don't have patches, so we don't log warnings | ||
| // Silently return empty map for "not found" errors - this is expected | ||
| if (!isNotFoundError(error)) { | ||
| console.warn(`Could not scan patches directory ${patchesDir}:`, error); | ||
| } | ||
| } | ||
|
|
||
| return patches; | ||
| } | ||
|
|
||
| export async function findPatchesDirectory(configFilePath: string): Promise<string> { | ||
| const configDir = normalizePath(dirname(configFilePath)); | ||
|
|
||
| // First, try to find workspace root (in case this is a workspace setup) | ||
| const workspaceRoot = await findWorkspaceRoot(configFilePath); | ||
|
|
||
| // Common locations: ./patches relative to config, ../patches, and workspace root/patches | ||
| const candidates = [ | ||
| normalizePath(join(configDir, PATCHES_DIR_NAME)), | ||
| normalizePath(join(configDir, '..', PATCHES_DIR_NAME)), | ||
| normalizePath(join(workspaceRoot, PATCHES_DIR_NAME)), | ||
| ]; | ||
|
|
||
| // Remove duplicates | ||
| const uniqueCandidates = Array.from(new Set(candidates)); | ||
|
|
||
| for (const candidate of uniqueCandidates) { | ||
| try { | ||
| const stats = await stat(candidate); | ||
| if (stats.isDirectory()) { | ||
| return candidate; | ||
| } | ||
| } catch { | ||
| // Directory doesn't exist, try next candidate | ||
| } | ||
| } | ||
|
|
||
| // Default to ./patches relative to config file if not found | ||
| return normalizePath(join(configDir, PATCHES_DIR_NAME)); | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| import type { SgNode, SgRoot } from "codemod:ast-grep"; | ||
| import type JSON from "codemod:ast-grep/langs/json"; | ||
| import { normalizePath } from "../utils/path.ts"; | ||
| import { findPatchesDirectory, scanForConvertedPatches } from "../scanners/patch-scanner.ts"; | ||
|
|
||
| export interface PatchedDependencies { | ||
| [key: string]: string; | ||
| } | ||
| export interface PnpmConfig { | ||
| patchedDependencies?: PatchedDependencies; | ||
| [key: string]: unknown; | ||
| } | ||
| export interface PackageJson { | ||
| name?: string; | ||
| version?: string; | ||
| pnpm?: PnpmConfig; | ||
| [key: string]: unknown; | ||
| } | ||
|
|
||
btea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| export async function transformPackageJson( | ||
| rootNode: SgNode<JSON>, | ||
| root: SgRoot<JSON> | ||
| ): Promise<string | null> { | ||
| const fileName = root.filename(); | ||
| const content = root.root().text(); | ||
|
|
||
| const patchesDir = await findPatchesDirectory(fileName); | ||
| const convertedPatches = await scanForConvertedPatches(patchesDir); | ||
|
|
||
| if (convertedPatches.size === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| let packageJson: PackageJson; | ||
| try { | ||
| packageJson = JSON.parse(content) as PackageJson; | ||
btea marked this conversation as resolved.
Show resolved
Hide resolved
btea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } catch (error) { | ||
| console.error(`Failed to parse package.json:`, error); | ||
| return null; | ||
| } | ||
|
|
||
| if (!packageJson.pnpm) { | ||
| return null; | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| if (!packageJson.pnpm.patchedDependencies) { | ||
| packageJson.pnpm.patchedDependencies = {}; | ||
| } | ||
|
|
||
| const existingDeps = packageJson.pnpm.patchedDependencies; | ||
| for (const [key, patchPath] of convertedPatches.entries()) { | ||
| const relativePatchPath = normalizePath(patchPath); | ||
| existingDeps[key] = relativePatchPath; | ||
| } | ||
|
|
||
| const updatedContent = JSON.stringify(packageJson, null, 2) + '\n'; | ||
btea marked this conversation as resolved.
Show resolved
Hide resolved
btea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (updatedContent === content) { | ||
| return null; | ||
| } | ||
|
|
||
| return updatedContent; | ||
| } | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
|
|
||
| import type { SgRoot } from "codemod:ast-grep"; | ||
| import type JSON from "codemod:ast-grep/langs/json"; | ||
| import { writeFile, rm } from "fs/promises"; | ||
| import { basename } from "path"; | ||
| import { findWorkspaceRoot } from "../utils/path.ts"; | ||
|
|
||
| function generateReplacePattern (patchFilePath: string): string { | ||
| const baseName = basename(patchFilePath) | ||
| const packageInfo = baseName.split('+').slice(0, -1).join('/') | ||
| return `/node_modules/${packageInfo}`.replace(/\\/g, '/') | ||
| } | ||
|
|
||
| function convertPatchNameToPnpmFormat (patchFileName: string): string { | ||
| const parts = patchFileName.split('+') | ||
| const version = parts.pop() | ||
btea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return `${parts.join('__')}@${version}` | ||
| } | ||
|
|
||
| const NODE_MODULES_PATTERNS = [ | ||
| 'diff --git a/node_modules/', | ||
| '--- a/node_modules/', | ||
| '+++ b/node_modules/', | ||
| ] as const | ||
| function needsConversion (content: string): boolean { | ||
| return NODE_MODULES_PATTERNS.some(pattern => content.includes(pattern)) | ||
| } | ||
|
|
||
| export async function transformPatchFile(root: SgRoot<JSON>): Promise<string | null> { | ||
| const fileName = root.filename(); | ||
| const workspaceRoot = await findWorkspaceRoot(fileName); | ||
| console.log(`Workspace root for patch file: ${workspaceRoot}`); | ||
| const content = root.root().text(); | ||
|
|
||
| if (!needsConversion(content)) { | ||
| return null; // Skip if no conversion needed | ||
| } | ||
|
|
||
| const replacePattern = generateReplacePattern(fileName) | ||
| const convertedContent = content.replace(new RegExp(replacePattern, 'g'), '') | ||
| const outputPath = convertPatchNameToPnpmFormat(fileName) | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| await writeFile(outputPath, convertedContent, 'utf-8') | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| await rm(fileName) | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return convertedContent | ||
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
btea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.