Skip to content

Commit

Permalink
Reformat all files using "prettier -w ."
Browse files Browse the repository at this point in the history
  • Loading branch information
octogonz committed Feb 16, 2024
1 parent feb112b commit 8ef31b1
Show file tree
Hide file tree
Showing 16 changed files with 92 additions and 167 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ jobs:
- name: Build and run tests for pnpm-sync-lib
run: pnpm --filter pnpm-sync-lib run build && pnpm --filter pnpm-sync-lib run test
- name: Build and run tests for pnpm-sync
run: pnpm --filter pnpm-sync run build && pnpm --filter pnpm-sync run test
run: pnpm --filter pnpm-sync run build && pnpm --filter pnpm-sync run test
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ jobs:
run: |
npm config set "//registry.npmjs.org/:_authToken" "${NPM_AUTH_TOKEN}"
pnpm --filter pnpm-sync-lib publish --no-git-checks
pnpm --filter pnpm-sync publish --no-git-checks
pnpm --filter pnpm-sync publish --no-git-checks
4 changes: 2 additions & 2 deletions packages/pnpm-sync-lib/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
require("@rushstack/eslint-patch/modern-module-resolution");
require('@rushstack/eslint-patch/modern-module-resolution');
module.exports = {
extends: ['@rushstack/eslint-config/profile/node'],
parserOptions: { tsconfigRootDir: __dirname }
};
};
14 changes: 3 additions & 11 deletions packages/pnpm-sync-lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,6 @@
* @packageDocumentation
*/

export { pnpmSyncCopyAsync, type IPnpmSyncCopyOptions } from "./pnpmSyncCopy";
export {
pnpmSyncPrepareAsync,
type IPnpmSyncPrepareOptions,
} from "./pnpmSyncPrepare";
export type {
ILockfile,
ILockfileImporter,
IVersionSpecifier,
IDependencyMeta,
} from "./interfaces";
export { pnpmSyncCopyAsync, type IPnpmSyncCopyOptions } from './pnpmSyncCopy';
export { pnpmSyncPrepareAsync, type IPnpmSyncPrepareOptions } from './pnpmSyncPrepare';
export type { ILockfile, ILockfileImporter, IVersionSpecifier, IDependencyMeta } from './interfaces';
45 changes: 15 additions & 30 deletions packages/pnpm-sync-lib/src/pnpmSyncCopy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from "path";
import fs from "fs";
import path from 'path';
import fs from 'fs';

