"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const command_1 = require("@oclif/command");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const rc_1 = tslib_1.__importDefault(require("rc"));
const git_1 = require("./utils/git");
const config_1 = tslib_1.__importDefault(require("./config"));
const constants_1 = require("./constants");
class BaseCommand extends command_1.Command {
    constructor() {
        super(...arguments);
        // User configurations.
        this.userConfig = config_1.default;
    }
    async init() {
        this.userConfig = rc_1.default('tuture', config_1.default);
        git_1.appendGitHook();
        if (!fs_extra_1.default.existsSync(constants_1.TUTURE_ROOT)) {
            fs_extra_1.default.mkdirSync(constants_1.TUTURE_ROOT);
        }
        if (fs_extra_1.default.existsSync(constants_1.TUTURE_IGNORE_PATH)) {
            const patterns = this.userConfig.ignoredFiles.concat(fs_extra_1.default
                .readFileSync(constants_1.TUTURE_IGNORE_PATH)
                .toString()
                .split('\n')
                .filter((pattern) => !pattern.match(/#/) && pattern.match(/\b/)));
            this.userConfig.ignoredFiles = patterns;
        }
    }
    async finally() {
        // Clean tuture root if it's empty, since it's created for no reason..
        if (fs_extra_1.default.existsSync(constants_1.TUTURE_ROOT) &&
            fs_extra_1.default.readdirSync(constants_1.TUTURE_ROOT).length === 0) {
            fs_extra_1.default.removeSync(constants_1.TUTURE_ROOT);
            git_1.removeGitHook();
        }
        if (await git_1.git.checkIsRepo()) {
            const { all } = await git_1.git.branchLocal();
            if (all.includes('master')) {
                // Ensure we are back to master branch.
                await git_1.git.checkout(['-q', 'master']);
            }
        }
    }
}
exports.default = BaseCommand;
