1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import { logger } from "@atomist/automation-client";
|
18 | import {
|
19 | RepoContext,
|
20 | SdmGoalEvent,
|
21 | } from "@atomist/sdm";
|
22 | import * as _ from "lodash";
|
23 | import * as os from "os";
|
24 | import { getGoalVersion } from "../../internal/delivery/build/local/projectVersioner";
|
25 | import { camelCase } from "./util";
|
26 |
|
27 | const PlaceholderExpression = /\$\{([.a-zA-Z_-]+)([.:0-9a-zA-Z-_ \" ]+)*\}/g;
|
28 |
|
29 | export async function resolvePlaceholder(value: string,
|
30 | goal: SdmGoalEvent,
|
31 | ctx: Pick<RepoContext, "configuration" | "context">,
|
32 | parameters: Record<string, any>,
|
33 | raiseError: boolean = true): Promise<string> {
|
34 | if (!PlaceholderExpression.test(value)) {
|
35 | return value;
|
36 | }
|
37 | PlaceholderExpression.lastIndex = 0;
|
38 | let currentValue = value;
|
39 | let result: RegExpExecArray;
|
40 |
|
41 | while (result = PlaceholderExpression.exec(currentValue)) {
|
42 | const fm = result[0];
|
43 | let envValue = _.get(goal, result[1]) ||
|
44 | _.get(ctx.configuration, result[1]) ||
|
45 | _.get(ctx.configuration, camelCase(result[1])) ||
|
46 | _.get(ctx.context, result[1]) ||
|
47 | _.get(ctx.context, camelCase(result[1])) ||
|
48 | _.get({ parameters }, result[1]) ||
|
49 | _.get({ parameters }, camelCase(result[1]));
|
50 | if (result[1] === "home") {
|
51 | envValue = os.userInfo().homedir;
|
52 | } else if (result[1] === "push.after.version" && !!goal) {
|
53 | envValue = await getGoalVersion({
|
54 | context: ctx.context,
|
55 | owner: goal.repo.owner,
|
56 | repo: goal.repo.name,
|
57 | providerId: goal.repo.providerId,
|
58 | branch: goal.branch,
|
59 | sha: goal.sha,
|
60 | });
|
61 | }
|
62 | const defaultValue = result[2] ? result[2].trim().slice(1) : undefined;
|
63 |
|
64 | if (typeof envValue === "string") {
|
65 | currentValue = currentValue.split(fm).join(envValue);
|
66 | PlaceholderExpression.lastIndex = 0;
|
67 | } else if (typeof envValue === "object" && value === fm) {
|
68 | return envValue;
|
69 | } else if (defaultValue) {
|
70 | currentValue = currentValue.split(fm).join(defaultValue);
|
71 | PlaceholderExpression.lastIndex = 0;
|
72 | } else if (raiseError) {
|
73 | logger.warn(`Placeholder replacement failed for '%s', value: '%j', goal: '%j', parameters: '%j'`,
|
74 | result[1], value, goal, parameters);
|
75 | throw new Error(`Placeholder '${result[1]}' can't be resolved`);
|
76 | }
|
77 | }
|
78 | return currentValue;
|
79 | }
|