"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configSigningKey = exports.writePrivateKey = exports.setPrivateKey = void 0;
const tslib_1 = require("tslib");
const node_os_1 = tslib_1.__importDefault(require("node:os"));
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const upath_1 = tslib_1.__importDefault(require("upath"));
const error_messages_1 = require("../../constants/error-messages");
const logger_1 = require("../../logger");
const exec_1 = require("../exec");
const regex_1 = require("../regex");
const sanitize_1 = require("../sanitize");
let gitPrivateKey;
class PrivateKey {
    key;
    keyId;
    constructor(key) {
        this.key = key.trim();
        (0, sanitize_1.addSecretForSanitizing)(this.key, 'global');
        logger_1.logger.debug('gitPrivateKey: successfully set (but not yet written/configured)');
    }
    async writeKey() {
        try {
            if (!this.keyId) {
                this.keyId = await this.importKey();
            }
            logger_1.logger.debug('gitPrivateKey: imported');
        }
        catch (err) {
            logger_1.logger.warn({ err }, 'gitPrivateKey: error importing');
            throw new Error(error_messages_1.PLATFORM_GPG_FAILED);
        }
    }
    async configSigningKey(cwd) {
        logger_1.logger.debug('gitPrivateKey: configuring commit signing');
        // TODO: types (#22198)
        await (0, exec_1.exec)(`git config user.signingkey ${this.keyId}`, { cwd });
        await (0, exec_1.exec)(`git config commit.gpgsign true`, { cwd });
    }
}
class GPGKey extends PrivateKey {
    async importKey() {
        const keyFileName = upath_1.default.join(node_os_1.default.tmpdir() + '/git-private-gpg.key');
        await fs_extra_1.default.outputFile(keyFileName, this.key);
        const { stdout, stderr } = await (0, exec_1.exec)(`gpg --import ${keyFileName}`);
        logger_1.logger.debug({ stdout, stderr }, 'Private key import result');
        await fs_extra_1.default.remove(keyFileName);
        return `${stdout}${stderr}`
            .split(regex_1.newlineRegex)
            .find((line) => line.includes('secret key imported'))
            ?.replace('gpg: key ', '')
            .split(':')
            .shift();
    }
}
function setPrivateKey(key) {
    if (!is_1.default.nonEmptyStringAndNotWhitespace(key)) {
        return;
    }
    gitPrivateKey = new GPGKey(key);
}
exports.setPrivateKey = setPrivateKey;
async function writePrivateKey() {
    await gitPrivateKey?.writeKey();
}
exports.writePrivateKey = writePrivateKey;
async function configSigningKey(cwd) {
    await gitPrivateKey?.configSigningKey(cwd);
}
exports.configSigningKey = configSigningKey;
//# sourceMappingURL=private-key.js.map