"use strict";
/*
 * Copyright © 2019 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.doWithProject = exports.toProjectAwareGoalInvocation = void 0;
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const child_process_1 = require("../misc/child_process");
/**
 * Convenience method to create project aware goal invocations with
 * spawn and exec functions that, by default, use the cloned project
 * base directory as the current working directory.
 *
 * @param project locally cloned project
 * @param gi SDM goal invocation
 * @return goal invocation made project aware
 */
function toProjectAwareGoalInvocation(project, gi) {
    const { progressLog } = gi;
    const spawn = pagiSpawn(project, progressLog);
    const exec = pagiExec(project);
    return Object.assign(Object.assign({}, gi), { project, spawn, exec });
}
exports.toProjectAwareGoalInvocation = toProjectAwareGoalInvocation;
/**
 * Convenience method to create goal implementations that require a local clone of the project.
 * @param {(pa: ProjectGoalInvocation) => Promise<ExecuteGoalResult>} action
 * @param {CloneOptions & {readOnly: boolean}} cloneOptions
 * @returns {ExecuteGoal}
 */
function doWithProject(action, cloneOptions = { readOnly: false }) {
    return gi => {
        const { context, credentials, id, configuration, progressLog } = gi;
        return configuration.sdm.projectLoader.doWithProject({
            context,
            credentials,
            id,
            readOnly: cloneOptions.readOnly,
            cloneOptions,
        }, (p) => action(Object.assign(Object.assign({}, gi), { project: p, spawn: pagiSpawn(p, progressLog), exec: pagiExec(p) })));
    };
}
exports.doWithProject = doWithProject;
/**
 * Return spawn function for project-aware goal invocations.
 */
function pagiSpawn(p, log) {
    return (cmd, args = [], opts) => {
        const optsToUse = Object.assign({ cwd: p.baseDir, log }, opts);
        return child_process_1.spawnLog(cmd, string_1.toStringArray(args), optsToUse);
    };
}
/**
 * Return exec function for project-aware goal invocations.
 */
function pagiExec(p) {
    return (cmd, args = [], opts = {}) => {
        const optsToUse = Object.assign({ cwd: p.baseDir }, opts);
        return child_process_1.execPromise(cmd, string_1.toStringArray(args), optsToUse);
    };
}
//# sourceMappingURL=withProject.js.map