UNPKG

3.31 kBPlain TextView Raw
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
17import { logger } from "@atomist/automation-client";
18import {
19 RepoContext,
20 SdmGoalEvent,
21} from "@atomist/sdm";
22import * as _ from "lodash";
23import * as os from "os";
24import { getGoalVersion } from "../../internal/delivery/build/local/projectVersioner";
25import { camelCase } from "./util";
26
27const PlaceholderExpression = /\$\{([.a-zA-Z_-]+)([.:0-9a-zA-Z-_ \" ]+)*\}/g;
28
29export 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 // tslint:disable-next-line:no-conditional-assignment
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}