"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTag = exports.isDirty = exports.getCommitInfo = exports.getRemoteURL = exports.getDefaultBranchName = exports.getBranchName = exports.isRepository = exports.GITLAB_REF_FLAG = void 0;
const child_process_1 = require("child_process");
const createDebugger_1 = __importDefault(require("./createDebugger"));
const debugLogger = (0, createDebugger_1.default)('git');
exports.GITLAB_REF_FLAG = 'CI_COMMIT_REF_NAME';
const isRepository = (dir = process.cwd()) => {
    try {
        debugLogger('Checking if directory is a Git repository:', dir);
        (0, child_process_1.execSync)('git rev-parse --is-inside-work-tree', {
            cwd: dir,
            stdio: 'ignore'
        });
        debugLogger('Directory is a Git repository');
        return true;
    }
    catch (e) {
        if (e instanceof Error)
            debugLogger('Error while checking if directory is a Git repository:', {
                message: e.message,
                stack: e.stack
            });
        return false;
    }
};
exports.isRepository = isRepository;
const getBranchName = (dir = process.cwd()) => {
    const gitLabBranchName = process.env[exports.GITLAB_REF_FLAG];
    if (gitLabBranchName) {
        debugLogger(`Found current branch name by GitLab CI flag ${exports.GITLAB_REF_FLAG}: ${gitLabBranchName}`);
        return gitLabBranchName;
    }
    try {
        debugLogger('Getting current branch name for directory:', dir);
        const branchName = (0, child_process_1.execSync)('git rev-parse --abbrev-ref HEAD', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        })
            .toString()
            .trim();
        if (!branchName) {
            throw new Error('No output from the git command');
        }
        debugLogger('Current branch name:', branchName);
        return branchName;
    }
    catch (e) {
        debugLogger('Error while getting current branch name:', e);
        return null;
    }
};
exports.getBranchName = getBranchName;
const getDefaultBranchName = (dir = process.cwd()) => {
    try {
        debugLogger('Getting default branch name for directory:', dir);
        const stdout = (0, child_process_1.execSync)('git symbolic-ref --short refs/remotes/origin/HEAD', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        }).toString();
        if (!stdout) {
            throw new Error('No output from the git command');
        }
        const remoteOutput = parseDefaultFromShowRemoteOutput(stdout);
        debugLogger('Default branch name:', remoteOutput);
        return remoteOutput;
    }
    catch (e) {
        debugLogger('Error while getting default branch name:', e);
        return getDefaultBranchNameByRemote(dir);
    }
};
exports.getDefaultBranchName = getDefaultBranchName;
const getDefaultBranchNameByRemote = (dir = process.cwd()) => {
    debugLogger('Getting default branch with `git remote show origin`');
    try {
        const stdout = (0, child_process_1.execSync)('git remote show origin', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        }).toString();
        if (!stdout) {
            throw new Error('No output from the git command');
        }
        return parseDefaultFromRemoteShowOriginOutput(stdout);
    }
    catch (e) {
        debugLogger('Error getting default branch by `git remote show origin`:', e);
        return null;
    }
};
const parseDefaultFromRemoteShowOriginOutput = (output) => {
    const match = output.match(/HEAD branch: (.*)/);
    return match ? match[1] : null;
};
const parseDefaultFromShowRemoteOutput = (output) => {
    const match = output.match(/origin\/(.+)/);
    return match ? match[1] : null;
};
const getRemoteURL = (dir = process.cwd()) => {
    try {
        debugLogger('Getting remote URL for directory:', dir);
        const remoteUrl = (0, child_process_1.execSync)('git config --get remote.origin.url', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        })
            .toString()
            .trim();
        if (!remoteUrl) {
            throw new Error('No output from the git command');
        }
        debugLogger('Remote URL:', remoteUrl);
        return remoteUrl;
    }
    catch (e) {
        debugLogger('Error while getting remote URL:', e);
        return null;
    }
};
exports.getRemoteURL = getRemoteURL;
const getCommitInfo = (dir = process.cwd()) => {
    try {
        debugLogger('Getting most recent commit info for directory:', dir);
        const stdout = (0, child_process_1.execSync)('git show --no-patch --format="%s%n%H%n%an%n%ae"', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        })
            .toString()
            .trim();
        if (!stdout) {
            throw new Error('No output from the git command');
        }
        const [message, hash, author, email] = stdout.split('\n');
        debugLogger('Most recent commit info:', {
            message,
            hash,
            author,
            email
        });
        return { message, hash, author, email };
    }
    catch (e) {
        debugLogger('Error while getting most recent commit info:', e);
        return null;
    }
};
exports.getCommitInfo = getCommitInfo;
const isDirty = (dir = process.cwd()) => {
    try {
        debugLogger('Checking if repository contains unstaged changes for directory:', dir);
        const stdout = (0, child_process_1.execSync)('git status --short', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        });
        if (!stdout) {
            throw new Error('No output from the git command');
        }
        debugLogger('Repository contains unstaged changes:', stdout.length > 0);
        return stdout.length > 0;
    }
    catch (e) {
        debugLogger('Error while checking if repository contains unstaged changes:', e);
        return false;
    }
};
exports.isDirty = isDirty;
const getTag = (dir = process.cwd()) => {
    try {
        debugLogger('Getting tag name for directory:', dir);
        const tag = (0, child_process_1.execSync)('git describe --tags --exact', {
            cwd: dir,
            stdio: ['ignore', 'pipe', 'ignore']
        })
            .toString()
            .trim();
        if (!tag) {
            throw new Error('No output from the git command');
        }
        debugLogger('Current tag name:', tag);
        return tag;
    }
    catch (e) {
        debugLogger('Error while getting tag name:', e);
        return null;
    }
};
exports.getTag = getTag;
//# sourceMappingURL=git.js.map