Skip to content

Commit

Permalink
fix(package): Add Package.lazy() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
evocateur committed Dec 20, 2018
1 parent 98c812c commit 4aa9d37
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
32 changes: 32 additions & 0 deletions core/package/__tests__/core-package.test.js
Expand Up @@ -239,3 +239,35 @@ describe("Package", () => {
});
});
});

describe("Package.lazy()", () => {
loadJsonFile.sync.mockImplementation(() => ({ name: "bar", version: "1.0.0" }));

it("returns package instance from string directory argument", () => {
const pkg = Package.lazy("/foo/bar");

expect(pkg).toBeInstanceOf(Package);
expect(pkg.location).toBe("/foo/bar");
});

it("returns package instance from package.json file argument", () => {
const pkg = Package.lazy("/foo/bar/package.json");

expect(pkg).toBeInstanceOf(Package);
expect(pkg.location).toBe("/foo/bar");
});

it("returns package instance from json and dir arguments", () => {
const pkg = Package.lazy({ name: "bar", version: "1.2.3" }, "/foo/bar");

expect(pkg).toBeInstanceOf(Package);
expect(pkg.version).toBe("1.2.3");
});

it("returns existing package instance", () => {
const existing = new Package({ name: "existing" }, "/foo/bar", "/foo");
const pkg = Package.lazy(existing);

expect(pkg).toBe(existing);
});
});
22 changes: 22 additions & 0 deletions core/package/index.js
Expand Up @@ -58,6 +58,10 @@ class Package {
configurable: true,
value: pkg,
},
// safer than instanceof across module boundaries
__isLernaPackage: {
value: true,
},
// immutable
bin: {
value:
Expand Down Expand Up @@ -205,4 +209,22 @@ class Package {
}
}

function lazy(ref, dir = ".") {
if (typeof ref === "string") {
const location = path.resolve(path.basename(ref) === "package.json" ? path.dirname(ref) : ref);
const manifest = loadJsonFile.sync(path.join(location, "package.json"));

return new Package(manifest, location);
}

// don't use instanceof because it fails across nested module boundaries
if ("__isLernaPackage" in ref) {
return ref;
}

// assume ref is a json object
return new Package(ref, dir);
}

module.exports = Package;
module.exports.lazy = lazy;

0 comments on commit 4aa9d37

Please sign in to comment.