1 | /*
|
2 | * Copyright © 2019 Atomist, Inc.
|
3 | *
|
4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | * you may not use this file except in compliance with the License.
|
6 | * You may obtain a copy of the License at
|
7 | *
|
8 | * http://www.apache.org/licenses/LICENSE-2.0
|
9 | *
|
10 | * Unless required by applicable law or agreed to in writing, software
|
11 | * distributed under the License is distributed on an "AS IS" BASIS,
|
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 | * See the License for the specific language governing permissions and
|
14 | * limitations under the License.
|
15 | */
|
16 |
|
17 | import {
|
18 | automationClientInstance,
|
19 | AutomationContextAware,
|
20 | HandlerContext,
|
21 | HandlerResult,
|
22 | ParameterType,
|
23 | } from "@atomist/automation-client";
|
24 | import { CommandRegistration } from "@atomist/sdm";
|
25 | import {
|
26 | prepareCommandInvocation,
|
27 | prepareHandlerContext,
|
28 | } from "./helpers";
|
29 |
|
30 | /**
|
31 | * Invoke any registered command programmatically in this SDM instance
|
32 | *
|
33 | * @param command name of the CommandRegistration or actual CommandRegistration instance to run
|
34 | * @param parameters parameters to be passed to the command
|
35 | * @param ctx HandlerContext instance
|
36 | */
|
37 | export async function invokeCommand<T extends ParameterType>(command: string | CommandRegistration<T>,
|
38 | parameters: T,
|
39 | ctx: HandlerContext): Promise<HandlerResult> {
|
40 | const name = typeof command === "string" ? command : command.name;
|
41 | const trigger = (ctx as any as AutomationContextAware).trigger;
|
42 |
|
43 | const md = automationClientInstance().automationServer.automations.commands
|
44 | .find(c => c.name === name);
|
45 |
|
46 | if (!md) {
|
47 | return {
|
48 | code: 1,
|
49 | message: `Command '${name}' could not be found`,
|
50 | };
|
51 | } else {
|
52 | // Invoke the command
|
53 | return automationClientInstance().automationServer.invokeCommand(
|
54 | prepareCommandInvocation(md, parameters),
|
55 | prepareHandlerContext(ctx, trigger),
|
56 | );
|
57 | }
|
58 | }
|