diff --git a/lib/src/Program.js b/lib/src/Program.js index 51727306..ce646f93 100644 --- a/lib/src/Program.js +++ b/lib/src/Program.js @@ -20,10 +20,15 @@ class Program { .description(this.description) .parse(props.argv); + // Commander keeps the parsed options on opts(). Reading one off the command itself gives + // undefined without complaining, which here meant --config was ignored and the changelog + // was built from whichever .grenrc happened to be in the directory. + const opts = this.program.opts(); + this.options = Object.assign( {}, - getGrenConfig(props.cwd, program.config), - this._getOptionsFromObject(this.program.opts(), this.defaults), + getGrenConfig(props.cwd, opts.config), + this._getOptionsFromObject(opts, this.defaults), ); } diff --git a/test/Program.spec.js b/test/Program.spec.js index f8a0cdaf..741e8f25 100644 --- a/test/Program.spec.js +++ b/test/Program.spec.js @@ -1,5 +1,8 @@ import { assert } from "chai"; import Program from "../lib/src/Program.js"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; describe("Program", () => { const testCommand = new Program({ @@ -164,6 +167,50 @@ describe("Program", () => { }); }); + describe("config", () => { + const options = [ + { short: "-c", name: "config", valueType: "", description: "Custom config" }, + ]; + let cwd; + + before(() => { + cwd = fs.mkdtempSync(path.join(os.tmpdir(), "gren-config-")); + fs.writeFileSync(path.join(cwd, ".grenrc"), JSON.stringify({ repo: "from-the-default" })); + fs.writeFileSync(path.join(cwd, "custom.json"), JSON.stringify({ repo: "from-the-custom" })); + }); + + after(() => { + fs.rmSync(cwd, { recursive: true, force: true }); + }); + + const program = (argv) => + new Program({ name: "Test", description: "This is a test", options, argv, cwd }); + + it("Should read the file --config names", () => { + assert.equal( + program(["node", "gren", "--config", "custom.json"]).options.repo, + "from-the-custom", + ); + }); + + it("Should read the file -c names", () => { + assert.equal(program(["node", "gren", "-c", "custom.json"]).options.repo, "from-the-custom"); + }); + + it("Should fall back to the conventional filenames", () => { + assert.equal(program(["node", "gren"]).options.repo, "from-the-default"); + }); + + it("Should stop when --config names a file that is not there", () => { + // Silently using another file would build the changelog from a configuration the user + // did not ask for, and the output would look like a bug in gren. + assert.throws( + () => program(["node", "gren", "--config", "not-there.json"]), + /Could not find custom config file/, + ); + }); + }); + describe("_filterObject", () => { it("Should return an object without undefined values", () => { assert.deepEqual(