"use strict";
/*
 * Copyright © 2020 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.CloningProjectLoader = void 0;
const GitCommandGitProject_1 = require("@atomist/automation-client/lib/project/git/GitCommandGitProject");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const fs = require("fs-extra");
/**
 * Non caching ProjectLoader that uses a separate clone for each project accessed
 */
exports.CloningProjectLoader = {
    async doWithProject(coords, action) {
        const cloneOptions = coords.cloneOptions ? coords.cloneOptions : {};
        // If we get a cloneDir we need to wrap the DirectoryManager to return the directory
        const directoryManager = !!coords.cloneDir
            ? new ExplicitDirectoryManager(coords.cloneDir)
            : GitCommandGitProject_1.DefaultDirectoryManager;
        const p = await GitCommandGitProject_1.GitCommandGitProject.cloned(coords.credentials, coords.id, cloneOptions, directoryManager);
        if (p.id.sha === "HEAD") {
            const gs = await p.gitStatus();
            p.id.sha = gs.sha;
        }
        if (!!coords.readOnly) {
            p.shouldCache = true;
        }
        else {
            p.shouldCache = false;
        }
        return action(p);
    },
};
class ExplicitDirectoryManager {
    constructor(cloneDir) {
        this.cloneDir = cloneDir;
    }
    async directoryFor(owner, repo, branch, opts) {
        await fs.emptyDir(this.cloneDir);
        return {
            path: this.cloneDir,
            release: () => this.cleanup(this.cloneDir, opts.keep),
            invalidate: () => Promise.resolve(),
            transient: opts.keep === false,
            provenance: "explicit-directory",
            type: "empty-directory",
        };
    }
    async cleanup(p, keep) {
        if (keep) {
            return;
        }
        try {
            await fs.remove(p);
        }
        catch (e) {
            logger_1.logger.warn(`Failed to remove '${p}': ${e.message}`);
        }
    }
}
//# sourceMappingURL=cloningProjectLoader.js.map