Skip to content

Commit

Permalink
fix(devkit): fix issue replacing package dependencies in malformed pa… (
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenPandaz committed May 5, 2023
1 parent 197105a commit b93d46d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 17 deletions.
8 changes: 8 additions & 0 deletions packages/devkit/src/utils/replace-package.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,14 @@ describe('replaceNrwlPackageWithNxPackage', () => {
});
});

it('should handle broken package.json files', () => {
tree.write('package.json', '{ broken: "json ');

expect(() =>
replaceNrwlPackageWithNxPackage(tree, 'old-package', 'new-package')
).not.toThrow();
});

it('should replace any mentions in files', () => {
expect(tree.read('README.txt').toString()).toContain('new-package');
expect(tree.read('README.txt').toString()).not.toContain('old-package');
Expand Down
32 changes: 19 additions & 13 deletions packages/devkit/src/utils/replace-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,26 @@ function replacePackageInDependencies(
return;
}

updateJson<PackageJson>(tree, path, (packageJson) => {
for (const deps of [
packageJson.dependencies ?? {},
packageJson.devDependencies ?? {},
packageJson.peerDependencies ?? {},
packageJson.optionalDependencies ?? {},
]) {
if (oldPackageName in deps) {
deps[newPackageName] = deps[oldPackageName];
delete deps[oldPackageName];
try {
updateJson<PackageJson>(tree, path, (packageJson) => {
for (const deps of [
packageJson.dependencies ?? {},
packageJson.devDependencies ?? {},
packageJson.peerDependencies ?? {},
packageJson.optionalDependencies ?? {},
]) {
if (oldPackageName in deps) {
deps[newPackageName] = deps[oldPackageName];
delete deps[oldPackageName];
}
}
}
return packageJson;
});
return packageJson;
});
} catch (e) {
console.warn(
`Could not replace ${oldPackageName} with ${newPackageName} in ${path}.`
);
}
});
}

Expand Down
10 changes: 6 additions & 4 deletions packages/nx/src/generators/utils/project-configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,12 @@ function findCreatedProjectFiles(tree: Tree) {
if (fileName === 'project.json') {
createdProjectFiles.push(change.path);
} else if (fileName === 'package.json') {
const contents: PackageJson = JSON.parse(change.content.toString());
if (contents.nx) {
createdProjectFiles.push(change.path);
}
try {
const contents: PackageJson = JSON.parse(change.content.toString());
if (contents.nx) {
createdProjectFiles.push(change.path);
}
} catch {}
}
}
}
Expand Down

0 comments on commit b93d46d

Please sign in to comment.