"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseGit = void 0;
//#region imports
const lib_1 = require("tnp-core/lib");
const lib_2 = require("tnp-core/lib");
const lib_3 = require("tnp-core/lib");
const lib_4 = require("tnp-core/lib");
const index_1 = require("../../index");
const constants_1 = require("../constants");
const translate_1 = require("../translate");
const base_feature_for_project_1 = require("./base-feature-for-project");
//#endregion
class BaseGit extends base_feature_for_project_1.BaseFeatureForProject {
    //#region methods & getters / unstage all files
    unstageAllFiles() {
        //#region @backendFunc
        index_1.HelpersTaon.git.unstageAllFiles(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / revert file changes
    revertFileChanges(fileReletivePath) {
        //#region @backendFunc
        index_1.HelpersTaon.git.revertFileChanges(this.project.location, fileReletivePath);
        //#endregion
    }
    //#endregion
    //#region methods & getters / clone
    async clone(url, destinationFolderName = '', branchName) {
        //#region @backendFunc
        const clondeFolderpath = await index_1.HelpersTaon.git.clone({
            cwd: this.project.location,
            url,
            destinationFolderName,
        });
        if (branchName) {
            try {
                index_1.HelpersTaon.git.checkout(clondeFolderpath, branchName);
                await index_1.HelpersTaon.git.pullCurrentBranch(clondeFolderpath, {
                    askToRetry: true,
                });
            }
            catch (error) { }
        }
        return (0, lib_3.crossPlatformPath)([
            clondeFolderpath,
            destinationFolderName || '',
        ]).replace(/\/$/g, '');
        //#endregion
    }
    //#endregion
    //#region methods & getters / restore last version
    restoreLastVersion(relativeFilePath) {
        //#region @backendFunc
        index_1.HelpersTaon.git.restoreLastVersion(this.project.location, relativeFilePath);
        //#endregion
    }
    //#endregion
    //#region methods & getters / stage all files
    stageAllFiles() {
        //#region @backendFunc
        index_1.HelpersTaon.git.stageAllFiles(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / stage all files
    stageFile(relativeFilePath) {
        //#region @backendFunc
        index_1.HelpersTaon.git.stageFile(this.project.location, relativeFilePath);
        //#endregion
    }
    //#endregion
    //#region methods & getters / stash
    stash(options) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.stash(this.project.location, options);
        //#endregion
    }
    //#endregion
    //#region methods & getters / stash
    rebase(toBranch) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.rebase(this.project.location, toBranch);
        //#endregion
    }
    //#endregion
    //#region methods & getters / stash apply
    stashApply() {
        //#region @backendFunc
        index_1.HelpersTaon.git.stashApply(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / fetch
    fetch(all = false) {
        //#region @backendFunc
        index_1.HelpersTaon.git.fetch(this.project.location, all);
        //#endregion
    }
    //#endregion
    //#region methods & getters / reset files
    resetFiles(...relativePathes) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.resetFiles(this.project.location, ...relativePathes);
        //#endregion
    }
    //#endregion
    //#region methods & getters / is inside git repo
    get isInsideGitRepo() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.isInsideGitRepo(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / is without git repository
    get isWithoutGitRepository() {
        //#region @backendFunc
        return !lib_2.fse.existsSync(lib_3.path.join(this.project.location, '.git'));
        //#endregion
    }
    //#endregion
    //#region methods & getters / is git root
    get isGitRoot() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.isGitRoot(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / origin url
    get originURL() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getOriginURL(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / commit
    commit(commitMessage) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.commit(this.project.location, commitMessage);
        //#endregion
    }
    //#endregion
    //#region methods & getters / add and commit
    /**
     * alias to stage all and commit
     */
    addAndCommit(commitMessage) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.stageAllAndCommit(this.project.location, commitMessage);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get default develop Branch
    /**
     * general default development branch for all kinds of projects
     */
    getDefaultDevelopmentBranch() {
        return 'develop';
    }
    //#endregion
    //#region methods & getters / is using action commit
    isUsingActionCommit() {
        return false;
    }
    //#endregion
    jiraIssuesAreOutsideBrackets() {
        return false;
    }
    async getUserInfo(global = false) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.getUserInfo(this.project.location, global);
        //#endregion
    }
    async setUserInfo({ name, email }, global = false) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.setUserInfos({
            cwd: this.project.location,
            name,
            email,
            global,
        });
        //#endregion
    }
    //#region methods & getters / stage all and commit
    stageAllAndCommit(commitMessage) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.stageAllAndCommit(this.project.location, commitMessage);
        //#endregion
    }
    //#endregion
    //#region methods & getters / push current branch
    async pushCurrentBranch(options) {
        //#region @backendFunc
        const res = await index_1.HelpersTaon.git.pushCurrentBranch(this.project.location, options);
        lib_4.GlobalTaskManager.addProgress(constants_1.PUSH_ACTION_NAME);
        return res;
        //#endregion
    }
    //#endregion
    //#region methods & getters / all origins
    get allOrigins() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.allOrigins(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / uncommited files
    get uncommitedFiles() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.uncommitedFiles(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / there are some uncommited change
    get thereAreSomeUncommitedChange() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.checkIfthereAreSomeUncommitedChange(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / there are some uncommited change except
    thereAreSomeUncommitedChangeExcept(filesList = []) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.thereAreSomeUncommitedChangeExcept(filesList, this.project.location);
        //#endregion
    }
    //#endregion
    /**
     * Resolve last changes
     * - uncommited changes
     * - action commits to melt
     */
    async resolveLastChanges(options) {
        //#region @backendFunc
        options = options || {};
        const displayLastCommitInfo = () => {
            lib_1.Helpers.info(`
        Project: ${this.project.genericName}
        ${lib_2.chalk.gray(`Last commit hash: ${this.project.git.lastCommitHash()}`)}
        ${lib_2.chalk.gray(`Last commit date: ${(0, lib_2.dateformat)(this.project.git.lastCommitDate(), 'dd-mm-yyyy HH:MM:ss')}`)}
        ${lib_2.chalk.gray(`Last commit message: "${this.project.git.lastCommitMessage()}"`)}
      `);
        };
        const getUncommitedFiles = () => {
            return lib_2.Utils.uniqArray([
                ...this.uncommitedFiles,
                ...this.stagedFilesRelativePaths,
            ]);
        };
        let hadMeltedActionCommits = false;
        while (true) {
            let uncommitedFiles = getUncommitedFiles();
            let hasUncommitedChanges = uncommitedFiles.length > 0;
            let lastCommitName = this.lastCommitMessage();
            const hasActionCommitsToMelt = this.hasActionCommitsToMelt;
            if (!hasUncommitedChanges && !hasActionCommitsToMelt) {
                break;
            }
            displayLastCommitInfo();
            if (hasActionCommitsToMelt) {
                hadMeltedActionCommits = true;
                lib_1.Helpers.info(`LAST COMMIT MESSAGE SUGGEST TEMPORARY CHANGES`);
                // if (!options.tryAutomaticActionFirst) {
                await lib_3.UtilsTerminal.pressAnyKeyToContinueAsync({
                    message: `Melting last changes.. press any key to continue`,
                });
                // }
                this.project.git.meltActionCommits();
                lastCommitName = this.lastCommitMessage();
                uncommitedFiles = getUncommitedFiles();
                hasUncommitedChanges = uncommitedFiles.length > 0;
            }
            if (hasUncommitedChanges) {
                const reason = 'THERE ARE SOME UNCOMMITED CHANGES';
                const data = `
${uncommitedFiles
                    .map(c => `${options.projectNameAsOutputPrefix ? ` ${options.projectNameAsOutputPrefix}/` : ''}${c}`)
                    .join('\n')}`;
                lib_1.Helpers.info(`
Please provide proper commit message for lastest changes in your project:

          ${this.project.genericName}

        ${lib_2.chalk.yellow(reason)}
        ${data}

        `);
                //#region handle select options
                const optionsSelect = {
                    openInVscode: {
                        name: 'Open in vscode',
                    },
                    // autoCommit: {
                    //   name: 'Inteligently auto commit all changes',
                    // },
                    addToLastCommitAndPush: {
                        name: `Add to last commit ("${lastCommitName}") and ${hadMeltedActionCommits ? 'force ' : ''}push`,
                    },
                    commitAsChoreUpdateAndPushNormal: {
                        name: `Commit as "chore: update" and normal push`,
                    },
                    commitAsChoreUpdateAndPushForce: {
                        name: `Commit as "chore: update" and force push`,
                    },
                    discard: {
                        name: `Discard all changes`,
                    },
                    discardAndPushNormal: {
                        name: `Discard all changes and normal push`,
                    },
                    discardAndPushForce: {
                        name: `Discard all changes and force push`,
                    },
                    push: {
                        name: `Just ${hadMeltedActionCommits ? 'force ' : ''}push changes...`,
                    },
                    // commitAsAndPush: {
                    //   name: `Commit as < you will choose commit message > and ${hadMeltedActionCommits ? 'force ' : ''}push`,
                    // },
                    skip: {
                        name: 'Skip resolving last changes for this project',
                    },
                    exit: {
                        name: 'Exit',
                    },
                };
                const selected = await lib_3.UtilsTerminal.select({
                    choices: optionsSelect,
                    question: `${options.questionPrefixMessage ? `[${options.questionPrefixMessage}] ` : ''}What to do with uncommited changes ?`,
                    // autocomplete: true,
                });
                //#endregion
                //#region handle actions
                if (selected === 'openInVscode') {
                    await this.project.openInEditor();
                    await lib_3.UtilsTerminal.pressAnyKeyToContinueAsync({
                        message: `Press any key to continue when you done`,
                    });
                }
                // if (selected === 'autoCommit') {
                //   await automaticAction();
                // }
                if (selected === 'skip') {
                    return;
                }
                if (selected === 'discardAndPushNormal' ||
                    selected === 'discardAndPushForce') {
                    try {
                        this.project.git.resetHard({ HEAD: 0 });
                    }
                    catch (error) { }
                    await this.project.git.pushCurrentBranch({
                        askToRetry: true,
                        force: selected === 'discardAndPushForce',
                    });
                    return;
                }
                if (selected === 'discard') {
                    try {
                        this.project.git.resetHard({ HEAD: 0 });
                    }
                    catch (error) { }
                    return;
                }
                if (selected === 'exit') {
                    process.exit(0);
                }
                if (selected === 'commitAsChoreUpdateAndPushNormal') {
                    this.project.git.stageAllFiles();
                    this.project.git.commit('chore: update');
                    await this.project.git.pushCurrentBranch({
                        askToRetry: true,
                        force: false,
                    });
                    return;
                }
                if (selected === 'commitAsChoreUpdateAndPushForce') {
                    this.project.git.stageAllFiles();
                    this.project.git.commit('chore: update');
                    await this.project.git.pushCurrentBranch({
                        askToRetry: true,
                        force: true,
                    });
                    return;
                }
                if (selected === 'push') {
                    await this.project.git.pushCurrentBranch({
                        askToRetry: true,
                        force: hadMeltedActionCommits,
                    });
                    return;
                }
                // if (selected === 'commitAsAndPush') {
                //   const input = await UtilsTerminal.input({
                //     question: `Commit message`,
                //     defaultValue: lastCommitName,
                //   });
                //   this.project.git.stageAllFiles();
                //   this.project.git.commit(input);
                //   await this.project.git.pushCurrentBranch({
                //     askToRetry: true,
                //     force: hadMeltedActionCommits,
                //   });
                //   return;
                // }
                if (selected == 'addToLastCommitAndPush') {
                    this.project.git.resetSoftHEAD(1);
                    this.project.git.stageAllFiles();
                    this.project.git.commit(lastCommitName);
                    await this.project.git.pushCurrentBranch({
                        askToRetry: true,
                        force: hadMeltedActionCommits,
                    });
                    return;
                }
                //#endregion
            }
        }
        //#endregion
    }
    //#region methods & getters / has action commits to melt
    get hasActionCommitsToMelt() {
        //#region @backendFunc
        const lastCommitMessage = this.lastCommitMessage() || '';
        return (lastCommitMessage.trim() ===
            index_1.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT());
        //#endregion
    }
    //#endregion
    //#region methods & getters / melt action commits
    /**
     * @returns number of melted commits
     */
    meltActionCommits() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.meltActionCommits(this.project.location);
        //#endregion
    }
    //#endregion
    //#region push to git repo
    /**
     *
     * @param newVersion
     * @param pushWithoutAsking
     */
    async tagAndPushToGitRepo(newVersion, autoReleaseUsingConfig, isCiProcess) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.tagAndPushToGitRepo(this.project.location, {
            newVersion,
            skipAskingQuestionBeforePush: autoReleaseUsingConfig,
            isCiProcess,
        });
        //#endregion
    }
    //#endregion
    //#region methods & getters / pull current branch
    async pullCurrentBranch(options) {
        //#region @backendFunc
        await index_1.HelpersTaon.git.pullCurrentBranch(this.project.location, {
            ...options,
        });
        lib_4.GlobalTaskManager.addProgress(constants_1.PULL_ACTION_NAME);
        //#endregion
    }
    //#endregion
    //#region methods & getters / current branch name
    get currentBranchName() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.currentBranchName(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / list of current git changes
    get listOfCurrentGitChanges() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getListOfCurrentGitChanges(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get branches names by
    getBranchesNamesBy(pattern) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getBranchesNames(this.project.location, pattern);
        //#endregion
    }
    //#endregion
    //#region methods & getters / reset soft HEAD
    resetSoftHEAD(HEAD = 1) {
        //#region @backendFunc
        index_1.HelpersTaon.git.resetSoftHEAD(this.project.location, HEAD);
        //#endregion
    }
    //#endregion
    //#region methods & getters / reset hard
    resetHard(options) {
        //#region @backendFunc
        index_1.HelpersTaon.git.resetHard(this.project.location, options);
        //#endregion
    }
    //#endregion
    //#region methods & getters / count commits
    countCommits() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.countCommits(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / has any commits
    hasAnyCommits() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.hasAnyCommits(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / is in merge process
    get isInMergeProcess() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.isInMergeProcess(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last commit date
    lastCommitDate() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastCommitDate(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last commit hash
    lastCommitHash() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastCommitHash(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last commit message
    lastCommitMessage() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastCommitMessage(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last commit message
    async penultimateCommitMessage() {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.penultimateCommitMessage(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get commit message by index
    async getCommitMessageByIndex(index) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.getCommitMessageByIndex(this.project.location, index);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get commit message by hash
    async getCommitMessageByHash(hash) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.getCommitMessageByHash(this.project.location, hash);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get commit hash by index
    async getCommitHashByIndex(index) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.getCommitHashByIndex(this.project.location, index);
        //#endregion
    }
    //#endregion
    //#region methods & getters / penultimate commit hash
    penultimateCommitHash() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.penultimateCommitHash(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / check tag exists
    checkTagExists(tag) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.checkTagExists(tag, this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / checkout
    checkout(branchName, options) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.checkout(this.project.location, branchName, options);
        //#endregion
    }
    //#endregion
    allowedGitEmailDomains() {
        return [];
    }
    skipLintOnPush() {
        return true;
    }
    cleanRepoFromAnyFilesExceptDotGitFolder() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.cleanRepoFromAnyFilesExceptDotGitFolder(this.project.location);
        //#endregion
    }
    //#region methods & getters / checkout from to
    checkoutFromTo(checkoutFromBranch, branch, origin = 'origin') {
        //#region @backendFunc
        return index_1.HelpersTaon.git.checkoutFromTo(checkoutFromBranch, branch, origin, this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last tag name for major version
    /**
     *
     * @param majorVersion example: v1, v2 etc.
     * @returns tag name
     */
    lastTagNameForMajorVersion(majorVersion) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastTagNameForMajorVersion(this.project.location, majorVersion);
        //#endregion
    }
    //#endregion
    //#region methods & getters / last tag hash
    lastTagHash() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastTagHash(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / remote origin url
    get remoteOriginUrl() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getOriginURL(this.project.location);
        //#endregion
    }
    //#endregion
    //#region methods & getters / remote origin url
    /**
     * get provider of remote origin
     */
    get remoteProvider() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getRemoteProvider(this.project.location) || '';
        //#endregion
    }
    //#endregion
    //#region methods & getters / last tag version name
    get lastTagVersionName() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.lastTagVersionName(this.project.location) || '';
        //#endregion
    }
    //#endregion
    //#region methods & getters / staged files
    get stagedFiles() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.stagedFiles(this.project.location);
        //#endregion
    }
    get stagedFilesRelativePaths() {
        //#region @backendFunc
        return index_1.HelpersTaon.git.stagedFiles(this.project.location, true);
        //#endregion
    }
    //#endregion
    //#region methods & getters / rename origin
    /**
     * TODO does this make any sense
     */
    renameOrigin(newNameOrUlr) {
        //#region @backendFunc
        if (!newNameOrUlr.endsWith('.git')) {
            newNameOrUlr = newNameOrUlr + '.git';
        }
        const oldOrigin = this.project.git.originURL;
        if (!newNameOrUlr.startsWith('git@') &&
            !newNameOrUlr.startsWith('https://')) {
            newNameOrUlr = oldOrigin.replace(lib_3.path.basename(oldOrigin), newNameOrUlr);
        }
        try {
            this.project.run(`git remote rm origin`).sync();
        }
        catch (error) { }
        try {
            this.project.run(`git remote add origin ${newNameOrUlr}`).sync();
            lib_1.Helpers.info(`Origin changed:
    from: ${oldOrigin}
      to: ${newNameOrUlr}\n`);
        }
        catch (e) {
            lib_1.Helpers.error(`Not able to change origin.. reverting to old`, true, true);
            this.project.run(`git remote add origin ${oldOrigin}`).sync();
        }
        //#endregion
    }
    //#endregion
    //#region getters & methods / translate git commit from args
    /**
     * By default no translation of commit
     */
    transalteGitCommitFromArgs() {
        return { from: void 0, to: void 0 };
    }
    //#endregion
    //#region getters & methods / us git branches when commiting and pushing
    /**
     * By defult true.. when commit branches will not function.
     * (false is better for simple projects)
     */
    useGitBranchesWhenCommitingAndPushing() {
        return true;
    }
    //#endregion
    //#region getters & methods / automatically add all changes when pushing to git
    /**
     * usefull when pushing in project with childrens as git repos
     */
    automaticallyAddAllChangesWhenPushingToGit() {
        return false;
    }
    //#endregion
    //#region getters & methods / use git branches as metadata for commits
    /**
     * usefull when pushing in project with childrens as git repos
     */
    useGitBranchesAsMetadataForCommits() {
        return true;
    }
    //#endregion
    //#region getters & methods / clone to
    /**
     * @returns true if clone was successful
     */
    async cloneTo(cwd, newProjectName) {
        //#region @backendFunc
        if (!newProjectName) {
            newProjectName = lib_3.path.basename(this.project.location);
        }
        const dest = (0, lib_3.crossPlatformPath)([newProjectName, newProjectName]);
        if (lib_2.fse.existsSync(dest)) {
            const res = await lib_1.Helpers.questionYesNo(`Folder ${newProjectName} alredy exist, delete it ?`);
            if (res) {
                lib_1.Helpers.tryRemoveDir(dest);
            }
            else {
                index_1.HelpersTaon.pressKeyAndContinue('Operation not completed... press any key');
                return false;
            }
        }
        lib_1.Helpers.info(`Cloning ${this.project.name}...`);
        // copy instead cloning
        await index_1.HelpersTaon.git.clone({
            cwd,
            url: this.project.git.remoteOriginUrl,
            destinationFolderName: newProjectName,
        });
        lib_1.Helpers.info(`Clone success`);
        return true;
        //#endregion
    }
    //#endregion
    //#region getters & methods / get children
    /**
     * This is only for push/pull process
     *
     * There are 2 types of projects:
     * - with linked-projects.json
     * - with children from external folder
     *
     * projects that are children of this project (with its own git repo)
     */
    get gitChildren() {
        let childrenRepos = [];
        if (this.project.linkedProjects.linkedProjects.length > 0) {
            childrenRepos = this.project.linkedProjects.linkedProjects
                .map(c => {
                return this.project.ins.From([
                    this.project.location,
                    c.relativeClonePath,
                ]);
            })
                .filter(f => !!f);
        }
        else {
            childrenRepos = this.project.children;
        }
        childrenRepos = childrenRepos.filter(f => f.git.isInsideGitRepo && f.git.isGitRoot);
        return childrenRepos;
    }
    //#endregion
    //#region getters & methods / set remote origin type
    async setRemoteOriginType(setOrigin) {
        //#region @backendFunc
        if (setOrigin === 'https') {
            setOrigin = 'http';
        }
        if (setOrigin === 'ssh') {
            await index_1.HelpersTaon.git.changeRemoteFromHttpsToSSh(this.project.location);
        }
        else if (setOrigin === 'http') {
            await index_1.HelpersTaon.git.changeRemoveFromSshToHttps(this.project.location);
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters / push process
    async pullProcess(options = {}) {
        //#region @backendFunc
        options = options || {};
        options.skipCloneGitChildren = !!options.skipCloneGitChildren;
        let { skipCloneGitChildren, setOrigin } = options;
        await this._beforePullProcessAction(setOrigin, skipCloneGitChildren);
        await this.setRemoteOriginType(setOrigin);
        let uncommitedChanges = this.project.git.thereAreSomeUncommitedChange;
        if (uncommitedChanges) {
            lib_1.Helpers.warn(`Stashing uncommit changes... in ${this.project.genericName}`);
            try {
                this.project.git.stageAllFiles();
            }
            catch (error) { }
            try {
                this.project.git.stash();
            }
            catch (error) { }
        }
        await this.project.git.pullCurrentBranch({ askToRetry: true });
        await this._afterPullProcessAction(setOrigin, skipCloneGitChildren);
        const location = this.project.location;
        this.project.ins.unload(this);
        this.project.ins.add(this.project.ins.From(location));
        await this.project.linkedProjects.saveLocationToDB();
        if (this.automaticallyAddAllChangesWhenPushingToGit()) {
            for (const child of this.gitChildren) {
                await child.git.pullProcess(options);
            }
        }
        await this.project.linkedProjects.saveAllLinkedProjectsToDB();
        //#endregion
    }
    //#endregion
    async validateEmailDomain(allowedEmailsEnds) {
        //#region @backendFunc
        if (allowedEmailsEnds.length === 0) {
            return;
        }
        while (true) {
            let gitConfig = null;
            try {
                gitConfig = await this.project.git.getUserInfo();
            }
            catch (error) { }
            const errorsMgs = {
                notUsingEmail: `You are not using any email(s) address(es) for git operations.`,
                notUsingName: `You are not using name for git operations`,
                notUsingEmailAndName: `You are not using any email(s) address(es) for git operations.`,
                notUsingAllowedEmails: `You are not using allowed ${allowedEmailsEnds.join(',')} email domains.`,
            };
            const errors = {
                notUsingEmail: !gitConfig?.email ? errorsMgs.notUsingEmail : null,
                notUsingName: !gitConfig?.name ? errorsMgs.notUsingName : null,
                notUsingAllowedEmails: !allowedEmailsEnds.some(allowedEmailEnd => gitConfig?.email?.endsWith(allowedEmailEnd))
                    ? errorsMgs.notUsingAllowedEmails
                    : null,
            };
            if (allowedEmailsEnds.length === 0) {
                delete errors.notUsingAllowedEmails;
            }
            if (!Object.values(errors).some(e => e)) {
                return;
            }
            Object.values(errors)
                .filter(e => e)
                .forEach(e => {
                lib_1.Helpers.warn(e);
            });
            lib_1.Helpers.warn(`
        Please provide proper email and name for git operations.

        `);
            const options = {
                changeLocalEmailAndName: {
                    name: 'Change local .git/config email and name',
                },
                useItAnyway: {
                    name: 'Use it anyway',
                },
                exitProcess: {
                    name: 'Exit process',
                },
            };
            if (!gitConfig?.email || !gitConfig?.name) {
                delete options.useItAnyway;
            }
            const selected = await lib_3.UtilsTerminal.select({
                question: 'Select action',
                choices: options,
            });
            if (selected === 'changeLocalEmailAndName') {
                const email = await lib_3.UtilsTerminal.input({
                    question: 'Enter git email',
                });
                const name = await lib_3.UtilsTerminal.input({
                    question: 'Enter your git name and surname (or just name)',
                });
                await this.project.git.setUserInfo({ email, name });
            }
            if (selected === 'exitProcess') {
                process.exit(0);
            }
        }
        //#endregion
    }
    async _afterPullProcessAction(setOrigin, skipCloneGitChildren = false) {
        if (!skipCloneGitChildren) {
            await this.project.linkedProjects.cloneNonexistedLinkedProjects(setOrigin);
        }
    }
    async backupBranch(branchName) {
        //#region @backendFunc
        return await index_1.HelpersTaon.git.backupBranch(this.project.location, branchName);
        //#endregion
    }
    //#region methods & getters / push process
    async pushProcess(options = {}) {
        //#region @backendFunc
        let { force = false, typeofCommit, skipLint, forcePushNoQuestion, origin = 'origin', exitCallBack, askToConfirmPush, askToConfirmCommit, askToConfirmBranchChange, args = [], commitMessageRequired, overrideCommitMessage, skipChildren, setOrigin, currentOrigin, mergeUpdateCommits, } = options;
        await this._beforePushProcessAction(setOrigin);
        await this.setRemoteOriginType(setOrigin);
        await this.project.linkedProjects.saveLocationToDB();
        const commitData = await this._getCommitMessage(typeofCommit, args, commitMessageRequired, currentOrigin);
        if (mergeUpdateCommits && this.project.git.stagedFiles.length > 0) {
            //#region merge update commits
            lib_1.Helpers.logInfo(`Pushing detailed changes to project: ${this.project.genericName}`);
            lib_1.Helpers.logInfo(`Modified files... `);
            lib_1.Helpers.logInfo([...this.project.git.stagedFiles]
                .map(f => ` - ${lib_2.chalk.underline(f)}`)
                .join('\n'));
            while (true) {
                const mergeAction = {
                    useUpdateCommit: {
                        name: `Use temporary update commit ` +
                            `"${index_1.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT()}" and force push`,
                    },
                    provideCommitMessage: {
                        name: 'Provide commit message and force push',
                    },
                    resetRemoveChanges: {
                        name: 'Reset/remove changes and force push',
                    },
                    openInVscode: {
                        name: 'Open project in vscode',
                    },
                };
                const action = force
                    ? 'useUpdateCommit'
                    : await lib_3.UtilsTerminal.select({
                        choices: mergeAction,
                        question: 'What to do ?',
                    });
                if (action === 'openInVscode') {
                    await this.project.openInEditor();
                    continue;
                }
                if (action === 'resetRemoveChanges') {
                    force = true;
                    forcePushNoQuestion = true;
                    this.project.git.resetHard();
                    break;
                }
                if (action === 'useUpdateCommit') {
                    force = true;
                    forcePushNoQuestion = true;
                    overrideCommitMessage =
                        index_1.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT();
                }
                if (action === 'provideCommitMessage') {
                    force = true;
                    forcePushNoQuestion = true;
                    try {
                        overrideCommitMessage = await lib_3.UtilsTerminal.input({
                            question: `Please provide commit message for current changes:`,
                            defaultValue: 'update',
                        });
                    }
                    catch (error) { }
                }
                if (overrideCommitMessage) {
                    break;
                }
                //#endregion
            }
        }
        // #region warning about missing sub-issue
        if (commitData.typeOfCommit === 'feature' &&
            commitData.jiraNumbers?.length === 1 &&
            commitData.issuesFromOtherProjects?.length === 0) {
            lib_1.Helpers.info(`

        You current feature branch "${this.project.git.currentBranchName}"
        doesn't have ${lib_2.chalk.bold('main-issue')} and ${lib_2.chalk.bold('sub-issue')} inlcueded.

        Proper example: feature/JIRANUM-<number-of-sub-issue>-JIRANUM-<number-of-main-issue>-commit-name

          `);
            if (!(await lib_1.Helpers.questionYesNo('Continue without sub-issue?'))) {
                process.exit(0);
            }
        }
        //#endregion
        //#region automatic push to git
        if (!this.automaticallyAddAllChangesWhenPushingToGit()) {
            if (commitData.commitMessage
                ?.split(':')
                .map(p => p.trim())
                .every(p => p === this.project.git.currentBranchName)) {
                // QUICK_FIX
                lib_1.Helpers.error(`

        Please provide more specific commit message than branch name
        or maybe you forgot ?
        - TEAM ID? (example TEAM2# <= hash at the end)
        - JIRA ISSUE? (example JIRA-1234)

        `, false, true);
            }
        }
        //#endregion
        //#region lint
        if (this.skipLintOnPush()) {
            skipLint = true;
        }
        if (commitData.typeOfCommit === 'release') {
            skipLint = true;
        }
        // console.log({ skipLint, typeofCommit });
        const numberOfStagedFiles = this.project.git.stagedFiles.length;
        if (numberOfStagedFiles === 0) {
            lib_1.Helpers.warn(`No staged files...`);
            skipLint = true;
        }
        if (!skipLint) {
            while (true) {
                try {
                    await this.project.lint(options);
                    break;
                }
                catch (error) {
                    lib_1.Helpers.warn('Fix your code...');
                    if (!(await index_1.HelpersTaon.consoleGui.question.yesNo('Try again lint before commit ?'))) {
                        break;
                    }
                }
            }
        }
        //#endregion
        if (this.project.useFeatureInBranchNameForTests() &&
            commitData.typeOfCommit === 'test') {
            commitData.useFeatureBranchForTestBranch = true;
        }
        if (!commitData.isActionCommit) {
            const commitMessageFromBranch = (await index_1.CommitData.getFromBranch(commitData.branchName, {
                currentOrigin,
                jiraIssuesAreOutsideBrackets: this.project.git.jiraIssuesAreOutsideBrackets(),
            })).commitMessage;
            lib_1.Helpers.info(`

      PROJECT: ${this.project.genericName}

      Current commit:
      - message to include {${overrideCommitMessage ? overrideCommitMessage : commitData.commitMessage}}
      ${this.useGitBranchesAsMetadataForCommits() && !overrideCommitMessage
                ? `- branch to checkout {${commitData.branchName}}`
                : `- using ${lib_2.chalk.bold('current')} branch {${this.project.git.currentBranchName}} \n` +
                    `(generated branches from metadata not allowed for this project) \n
          `}`);
            if (!overrideCommitMessage &&
                commitMessageFromBranch !== commitData.commitMessage) {
                lib_1.Helpers.logWarn(`Commit from args and commit from branch are different
        commit message from args: ${commitData.commitMessage}
        commit message from branch: ${commitMessageFromBranch}

        ADVICE: Is is better to use words instead characters to describe multiple
        commit changes in one commit message

        `);
            }
            else {
                lib_1.Helpers.logInfo(lib_2.chalk.gray(`Commit from args and commit from branch are the same...`));
            }
            const lastCommitMessage = this.project.git.lastCommitMessage();
            if (lastCommitMessage &&
                [commitData.commitMessage, overrideCommitMessage]
                    .filter(f => !!f)
                    .some(m => m === lastCommitMessage)) {
                if (await lib_1.Helpers.questionYesNo('Soft reset last commit with same message ?')) {
                    this.project.git.resetSoftHEAD(1);
                }
            }
            if (!(await lib_1.Helpers.questionYesNo('Commit and push this ?'))) {
                exitCallBack();
            }
        }
        if (this.automaticallyAddAllChangesWhenPushingToGit()) {
            // my project
            this.project.git.stageAllFiles();
        }
        if (this.useGitBranchesAsMetadataForCommits() && !overrideCommitMessage) {
            lib_1.Helpers.info('Checkingout branches (if needed)...');
            if (this.project.git.currentBranchName?.trim() !== commitData.branchName) {
                if (askToConfirmBranchChange) {
                    lib_1.Helpers.info(`Changing branch to: ${commitData.branchName}`);
                    if (!(await lib_1.Helpers.questionYesNo('Confirm branch change ?'))) {
                        exitCallBack();
                    }
                }
                try {
                    this.project.git.checkout(commitData.branchName, {
                        createBranchIfNotExists: true,
                    });
                }
                catch (error) {
                    lib_1.Helpers.error('Please modyfiy you commit message or delete branch,');
                }
            }
        }
        if (askToConfirmCommit) {
            lib_1.Helpers.info(`Commit message: ${overrideCommitMessage
                ? overrideCommitMessage
                : commitData.commitMessage}`);
            if (!(await lib_1.Helpers.questionYesNo('Confirm commit ?'))) {
                exitCallBack();
            }
        }
        try {
            this.project.git.commit(overrideCommitMessage
                ? overrideCommitMessage
                : commitData.commitMessage);
        }
        catch (error) {
            lib_1.Helpers.warn(`Not commiting anything... `);
        }
        if (askToConfirmPush) {
            if (!(await lib_1.Helpers.questionYesNo('Confirm push ?'))) {
                exitCallBack();
            }
        }
        await this.project.git.pushCurrentBranch({
            force,
            origin,
            forcePushNoQuestion,
            askToRetry: true,
        });
        if (this.automaticallyAddAllChangesWhenPushingToGit() && !skipChildren) {
            if (this.project.linkedProjects.getLinkedProjectsConfig().skipRecrusivePush) {
                lib_1.Helpers.warn(`Skipping recrusive (children) push for ${this.project.genericName}`);
                return;
            }
            for (const child of this.gitChildren) {
                if (mergeUpdateCommits) {
                    await child.git.meltActionCommits();
                }
                await child.git.pushProcess(options);
            }
        }
        await this.project.linkedProjects.saveAllLinkedProjectsToDB();
        //#endregion
    }
    //#endregion
    //#region methods & getters / before any action on git root
    _beforeAnyActionOnGitRoot() {
        //#region @backendFunc
        if (!this.project.git.isInsideGitRepo) {
            lib_1.Helpers.error(`Project ${lib_2.chalk.bold(this.project.name)} is not a git repository
      locaiton: ${this.project.location}`, false, true);
        }
        if (!this.project.git.isGitRoot) {
            lib_1.Helpers.error(`Project ${lib_2.chalk.bold(this.project.name)} is not a git root
      locaiton: ${this.project.location}`, false, true);
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters / before push action
    async _beforePushProcessAction(setOrigin) {
        //#region @backendFunc
        this._beforeAnyActionOnGitRoot();
        // for first projects
        if (this.project.git.isInsideGitRepo &&
            this.project.git.isGitRoot &&
            !this.project.git.currentBranchName?.trim()) {
            if (await index_1.HelpersTaon.consoleGui.question.yesNo('Repository is empty...Commit "master" branch and commit all as "first commit" ?')) {
                this.project.git.checkout('master');
                this.project.git.stageAllFiles();
                this.project.git.commit('first commit ');
            }
        }
        await this.validateEmailDomain(this.allowedGitEmailDomains());
        //#endregion
    }
    //#endregion
    //#region methods & getters / before push action
    async _beforePullProcessAction(setOrigin, skipCloneGitChildren = false) {
        //#region @backendFunc
        this._beforeAnyActionOnGitRoot();
        if (!skipCloneGitChildren) {
            await this.project.linkedProjects.cloneNonexistedLinkedProjects(setOrigin);
        }
        //#endregion
    }
    //#endregion
    //#region methods & getters / resovle commit message
    async _getCommitMessage(typeOfCommit, args, commitMessageRequired, 
    /**
     * only needed when push github
     * and I forgot to add my username before issue
     * taon pfix proper input my-repo#344
     * that should be
     * taon pfix proper input my-username/my-repo#344
     */
    currentOrigin) {
        //#region @backendFunc
        let commitData;
        if (this.useGitBranchesWhenCommitingAndPushing()) {
            let argsCommitData = await index_1.CommitData.getFromArgs(args, {
                typeOfCommit,
                currentOrigin,
                jiraIssuesAreOutsideBrackets: this.project.git.jiraIssuesAreOutsideBrackets(),
            });
            // console.log({ argsCommitData })
            if (argsCommitData.message) {
                commitData = argsCommitData;
            }
            else {
                const commitDataBranch = await index_1.CommitData.getFromBranch(this.project.git.currentBranchName, {
                    releaseWords: this.project.releaseProcess.getReleaseWords(),
                    currentOrigin,
                    jiraIssuesAreOutsideBrackets: this.project.git.jiraIssuesAreOutsideBrackets(),
                });
                commitData = commitDataBranch;
                // console.log({ commitDataBranch })
            }
        }
        else {
            let argsCommitData = await index_1.CommitData.getFromArgs(args, {
                typeOfCommit,
                currentOrigin,
                jiraIssuesAreOutsideBrackets: this.project.git.jiraIssuesAreOutsideBrackets(),
            });
            // console.log({ argsCommitData })
            // console.log(argsCommitData)
            if (!argsCommitData.message && commitMessageRequired) {
                lib_1.Helpers.error('Please provide message in argument', false, true);
            }
            if (!argsCommitData.message) {
                argsCommitData.message =
                    index_1.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT();
            }
            commitData = argsCommitData;
        }
        if (commitData.message !==
            index_1.HelpersTaon.git.getACTION_MSG_RESET_GIT_HARD_COMMIT()) {
            const { from, to } = this.transalteGitCommitFromArgs();
            if (from && to) {
                commitData.message = lib_3._.kebabCase(await (0, translate_1.translate)(commitData.message, { from, to }));
            }
        }
        return commitData;
        //#endregion
    }
    //#endregion
    //#region methods & getters / prevent accidental branch change for taon projects
    /**
     * This will prevent accidental branch change for taon projects
     * @returns branch name
     */
    duringPushWarnIfProjectNotOnSpecyficDevBranch() {
        return '';
    }
    //#endregion
    //#region methods & getters / get changed files in commit by hash
    async getChangedFilesInCommitByHash(hash) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getChangedFilesInCommitByHash(this.project.location, hash);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get changed files in commit
    /**
     * @param index 0 - means last commit
     */
    async getChangedFilesInCommitByIndex(index) {
        //#region @backendFunc
        return index_1.HelpersTaon.git.getChangedFilesInCommitByIndex(this.project.location, index);
        //#endregion
    }
    //#endregion
    //#region methods & getters / get changes summary
    async changesSummary(options) {
        //#region @backendFunc
        options = options || {};
        const fillStringWithSpaceUpTo = (str, length, specialCharacter = ' ') => {
            return str + specialCharacter.repeat(length - str.length);
        };
        options.prefix =
            options.prefix ??
                `${fillStringWithSpaceUpTo(`[${this.project.name}]`, 40, '.')} `;
        return await index_1.HelpersTaon.git.changesSummary(this.project.location, options.prefix);
        //#endregion
    }
    //#endregion
    useBranchNameDirectlyAsCommitMessage() {
        return false;
    }
}
exports.BaseGit = BaseGit;
//# sourceMappingURL=base-git.js.map