Skip to content

Commit

Permalink
feat: add run commands for ad-hoc runs of modules, services and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
edvald committed May 14, 2018
1 parent 6ea60b0 commit 3aca6ac
Show file tree
Hide file tree
Showing 30 changed files with 730 additions and 160 deletions.
12 changes: 7 additions & 5 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import * as sywac from "sywac"
import chalk from "chalk"
import { RunCommand } from "./commands/run"
import { enumToArray, shutdown } from "./util"
import { merge, intersection, reduce } from "lodash"
import {
Expand Down Expand Up @@ -220,17 +221,18 @@ export class GardenCli {
const commands = [
new BuildCommand(),
new CallCommand(),
new ConfigCommand(),
new DeployCommand(),
new DevCommand(),
new EnvironmentCommand(),
new LoginCommand(),
new LogoutCommand(),
new LogsCommand(),
new PushCommand(),
new RunCommand(),
new StatusCommand(),
new TestCommand(),
new ConfigCommand(),
new ValidateCommand(),
new StatusCommand(),
new PushCommand(),
new LoginCommand(),
new LogoutCommand(),
]
const globalOptions = Object.entries(GLOBAL_OPTIONS)

Expand Down
2 changes: 1 addition & 1 deletion src/commands/environment/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { EnvironmentDestroyCommand } from "./destroy"
export class EnvironmentCommand extends Command {
name = "environment"
alias = "env"
help = "Outputs the status of your environment"
help = "Manage your runtime environment(s)"

subCommands = [
new EnvironmentConfigureCommand(),
Expand Down
39 changes: 39 additions & 0 deletions src/commands/run/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import { safeDump } from "js-yaml"
import { PluginContext } from "../../plugin-context"
import { RuntimeContext } from "../../types/service"
import { highlightYaml } from "../../util"
import { Command } from "../base"
import { RunModuleCommand } from "./module"
import { RunServiceCommand } from "./service"
import { RunTestCommand } from "./test"

export class RunCommand extends Command {
name = "run"
alias = "r"
help = "Run ad-hoc instances of your modules, services and tests"

subCommands = [
new RunModuleCommand(),
new RunServiceCommand(),
new RunTestCommand(),
]

async action() { }
}

export function printRuntimeContext(ctx: PluginContext, runtimeContext: RuntimeContext) {
ctx.log.verbose("-----------------------------------\n")
ctx.log.verbose("Environment variables:")
ctx.log.verbose(highlightYaml(safeDump(runtimeContext.envVars)))
ctx.log.verbose("Dependencies:")
ctx.log.verbose(highlightYaml(safeDump(runtimeContext.dependencies)))
ctx.log.verbose("-----------------------------------\n")
}
85 changes: 85 additions & 0 deletions src/commands/run/module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright (C) 2018 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import { PluginContext } from "../../plugin-context"
import { BuildTask } from "../../tasks/build"
import { RunResult } from "../../types/plugin"
import { BooleanParameter, Command, ParameterValues, StringParameter } from "../base"
import {
uniq,
values,
flatten,
} from "lodash"
import { printRuntimeContext } from "./index"

export const runArgs = {
module: new StringParameter({
help: "The name of the module to run",
required: true,
}),
// TODO: make this a variadic arg
command: new StringParameter({
help: "The command to run in the module",
}),
}

export const runOpts = {
// TODO: we could provide specific parameters like this by adding commands for specific modules, via plugins
//entrypoint: new StringParameter({ help: "Override default entrypoint in module" }),
interactive: new BooleanParameter({
help: "Set to false to skip interactive mode and just output the command result",
defaultValue: true,
}),
"force-build": new BooleanParameter({ help: "Force rebuild of module" }),
}

export type Args = ParameterValues<typeof runArgs>
export type Opts = ParameterValues<typeof runOpts>

export class RunModuleCommand extends Command<typeof runArgs, typeof runOpts> {
name = "module"
alias = "m"
help = "Run the specified module"

arguments = runArgs
options = runOpts

async action(ctx: PluginContext, args: Args, opts: Opts): Promise<RunResult> {
const name = args.module
const module = await ctx.getModule(name)

const msg = args.command
? `Running command ${chalk.white(args.command)} in module ${chalk.white(name)}`
: `Running module ${chalk.white(name)}`

ctx.log.header({
emoji: "runner",
command: msg,
})

await ctx.configureEnvironment()

const buildTask = new BuildTask(ctx, module, opts["force-build"])
await ctx.addTask(buildTask)
await ctx.processTasks()

const command = args.command ? args.command.split(" ") : []

// combine all dependencies for all services in the module, to be sure we have all the context we need
const services = values(await module.getServices())
const depNames = uniq(flatten(services.map(s => s.config.dependencies)))
const deps = values(await ctx.getServices(depNames))

const runtimeContext = await module.prepareRuntimeContext(deps)

printRuntimeContext(ctx, runtimeContext)

return ctx.runModule({ module, command, runtimeContext, silent: false, interactive: opts.interactive })
}
}
65 changes: 65 additions & 0 deletions src/commands/run/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2018 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import { PluginContext } from "../../plugin-context"
import { BuildTask } from "../../tasks/build"
import { RunResult } from "../../types/plugin"
import { BooleanParameter, Command, ParameterValues, StringParameter } from "../base"
import { printRuntimeContext } from "./index"

export const runArgs = {
service: new StringParameter({
help: "The command to run in the module",
required: true,
}),
}

export const runOpts = {
interactive: new BooleanParameter({
help: "Set to false to skip interactive mode and just output the command result",
defaultValue: true,
}),
"force-build": new BooleanParameter({ help: "Force rebuild of module" }),
}

export type Args = ParameterValues<typeof runArgs>
export type Opts = ParameterValues<typeof runOpts>

export class RunServiceCommand extends Command<typeof runArgs, typeof runOpts> {
name = "service"
alias = "s"
help = "Run an ad-hoc instance of the specified service"

arguments = runArgs
options = runOpts

async action(ctx: PluginContext, args: Args, opts: Opts): Promise<RunResult> {
const name = args.service
const service = await ctx.getService(name)
const module = service.module

ctx.log.header({
emoji: "runner",
command: `Running service ${chalk.cyan(name)} in module ${chalk.cyan(module.name)}`,
})

await ctx.configureEnvironment()

const buildTask = new BuildTask(ctx, module, opts["force-build"])
await ctx.addTask(buildTask)
await ctx.processTasks()

const dependencies = await service.getDependencies()
const runtimeContext = await module.prepareRuntimeContext(dependencies)

printRuntimeContext(ctx, runtimeContext)

return ctx.runService({ service, runtimeContext, silent: false, interactive: opts.interactive })
}
}
83 changes: 83 additions & 0 deletions src/commands/run/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2018 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import chalk from "chalk"
import { ParameterError } from "../../exceptions"
import { PluginContext } from "../../plugin-context"
import { BuildTask } from "../../tasks/build"
import { RunResult } from "../../types/plugin"
import { BooleanParameter, Command, ParameterValues, StringParameter } from "../base"
import { values } from "lodash"
import { printRuntimeContext } from "./index"

export const runArgs = {
module: new StringParameter({
help: "The name of the module to run",
required: true,
}),
test: new StringParameter({
help: "The name of the test to run in the module",
required: true,
}),
}

export const runOpts = {
interactive: new BooleanParameter({
help: "Set to false to skip interactive mode and just output the command result",
defaultValue: true,
}),
"force-build": new BooleanParameter({ help: "Force rebuild of module" }),
}

export type Args = ParameterValues<typeof runArgs>
export type Opts = ParameterValues<typeof runOpts>

export class RunTestCommand extends Command<typeof runArgs, typeof runOpts> {
name = "test"
alias = "t"
help = "Run the specified module test"

arguments = runArgs
options = runOpts

async action(ctx: PluginContext, args: Args, opts: Opts): Promise<RunResult> {
const moduleName = args.module
const testName = args.test
const module = await ctx.getModule(moduleName)
const config = await module.getConfig()

const testSpec = config.test[testName]

if (!testSpec) {
throw new ParameterError(`Could not find test "${testName}" in module ${moduleName}`, {
moduleName,
testName,
availableTests: Object.keys(config.test),
})
}

ctx.log.header({
emoji: "runner",
command: `Running test ${chalk.cyan(testName)} in module ${chalk.cyan(moduleName)}`,
})

await ctx.configureEnvironment()

const buildTask = new BuildTask(ctx, module, opts["force-build"])
await ctx.addTask(buildTask)
await ctx.processTasks()

const interactive = opts.interactive
const deps = await ctx.getServices(testSpec.dependencies)
const runtimeContext = await module.prepareRuntimeContext(values(deps))

printRuntimeContext(ctx, runtimeContext)

return ctx.testModule({ module, interactive, runtimeContext, silent: false, testName, testSpec })
}
}
14 changes: 8 additions & 6 deletions src/garden.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from "./plugins"
import {
Module,
ModuleConfig,
ModuleConfigType,
} from "./types/module"
import {
Expand Down Expand Up @@ -98,8 +99,8 @@ export interface ModuleMap<T extends Module> {
[key: string]: T
}

export interface ServiceMap {
[key: string]: Service<any>
export interface ServiceMap<T extends Module = Module> {
[key: string]: Service<T>
}

export interface ActionHandlerMap<T extends keyof PluginActions> {
Expand All @@ -123,7 +124,7 @@ export type ModuleActionMap = {
}

export interface ContextOpts {
config?: object,
config?: GardenConfig,
env?: string,
logger?: RootLogNode,
plugins?: RegisterPluginParam[],
Expand Down Expand Up @@ -193,8 +194,9 @@ export class Garden {
})
}
} else {
config = await loadConfig(projectRoot, projectRoot)
const templateContext = await getTemplateContext()
parsedConfig = await resolveTemplateStrings(await loadConfig(projectRoot, projectRoot), templateContext)
parsedConfig = await resolveTemplateStrings(config, templateContext)

if (!parsedConfig.project) {
throw new ConfigurationError(`Path ${projectRoot} does not contain a project configuration`, {
Expand Down Expand Up @@ -498,7 +500,7 @@ export class Garden {
/**
* Returns the module with the specified name. Throws error if it doesn't exist.
*/
async getModule(name: string, noScan?: boolean): Promise<Module<any>> {
async getModule(name: string, noScan?: boolean): Promise<Module<ModuleConfig>> {
return (await this.getModules([name], noScan))[name]
}

Expand Down Expand Up @@ -542,7 +544,7 @@ export class Garden {
/**
* Returns the service with the specified name. Throws error if it doesn't exist.
*/
async getService(name: string, noScan?: boolean): Promise<Service<any>> {
async getService(name: string, noScan?: boolean): Promise<Service<Module>> {
return (await this.getServices([name], noScan))[name]
}

Expand Down

0 comments on commit 3aca6ac

Please sign in to comment.