/**
* @beta
Expand Down Expand Up @@ -29,26 +29,24 @@ export interface IPnpmSyncCopyOptions {
* @beta
*/
export async function pnpmSyncCopyAsync({
pnpmSyncJsonPath = "",
pnpmSyncJsonPath = '',
getPackageIncludedFiles,
forEachAsyncWithConcurrency,
ensureFolder,
ensureFolder
}: IPnpmSyncCopyOptions): Promise<void> {
if (pnpmSyncJsonPath === "") {
if (pnpmSyncJsonPath === '') {
// if user does not input .pnpm-sync.json file path
// then we assume .pnpm-sync.json is always under node_modules folder
pnpmSyncJsonPath = "node_modules/.pnpm-sync.json";
pnpmSyncJsonPath = 'node_modules/.pnpm-sync.json';
}

let pnpmSyncJsonContents: string;
try {
pnpmSyncJsonContents = (
await fs.promises.readFile(pnpmSyncJsonPath)
).toString();
pnpmSyncJsonContents = (await fs.promises.readFile(pnpmSyncJsonPath)).toString();
} catch (e) {
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
console.warn(
"You are executing pnpm-sync for a package, but we can not find the .pnpm-sync.json inside node_modules folder"
'You are executing pnpm-sync for a package, but we can not find the .pnpm-sync.json inside node_modules folder'
);
return;
} else {
Expand All @@ -64,33 +62,22 @@ export async function pnpmSyncCopyAsync({
//get npmPackFiles
const npmPackFiles: string[] = await getPackageIncludedFiles(sourcePath);

console.time(
`pnpm-sync => ${sourcePath}, total ${npmPackFiles.length} files`
);
console.time(`pnpm-sync => ${sourcePath}, total ${npmPackFiles.length} files`);

//clear the destination folder first
for (const targetFolder of targetFolders) {
const destinationPath = path.resolve(
pnpmSyncJsonPath,
targetFolder.folderPath
);
const destinationPath = path.resolve(pnpmSyncJsonPath, targetFolder.folderPath);
await fs.promises.rm(destinationPath, { recursive: true });
}

await forEachAsyncWithConcurrency(
npmPackFiles,
async (npmPackFile: string) => {
for (const targetFolder of targetFolders) {
const destinationPath = path.resolve(
pnpmSyncJsonPath,
targetFolder.folderPath
);
const destinationPath = path.resolve(pnpmSyncJsonPath, targetFolder.folderPath);

const copySourcePath: string = path.join(sourcePath, npmPackFile);
const copyDestinationPath: string = path.join(
destinationPath,
npmPackFile
);
const copyDestinationPath: string = path.join(destinationPath, npmPackFile);

await ensureFolder(path.dirname(copyDestinationPath));

Expand All @@ -99,11 +86,9 @@ export async function pnpmSyncCopyAsync({
}
},
{
concurrency: 10,
concurrency: 10
}
);

console.timeEnd(
`pnpm-sync => ${sourcePath}, total ${npmPackFiles.length} files`
);
console.timeEnd(`pnpm-sync => ${sourcePath}, total ${npmPackFiles.length} files`);
}
107 changes: 34 additions & 73 deletions packages/pnpm-sync-lib/src/pnpmSyncPrepare.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import path from "path";
import fs from "fs";
import { cwd } from "process";
import path from 'path';
import fs from 'fs';
import { cwd } from 'process';

import type { ILockfile, IPnpmSyncJson, IVersionSpecifier } from "./interfaces";
import type { ILockfile, IPnpmSyncJson, IVersionSpecifier } from './interfaces';

/**
* @beta
Expand Down Expand Up @@ -30,79 +30,56 @@ export interface IPnpmSyncPrepareOptions {
export async function pnpmSyncPrepareAsync({
lockfilePath,
storePath,
readPnpmLockfile,
readPnpmLockfile
}: IPnpmSyncPrepareOptions): Promise<void> {
console.log("Generate pnpm-sync.json ...");
console.log('Generate pnpm-sync.json ...');

// get the pnpm-lock.yaml path
lockfilePath = path.resolve(cwd(), lockfilePath);
storePath = path.resolve(cwd(), storePath);

console.log("The pnpm-lock.yaml file path =>", lockfilePath);
console.log("The .pnpm folder path =>", storePath);
console.log('The pnpm-lock.yaml file path =>', lockfilePath);
console.log('The .pnpm folder path =>', storePath);

if (!fs.existsSync(lockfilePath)) {
throw Error("The input pnpm-lock.yaml path is not correct!");
throw Error('The input pnpm-lock.yaml path is not correct!');
}

console.time(`pnpm-sync prepare`);

// read the pnpm-lock.yaml
const pnpmLockfile = await readPnpmLockfile(lockfilePath, {
ignoreIncompatible: true,
ignoreIncompatible: true
});

// find injected dependency and all its available versions
const injectedDependencyToVersion: Map<
string,
Set<string>
> = getInjectedDependencyToVersion(pnpmLockfile);
const injectedDependencyToVersion: Map<string, Set<string>> = getInjectedDependencyToVersion(pnpmLockfile);

// get pnpm-lock.yaml folder path
const pnpmLockFolder = lockfilePath.slice(
0,
lockfilePath.length - "pnpm-lock.yaml".length
);
const pnpmLockFolder = lockfilePath.slice(0, lockfilePath.length - 'pnpm-lock.yaml'.length);

// generate a map, where key is the actual path of the injectedDependency, value is all available paths in .pnpm folder
const injectedDependencyToFilePathSet: Map<string, Set<string>> = new Map();
for (const [
injectedDependency,
injectedDependencyVersionSet,
] of injectedDependencyToVersion) {
for (const [injectedDependency, injectedDependencyVersionSet] of injectedDependencyToVersion) {
for (const injectedDependencyVersion of injectedDependencyVersionSet) {
// this logic is heavily depends on pnpm-lock formate
// the current logic is for pnpm v8
// for example: file:../../libraries/lib1([email protected]) -> ../../libraries/lib1
let injectedDependencyPath = injectedDependencyVersion
.split("(")[0]
.slice("file:".length);
injectedDependencyPath = path.resolve(
pnpmLockFolder,
injectedDependencyPath
);
let injectedDependencyPath = injectedDependencyVersion.split('(')[0].slice('file:'.length);
injectedDependencyPath = path.resolve(pnpmLockFolder, injectedDependencyPath);
if (!injectedDependencyToFilePathSet.has(injectedDependencyPath)) {
injectedDependencyToFilePathSet.set(injectedDependencyPath, new Set());
}

injectedDependencyToFilePathSet
.get(injectedDependencyPath)
?.add(
transferFilePathToPnpmStorePath(
injectedDependencyVersion,
injectedDependency,
storePath
)
);
?.add(transferFilePathToPnpmStorePath(injectedDependencyVersion, injectedDependency, storePath));
}
}

// now, we have everything we need to generate the the pnpm-sync.json
// console.log('injectedDependencyToFilePathSet =>', injectedDependencyToFilePathSet);
for (const [
projectFolder,
targetFolderSet,
] of injectedDependencyToFilePathSet) {
for (const [projectFolder, targetFolderSet] of injectedDependencyToFilePathSet) {
if (targetFolderSet.size === 0) {
continue;
}
Expand All @@ -111,37 +88,31 @@ export async function pnpmSyncPrepareAsync({

let pnpmSyncJsonFile: IPnpmSyncJson = {
postbuildInjectedCopy: {
sourceFolder: "../..",
targetFolders: [],
},
sourceFolder: '../..',
targetFolders: []
}
};

// if .pnpm-sync.json already exists, read it first
if (fs.existsSync(pnpmSyncJsonPath)) {
pnpmSyncJsonFile = JSON.parse(
fs.readFileSync(pnpmSyncJsonPath).toString()
);
pnpmSyncJsonFile = JSON.parse(fs.readFileSync(pnpmSyncJsonPath).toString());
}

const existingTargetFolderSet: Set<string> = new Set();

for (const targetFolder of pnpmSyncJsonFile.postbuildInjectedCopy
.targetFolders) {
for (const targetFolder of pnpmSyncJsonFile.postbuildInjectedCopy.targetFolders) {
existingTargetFolderSet.add(targetFolder.folderPath);
}

for (const targetFolder of targetFolderSet) {
const relativePath = path.relative(pnpmSyncJsonPath, targetFolder);
if (!existingTargetFolderSet.has(relativePath)) {
pnpmSyncJsonFile.postbuildInjectedCopy.targetFolders.push({
folderPath: relativePath,
folderPath: relativePath
});
}
}
fs.writeFileSync(
pnpmSyncJsonPath,
JSON.stringify(pnpmSyncJsonFile, null, 2)
);
fs.writeFileSync(pnpmSyncJsonPath, JSON.stringify(pnpmSyncJsonFile, null, 2));
}
console.timeEnd(`pnpm-sync prepare`);
}
Expand All @@ -157,36 +128,33 @@ function transferFilePathToPnpmStorePath(
// an example, file:../../libraries/lib1([email protected]) -> [email protected]

// 1. replace ':' with '+'
rawFilePath = rawFilePath.replaceAll(":", "+");
rawFilePath = rawFilePath.replaceAll(':', '+');

// 2. replace '/' with '+'
rawFilePath = rawFilePath.replaceAll("/", "+");
rawFilePath = rawFilePath.replaceAll('/', '+');

// 3. replace '(' with '_'
rawFilePath = rawFilePath.replaceAll("(", "_");
rawFilePath = rawFilePath.replaceAll('(', '_');

// 4. remove ')'
rawFilePath = rawFilePath.replaceAll(")", "");
rawFilePath = rawFilePath.replaceAll(')', '');

// 5. add dependencyName
rawFilePath = rawFilePath + `/node_modules/${dependencyName}`;

rawFilePath = storePath + "/" + rawFilePath;
rawFilePath = storePath + '/' + rawFilePath;

return rawFilePath;
}

// process dependencies and devDependencies to generate injectedDependencyToFilePath
function getInjectedDependencyToVersion(
pnpmLockfile: ILockfile | undefined
): Map<string, Set<string>> {
function getInjectedDependencyToVersion(pnpmLockfile: ILockfile | undefined): Map<string, Set<string>> {
const injectedDependencyToVersion: Map<string, Set<string>> = new Map();
for (const importerKey in pnpmLockfile?.importers) {
if (!pnpmLockfile?.importers[importerKey]?.dependenciesMeta) {
continue;
}
const dependenciesMeta =
pnpmLockfile?.importers[importerKey]?.dependenciesMeta;
const dependenciesMeta = pnpmLockfile?.importers[importerKey]?.dependenciesMeta;

for (const dependency in dependenciesMeta) {
if (dependenciesMeta[dependency]?.injected) {
Expand All @@ -198,14 +166,8 @@ function getInjectedDependencyToVersion(

// based on https://pnpm.io/package_json#dependenciesmeta
// the injected dependencies could available inside dependencies, optionalDependencies, and devDependencies.
processDependencies(
pnpmLockfile?.importers[importerKey]?.dependencies,
injectedDependencyToVersion
);
processDependencies(
pnpmLockfile?.importers[importerKey]?.devDependencies,
injectedDependencyToVersion
);
processDependencies(pnpmLockfile?.importers[importerKey]?.dependencies, injectedDependencyToVersion);
processDependencies(pnpmLockfile?.importers[importerKey]?.devDependencies, injectedDependencyToVersion);
processDependencies(
pnpmLockfile?.importers[importerKey]?.optionalDependencies,
injectedDependencyToVersion
Expand All @@ -220,8 +182,7 @@ function processDependencies(
if (dependencies) {
for (const [dependency, specifier] of Object.entries(dependencies)) {
if (injectedDependencyToVersion.has(dependency)) {
const specifierToUse: string =
typeof specifier === "string" ? specifier : specifier.version;
const specifierToUse: string = typeof specifier === 'string' ? specifier : specifier.version;
injectedDependencyToVersion.get(dependency)?.add(specifierToUse);
}
}
Expand Down
4 changes: 1 addition & 3 deletions packages/pnpm-sync-lib/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
"extends": "./node_modules/@rushstack/heft-node-rig/profiles/default/tsconfig-base.json",
"compilerOptions": {
"types": ["heft-jest", "node"],
"lib": [
"ES2021.String"
]
"lib": ["ES2021.String"]
}
}
4 changes: 2 additions & 2 deletions packages/pnpm-sync/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
require("@rushstack/eslint-patch/modern-module-resolution");
require('@rushstack/eslint-patch/modern-module-resolution');
module.exports = {
extends: ['@rushstack/eslint-config/profile/node'],
parserOptions: { tsconfigRootDir: __dirname }
};
};
Loading

0 comments on commit 8ef31b1

Please sign in to comment.