Skip to content

Commit

Permalink
Merge pull request #789 from garden-io/fix-global-cmd-opts
Browse files Browse the repository at this point in the history
fix: make global CLI opts available to commands
  • Loading branch information
thsig authored May 20, 2019
2 parents 50ce354 + 70bce73 commit 217242d
Show file tree
Hide file tree
Showing 27 changed files with 125 additions and 104 deletions.
10 changes: 5 additions & 5 deletions garden-service/package-lock.json

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

8 changes: 4 additions & 4 deletions garden-service/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { Writer } from "../logger/writers/base"
import {
envSupportsEmoji,
failOnInvalidOptions,
falsifyConflictingParams,
negateConflictingParams,
filterByKeys,
getArgSynopsis,
getKeys,
Expand Down Expand Up @@ -140,6 +140,8 @@ export const GLOBAL_OPTIONS = {
}),
}

export type GlobalOptions = typeof GLOBAL_OPTIONS

function initLogger({ level, logEnabled, loggerType, emoji }: {
level: LogLevel, logEnabled: boolean, loggerType: LoggerType, emoji: boolean,
}) {
Expand Down Expand Up @@ -182,7 +184,7 @@ export class GardenCli {
.showHelpByDefault()
.check((argv, _ctx) => {
// NOTE: Need to mutate argv!
merge(argv, falsifyConflictingParams(argv, GLOBAL_OPTIONS))
merge(argv, negateConflictingParams(argv, GLOBAL_OPTIONS))
})
.style(styleConfig)

Expand Down Expand Up @@ -276,7 +278,6 @@ export class GardenCli {
await command.prepare({
log,
logFooter,
output,
args: parsedArgs,
opts: parsedOpts,
})
Expand All @@ -293,7 +294,6 @@ export class GardenCli {
garden,
log,
logFooter,
output,
args: parsedArgs,
opts: parsedOpts,
})
Expand Down
2 changes: 1 addition & 1 deletion garden-service/src/cli/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export type FalsifiedParams = { [key: string]: false }
/**
* Returns the params that need to be overridden set to false
*/
export function falsifyConflictingParams(argv, params: ParameterValues<any>): FalsifiedParams {
export function negateConflictingParams(argv, params: ParameterValues<any>): FalsifiedParams {
return reduce(argv, (acc: {}, val: any, key: string) => {
const param = params[key]
const overrides = (param || {}).overrides || []
Expand Down
4 changes: 2 additions & 2 deletions garden-service/src/commands/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { ProcessResults } from "../process"
import { Garden } from "../garden"
import { LogEntry } from "../logger/log-entry"
import { logHeader } from "../logger/util"
import { GlobalOptions } from "../cli/cli"

export class ValidationError extends Error { }

Expand Down Expand Up @@ -207,10 +208,9 @@ export interface CommandResult<T = any> {

export interface PrepareParams<T extends Parameters = {}, U extends Parameters = {}> {
args: ParameterValues<T>
opts: ParameterValues<U>
opts: ParameterValues<GlobalOptions & U>
log: LogEntry
logFooter: LogEntry
output?: string
}

export interface CommandParams<T extends Parameters = {}, U extends Parameters = {}> extends PrepareParams<T, U> {
Expand Down
4 changes: 2 additions & 2 deletions garden-service/src/commands/get/get-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ export class GetStatusCommand extends Command {
name = "status"
help = "Outputs the status of your environment."

async action({ garden, log, output }: CommandParams): Promise<CommandResult<EnvironmentStatus>> {
async action({ garden, log, opts }: CommandParams): Promise<CommandResult<EnvironmentStatus>> {
const status = await garden.actions.getStatus({ log })

let result
if (output) {
if (opts.output) {
const graph = await garden.getConfigGraph()
result = await Bluebird.props({
...status,
Expand Down
6 changes: 3 additions & 3 deletions garden-service/src/commands/update-remote/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class UpdateRemoteAllCommand extends Command {
garden update-remote all # update all remote sources and modules in the project
`

async action({ garden, log, logFooter }: CommandParams): Promise<CommandResult<UpdateRemoteAllResult>> {
async action({ garden, log, logFooter, opts }: CommandParams): Promise<CommandResult<UpdateRemoteAllResult>> {
logHeader({ log, emoji: "hammer_and_wrench", command: "update-remote all" })

const sourcesCmd = new UpdateRemoteSourcesCommand()
Expand All @@ -43,15 +43,15 @@ export class UpdateRemoteAllCommand extends Command {
garden,
log,
logFooter,
opts,
args: { sources: undefined },
opts: {},
})
const { result: moduleSources } = await modulesCmd.action({
garden,
log,
logFooter,
opts,
args: { modules: undefined },
opts: {},
})

return { result: { projectSources: projectSources!, moduleSources: moduleSources! } }
Expand Down
16 changes: 10 additions & 6 deletions garden-service/src/server/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@

import Joi = require("joi")
import Koa = require("koa")
import { Command, Parameters } from "../commands/base"
import { Command, Parameters, ParameterValues } from "../commands/base"
import { validate } from "../config/common"
import { mapValues, omitBy } from "lodash"
import { extend, mapValues, omitBy } from "lodash"
import { Garden } from "../garden"
import { LogLevel } from "../logger/log-node"
import { LogEntry } from "../logger/log-entry"
import { GLOBAL_OPTIONS } from "../cli/cli"

export interface CommandMap {
[key: string]: {
Expand Down Expand Up @@ -73,7 +74,8 @@ export async function resolveRequest(
const cmdLog = log.placeholder(LogLevel.silly, { childEntriesInheritLevel: true })

const cmdArgs = mapParams(ctx, request.parameters, command.arguments)
const cmdOpts = mapParams(ctx, request.parameters, command.options)
const optParams = extend({ ...GLOBAL_OPTIONS, ...command.options })
const cmdOpts = mapParams(ctx, request.parameters, optParams)

return command.action({
garden: cmdGarden,
Expand Down Expand Up @@ -136,12 +138,14 @@ function paramsToJoi(params?: Parameters) {
/**
* Prepare the args or opts for a Command action, by mapping input values to the parameter specs.
*/
function mapParams(ctx: Koa.ParameterizedContext, values: object, params?: Parameters) {
function mapParams<P extends Parameters>(
ctx: Koa.ParameterizedContext, values: object, params?: P,
): ParameterValues<P> {
if (!params) {
return {}
return <ParameterValues<P>>{}
}

const output = mapValues(params, (p, key) => {
const output = <ParameterValues<P>>mapValues(params, (p, key) => {
if (p.cliOnly) {
return p.defaultValue
}
Expand Down
6 changes: 6 additions & 0 deletions garden-service/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import * as td from "testdouble"
import * as Joi from "joi"
import { resolve, join } from "path"
import { extend } from "lodash"
import { remove, readdirSync, existsSync } from "fs-extra"
import { containerModuleSpecSchema, containerTestSchema, containerTaskSchema } from "../src/plugins/container/config"
import { testExecModule, buildExecModule, execBuildSpecSchema } from "../src/plugins/exec"
Expand Down Expand Up @@ -42,6 +43,7 @@ import { SourceConfig } from "../src/config/project"
import { BuildDir } from "../src/build-dir"
import { LogEntry } from "../src/logger/log-entry"
import timekeeper = require("timekeeper")
import { GLOBAL_OPTIONS } from "../src/cli/cli"

export const dataDir = resolve(__dirname, "unit", "data")
export const examplesDir = resolve(__dirname, "..", "..", "examples")
Expand Down Expand Up @@ -386,6 +388,10 @@ export function getExampleProjects() {
return fromPairs(names.map(n => [n, join(examplesDir, n)]))
}

export function withDefaultGlobalOpts(opts: any) {
return extend(mapValues(GLOBAL_OPTIONS, (opt) => opt.defaultValue), opts)
}

export function freezeTime(date?: Date) {
if (!date) {
date = new Date()
Expand Down
6 changes: 3 additions & 3 deletions garden-service/test/unit/src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BuildCommand } from "../../../../src/commands/build"
import { expect } from "chai"
import { makeTestGardenA } from "../../../helpers"
import { makeTestGardenA, withDefaultGlobalOpts } from "../../../helpers"
import { taskResultOutputs } from "../../../helpers"

describe("commands.build", () => {
Expand All @@ -15,7 +15,7 @@ describe("commands.build", () => {
log,
logFooter,
args: { modules: undefined },
opts: { watch: false, force: true },
opts: withDefaultGlobalOpts({ watch: false, force: true }),
})

expect(taskResultOutputs(result!)).to.eql({
Expand All @@ -36,7 +36,7 @@ describe("commands.build", () => {
log,
logFooter,
args: { modules: ["module-b"] },
opts: { watch: false, force: true },
opts: withDefaultGlobalOpts({ watch: false, force: true }),
})

expect(taskResultOutputs(result!)).to.eql({
Expand Down
14 changes: 7 additions & 7 deletions garden-service/test/unit/src/commands/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { PluginFactory } from "../../../../src/types/plugin/plugin"
import { GetServiceStatusParams } from "../../../../src/types/plugin/params"
import { ServiceStatus } from "../../../../src/types/service"
import nock = require("nock")
import { configureTestModule } from "../../../helpers"
import { configureTestModule, withDefaultGlobalOpts } from "../../../helpers"

const testProvider: PluginFactory = () => {
const testStatuses: { [key: string]: ServiceStatus } = {
Expand Down Expand Up @@ -71,7 +71,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-a/path-a" },
opts: {},
opts: withDefaultGlobalOpts({}),
})

expect(result.url).to.equal("http://service-a.test-project-b.local.app.garden:32000/path-a")
Expand All @@ -96,7 +96,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-a" },
opts: {},
opts: withDefaultGlobalOpts({}),
})

expect(result.url).to.equal("http://service-a.test-project-b.local.app.garden:32000/path-a")
Expand All @@ -120,7 +120,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-b" },
opts: {},
opts: withDefaultGlobalOpts({}),
})

expect(result.url).to.equal("http://service-b.test-project-b.local.app.garden:32000/")
Expand All @@ -141,7 +141,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-d/path-d" },
opts: {},
opts: withDefaultGlobalOpts({}),
})
} catch (err) {
expect(err.type).to.equal("runtime")
Expand All @@ -162,7 +162,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-c/path-c" },
opts: {},
opts: withDefaultGlobalOpts({}),
})
} catch (err) {
expect(err.type).to.equal("parameter")
Expand All @@ -183,7 +183,7 @@ describe("commands.call", () => {
log,
logFooter: log,
args: { serviceAndPath: "service-a/bla" },
opts: {},
opts: withDefaultGlobalOpts({}),
})
} catch (err) {
expect(err.type).to.equal("parameter")
Expand Down
12 changes: 6 additions & 6 deletions garden-service/test/unit/src/commands/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import { Garden } from "../../../../src/garden"
import { EnvironmentStatus } from "../../../../src/types/plugin/outputs"
import { PluginFactory } from "../../../../src/types/plugin/plugin"
import { expectError, makeTestGardenA, getDataDir, configureTestModule } from "../../../helpers"
import { expectError, makeTestGardenA, getDataDir, configureTestModule, withDefaultGlobalOpts } from "../../../helpers"
import { expect } from "chai"
import { ServiceStatus } from "../../../../src/types/service"
import { DeleteServiceParams } from "../../../../src/types/plugin/params"
Expand All @@ -30,7 +30,7 @@ describe("DeleteSecretCommand", () => {
log,
logFooter: log,
args: { provider, key },
opts: {},
opts: withDefaultGlobalOpts({}),
})

expect(await garden.actions.getSecret({ log, pluginName, key })).to.eql({ value: null })
Expand All @@ -47,7 +47,7 @@ describe("DeleteSecretCommand", () => {
log,
logFooter: log,
args: { provider, key: "foo" },
opts: {},
opts: withDefaultGlobalOpts({}),
}),
"not-found",
)
Expand Down Expand Up @@ -85,7 +85,7 @@ describe("DeleteEnvironmentCommand", () => {
const garden = await Garden.factory(projectRootB, { plugins })
const log = garden.log

const { result } = await command.action({ garden, log, logFooter: log, args: {}, opts: {} })
const { result } = await command.action({ garden, log, logFooter: log, args: {}, opts: withDefaultGlobalOpts({}) })

expect(result!["test-plugin"]["ready"]).to.be.false
})
Expand Down Expand Up @@ -132,7 +132,7 @@ describe("DeleteServiceCommand", () => {
log,
logFooter: log,
args: { services: ["service-a"] },
opts: {},
opts: withDefaultGlobalOpts({}),
})
expect(result).to.eql({
"service-a": { state: "unknown", ingresses: [] },
Expand All @@ -148,7 +148,7 @@ describe("DeleteServiceCommand", () => {
log,
logFooter: log,
args: { services: ["service-a", "service-b"] },
opts: {},
opts: withDefaultGlobalOpts({}),
})
expect(result).to.eql({
"service-a": { state: "unknown", ingresses: [] },
Expand Down
Loading

0 comments on commit 217242d

Please sign in to comment.