Skip to content

Commit

Permalink
Merge pull request #13 from jalal246/dev
Browse files Browse the repository at this point in the history
fix bug in dealing with empty json and invalid name
  • Loading branch information
jalal246 authored May 6, 2020
2 parents 7719552 + f830727 commit 16ff422
Show file tree
Hide file tree
Showing 8 changed files with 25 additions and 8 deletions.
29 changes: 22 additions & 7 deletions src/getJsonByPath.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ function getJsonByPath(...defaultPaths) {
const pkgInfo = {};
const unfoundJson = [];

let i = 0;

const packagesJson = foundPaths
.map((pkgPath) => {
const pkgJson = resolve(pkgPath, "package.json");
Expand All @@ -48,27 +50,40 @@ function getJsonByPath(...defaultPaths) {

if (!isValid) {
unfoundJson.push(pkgJson);

return null;
}

const json = fs.readFileSync(pkgJson, "utf8");

const { name, peerDependencies, dependencies, ...other } = JSON.parse(
json
);
if (!json) {
unfoundJson.push(pkgJson);

return null;
}

const parsed = JSON.parse(json);

if (parsed.constructor !== Object || Object.keys(parsed).length === 0) {
unfoundJson.push(pkgJson);

return null;
}

const { name, ...rest } = JSON.parse(json);

/**
* Add extracted extra info to pkgInfo and keep pkgJson as it is.
*/
pkgInfo[name] = {
pkgInfo[name || i] = {
path: pkgPath,
};

i += 1;

return {
name,
peerDependencies,
dependencies,
...other,
...rest,
};
})
.filter(Boolean);
Expand Down
Empty file.
1 change: 1 addition & 0 deletions test/fixtures/empty-json/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions test/fixtures/invlaid-json/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
""
Empty file.
Empty file.
Empty file added test/fixtures/no-json/index.js
Empty file.
2 changes: 1 addition & 1 deletion test/getJsonByPath.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe("getJsonByPath", () => {
const { json, pkgInfo, unfoundJson } = getJsonByPath(...rootPath);

expect(json.length).to.be.equal(6);
expect(unfoundJson.length).to.be.equal(1);
expect(unfoundJson.length).to.be.equal(4);

json.forEach(({ name }) => {
expect(name).to.be.an("string");
Expand Down

0 comments on commit 16ff422

Please sign in to comment.