Skip to content

Commit

Permalink
feat(package): Add .refresh() method to update internal state when ex…
Browse files Browse the repository at this point in the history
…ternal changes have occurred
  • Loading branch information
evocateur committed Dec 10, 2018
1 parent a1692ce commit 905ba10
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/package/__tests__/core-package.test.js
@@ -1,9 +1,11 @@
"use strict";

jest.mock("load-json-file");
jest.mock("write-pkg");

const os = require("os");
const path = require("path");
const loadJsonFile = require("load-json-file");
const writePkg = require("write-pkg");

// file under test
Expand Down Expand Up @@ -204,6 +206,21 @@ describe("Package", () => {
});
});

describe(".refresh()", () => {
it("reloads private state from disk", async () => {
loadJsonFile.mockImplementationOnce(() => Promise.resolve({ name: "ignored", mutated: true }));

const pkg = factory({ name: "refresh" });

await pkg.refresh();

// a package's name never changes
expect(pkg.name).toBe("refresh");
expect(pkg.get("mutated")).toBe(true);
expect(loadJsonFile).toHaveBeenLastCalledWith(pkg.manifestLocation);
});
});

describe(".serialize()", () => {
it("writes changes to disk", async () => {
writePkg.mockImplementation(() => Promise.resolve());
Expand Down
15 changes: 15 additions & 0 deletions core/package/index.js
Expand Up @@ -2,6 +2,7 @@

const npa = require("libnpm/parse-arg");
const path = require("path");
const loadJsonFile = require("load-json-file");
const writePkg = require("write-pkg");

// symbol used to "hide" internal state
Expand Down Expand Up @@ -136,6 +137,20 @@ class Package {
return shallowCopy(this[PKG]);
}

/**
* Refresh internal state from disk (e.g., changed by external lifecycles)
*/
refresh() {
return loadJsonFile(this.manifestLocation).then(pkg => {
// overwrite configurable property
Object.defineProperty(this, PKG, {
value: pkg,
});

return this;
});
}

/**
* Write manifest changes to disk
* @returns {Promise} resolves when write finished
Expand Down
1 change: 1 addition & 0 deletions core/package/package.json
Expand Up @@ -31,6 +31,7 @@
},
"dependencies": {
"libnpm": "^2.0.1",
"load-json-file": "^4.0.0",
"write-pkg": "^3.1.0"
}
}
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 905ba10

Please sign in to comment.