Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@
"packageManager": "[email protected]",
"devDependencies": {
"@biomejs/biome": "^1.8.3"
},
"scripts": {
"startRun": "pnpm -C patch startRun"
}
}
2 changes: 2 additions & 0 deletions patch/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
9 changes: 9 additions & 0 deletions patch/LICENSE
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.
6 changes: 6 additions & 0 deletions patch/README.md
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
```
22 changes: 22 additions & 0 deletions patch/codemod.yaml
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."
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
17 changes: 17 additions & 0 deletions patch/package.json
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"
}
}
49 changes: 49 additions & 0 deletions patch/src/codemod.ts
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);
}

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;
28 changes: 28 additions & 0 deletions patch/src/constants.ts
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';
100 changes: 100 additions & 0 deletions patch/src/scanners/patch-scanner.ts
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));
}

63 changes: 63 additions & 0 deletions patch/src/transforms/package-json.ts
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;
}

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;
} catch (error) {
console.error(`Failed to parse package.json:`, error);
return null;
}

if (!packageJson.pnpm) {
return null;
}
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';

if (updatedContent === content) {
return null;
}

return updatedContent;
}

48 changes: 48 additions & 0 deletions patch/src/transforms/patch-file.ts
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()
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)

await writeFile(outputPath, convertedContent, 'utf-8')
await rm(fileName)

return convertedContent
}

Loading
Loading