"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDependencyUrlWithNewHash = exports.getVersionFromUrl = exports.isGitlabUrl = exports.getDependencyTags = void 0;
const child_process_1 = require("child_process");
const simple_git_1 = require("simple-git");
const GitUrlParse = require("git-url-parse");
const npm = require.resolve('npm');
const GITLAB_HOST = 'git.qapint.com';
function getDependencyTags(packageUrl, name) {
    return __awaiter(this, void 0, void 0, function* () {
        return isGitlabUrl(packageUrl) ? getGitTags(packageUrl) : getNpmTags(name);
    });
}
exports.getDependencyTags = getDependencyTags;
function getGitTags(gitUrl) {
    return __awaiter(this, void 0, void 0, function* () {
        const gitUrlObj = GitUrlParse(gitUrl);
        const protocol = gitUrlObj.protocol === 'ssh' ? 'ssh' : 'https';
        const remoteUrl = GitUrlParse.stringify(gitUrlObj, protocol);
        const tags = yield simple_git_1.default().listRemote(['--refs', remoteUrl, '*tags*']);
        return tags.trim()
            .split('\n')
            .map(tag => tag.replace(/.*tags\//, ''))
            .filter(tag => tag);
    });
}
function getNpmTags(packageName) {
    return new Promise((resolve, reject) => {
        const spawnedNpm = child_process_1.fork(npm, ['view', packageName, 'versions', '--json'], { silent: true });
        spawnedNpm.stdout.on('data', (data) => resolve(JSON.parse(data)));
        spawnedNpm.stderr.on('error', (error) => reject(error));
    });
}
function isGitlabUrl(packageUrl) {
    return packageUrl.includes(GITLAB_HOST);
}
exports.isGitlabUrl = isGitlabUrl;
function getVersionFromUrl(url) {
    const [packageUrl, hash] = url.split('#');
    const tag = packageUrl === null || packageUrl === void 0 ? void 0 : packageUrl.replace(/[\^~]/, '');
    return isGitlabUrl(url) ? hash : tag;
}
exports.getVersionFromUrl = getVersionFromUrl;
function getDependencyUrlWithNewHash(url, version) {
    const [packageUrl] = url.split('#');
    return isGitlabUrl(url) ? `${packageUrl}#${version}` : version;
}
exports.getDependencyUrlWithNewHash = getDependencyUrlWithNewHash;
//# sourceMappingURL=utils.js.map